Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(glance): add the Swift GlanceKit client and an Apple hand-off on the glance page

nirholasb89d6ea80405
diff --git a/api/glance/token.js b/api/glance/token.js
index 77ae52324..c195c3258 100644
--- a/api/glance/token.js
+++ b/api/glance/token.js
@@ -6,7 +6,9 @@
*
* GET list the caller's live tokens (prefix, label, platform, last seen)
* POST mint one: { label?, platform?, agent? }. Answers the plaintext
- * exactly once, plus the Android deep link that hands it to the app.
+ * exactly once, plus the deep links that hand it to a native app
+ * (Android's intent: URL, and the threews:// URL both Apple apps
+ * claim).
* PATCH { id, agent } repoint a token at another owned agent (null = first)
* DELETE ?id=<uuid> revoke one. Idempotent; 404 for an id that is not
* the caller's live token.
@@ -42,6 +44,20 @@ export function androidLinkUrl(token) {
return `intent://glance/link?token=${encodeURIComponent(token)}#Intent;scheme=threews;package=${ANDROID_PACKAGE};S.browser_fallback_url=${fallback};end`;
}
+/**
+ * The URL that hands the token to an Apple app: the three.ws iPhone app or the
+ * three.ws Glance app on a Mac, both of which register the `threews` scheme.
+ *
+ * There is no intent-style fallback here because neither platform has one: a
+ * Mac or an iPhone without the app installed simply does nothing with the URL,
+ * which is why /glance also reveals the code for a person to paste. The link
+ * activity is native on both platforms (SceneDelegate on iOS, the app delegate
+ * on macOS), so the token never reaches the WebView.
+ */
+export function appleLinkUrl(token) {
+ return `threews://glance/link?token=${encodeURIComponent(token)}`;
+}
+
async function ownsAgent(userId, agentId) {
const rows = await sql`
SELECT 1 FROM agent_identities
@@ -111,7 +127,7 @@ export default wrap(async (req, res) => {
});
return json(res, 201, {
...minted,
- links: { android: androidLinkUrl(minted.token) },
+ links: { android: androidLinkUrl(minted.token), apple: appleLinkUrl(minted.token) },
});
} catch (e) {
if (e.code === 'too_many_tokens') return error(res, 409, e.code, e.message);
diff --git a/apple/GlanceKit/GlanceCache.swift b/apple/GlanceKit/GlanceCache.swift
new file mode 100644
index 000000000..e4427c7c3
--- /dev/null
+++ b/apple/GlanceKit/GlanceCache.swift
@@ -0,0 +1,69 @@
+import Foundation
+
+/// The last card this device successfully downloaded, on disk in the App Group
+/// container so the host app and the widget extension read the same copy.
+///
+/// This is what makes an offline widget show yesterday's card with an honest
+/// timestamp instead of a spinner or a broken image. Writes are atomic, so a
+/// refresh killed halfway through leaves the previous card intact rather than a
+/// truncated PNG.
+struct GlanceCache {
+ private let directory: URL
+
+ init?(fileManager: FileManager = .default) {
+ let base: URL?
+ if let group = GlanceConfig.appGroup {
+ base = fileManager.containerURL(forSecurityApplicationGroupIdentifier: group)
+ } else {
+ // No App Group (a single-target development run): the extension and
+ // the app each keep their own copy. The widget still works; the two
+ // simply do not share a cache.
+ base = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first
+ }
+ guard let root = base else { return nil }
+ directory = root.appendingPathComponent("glance", isDirectory: true)
+ try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
+ }
+
+ func read(size: GlanceSize, theme: GlanceTheme) -> GlanceCard? {
+ guard let data = try? Data(contentsOf: url(size: size, theme: theme)) else { return nil }
+ return try? decoder.decode(GlanceCard.self, from: data)
+ }
+
+ @discardableResult
+ func write(_ card: GlanceCard, size: GlanceSize, theme: GlanceTheme) -> Bool {
+ guard let data = try? encoder.encode(card) else { return false }
+ do {
+ try data.write(to: url(size: size, theme: theme), options: .atomic)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ /// Drop every cached card. Called on unlink, so a revoked widget cannot keep
+ /// painting the agent it no longer has a credential for.
+ func clear() {
+ for size in GlanceSize.allCases {
+ for theme in GlanceTheme.allCases {
+ try? FileManager.default.removeItem(at: url(size: size, theme: theme))
+ }
+ }
+ }
+
+ private func url(size: GlanceSize, theme: GlanceTheme) -> URL {
+ directory.appendingPathComponent("card-\(size.rawValue)-\(theme.rawValue).json")
+ }
+
+ private var encoder: JSONEncoder {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ return encoder
+ }
+
+ private var decoder: JSONDecoder {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return decoder
+ }
+}
diff --git a/apple/GlanceKit/GlanceCard.swift b/apple/GlanceKit/GlanceCard.swift
new file mode 100644
index 000000000..3d8e0225d
--- /dev/null
+++ b/apple/GlanceKit/GlanceCard.swift
@@ -0,0 +1,68 @@
+import Foundation
+
+/// The states `/api/glance/mine` answers with, plus the one the client owns.
+///
+/// The server never returns an error status for a widget: every situation is a
+/// designed card, and the state travels beside the bitmap in `x-glance-state`.
+/// `.unlinked` here covers both halves of the same problem, a token that was
+/// revoked and a device that never had one, because the card and the tap
+/// target are identical either way.
+enum GlanceState: String, Codable {
+ case agent
+ case unlinked
+ case noAgent = "no-agent"
+ case signedOut = "signed-out"
+
+ init(header: String?) {
+ self = GlanceState(rawValue: header ?? "") ?? .agent
+ }
+}
+
+/// The three card sizes the server renders, mapped to the widget families that
+/// want them. Pinned in specs/GLANCE_CARD.md.
+enum GlanceSize: String, Codable, CaseIterable {
+ case small
+ case medium
+ case large
+
+ /// Pixel density to ask for. Large is the biggest canvas, so it asks for
+ /// less density to keep the decoded bitmap inside a widget's memory budget.
+ var scale: Int { self == .large ? 2 : 3 }
+
+ /// The card's aspect ratio, used to lay the bitmap out before it arrives.
+ var aspectRatio: Double {
+ switch self {
+ case .small: return 1
+ case .medium: return 480.0 / 200.0
+ case .large: return 480.0 / 300.0
+ }
+ }
+}
+
+enum GlanceTheme: String, Codable, CaseIterable {
+ case dark
+ case light
+}
+
+/// One rendered card: the bitmap, plus the facts the server puts in headers so
+/// a native widget learns everything it needs from the request that fetched
+/// the image and never needs a JSON parser.
+struct GlanceCard: Codable, Equatable {
+ var png: Data
+ var state: GlanceState
+ /// Where a tap goes. Always an absolute https URL on the platform origin.
+ var url: URL
+ var name: String
+ var metric: String
+ var agentID: String
+ /// When the server computed the card.
+ var updatedAt: Date?
+ /// When this device last got a fresh copy. Drives the offline footer.
+ var fetchedAt: Date
+
+ /// A card older than this is stale enough that the widget says so rather
+ /// than presenting yesterday's number as today's.
+ static let staleAfter: TimeInterval = 60 * 90
+
+ var isStale: Bool { Date().timeIntervalSince(fetchedAt) > Self.staleAfter }
+}
diff --git a/apple/GlanceKit/GlanceCardView.swift b/apple/GlanceKit/GlanceCardView.swift
new file mode 100644
index 000000000..c54772ce6
--- /dev/null
+++ b/apple/GlanceKit/GlanceCardView.swift
@@ -0,0 +1,152 @@
+import SwiftUI
+import WidgetKit
+
+/// The widget's ink. Every state is drawn, because a widget that renders an
+/// error is a widget people remove.
+///
+/// Three of the four server states arrive as a designed card already (signed
+/// out, no agent yet, token revoked), so they need no special case here: the
+/// bitmap says the right thing and `x-glance-url` points at the right place.
+/// The two the client owns are "no token on this device" and "no card
+/// downloaded yet", and they are drawn below.
+struct GlanceCardView: View {
+ let entry: GlanceEntry
+ let size: GlanceSize
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ /// The ground a card sits on. It matches the card's own background, so a
+ /// bitmap that does not fill its slot exactly reads as one surface rather
+ /// than as an image floating on the system's material.
+ static let darkCanvas = Color(red: 0.043, green: 0.043, blue: 0.086)
+ static let lightCanvas = Color(red: 0.976, green: 0.976, blue: 0.988)
+
+ private var theme: GlanceTheme { colorScheme == .light ? .light : .dark }
+ private var canvas: Color { theme == .light ? Self.lightCanvas : Self.darkCanvas }
+ private var ink: Color { theme == .light ? .black : .white }
+
+ var body: some View {
+ content
+ .containerBackground(canvas, for: .widget)
+ .widgetURL(entry.card(for: theme)?.url ?? GlanceConfig.linkPageURL)
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ if let card = entry.card(for: theme), let image = GlanceImage.make(card.png) {
+ rendered(image: image, card: card)
+ } else if entry.linked {
+ GlancePlaceholderView(
+ title: "Fetching your agent",
+ detail: "The card appears as soon as it downloads.",
+ symbol: "arrow.down.circle",
+ ink: ink
+ )
+ } else {
+ GlancePlaceholderView(
+ title: "Add your agent",
+ detail: "Open three.ws and link this widget to your account.",
+ symbol: "person.crop.circle.badge.plus",
+ ink: ink
+ )
+ }
+ }
+
+ private func rendered(image: Image, card: GlanceCard) -> some View {
+ VStack(spacing: 0) {
+ image
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ if let footer = footer(for: card) {
+ Text(footer)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(ink.opacity(0.62))
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ .padding(.top, 4)
+ }
+ if size == .large {
+ GlanceActionsRow(ink: ink)
+ .padding(.top, 8)
+ }
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(accessibilityLabel(for: card))
+ }
+
+ /// The honest line under a card that is not current. A widget showing an
+ /// hour-old number without saying so is lying about the number.
+ private func footer(for card: GlanceCard) -> String? {
+ guard entry.offline || card.isStale else { return nil }
+ let time = card.fetchedAt.formatted(date: .omitted, time: .shortened)
+ return entry.offline ? "From \(time) (offline)" : "From \(time)"
+ }
+
+ private func accessibilityLabel(for card: GlanceCard) -> String {
+ var parts = [card.name, card.metric].filter { !$0.isEmpty }
+ if let footer = footer(for: card) { parts.append(footer) }
+ return parts.isEmpty ? "three.ws agent glance" : parts.joined(separator: ", ")
+ }
+}
+
+/// The two states the server never sends, drawn to the same weight as a real
+/// card so an unlinked widget still looks like it belongs on the screen.
+struct GlancePlaceholderView: View {
+ let title: String
+ let detail: String
+ let symbol: String
+ let ink: Color
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Image(systemName: symbol)
+ .font(.system(size: 22, weight: .regular))
+ .foregroundStyle(
+ LinearGradient(
+ colors: [
+ Color(red: 0.31, green: 0.27, blue: 0.9),
+ Color(red: 0.49, green: 0.23, blue: 0.93),
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ Spacer(minLength: 0)
+ Text(title)
+ .font(.system(size: 15, weight: .semibold))
+ .foregroundStyle(ink)
+ Text(detail)
+ .font(.system(size: 11.5))
+ .foregroundStyle(ink.opacity(0.62))
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// The large family has room for the two things an owner reaches for next,
+/// which is exactly what the Android 4x3 widget offers.
+struct GlanceActionsRow: View {
+ let ink: Color
+
+ var body: some View {
+ HStack(spacing: 8) {
+ action(title: "Create", url: GlanceConfig.origin.appendingPathComponent("create"))
+ action(title: "My agents", url: GlanceConfig.origin.appendingPathComponent("my-agents"))
+ }
+ }
+
+ private func action(title: String, url: URL) -> some View {
+ Link(destination: url) {
+ Text(title)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(ink)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 7)
+ .background(ink.opacity(0.1), in: Capsule())
+ }
+ .accessibilityLabel("Open \(title.lowercased()) on three.ws")
+ }
+}
diff --git a/apple/GlanceKit/GlanceClient.swift b/apple/GlanceKit/GlanceClient.swift
new file mode 100644
index 000000000..5edd53f5a
--- /dev/null
+++ b/apple/GlanceKit/GlanceClient.swift
@@ -0,0 +1,100 @@
+import Foundation
+
+enum GlanceClientError: Error, LocalizedError {
+ case noToken
+ case badStatus(Int)
+ case notAnImage(String)
+ case empty
+
+ var errorDescription: String? {
+ switch self {
+ case .noToken:
+ return "This widget is not linked to a three.ws account yet."
+ case .badStatus(let code):
+ return "three.ws answered \(code)."
+ case .notAnImage(let type):
+ return "three.ws answered \(type) instead of a card."
+ case .empty:
+ return "three.ws answered an empty card."
+ }
+ }
+}
+
+/// One request per card: `GET /api/glance/mine?format=png`, the widget token as
+/// a bearer, the bitmap in the body and the card's facts in the headers.
+///
+/// The endpoint answers 200 for every state, including a revoked token and a
+/// signed-out account, so anything other than 200 here is a transport problem
+/// and the caller falls back to the cached card.
+struct GlanceClient {
+ /// A card is at most a few hundred kilobytes; past this it is not a card.
+ static let maxBytes = 4 * 1024 * 1024
+
+ var origin: URL = GlanceConfig.origin
+ var session: URLSession = {
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForRequest = 20
+ config.timeoutIntervalForResource = 30
+ // A widget refresh has a hard deadline: failing fast and painting the
+ // cached card beats waiting for a network that is not there.
+ config.waitsForConnectivity = false
+ config.requestCachePolicy = .reloadIgnoringLocalCacheData
+ return URLSession(configuration: config)
+ }()
+
+ func fetch(size: GlanceSize, theme: GlanceTheme, token: String) async throws -> GlanceCard {
+ guard GlanceTokenStore.isWellFormed(token) else { throw GlanceClientError.noToken }
+
+ var components = URLComponents(url: origin.appendingPathComponent("api/glance/mine"),
+ resolvingAgainstBaseURL: false)
+ components?.queryItems = [
+ URLQueryItem(name: "format", value: "png"),
+ URLQueryItem(name: "size", value: size.rawValue),
+ URLQueryItem(name: "theme", value: theme.rawValue),
+ URLQueryItem(name: "scale", value: String(size.scale)),
+ ]
+ guard let url = components?.url else { throw GlanceClientError.badStatus(0) }
+
+ var request = URLRequest(url: url)
+ request.setValue("image/png", forHTTPHeaderField: "Accept")
+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ request.setValue(Self.userAgent, forHTTPHeaderField: "User-Agent")
+
+ let (data, response) = try await session.data(for: request)
+ guard let http = response as? HTTPURLResponse else { throw GlanceClientError.badStatus(0) }
+ guard http.statusCode == 200 else { throw GlanceClientError.badStatus(http.statusCode) }
+
+ let type = http.value(forHTTPHeaderField: "Content-Type") ?? ""
+ guard type.hasPrefix("image/png") else { throw GlanceClientError.notAnImage(type) }
+ guard !data.isEmpty, data.count <= Self.maxBytes else { throw GlanceClientError.empty }
+
+ let tap = http.value(forHTTPHeaderField: "x-glance-url").flatMap(URL.init(string:))
+ return GlanceCard(
+ png: data,
+ state: GlanceState(header: http.value(forHTTPHeaderField: "x-glance-state")),
+ url: tap ?? GlanceConfig.linkPageURL,
+ name: http.value(forHTTPHeaderField: "x-glance-name") ?? "",
+ metric: http.value(forHTTPHeaderField: "x-glance-metric") ?? "",
+ agentID: http.value(forHTTPHeaderField: "x-glance-agent") ?? "",
+ updatedAt: Self.parseDate(http.value(forHTTPHeaderField: "x-glance-updated")),
+ fetchedAt: Date()
+ )
+ }
+
+ static let userAgent: String = {
+ let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown"
+ #if os(macOS)
+ return "three.ws-macos-widget/\(version)"
+ #else
+ return "three.ws-ios-widget/\(version)"
+ #endif
+ }()
+
+ private static func parseDate(_ raw: String?) -> Date? {
+ guard let raw, !raw.isEmpty else { return nil }
+ let withFraction = ISO8601DateFormatter()
+ withFraction.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ if let date = withFraction.date(from: raw) { return date }
+ return ISO8601DateFormatter().date(from: raw)
+ }
+}
diff --git a/apple/GlanceKit/GlanceConfig.swift b/apple/GlanceKit/GlanceConfig.swift
new file mode 100644
index 000000000..b7f4c24e2
--- /dev/null
+++ b/apple/GlanceKit/GlanceConfig.swift
@@ -0,0 +1,54 @@
+import Foundation
+
+/// Where a widget reads its card from, and which containers it shares with its
+/// host app.
+///
+/// Every value is read from the running target's Info.plist rather than hard
+/// coded, because the two platforms cannot agree on the strings. An App Group
+/// on iOS is `group.ws.three.app`; the same group on a Mac distributed with a
+/// Developer ID has to carry the team prefix. Both projects set the build
+/// settings `GLANCE_ORIGIN`, `GLANCE_APP_GROUP` and `GLANCE_KEYCHAIN_GROUP`,
+/// Xcode expands them into the Info.plist and the entitlements, and this file
+/// stays identical on both.
+enum GlanceConfig {
+ /// The production origin. Used when the Info.plist key is missing, which is
+ /// what a bare `swift build` of the sources sees.
+ static let defaultOrigin = URL(string: "https://three.ws")!
+
+ static var origin: URL {
+ guard let raw = infoString("GlanceOrigin"),
+ let url = URL(string: raw),
+ url.scheme == "https"
+ else { return defaultOrigin }
+ return url
+ }
+
+ /// The App Group container holding the last card. `nil` on a single-target
+ /// development run, where the extension falls back to its own container and
+ /// simply cannot see what the app cached.
+ static var appGroup: String? { infoString("GlanceAppGroup") }
+
+ /// The shared keychain group. `nil` when `DEVELOPMENT_TEAM` was not set at
+ /// build time, in which case the value expands to a bare `.ws.three.shared`
+ /// and the token lives in the target's own keychain instead.
+ static var keychainGroup: String? {
+ guard let raw = infoString("GlanceKeychainGroup"), !raw.hasPrefix(".") else { return nil }
+ return raw
+ }
+
+ static let keychainService = "ws.three.glance"
+ static let keychainAccount = "widget-token"
+
+ /// The scheme both Apple apps claim, and the one `/api/glance/token` builds
+ /// its `links.apple` URL with.
+ static let urlScheme = "threews"
+
+ /// The page that mints and revokes widget tokens.
+ static var linkPageURL: URL { origin.appendingPathComponent("glance") }
+
+ private static func infoString(_ key: String) -> String? {
+ guard let value = Bundle.main.object(forInfoDictionaryKey: key) as? String else { return nil }
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? nil : trimmed
+ }
+}
diff --git a/apple/GlanceKit/GlanceEntry.swift b/apple/GlanceKit/GlanceEntry.swift
new file mode 100644
index 000000000..2d5c1f016
--- /dev/null
+++ b/apple/GlanceKit/GlanceEntry.swift
@@ -0,0 +1,38 @@
+import Foundation
+import WidgetKit
+
+/// One moment in a widget's timeline.
+///
+/// It carries both themes because the provider cannot see the reader's
+/// appearance: `colorScheme` is a view environment, and a timeline is built
+/// long before anything is drawn. Fetching both is cheap (the server caches
+/// each rendered card in object storage) and it is what lets a Mac in light
+/// mode show a light card instead of a dark rectangle.
+struct GlanceEntry: TimelineEntry {
+ let date: Date
+ /// False when this device holds no widget token, which is the one state the
+ /// server cannot answer because nothing can be asked of it yet.
+ let linked: Bool
+ /// True when the last refresh could not reach three.ws, so the card being
+ /// drawn came off the disk.
+ let offline: Bool
+
+ private let cards: [GlanceTheme: GlanceCard]
+
+ init(date: Date, linked: Bool, offline: Bool, cards: [GlanceTheme: GlanceCard]) {
+ self.date = date
+ self.linked = linked
+ self.offline = offline
+ self.cards = cards
+ }
+
+ func card(for theme: GlanceTheme) -> GlanceCard? {
+ cards[theme] ?? cards[.dark] ?? cards[.light]
+ }
+
+ var hasCard: Bool { !cards.isEmpty }
+
+ static func unlinked(date: Date = Date()) -> GlanceEntry {
+ GlanceEntry(date: date, linked: false, offline: false, cards: [:])
+ }
+}
diff --git a/apple/GlanceKit/GlanceImage.swift b/apple/GlanceKit/GlanceImage.swift
new file mode 100644
index 000000000..1a2545476
--- /dev/null
+++ b/apple/GlanceKit/GlanceImage.swift
@@ -0,0 +1,26 @@
+import SwiftUI
+
+#if canImport(UIKit)
+import UIKit
+#elseif canImport(AppKit)
+import AppKit
+#endif
+
+/// One PNG, decoded into a SwiftUI `Image` on whichever platform is asking.
+///
+/// The card is a server-rendered bitmap on every platform for the same reason:
+/// no widget host anywhere can run WebGL, so the 3D agent stays one tap away on
+/// its page and the slot gets a picture.
+enum GlanceImage {
+ static func make(_ data: Data) -> Image? {
+ #if canImport(UIKit)
+ guard let image = UIImage(data: data) else { return nil }
+ return Image(uiImage: image)
+ #elseif canImport(AppKit)
+ guard let image = NSImage(data: data) else { return nil }
+ return Image(nsImage: image)
+ #else
+ return nil
+ #endif
+ }
+}
diff --git a/apple/GlanceKit/GlanceLink.swift b/apple/GlanceKit/GlanceLink.swift
new file mode 100644
index 000000000..794b0448a
--- /dev/null
+++ b/apple/GlanceKit/GlanceLink.swift
@@ -0,0 +1,60 @@
+import Foundation
+import WidgetKit
+
+/// The `threews://glance/link?token=glw_…` hand-off, on both Apple platforms.
+///
+/// This is the same trade the Android app makes with its `intent://` URL: the
+/// page mints the token against the session, and the operating system hands it
+/// to the one app that claims the scheme, so the credential never touches a web
+/// page or a pasteboard unless the owner asks for the code instead.
+///
+/// A custom scheme is an entry point any app can call, so nothing here trusts
+/// the payload: the token has to match the minted shape before it is stored,
+/// and anything else is refused without a trace of it reaching the keychain.
+enum GlanceLink {
+ static let host = "glance"
+ static let path = "/link"
+
+ enum Outcome: Equatable {
+ case linked
+ case notALinkURL
+ case malformedToken
+ case keychainRefused
+ }
+
+ static func isLinkURL(_ url: URL) -> Bool {
+ guard url.scheme?.lowercased() == GlanceConfig.urlScheme else { return false }
+ // threews://glance/link puts "glance" in the host and "/link" in the path.
+ return url.host?.lowercased() == host && url.path == path
+ }
+
+ /// Claim a URL. Returns `.notALinkURL` for anything else, which is the
+ /// caller's signal to pass it on to whatever normally handles deep links.
+ @discardableResult
+ static func claim(_ url: URL) -> Outcome {
+ guard isLinkURL(url) else { return .notALinkURL }
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ guard let token = items.first(where: { $0.name == "token" })?.value,
+ GlanceTokenStore.isWellFormed(token)
+ else { return .malformedToken }
+
+ guard GlanceTokenStore.save(token) else { return .keychainRefused }
+ // The previous account's card must not survive a relink.
+ GlanceCache()?.clear()
+ reloadWidgets()
+ return .linked
+ }
+
+ /// Forget the token and everything drawn from it. The token itself stays
+ /// live on the server until it is revoked from three.ws/glance, which is
+ /// why the app sends the owner there rather than pretending otherwise.
+ static func unlink() {
+ GlanceTokenStore.clear()
+ GlanceCache()?.clear()
+ reloadWidgets()
+ }
+
+ static func reloadWidgets() {
+ WidgetCenter.shared.reloadAllTimelines()
+ }
+}
diff --git a/apple/GlanceKit/GlanceTokenStore.swift b/apple/GlanceKit/GlanceTokenStore.swift
new file mode 100644
index 000000000..df9067ddc
--- /dev/null
+++ b/apple/GlanceKit/GlanceTokenStore.swift
@@ -0,0 +1,78 @@
+import Foundation
+import Security
+
+/// The widget token, in the keychain, shared between the host app that mints
+/// it and the widget extension that spends it.
+///
+/// A home screen widget outlives every browser session and runs in a process
+/// with no cookie jar, so it carries `glw_…`, a credential that is accepted by
+/// exactly one endpoint and reads exactly one thing: the owner's own card. The
+/// item is `kSecAttrAccessibleAfterFirstUnlock` because WidgetKit refreshes
+/// timelines while the device is locked, and a token the widget cannot read
+/// then would show a stale card until the next unlock.
+enum GlanceTokenStore {
+ /// The shape `/api/_lib/glance-tokens.js` mints and validates.
+ static let pattern = "^glw_[A-Za-z0-9_-]{32}$"
+
+ static func isWellFormed(_ token: String) -> Bool {
+ token.range(of: pattern, options: .regularExpression) != nil
+ }
+
+ static func load() -> String? {
+ var query = baseQuery()
+ query[kSecReturnData as String] = true
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
+
+ var item: CFTypeRef?
+ guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
+ let data = item as? Data,
+ let token = String(data: data, encoding: .utf8)
+ else { return nil }
+ return token
+ }
+
+ /// Replace whatever is stored. Returns false only when the keychain itself
+ /// refuses, which the caller surfaces rather than silently dropping the
+ /// token and leaving the widget stuck on "link this widget".
+ @discardableResult
+ static func save(_ token: String) -> Bool {
+ guard isWellFormed(token) else { return false }
+ let data = Data(token.utf8)
+ let query = baseQuery()
+
+ let update: [String: Any] = [kSecValueData as String: data]
+ let updated = SecItemUpdate(query as CFDictionary, update as CFDictionary)
+ if updated == errSecSuccess { return true }
+ if updated != errSecItemNotFound { return false }
+
+ var insert = query
+ insert[kSecValueData as String] = data
+ insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
+ return SecItemAdd(insert as CFDictionary, nil) == errSecSuccess
+ }
+
+ /// Forget the token. Called when the owner unlinks from the app, and when
+ /// the server answers `unlinked`, which means the token was revoked from
+ /// three.ws/glance and will never work again.
+ static func clear() {
+ SecItemDelete(baseQuery() as CFDictionary)
+ }
+
+ private static func baseQuery() -> [String: Any] {
+ var query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: GlanceConfig.keychainService,
+ kSecAttrAccount as String: GlanceConfig.keychainAccount,
+ ]
+ if let group = GlanceConfig.keychainGroup {
+ query[kSecAttrAccessGroup as String] = group
+ }
+ #if os(macOS)
+ // Without this a Mac keychain item is invisible to the other target
+ // even with the access group set, because macOS defaults generic
+ // passwords to the legacy file keychain.
+ query[kSecUseDataProtectionKeychain as String] = true
+ #endif
+ return query
+ }
+}
diff --git a/apple/GlanceWidget/AgentGlanceWidget.swift b/apple/GlanceWidget/AgentGlanceWidget.swift
new file mode 100644
index 000000000..a50fd3b08
--- /dev/null
+++ b/apple/GlanceWidget/AgentGlanceWidget.swift
@@ -0,0 +1,40 @@
+import WidgetKit
+import SwiftUI
+
+/// The widget itself. One definition, three families, both platforms.
+///
+/// Nothing about the card is configurable from the widget: a home screen slot
+/// has no room to pick an agent in, so the server answers "your agent" and the
+/// owner repoints it from three.ws/glance, which is also where the token that
+/// fetches it can be revoked.
+struct AgentGlanceWidget: Widget {
+ static let kind = "ws.three.glance.agent"
+
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: Self.kind, provider: GlanceProvider()) { entry in
+ AgentGlanceEntryView(entry: entry)
+ }
+ .configurationDisplayName("Agent glance")
+ .description("Your three.ws agent: its avatar, its name, and how many moves it made today.")
+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
+ .contentMarginsDisabled()
+ }
+}
+
+/// The family is a view environment, not something the provider can see, so the
+/// size the card was fetched at is resolved here as well as in the timeline.
+struct AgentGlanceEntryView: View {
+ @Environment(\.widgetFamily) private var family
+ let entry: GlanceEntry
+
+ var body: some View {
+ GlanceCardView(entry: entry, size: GlanceSize(family: family))
+ }
+}
+
+@main
+struct GlanceWidgetBundle: WidgetBundle {
+ var body: some Widget {
+ AgentGlanceWidget()
+ }
+}
diff --git a/apple/GlanceWidget/GlanceProvider.swift b/apple/GlanceWidget/GlanceProvider.swift
new file mode 100644
index 000000000..d62180552
--- /dev/null
+++ b/apple/GlanceWidget/GlanceProvider.swift
@@ -0,0 +1,105 @@
+import WidgetKit
+import SwiftUI
+
+/// The timeline behind the Agent glance widget on both Apple platforms.
+///
+/// The shape is the same trade the Android widget makes: one request per
+/// refresh, the bitmap straight to disk, and the last good card kept so a
+/// device with no network paints yesterday's card with an honest timestamp
+/// instead of a spinner. WidgetKit decides when to actually run this; the
+/// policy below is a request, not a schedule.
+struct GlanceProvider: TimelineProvider {
+ /// What the system is asked for next. Half an hour matches the Android
+ /// WorkManager cadence and the 900 second refresh the Windows widget
+ /// declares, so the same number moves at the same speed on every surface.
+ static let refreshInterval: TimeInterval = 30 * 60
+ /// After a failed refresh, ask sooner: the usual cause is a network that
+ /// came back a minute later.
+ static let retryInterval: TimeInterval = 15 * 60
+
+ func placeholder(in context: Context) -> GlanceEntry {
+ cachedEntry(size: GlanceSize(family: context.family)) ?? .unlinked()
+ }
+
+ func getSnapshot(in context: Context, completion: @escaping (GlanceEntry) -> Void) {
+ let size = GlanceSize(family: context.family)
+ // A gallery preview must never spend the token or the network.
+ if context.isPreview {
+ completion(cachedEntry(size: size) ?? .unlinked())
+ return
+ }
+ Task { completion(await refresh(size: size).entry) }
+ }
+
+ func getTimeline(in context: Context, completion: @escaping (Timeline<GlanceEntry>) -> Void) {
+ let size = GlanceSize(family: context.family)
+ Task {
+ let result = await refresh(size: size)
+ let next = Date().addingTimeInterval(result.succeeded ? Self.refreshInterval : Self.retryInterval)
+ completion(Timeline(entries: [result.entry], policy: .after(next)))
+ }
+ }
+
+ // MARK: - Fetching
+
+ private struct Result {
+ let entry: GlanceEntry
+ let succeeded: Bool
+ }
+
+ private func refresh(size: GlanceSize) async -> Result {
+ guard let token = GlanceTokenStore.load() else {
+ // No credential on this device. Nothing to ask, and nothing stale to
+ // keep: the card that gets drawn is the link prompt.
+ return Result(entry: .unlinked(), succeeded: true)
+ }
+
+ let cache = GlanceCache()
+ let client = GlanceClient()
+ var cards: [GlanceTheme: GlanceCard] = [:]
+ var fetched = false
+
+ for theme in GlanceTheme.allCases {
+ do {
+ let card = try await client.fetch(size: size, theme: theme, token: token)
+ cards[theme] = card
+ cache?.write(card, size: size, theme: theme)
+ fetched = true
+ // A revoked token will never work again, so stop spending
+ // requests on it and let the unlinked card the server just sent
+ // tell the owner what happened.
+ if card.state == .unlinked { break }
+ } catch {
+ if let cached = cache?.read(size: size, theme: theme) { cards[theme] = cached }
+ }
+ }
+
+ return Result(
+ entry: GlanceEntry(date: Date(), linked: true, offline: !fetched, cards: cards),
+ succeeded: fetched
+ )
+ }
+
+ private func cachedEntry(size: GlanceSize) -> GlanceEntry? {
+ guard GlanceTokenStore.load() != nil, let cache = GlanceCache() else { return nil }
+ var cards: [GlanceTheme: GlanceCard] = [:]
+ for theme in GlanceTheme.allCases {
+ if let card = cache.read(size: size, theme: theme) { cards[theme] = card }
+ }
+ guard !cards.isEmpty else { return nil }
+ return GlanceEntry(date: Date(), linked: true, offline: true, cards: cards)
+ }
+}
+
+extension GlanceSize {
+ /// Which rendered card fills which slot. Anything the widget does not
+ /// declare support for still resolves, so a future family added by the
+ /// system gets the wide card rather than nothing.
+ init(family: WidgetFamily) {
+ switch family {
+ case .systemSmall: self = .small
+ case .systemLarge, .systemExtraLarge: self = .large
+ default: self = .medium
+ }
+ }
+}
diff --git a/apple/GlanceWidget/GlanceWidget.entitlements b/apple/GlanceWidget/GlanceWidget.entitlements
new file mode 100644
index 000000000..6002b6913
--- /dev/null
+++ b/apple/GlanceWidget/GlanceWidget.entitlements
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!--
+ The extension reads the token the host app wrote and the card cache the
+ two of them share. Both values come from the project's build settings so
+ this file is identical on iOS and macOS; see apple/README.md for why the
+ two platforms need different strings.
+ -->
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>$(GLANCE_APP_GROUP)</string>
+ </array>
+ <key>keychain-access-groups</key>
+ <array>
+ <string>$(GLANCE_KEYCHAIN_GROUP)</string>
+ </array>
+ <!--
+ macOS only: an app extension is sandboxed, and a widget that cannot open
+ an outgoing connection cannot fetch its card. Ignored on iOS.
+ -->
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/apple/GlanceWidget/Info.plist b/apple/GlanceWidget/Info.plist
new file mode 100644
index 000000000..7dbb201b2
--- /dev/null
+++ b/apple/GlanceWidget/Info.plist
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleDisplayName</key>
+ <string>Agent glance</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.widgetkit-extension</string>
+ </dict>
+ <!--
+ GlanceKit reads these three at runtime instead of hard coding them,
+ because iOS and macOS cannot agree on the strings: an App Group on a Mac
+ signed with a Developer ID has to carry the team prefix that the same
+ group on iPhone must not have. Each project defines the build settings
+ and Xcode expands them here and in the entitlements.
+ -->
+ <key>GlanceOrigin</key>
+ <string>$(GLANCE_ORIGIN)</string>
+ <key>GlanceAppGroup</key>
+ <string>$(GLANCE_APP_GROUP)</string>
+ <key>GlanceKeychainGroup</key>
+ <string>$(GLANCE_KEYCHAIN_GROUP)</string>
+</dict>
+</plist>
diff --git a/apple/macos/ThreeWSGlance/GlanceLinkModel.swift b/apple/macos/ThreeWSGlance/GlanceLinkModel.swift
new file mode 100644
index 000000000..1fc37a92a
--- /dev/null
+++ b/apple/macos/ThreeWSGlance/GlanceLinkModel.swift
@@ -0,0 +1,121 @@
+import AppKit
+import Foundation
+import SwiftUI
+
+/// The host app's whole job: hold the widget token, prove it works, and give
+/// the owner a way to drop it.
+///
+/// The Mac never sees a password. Signing in happens on three.ws in the
+/// browser, exactly as it does on the phone, and the page hands back a token
+/// through `threews://glance/link` or as a code to paste. Everything after that
+/// is one read-only endpoint.
+@MainActor
+final class GlanceLinkModel: ObservableObject {
+ enum Status: Equatable {
+ case idle
+ case working
+ case linked(name: String, metric: String)
+ case needsLink
+ case failed(String)
+ }
+
+ @Published private(set) var status: Status = .idle
+ @Published private(set) var card: GlanceCard?
+ @Published var pastedCode: String = ""
+
+ private let client = GlanceClient()
+ private let cache = GlanceCache()
+
+ var isLinked: Bool { GlanceTokenStore.load() != nil }
+
+ init() {
+ card = cache?.read(size: .medium, theme: .dark)
+ status = isLinked ? .idle : .needsLink
+ }
+
+ /// Open the page that mints a token. It is also where tokens are revoked,
+ /// which is why the app links to it rather than reimplementing the list.
+ func openLinkPage() {
+ var components = URLComponents(url: GlanceConfig.linkPageURL, resolvingAgainstBaseURL: false)
+ components?.queryItems = [URLQueryItem(name: "link", value: "apple")]
+ guard let url = components?.url else { return }
+ NSWorkspace.shared.open(url)
+ }
+
+ func openAgent() {
+ NSWorkspace.shared.open(card?.url ?? GlanceConfig.origin)
+ }
+
+ /// The deep link half of the hand-off.
+ func handle(_ url: URL) {
+ switch GlanceLink.claim(url) {
+ case .linked:
+ pastedCode = ""
+ Task { await refresh() }
+ case .malformedToken:
+ status = .failed("That link did not carry a usable code. Press Link this device on three.ws/glance again.")
+ case .keychainRefused:
+ status = .failed("macOS refused to store the code in the keychain.")
+ case .notALinkURL:
+ break
+ }
+ }
+
+ /// The paste half. A Mac whose browser is signed in on another machine has
+ /// no URL to follow, so the code on the page is the path that always works.
+ func linkWithPastedCode() {
+ let code = pastedCode.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard GlanceTokenStore.isWellFormed(code) else {
+ status = .failed("A widget code looks like glw_ followed by 32 characters.")
+ return
+ }
+ guard GlanceTokenStore.save(code) else {
+ status = .failed("macOS refused to store the code in the keychain.")
+ return
+ }
+ cache?.clear()
+ GlanceLink.reloadWidgets()
+ pastedCode = ""
+ Task { await refresh() }
+ }
+
+ /// Prove the token works and give the menu bar something live to show. The
+ /// widget does the same fetch on its own schedule; this one exists so a
+ /// person who just linked sees their agent immediately.
+ func refresh() async {
+ guard let token = GlanceTokenStore.load() else {
+ card = nil
+ status = .needsLink
+ return
+ }
+ status = .working
+ do {
+ let fresh = try await client.fetch(size: .medium, theme: .dark, token: token)
+ cache?.write(fresh, size: .medium, theme: .dark)
+ card = fresh
+ GlanceLink.reloadWidgets()
+ switch fresh.state {
+ case .agent:
+ status = .linked(name: fresh.name, metric: fresh.metric)
+ case .unlinked:
+ // The server says this credential is gone. Drop it rather than
+ // retrying it every half hour forever.
+ GlanceLink.unlink()
+ card = nil
+ status = .failed("This code was revoked on three.ws/glance. Link this device again.")
+ case .noAgent:
+ status = .failed("This account has no agent yet. Create one on three.ws and the widget fills in.")
+ case .signedOut:
+ status = .failed("three.ws did not recognise this code. Link this device again.")
+ }
+ } catch {
+ status = .failed(error.localizedDescription)
+ }
+ }
+
+ func unlink() {
+ GlanceLink.unlink()
+ card = nil
+ status = .needsLink
+ }
+}
diff --git a/apple/macos/ThreeWSGlance/LinkView.swift b/apple/macos/ThreeWSGlance/LinkView.swift
new file mode 100644
index 000000000..26e3e17c1
--- /dev/null
+++ b/apple/macos/ThreeWSGlance/LinkView.swift
@@ -0,0 +1,127 @@
+import SwiftUI
+
+/// The window: what state this Mac is in, and the one action that changes it.
+struct LinkView: View {
+ @ObservedObject var model: GlanceLinkModel
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+ header
+ statusRow
+ if model.isLinked {
+ linkedActions
+ } else {
+ linkSteps
+ }
+ Divider()
+ widgetHelp
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(minWidth: 420, minHeight: 460)
+ }
+
+ private var header: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Agent glance")
+ .font(.system(size: 22, weight: .semibold))
+ Text("Your three.ws agent in Notification Centre: its avatar, its name, and how many moves it made today.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ @ViewBuilder
+ private var statusRow: some View {
+ switch model.status {
+ case .idle:
+ label("Linked to this Mac.", symbol: "checkmark.circle.fill", tint: .green)
+ case .working:
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("Checking with three.ws").font(.system(size: 13))
+ }
+ case .linked(let name, let metric):
+ label("\(name). \(metric).", symbol: "checkmark.circle.fill", tint: .green)
+ case .needsLink:
+ label("Not linked yet.", symbol: "person.crop.circle.badge.plus", tint: .accentColor)
+ case .failed(let message):
+ label(message, symbol: "exclamationmark.triangle.fill", tint: .orange)
+ }
+ }
+
+ private func label(_ text: String, symbol: String, tint: Color) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Image(systemName: symbol).foregroundStyle(tint)
+ Text(text).font(.system(size: 13)).fixedSize(horizontal: false, vertical: true)
+ }
+ .accessibilityElement(children: .combine)
+ }
+
+ private var linkSteps: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ step(1, "Open three.ws/glance in your browser and sign in.")
+ step(2, "Press Link this device. If this app does not open by itself, copy the code the page shows.")
+ step(3, "Paste it here.")
+
+ Button("Open three.ws/glance") { model.openLinkPage() }
+ .buttonStyle(.borderedProminent)
+ .keyboardShortcut(.defaultAction)
+
+ HStack(spacing: 8) {
+ TextField("glw_", text: $model.pastedCode)
+ .textFieldStyle(.roundedBorder)
+ .font(.system(size: 13, design: .monospaced))
+ .onSubmit { model.linkWithPastedCode() }
+ .accessibilityLabel("Widget code from three.ws")
+ Button("Link") { model.linkWithPastedCode() }
+ .disabled(model.pastedCode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+
+ Text("The code reads one thing: your glance card. It cannot sign in, spend, or change anything, and you can revoke it on three.ws/glance at any time.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ private var linkedActions: some View {
+ HStack(spacing: 10) {
+ Button("Refresh now") { Task { await model.refresh() } }
+ Button("Open my agent") { model.openAgent() }
+ Spacer()
+ Button("Unlink this Mac", role: .destructive) { model.unlink() }
+ }
+ }
+
+ private var widgetHelp: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Adding the widget")
+ .font(.system(size: 14, weight: .semibold))
+ step(1, "Click the date in the menu bar to open Notification Centre.")
+ step(2, "Scroll down and click Edit Widgets.")
+ step(3, "Find three.ws Glance and drag Agent glance out. It comes in small, medium and large.")
+ Text("The widget refreshes on the system's own schedule, about every half hour. With no network it keeps the last card it downloaded and says when that was.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ private func step(_ number: Int, _ text: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text("\(number)")
+ .font(.system(size: 11, weight: .bold, design: .rounded))
+ .foregroundStyle(.white)
+ .frame(width: 18, height: 18)
+ .background(Color.accentColor, in: Circle())
+ Text(text)
+ .font(.system(size: 13))
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/apple/macos/ThreeWSGlance/MenuBarView.swift b/apple/macos/ThreeWSGlance/MenuBarView.swift
new file mode 100644
index 000000000..e8678ac3b
--- /dev/null
+++ b/apple/macos/ThreeWSGlance/MenuBarView.swift
@@ -0,0 +1,70 @@
+import AppKit
+import SwiftUI
+
+/// The menu bar companion: the card itself, small, plus the three things worth
+/// reaching for without opening a window.
+struct MenuBarView: View {
+ @ObservedObject var model: GlanceLinkModel
+ @Environment(\.openWindow) private var openWindow
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if let card = model.card, let image = GlanceImage.make(card.png) {
+ image
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: 260)
+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .accessibilityLabel(accessibilityLabel(for: card))
+ if card.isStale {
+ Text("From \(card.fetchedAt.formatted(date: .omitted, time: .shortened))")
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ }
+ } else {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(model.isLinked ? "No card yet" : "Not linked")
+ .font(.system(size: 13, weight: .semibold))
+ Text(model.isLinked
+ ? "Refresh to pull your agent's card."
+ : "Link this Mac to your three.ws account to see your agent here.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(width: 260, alignment: .leading)
+ }
+
+ Divider()
+
+ VStack(alignment: .leading, spacing: 2) {
+ if model.isLinked {
+ menuButton("Open my agent") { model.openAgent() }
+ menuButton("Refresh now") { Task { await model.refresh() } }
+ }
+ menuButton(model.isLinked ? "Settings" : "Link this Mac") {
+ openWindow(id: "glance-link")
+ NSApp.activate(ignoringOtherApps: true)
+ }
+ menuButton("Quit") { NSApp.terminate(nil) }
+ }
+ }
+ .padding(14)
+ .frame(width: 292)
+ }
+
+ private func menuButton(_ title: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Text(title)
+ .font(.system(size: 13))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .padding(.vertical, 4)
+ }
+
+ private func accessibilityLabel(for card: GlanceCard) -> String {
+ [card.name, card.metric].filter { !$0.isEmpty }.joined(separator: ", ")
+ }
+}
diff --git a/apple/macos/ThreeWSGlance/ThreeWSGlanceApp.swift b/apple/macos/ThreeWSGlance/ThreeWSGlanceApp.swift
new file mode 100644
index 000000000..8e642d5b2
--- /dev/null
+++ b/apple/macos/ThreeWSGlance/ThreeWSGlanceApp.swift
@@ -0,0 +1,27 @@
+import SwiftUI
+
+/// three.ws Glance for the Mac.
+///
+/// Two surfaces and nothing else: a menu bar item, which is the surface people
+/// actually keep, and one window that links the Mac to an account. The widget
+/// in Notification Centre is the point; this app exists to feed it a token and
+/// to prove the token works.
+@main
+struct ThreeWSGlanceApp: App {
+ @StateObject private var model = GlanceLinkModel()
+
+ var body: some Scene {
+ Window("three.ws Glance", id: "glance-link") {
+ LinkView(model: model)
+ .onOpenURL { model.handle($0) }
+ .task { if model.isLinked { await model.refresh() } }
+ }
+ .defaultSize(width: 460, height: 520)
+ .windowResizability(.contentMinSize)
+
+ MenuBarExtra("three.ws Glance", systemImage: "square.grid.2x2") {
+ MenuBarView(model: model)
+ }
+ .menuBarExtraStyle(.window)
+ }
+}
diff --git a/public/glance/glance-page.js b/public/glance/glance-page.js
index 8e4aaf885..b9f4717d3 100644
--- a/public/glance/glance-page.js
+++ b/public/glance/glance-page.js
@@ -194,6 +194,19 @@ const android = {
list: document.getElementById('device-list'),
};
+/**
+ * Apple hand-off. Same mint, a different delivery: an Apple app claims the
+ * `threews://glance/link` URL natively, and a Mac whose browser is signed in
+ * on a different machine has no URL to follow at all, so the code is revealed
+ * once beside the button for a person to paste into the app.
+ */
+const apple = {
+ button: document.getElementById('apple-link-button'),
+ status: document.getElementById('apple-link-status'),
+ code: document.getElementById('apple-link-code'),
+ value: document.getElementById('apple-link-token'),
+};
+
function deviceLabel() {
const ua = navigator.userAgent;
const model = ua.match(/;\s*([^;)]+?)\s+Build\//);
@@ -201,6 +214,19 @@ function deviceLabel() {
return /Android/i.test(ua) ? 'Android phone' : 'Home screen widget';
}
+/**
+ * Which Apple platform is asking. iPadOS reports itself as a Mac, so a Mac
+ * with a touch screen is an iPad; everything else Apple is a Mac.
+ */
+function applePlatform() {
+ const ua = navigator.userAgent;
+ if (/iPhone|iPod/.test(ua)) return { platform: 'ios', label: 'iPhone' };
+ if (/iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) {
+ return { platform: 'ios', label: 'iPad' };
+ }
+ return { platform: 'macos', label: 'Mac' };
+}
+
async function linkAndroid({ auto = false } = {}) {
android.button.disabled = true;
android.status.textContent = 'Linking…';
@@ -236,6 +262,45 @@ async function linkAndroid({ auto = false } = {}) {
}
}
+async function linkApple({ auto = false } = {}) {
+ const { platform, label } = applePlatform();
+ apple.button.disabled = true;
+ apple.status.textContent = 'Linking\u2026';
+ try {
+ const res = await fetch('/api/glance/token', {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ platform, label, agent: state.agentId || null }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (res.status === 401) {
+ const next = encodeURIComponent('/glance?link=apple');
+ apple.status.innerHTML = `<a href="/login?next=${next}">Sign in</a> first, then come back here.`;
+ if (auto) location.assign(`/login?next=${next}`);
+ return;
+ }
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ apple.status.textContent = body.message || body.error || `Could not link (${res.status}).`;
+ return;
+ }
+ // The code is the fallback, and it is shown every time rather than only
+ // on failure: nothing on the page can observe whether the app claimed
+ // the URL, and a person staring at a Mac that did nothing needs the code
+ // already in front of them.
+ apple.value.textContent = body.token;
+ apple.code.hidden = false;
+ apple.status.textContent = `Opening the three.ws app on this ${label}. If nothing happens, paste the code below into it.`;
+ await loadDevices();
+ location.assign(body.links.apple);
+ } catch (err) {
+ apple.status.textContent = `Could not link: ${err.message}`;
+ } finally {
+ apple.button.disabled = false;
+ }
+}
+
function relative(iso) {
if (!iso) return 'never used';
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
@@ -269,7 +334,7 @@ async function loadDevices() {
if (!tokens.length) {
const li = document.createElement('li');
li.className = 'glance-device-empty';
- li.textContent = 'No widget is linked yet. Link a phone above and it appears here.';
+ li.textContent = 'No widget is linked yet. Link a device above and it appears here.';
android.list.append(li);
return;
}
@@ -310,20 +375,24 @@ async function loadDevices() {
}
}
-function wireAndroid() {
+function wireLinking() {
android.button.addEventListener('click', () => linkAndroid());
+ apple.button.addEventListener('click', () => linkApple());
loadDevices();
- const params = new URL(location.href).searchParams;
- if (params.get('link') === 'android') {
+ const link = new URL(location.href).searchParams.get('link');
+ if (link === 'android') {
document.getElementById('android')?.scrollIntoView({ block: 'center' });
linkAndroid({ auto: true });
+ } else if (link === 'apple') {
+ document.getElementById('apple')?.scrollIntoView({ block: 'center' });
+ linkApple({ auto: true });
}
}
async function main() {
wireControls();
wireCopyButtons();
- wireAndroid();
+ wireLinking();
const fromUrl = new URL(location.href).searchParams.get('agent');
const { options, note } = await discoverAgents();
diff --git a/public/glance/glance.css b/public/glance/glance.css
index 82eb84399..d67596ae1 100644
--- a/public/glance/glance.css
+++ b/public/glance/glance.css
@@ -315,6 +315,17 @@ button.copy[data-state='done'] {
font-weight: 500;
padding: 0.35rem 0.75rem;
}
+.glance-token {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12.5px;
+ letter-spacing: 0.02em;
+ padding: 0.35rem 0.6rem;
+ border-radius: 8px;
+ border: 1px solid var(--line, #262842);
+ background: var(--panel, #15162a);
+ user-select: all;
+ word-break: break-all;
+}
.glance-devices {
margin-top: 2rem;
padding-top: 1.5rem;
diff --git a/public/glance/index.html b/public/glance/index.html
index 7c27a380a..4ac39aa39 100644
--- a/public/glance/index.html
+++ b/public/glance/index.html
@@ -196,20 +196,34 @@
its own token, which you can revoke below at any time.
</p>
</article>
- <article class="glance-surface">
+ <article class="glance-surface is-live" id="apple">
<h3>macOS and iOS</h3>
- <p class="glance-status">Planned</p>
- <p>
- A shared WidgetKit extension, gated on an Apple Developer account. Same card, same
- endpoint. See the
- <a href="https://github.com/nirholas/three.ws/blob/main/prompts/finish/roadmap-native-widgets.md">work order</a>.
+ <p class="glance-status">Live now</p>
+ <ol>
+ <li>Install the three.ws Glance app on the Mac, or the <a href="/docs/ios-app">three.ws iPhone app</a>.</li>
+ <li>Open this page on that device, signed in, and press <b>Link this device</b>.</li>
+ <li>Add <b>Agent glance</b> from the widget gallery (Mac: click the date, then <b>Edit widgets</b>).</li>
+ </ol>
+ <p class="glance-link" id="apple-link">
+ <button type="button" class="glance-btn" id="apple-link-button">Link this device</button>
+ <span class="glance-help" id="apple-link-status"></span>
+ </p>
+ <p class="glance-link" id="apple-link-code" hidden>
+ <code id="apple-link-token" class="glance-token">glw_</code>
+ <button class="copy glance-btn secondary" type="button" data-copy="apple-link-token">Copy</button>
+ <span class="glance-help">Paste this into the app if the link did not open it. It is shown once.</span>
+ </p>
+ <p class="glance-note">
+ One WidgetKit extension serves both platforms, in small, medium and large. It refreshes
+ on the system's timeline, keeps the last card offline, and opens your agent on click.
+ Same token, revocable below.
</p>
</article>
</div>
<div class="glance-devices" id="devices" hidden>
<h3>Linked widgets</h3>
<p class="glance-help">
- Every phone widget holds its own token that can only read your glance card. Revoke one
+ Every linked widget holds its own token that can only read your glance card. Revoke one
and that widget shows a "link again" card on its next refresh.
</p>
<ul id="device-list" class="glance-device-list" aria-live="polite"></ul>