graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(ios): add companion app source (sign-in, cube broker, sessions, chat)
Rach Pradhan7cd6adb9d0bf
diff --git a/apps/ios/.gitignore b/apps/ios/.gitignorenew file mode 100644index 00000000..e3095337--- /dev/null+++ b/apps/ios/.gitignore@@ -0,0 +1,4 @@+build/+DerivedData/+*.xcodeproj+.DS_Storediff --git a/apps/ios/Graff/Info.plist b/apps/ios/Graff/Info.plistnew file mode 100644index 00000000..c6a05101--- /dev/null+++ b/apps/ios/Graff/Info.plist@@ -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>+ <key>CFBundleDevelopmentRegion</key><string>en</string>+ <key>CFBundleExecutable</key><string>Graff</string>+ <key>CFBundleIdentifier</key><string>com.codegraff.graff</string>+ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>+ <key>CFBundleName</key><string>Graff</string>+ <key>CFBundleDisplayName</key><string>Graff</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleShortVersionString</key><string>0.1</string>+ <key>CFBundleVersion</key><string>1</string>+ <key>LSRequiresIPhoneOS</key><true/>+ <key>MinimumOSVersion</key><string>26.0</string>+ <key>UIDeviceFamily</key><array><integer>1</integer></array>+ <key>UILaunchScreen</key><dict/>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ </array>+ <key>DTPlatformName</key><string>iphonesimulator</string>+ <key>NSAppTransportSecurity</key>+ <dict>+ <key>NSAllowsLocalNetworking</key><true/>+ </dict>+</dict>+</plist>diff --git a/apps/ios/Graff/Sources/AccountView.swift b/apps/ios/Graff/Sources/AccountView.swiftnew file mode 100644index 00000000..fa276bfd--- /dev/null+++ b/apps/ios/Graff/Sources/AccountView.swift@@ -0,0 +1,179 @@+import SwiftUI++// Account sheet: device-code sign-in to codegraff (same flow as `graff+// login`), then the account's sandboxes with spin-down.+struct AccountView: View {+ @State private var signedIn = Gateway.apiKey != nil++ var body: some View {+ NavigationStack {+ if signedIn {+ SandboxesView(onSignOut: {+ Gateway.signOut()+ signedIn = false+ })+ } else {+ DeviceSignInView(onSignedIn: { signedIn = true })+ }+ }+ }+}++struct DeviceSignInView: View {+ var onSignedIn: () -> Void+ @State private var start: DeviceStart?+ @State private var status = ""+ @State private var failed = false++ var body: some View {+ VStack(spacing: 20) {+ Image(systemName: "cube.transparent")+ .font(.system(size: 44))+ .foregroundStyle(.tint)+ Text("Sign in to codegraff").font(.title2.bold())+ if let start {+ Text("Enter this code at codegraff.com:")+ .foregroundStyle(.secondary)+ Text(start.user_code)+ .font(.system(.largeTitle, design: .monospaced).bold())+ .padding(.horizontal, 24).padding(.vertical, 12)+ .glassPanel()+ if let s = start.verification_uri_complete ?? start.verification_uri,+ let url = URL(string: s) {+ Link("Open codegraff.com", destination: url)+ .buttonStyle(.borderedProminent)+ }+ Text(status.isEmpty ? "Waiting for approval…" : status)+ .font(.footnote).foregroundStyle(.secondary)+ } else if failed {+ Text(status).foregroundStyle(.red).font(.footnote)+ Button("Try again") {+ failed = false+ Task { await run() }+ }+ .buttonStyle(.borderedProminent)+ } else {+ ProgressView("Requesting device code…")+ }+ }+ .padding()+ .navigationTitle("Account")+ .task { await run() }+ }++ private func run() async {+ do {+ let s = try await Gateway.deviceStart()+ start = s+ let interval = max(1, s.interval ?? 2)+ var waited = 0+ let expires = s.expires_in ?? 600+ while waited < expires {+ try await Task.sleep(for: .seconds(interval))+ waited += interval+ let (st, key) = (try? await Gateway.devicePoll(s.device_code)) ?? ("pending", nil)+ if st == "ok", let key {+ Gateway.signIn(key: key)+ onSignedIn()+ return+ } else if st == "denied" || st == "expired" {+ status = "Authorization \(st)"+ failed = true+ start = nil+ return+ }+ }+ status = "Timed out waiting for approval"+ failed = true+ start = nil+ } catch {+ status = error.localizedDescription+ failed = true+ start = nil+ }+ }+}++// The account's gateway sandboxes. Started ones can be spun down right here -+// the same operation as `graff sandboxes stop <id>` in the CLI.+struct SandboxesView: View {+ var onSignOut: () -> Void+ var autoStopFirstStarted = false // --autotest-sandboxes: exercise spin-down headlessly+ @State private var sandboxes: [Sandbox] = []+ @State private var stopping: Set<String> = []+ @State private var note = ""++ var body: some View {+ List {+ if !note.isEmpty {+ Text(note).font(.footnote).foregroundStyle(.secondary)+ }+ ForEach(sandboxes) { sb in+ SandboxRow(sandbox: sb, stopping: stopping.contains(sb.id)) {+ Task { await stop(sb.id) }+ }+ }+ }+ .navigationTitle("Sandboxes")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ Button("Sign out", action: onSignOut)+ }+ }+ .refreshable { await load() }+ .task {+ await load()+ if autoStopFirstStarted, let first = sandboxes.first(where: { $0.state == "started" }) {+ await stop(first.id)+ }+ }+ }++ private func load() async {+ do { sandboxes = try await Gateway.sandboxes() }+ catch { note = error.localizedDescription }+ }++ private func stop(_ id: String) async {+ stopping.insert(id)+ defer { stopping.remove(id) }+ do {+ let state = try await Gateway.stopSandbox(id)+ note = "\(id.prefix(8))… → \(state)"+ await load()+ } catch { note = error.localizedDescription }+ }+}++struct SandboxRow: View {+ let sandbox: Sandbox+ let stopping: Bool+ var onStop: () -> Void++ private var running: Bool { sandbox.state == "started" }++ var body: some View {+ HStack(spacing: 12) {+ Circle()+ .fill(running ? Color.green : Color.secondary.opacity(0.4))+ .frame(width: 10, height: 10)+ VStack(alignment: .leading, spacing: 2) {+ Text(sandbox.label.isEmpty ? String(sandbox.id.prefix(13)) : sandbox.label)+ .font(.subheadline.weight(.medium))+ Text("\(sandbox.state) · \(sandbox.cpu)c/\(sandbox.memory)g/\(sandbox.disk)g · \(String(sandbox.createdAt?.prefix(10) ?? ""))")+ .font(.caption).foregroundStyle(.secondary)+ }+ Spacer()+ if running {+ Button {+ onStop()+ } label: {+ if stopping { ProgressView() } else { Text("Spin down") }+ }+ .buttonStyle(.bordered)+ .tint(.red)+ .disabled(stopping)+ }+ }+ }+}diff --git a/apps/ios/Graff/Sources/ChatView.swift b/apps/ios/Graff/Sources/ChatView.swiftnew file mode 100644index 00000000..dcd077f8--- /dev/null+++ b/apps/ios/Graff/Sources/ChatView.swift@@ -0,0 +1,332 @@+import SwiftUI++struct ChatView: View {+ @Binding var session: AgentSession+ var autoSend: String? = nil++ @State private var draft: String = ""+ // Cube sessions carry their own transport; everything else uses the+ // env/loopback default (local serve on the host Mac).+ private var client: GraffServeClient {+ session.cube.map { GraffServeClient(cube: $0) } ?? GraffServeClient()+ }+ @State private var serveSessionID: String?+ @State private var streaming = false+ @State private var didAutoSend = false++ private enum CubeLiveness { case unknown, alive, stopped, gone }+ @State private var cubeLiveness: CubeLiveness = .unknown+ @State private var resuming = false+ @State private var didHydrate = false++ var body: some View {+ VStack(spacing: 0) {+ if !session.todos.isEmpty {+ TaskProgressCard(session: session)+ .padding(.horizontal)+ .padding(.top, 8)+ }++ ScrollViewReader { proxy in+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 14) {+ ForEach(session.messages) { msg in+ MessageBubble(message: msg).id(msg.id)+ }+ }+ .padding()+ }+ .onChange(of: session.messages.last?.text) {+ if let last = session.messages.last {+ withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }+ }+ }+ }++ if session.planPending {+ PlanDecisionBar(+ onImplement: {+ session.planPending = false+ session.status = .working+ },+ onKeepPlanning: { session.planPending = false }+ )+ .padding(.horizontal)+ .padding(.bottom, 6)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }++ if session.cube != nil && (cubeLiveness == .stopped || cubeLiveness == .gone) {+ CubeStatusBar(+ message: cubeLiveness == .stopped+ ? "This cube is stopped. Waking it resumes sandbox billing (no reinstall)."+ : "This cube is gone. Resuming creates a fresh sandbox — full spin-up (~1 min) billed to your account.",+ resuming: resuming,+ onResume: { Task { await resumeCube() } }+ )+ .padding(.horizontal)+ .padding(.bottom, 6)+ }++ Composer(draft: $draft, streaming: streaming,+ disabled: session.cube != nil && cubeLiveness != .alive && cubeLiveness != .unknown,+ onSend: send)+ .padding(.horizontal)+ .padding(.bottom, 8)+ }+ .navigationTitle(session.title)+ .navigationBarTitleDisplayMode(.inline)+ .animation(.snappy, value: session.planPending)+ .task {+ await hydrateIfNeeded()+ await probeCube()+ if let p = autoSend, !didAutoSend {+ didAutoSend = true+ draft = p+ send()+ }+ }+ }++ private func send() {+ let t = draft.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !t.isEmpty, !streaming else { return }+ draft = ""+ session.messages.append(ChatMessage(role: .user, text: t))+ streaming = true+ session.status = .working+ Task { await runTurn(t) }+ }++ // For cube sessions the agent is told where it is and what credentials it+ // carries — without this, models reflexively claim they have no GitHub+ // access even when gh + git are fully provisioned.+ private var cubeSystemNote: String? {+ guard let cube = session.cube else { return nil }+ var note = "You are graff running inside a disposable cloud sandbox (a codegraff cube) on the user's account. Work directly: run commands, edit files, build."+ if let login = cube.githubLogin {+ note += " GitHub is pre-authenticated as \(login): git clone/push over https works via the credential store, and the gh CLI is installed with GH_TOKEN set (1-hour installation token). Use https://github.com/OWNER/REPO URLs."+ } else {+ note += " GitHub is NOT connected for this account, so you have no repo credentials."+ }+ return note+ }++ @MainActor+ private func runTurn(_ text: String) async {+ defer { streaming = false }+ do {+ if serveSessionID == nil {+ serveSessionID = try await client.createSession(model: session.model,+ yolo: session.cube != nil,+ appendSystemPrompt: cubeSystemNote)+ }+ session.messages.append(ChatMessage(role: .assistant, text: ""))+ let idx = session.messages.count - 1+ for try await ev in client.streamTurn(sessionID: serveSessionID!, text: text) {+ switch ev {+ case .reasoning(let r):+ session.messages[idx].reasoning = (session.messages[idx].reasoning ?? "") + r+ case .text(let d):+ session.messages[idx].text += d+ case .turn(let final, _, _):+ session.messages[idx].text = final+ case .error(let m):+ session.messages[idx].text = "Error: " + m+ case .toolCall(let name):+ session.messages[idx].reasoning = ((session.messages[idx].reasoning ?? "") + "\n⚙️ \(name)")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ case .other:+ break+ }+ }+ session.status = .idle+ } catch {+ session.messages.append(ChatMessage(role: .assistant,+ text: "Transport error: \(error.localizedDescription)"))+ session.status = .idle+ }+ session.lastActivity = "just now"+ AppSessionSync.save(session)+ }++ @MainActor+ private func hydrateIfNeeded() async {+ guard session.needsHydration, !didHydrate else { return }+ didHydrate = true+ if let full = try? await Gateway.fetchAppSession(session.id.uuidString.lowercased()) {+ session.messages = AppSessionSync.messages(fromTranscript: full.transcript)+ session.needsHydration = false+ }+ }++ @MainActor+ private func probeCube() async {+ guard let cube = session.cube else { return }+ let state = (try? await Gateway.sandboxInfo(cube.sandboxID))?.state+ cubeLiveness = state == "started" ? .alive : (state == "stopped" ? .stopped : .gone)+ }++ @MainActor+ private func resumeCube() async {+ resuming = true+ defer { resuming = false }+ // Seed the broker with THIS session's cube so a stopped one is woken+ // rather than a different stored cube being reused.+ session.cube?.store()+ do {+ let conn = try await CubeBroker.launch(purpose: "graff-ios") { _ in }+ session.cube = conn+ serveSessionID = nil // fresh serve session in the (re)woken cube+ cubeLiveness = .alive+ AppSessionSync.save(session)+ } catch {+ session.messages.append(ChatMessage(role: .assistant,+ text: "Resume failed: \(error.localizedDescription)"))+ }+ }+}++struct TaskProgressCard: View {+ let session: AgentSession+ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack {+ Label("Task progress", systemImage: "checklist")+ .font(.subheadline.weight(.semibold))+ Spacer()+ Text("\(session.progress.done)/\(session.progress.total)")+ .font(.caption.monospacedDigit().weight(.semibold))+ .foregroundStyle(.secondary)+ }+ ForEach(session.todos) { todo in+ HStack(spacing: 8) {+ Image(systemName: todo.status.symbol)+ .foregroundStyle(todo.status.tint)+ .symbolEffect(.pulse, isActive: todo.status == .inProgress)+ Text(todo.title)+ .font(.callout)+ .strikethrough(todo.status == .completed, color: .secondary)+ .foregroundStyle(todo.status == .completed ? .secondary : .primary)+ Spacer(minLength: 0)+ }+ }+ }+ .padding(16)+ .glassPanel(22)+ }+}++struct MessageBubble: View {+ let message: ChatMessage+ private var isBlank: Bool { message.text.isEmpty && (message.reasoning?.isEmpty ?? true) }+ var body: some View {+ HStack {+ if message.role == .user { Spacer(minLength: 40) }+ VStack(alignment: .leading, spacing: 6) {+ if let r = message.reasoning, !r.isEmpty {+ Label(r, systemImage: "brain")+ .font(.caption).italic()+ .foregroundStyle(.secondary)+ }+ if !message.text.isEmpty {+ Text(message.text)+ .foregroundStyle(message.role == .user ? Color.white : Color.primary)+ } else if message.role == .assistant && isBlank {+ TypingIndicator()+ }+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 10)+ .background(message.role == .user ? Color.blue.opacity(0.9) : Color(.secondarySystemBackground))+ .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))+ if message.role == .assistant { Spacer(minLength: 40) }+ }+ }+}++// Three pulsing dots shown in the assistant bubble while a turn is in flight+// but no reasoning/text has streamed yet (e.g. during a tool call) - so an+// in-progress turn never looks like an empty, stuck bubble.+struct TypingIndicator: View {+ @State private var animating = false+ var body: some View {+ HStack(spacing: 5) {+ ForEach(0..<3) { i in+ Circle()+ .frame(width: 7, height: 7)+ .foregroundStyle(.secondary)+ .scaleEffect(animating ? 1.0 : 0.5)+ .opacity(animating ? 1.0 : 0.4)+ .animation(.easeInOut(duration: 0.5).repeatForever(autoreverses: true).delay(Double(i) * 0.2), value: animating)+ }+ }+ .padding(.vertical, 2)+ .onAppear { animating = true }+ }+}++struct PlanDecisionBar: View {+ let onImplement: () -> Void+ let onKeepPlanning: () -> Void+ var body: some View {+ VStack(spacing: 12) {+ Label("Plan ready for review", systemImage: "list.clipboard")+ .font(.subheadline.weight(.semibold))+ .frame(maxWidth: .infinity, alignment: .leading)+ HStack(spacing: 12) {+ Button("Keep planning", action: onKeepPlanning)+ .buttonStyle(.glass)+ Button("Implement plan", action: onImplement)+ .buttonStyle(.glassProminent)+ }+ }+ .padding(16)+ .glassPanel(22)+ }+}++struct Composer: View {+ @Binding var draft: String+ var streaming: Bool = false+ var disabled: Bool = false+ let onSend: () -> Void+ var body: some View {+ HStack(spacing: 10) {+ TextField(disabled ? "Resume the cube to continue" : "Type a message", text: $draft, axis: .vertical)+ .lineLimit(1...4)+ .padding(.horizontal, 16)+ .padding(.vertical, 11)+ .glassCapsule()+ .disabled(streaming || disabled)+ Button(action: onSend) {+ Image(systemName: streaming ? "ellipsis" : "arrow.up")+ .font(.headline.weight(.bold))+ }+ .buttonStyle(.glassProminent)+ .disabled(streaming || disabled || draft.trimmingCharacters(in: .whitespaces).isEmpty)+ }+ }+}++// Shown when a session's cube is stopped or gone: the history stays readable,+// but continuing costs money — say exactly which kind before the user pays it.+struct CubeStatusBar: View {+ let message: String+ let resuming: Bool+ let onResume: () -> Void+ var body: some View {+ VStack(spacing: 12) {+ Label(message, systemImage: "shippingbox")+ .font(.footnote)+ .frame(maxWidth: .infinity, alignment: .leading)+ Button(action: onResume) {+ if resuming { ProgressView() } else { Text("Resume cube") }+ }+ .buttonStyle(.glassProminent)+ .disabled(resuming)+ }+ .padding(16)+ .glassPanel(22)+ }+}diff --git a/apps/ios/Graff/Sources/CubeBroker.swift b/apps/ios/Graff/Sources/CubeBroker.swiftnew file mode 100644index 00000000..735def60--- /dev/null+++ b/apps/ios/Graff/Sources/CubeBroker.swift@@ -0,0 +1,178 @@+import Foundation+import Security++// Everything a serve client needs to stream turns into a sandbox cube, plus+// the sandbox id for spin-down. Persisted in the Keychain so a relaunch can+// reattach to a still-running cube instead of paying spin-up again.+struct CubeConnection: Codable, Equatable {+ let sandboxID: String+ let base: String // Daytona preview URL fronting the serve port+ let serveToken: String+ let previewToken: String?+ var githubLogin: String? = nil // set when the cube carries repo access++ private static let account = "cube-connection"+ static func stored() -> CubeConnection? {+ guard let raw = KeychainStore.get(account), let data = raw.data(using: .utf8) else { return nil }+ return try? JSONDecoder().decode(CubeConnection.self, from: data)+ }+ func store() {+ if let data = try? JSONEncoder().encode(self), let s = String(data: data, encoding: .utf8) {+ KeychainStore.set(Self.account, s)+ }+ }+ static func clearStored() { KeychainStore.delete(account) }+}++// What /api/github/mint-token returns — a 1-hour installation token with the+// same scopes @codegraff-bot gets (contents/pull_requests/issues write).+struct MintedGitHub: Decodable {+ let token: String+ let expires_at: String+ let account_login: String+}++// Client-side mirror of `graff cube new` (the CLI got the capability first).+// Cost ladder, cheapest first: a running cube is reused as-is; a stopped one+// is woken without reinstalling (its disk survives a stop); only a gone one+// pays the full spin-up. Every bring-up wires the account's GitHub in (fresh+// 1-hour token) when connected, so the agent can clone, push, and open PRs.+enum CubeBroker {+ static let port = 8787+ static let mintURL = "https://codegraff.com/api/github/mint-token"++ struct StepError: LocalizedError {+ let message: String+ var errorDescription: String? { message }+ }++ static func launch(purpose: String, onStep: @escaping @MainActor (String) -> Void) async throws -> CubeConnection {+ var resumeID: String? = nil+ var wasRunning = false+ if let old = CubeConnection.stored() {+ await onStep("Checking the last cube…")+ let state = (try? await Gateway.sandboxInfo(old.sandboxID))?.state ?? "gone"+ if state == "started" && !old.base.isEmpty && !old.serveToken.isEmpty {+ await onStep("Reusing the running cube (no new spin-up cost)")+ return old+ }+ // started-but-credential-less happens when a history row from+ // another device seeded the stored connection: re-key it in place.+ if state == "started" || state == "stopped" {+ resumeID = old.sandboxID+ wasRunning = state == "started"+ } else {+ CubeConnection.clearStored()+ }+ }++ let id: String+ if let rid = resumeID {+ await onStep(wasRunning ? "Re-keying the running cube (no reinstall)…"+ : "Waking the stopped cube (cheaper — no reinstall)…")+ if !wasRunning { _ = try await Gateway.startSandbox(rid) }+ id = rid+ } else {+ await onStep("Creating sandbox (full spin-up)…")+ id = try await Gateway.createSandbox(purpose: purpose).id+ }++ var state = ""+ var waits = 0+ while state != "started" && waits < 60 {+ state = (try? await Gateway.sandboxInfo(id).state) ?? state+ if state == "started" { break }+ try await Task.sleep(for: .seconds(2))+ waits += 1+ }+ guard state == "started" else { throw StepError(message: "sandbox never reached started (\(state))") }++ if resumeID == nil {+ await onStep("Installing graff…")+ let inst = try await Gateway.exec(id,+ command: "curl -fsSL https://raw.githubusercontent.com/justrach/codegraff/main/install.sh | bash",+ timeoutSeconds: 120)+ guard inst.exitCode == 0 else {+ throw StepError(message: "graff install failed: \(String((inst.result ?? "").suffix(200)))")+ }+ }++ // Fresh token every bring-up — the previous one expires after an hour.+ let github = await provisionGitHub(sandboxID: id, onStep: onStep)++ // A resumed cube may still have an old serve bound to the port+ // (re-key case, or a crashed-but-lingering process after a wake).+ if resumeID != nil {+ _ = try? await Gateway.exec(id, command: "pkill -f 'graff serve' >/dev/null 2>&1; sleep 1; true", timeoutSeconds: 20)+ }+ await onStep("Starting graff serve…")+ guard let key = Gateway.apiKey else { throw StepError(message: "not signed in") }+ let token = freshToken()+ let env = github.map { "CODEGRAFF_API_KEY=\(key) GH_TOKEN=\($0.token) GITHUB_LOGIN=\($0.account_login)" }+ ?? "CODEGRAFF_API_KEY=\(key)"+ _ = try await Gateway.exec(id,+ command: "\(env) exec $HOME/bin/graff serve --host 0.0.0.0 --port \(port) --token \(token)",+ timeoutSeconds: 60, async: true)+ var up = false+ for _ in 0..<20 {+ if let probe = try? await Gateway.exec(id,+ command: "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:\(port)/", timeoutSeconds: 15) {+ let code = (probe.result ?? "").trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n'"))+ if !code.isEmpty && code != "000" { up = true; break }+ }+ try await Task.sleep(for: .seconds(1))+ }+ guard up else { throw StepError(message: "serve never came up in the sandbox") }++ await onStep("Minting preview URL…")+ let pv = try await Gateway.preview(id, port: port)+ let base = pv.url.hasSuffix("/") ? String(pv.url.dropLast()) : pv.url+ let conn = CubeConnection(sandboxID: id, base: base, serveToken: token,+ previewToken: pv.token, githubLogin: github?.account_login)+ conn.store()+ return conn+ }++ // GitHub for the cube — the same access @codegraff-bot gets. Degrades to a+ // plain cube when the account has no GitHub connected.+ private static func provisionGitHub(sandboxID: String, onStep: @escaping @MainActor (String) -> Void) async -> MintedGitHub? {+ guard let key = Gateway.apiKey, let url = URL(string: mintURL) else { return nil }+ var req = URLRequest(url: url)+ req.httpMethod = "POST"+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")+ req.setValue("Graff-iOS/0.1", forHTTPHeaderField: "User-Agent")+ req.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")+ req.httpBody = Data("{}".utf8)+ guard let (data, resp) = try? await URLSession.shared.data(for: req),+ (resp as? HTTPURLResponse)?.statusCode == 200,+ let minted = try? JSONDecoder().decode(MintedGitHub.self, from: data) else {+ await onStep("GitHub: not connected — cube gets no repo access")+ return nil+ }+ await onStep("Wiring GitHub (\(minted.account_login))…")+ let t = minted.token, l = minted.account_login+ let cmd = "mkdir -p $HOME/bin && git config --global credential.helper store && "+ + "printf 'https://x-access-token:%[email protected]\\n' '\(t)' > $HOME/.git-credentials && chmod 600 $HOME/.git-credentials && "+ + "printf '%s' '\(t)' > $HOME/.cube-github-token && chmod 600 $HOME/.cube-github-token && "+ + "git config --global user.name '\(l)' && git config --global user.email '\(l)@users.noreply.github.com' && "+ + "(command -v gh >/dev/null 2>&1 || (A=$(uname -m); case \"$A\" in x86_64) A=amd64;; aarch64|arm64) A=arm64;; esac; "+ + "V=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep -o '\"tag_name\": *\"[^\"]*\"' | head -1 | cut -d'\"' -f4); "+ + "curl -fsSL https://github.com/cli/cli/releases/download/$V/gh_${V#v}_linux_$A.tar.gz | tar -xz -C /tmp && "+ + "mv /tmp/gh_${V#v}_linux_$A/bin/gh $HOME/bin/gh)) && echo GH-PROVISIONED"+ guard let res = try? await Gateway.exec(sandboxID, command: cmd, timeoutSeconds: 90),+ (res.result ?? "").contains("GH-PROVISIONED") else {+ await onStep("GitHub: provisioning failed — continuing without")+ return nil+ }+ return minted+ }++ private static func freshToken() -> String {+ var bytes = [UInt8](repeating: 0, count: 24)+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)+ return Data(bytes).base64EncodedString()+ .replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_")+ .replacingOccurrences(of: "=", with: "")+ }+}diff --git a/apps/ios/Graff/Sources/GraffAccount.swift b/apps/ios/Graff/Sources/GraffAccount.swiftnew file mode 100644index 00000000..416ef07c--- /dev/null+++ b/apps/ios/Graff/Sources/GraffAccount.swift@@ -0,0 +1,298 @@+import Foundation+import Security++// Keychain-backed storage for the codegraff API key - same device-login+// credential the CLI keeps in ~/.simple-harness-codegraff.json.+enum KeychainStore {+ private static let service = "com.codegraff.graff"++ static func get(_ account: String) -> String? {+ let q: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]+ var out: AnyObject?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess,+ let data = out as? Data else { return nil }+ return String(data: data, encoding: .utf8)+ }++ @discardableResult+ static func set(_ account: String, _ value: String) -> OSStatus {+ delete(account)+ let q: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ kSecValueData as String: Data(value.utf8),+ ]+ return SecItemAdd(q as CFDictionary, nil)+ }++ static func delete(_ account: String) {+ let q: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ ]+ SecItemDelete(q as CFDictionary)+ }+}++// Gateway REST client: the same device-code login flow as `graff login`+// (POST /v1/device/start -> user approves on codegraff.com -> poll yields the+// cg_sk_ key), plus the account's sandboxes (list / spin down) - the iOS+// counterpart of `graff sandboxes`.+struct DeviceStart: Decodable {+ let device_code: String+ let user_code: String+ let verification_uri: String?+ let verification_uri_complete: String?+ let interval: Int?+ let expires_in: Int?+}++struct Sandbox: Decodable, Identifiable {+ let id: String+ let state: String+ let cpu: Int+ let memory: Int+ let disk: Int+ let labels: [String: String]?+ let createdAt: String?+ var label: String { labels?["purpose"] ?? labels?["app"] ?? "" }+}++// POST /v1/sandboxes returns a thinner object than the list rows, so decode+// just what the broker needs.+struct SandboxCreated: Decodable {+ let id: String+ let state: String?+}++struct ExecResult: Decodable {+ let exitCode: Int?+ let result: String?+ let execId: String?+}++struct PortPreview: Decodable {+ let url: String+ let token: String?+}++// /v1/app/sessions list rows (no transcript — the list stays light) and the+// full row fetched when a session is opened.+struct AppSessionRow: Decodable, Identifiable {+ let id: String+ let title: String+ let model: String+ let sandbox_id: String?+ let created_at: Int+ let updated_at: Int+}++struct AppSessionFull: Decodable {+ let id: String+ let title: String+ let model: String+ let sandbox_id: String?+ let transcript: String+ let updated_at: Int+}++enum GatewayError: LocalizedError {+ case http(Int, String)+ var errorDescription: String? {+ switch self { case .http(let c, let m): return "gateway HTTP \(c): \(m)" }+ }+}++enum Gateway {+ static let base = "https://gateway.codegraff.com"+ private static let keyAccount = "codegraff-api-key"++ // In-memory copy of the key: a Keychain persistence failure (ad-hoc sim+ // builds without entitlements hit errSecMissingEntitlement) must not kill+ // the just-signed-in session — worst case you sign in again next launch.+ private static var memoryKey: String?++ // GRAFF_GATEWAY_KEY env override mirrors GRAFF_SERVE_BASE/TOKEN: it lets+ // the autotest harness inject a signed-in state without a device approval.+ static var apiKey: String? {+ ProcessInfo.processInfo.environment["GRAFF_GATEWAY_KEY"] ?? memoryKey ?? KeychainStore.get(keyAccount)+ }+ static func signIn(key: String) {+ memoryKey = key+ let status = KeychainStore.set(keyAccount, key)+ if status != errSecSuccess { NSLog("Graff: keychain store failed (%d)", status) }+ }+ static func signOut() {+ memoryKey = nil+ KeychainStore.delete(keyAccount)+ }++ private static func request(_ path: String, method: String, json: [String: Any]? = nil, authed: Bool) -> URLRequest {+ var r = URLRequest(url: URL(string: base + path)!)+ r.httpMethod = method+ r.setValue("application/json", forHTTPHeaderField: "Content-Type")+ r.setValue("Graff-iOS/0.1", forHTTPHeaderField: "User-Agent") // CF WAF rejects empty UA+ if authed, let key = apiKey { r.setValue("Bearer " + key, forHTTPHeaderField: "Authorization") }+ if let json { r.httpBody = try? JSONSerialization.data(withJSONObject: json) }+ return r+ }++ private static func check(_ data: Data, _ resp: URLResponse) throws {+ let code = (resp as? HTTPURLResponse)?.statusCode ?? -1+ guard (200...299).contains(code) else {+ let msg = ((try? JSONSerialization.jsonObject(with: data)) as? [String: Any])+ .flatMap { $0["error"] as? [String: Any] }.flatMap { $0["message"] as? String }+ throw GatewayError.http(code, msg ?? String(decoding: data.prefix(120), as: UTF8.self))+ }+ }++ static func deviceStart() async throws -> DeviceStart {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/device/start", method: "POST", json: ["device_label": "graff-ios"], authed: false))+ try check(data, resp)+ return try JSONDecoder().decode(DeviceStart.self, from: data)+ }++ // One poll step: "ok" delivers the key; anything unparseable counts as pending.+ static func devicePoll(_ deviceCode: String) async throws -> (status: String, key: String?) {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/device/poll", method: "POST", json: ["device_code": deviceCode], authed: false))+ try check(data, resp)+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]+ return (obj["status"] as? String ?? "pending", obj["api_key"] as? String)+ }++ static func sandboxes() async throws -> [Sandbox] {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes", method: "GET", authed: true))+ try check(data, resp)+ return try JSONDecoder().decode([Sandbox].self, from: data)+ }++ static func stopSandbox(_ id: String) async throws -> String {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes/\(id)/stop", method: "POST", json: [:], authed: true))+ try check(data, resp)+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]+ return obj["state"] as? String ?? "stopped"+ }++ // The cube broker's REST legs — the same calls `graff cube new` makes.+ static func createSandbox(purpose: String, autoStopMinutes: Int = 30) async throws -> SandboxCreated {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes", method: "POST",+ json: ["autoStopMinutes": autoStopMinutes, "labels": ["purpose": purpose]], authed: true))+ try check(data, resp)+ return try JSONDecoder().decode(SandboxCreated.self, from: data)+ }++ static func sandboxInfo(_ id: String) async throws -> Sandbox {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes/\(id)", method: "GET", authed: true))+ try check(data, resp)+ return try JSONDecoder().decode(Sandbox.self, from: data)+ }++ static func exec(_ id: String, command: String, timeoutSeconds: Int, async asynch: Bool = false) async throws -> ExecResult {+ var body: [String: Any] = ["command": command, "timeoutSeconds": timeoutSeconds]+ if asynch { body["async"] = true }+ var req = request("/v1/sandboxes/\(id)/exec", method: "POST", json: body, authed: true)+ req.timeoutInterval = Double(timeoutSeconds) + 15 // outlive the sandbox-side timeout+ let (data, resp) = try await URLSession.shared.data(for: req)+ try check(data, resp)+ return try JSONDecoder().decode(ExecResult.self, from: data)+ }++ static func preview(_ id: String, port: Int) async throws -> PortPreview {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes/\(id)/ports/\(port)/preview", method: "GET", authed: true))+ try check(data, resp)+ return try JSONDecoder().decode(PortPreview.self, from: data)+ }++ static func startSandbox(_ id: String) async throws -> String {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/sandboxes/\(id)/start", method: "POST", json: [:], authed: true))+ try check(data, resp)+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]+ return obj["state"] as? String ?? "started"+ }++ // ── Account-synced session history (/v1/app/sessions) ──+ // The transcript is ours to shape; the gateway stores it as an opaque+ // JSON blob per (account, session id). History survives its sandbox.++ static func listAppSessions() async throws -> [AppSessionRow] {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/app/sessions", method: "GET", authed: true))+ try check(data, resp)+ return try JSONDecoder().decode([AppSessionRow].self, from: data)+ }++ static func fetchAppSession(_ id: String) async throws -> AppSessionFull {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/app/sessions/\(id)", method: "GET", authed: true))+ try check(data, resp)+ return try JSONDecoder().decode(AppSessionFull.self, from: data)+ }++ static func putAppSession(id: String, title: String, model: String, sandboxID: String?, transcript: String) async throws {+ var body: [String: Any] = ["title": title, "model": model, "transcript": transcript]+ if let sandboxID { body["sandbox_id"] = sandboxID }+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/app/sessions/\(id)", method: "PUT", json: body, authed: true))+ try check(data, resp)+ }++ static func deleteAppSession(_ id: String) async throws {+ let (data, resp) = try await URLSession.shared.data(for:+ request("/v1/app/sessions/\(id)", method: "DELETE", authed: true))+ try check(data, resp)+ }+}++// ── Transcript wire format + sync helpers ──++struct MessageDTO: Codable {+ let role: String+ let text: String+ let reasoning: String?+}++enum AppSessionSync {+ static func transcriptJSON(_ messages: [ChatMessage]) -> String {+ let dtos = messages.map { MessageDTO(role: $0.role == .user ? "user" : "assistant",+ text: $0.text, reasoning: $0.reasoning) }+ let data = (try? JSONEncoder().encode(dtos)) ?? Data("[]".utf8)+ return String(data: data, encoding: .utf8) ?? "[]"+ }++ static func messages(fromTranscript json: String) -> [ChatMessage] {+ guard let data = json.data(using: .utf8),+ let dtos = try? JSONDecoder().decode([MessageDTO].self, from: data) else { return [] }+ return dtos.map { ChatMessage(role: $0.role == "user" ? .user : .assistant,+ text: $0.text, reasoning: $0.reasoning) }+ }++ // Fire-and-forget: history sync must never block or break the chat.+ static func save(_ session: AgentSession) {+ guard Gateway.apiKey != nil else { return }+ let id = session.id.uuidString.lowercased()+ let transcript = transcriptJSON(session.messages)+ let title = session.title+ let model = session.model+ let sandboxID = session.cube?.sandboxID+ Task.detached {+ try? await Gateway.putAppSession(id: id, title: title, model: model,+ sandboxID: sandboxID, transcript: transcript)+ }+ }+}diff --git a/apps/ios/Graff/Sources/GraffApp.swift b/apps/ios/Graff/Sources/GraffApp.swiftnew file mode 100644index 00000000..114a34d4--- /dev/null+++ b/apps/ios/Graff/Sources/GraffApp.swift@@ -0,0 +1,204 @@+import SwiftUI++@main+struct GraffApp: App {+ var body: some Scene {+ WindowGroup {+ if CommandLine.arguments.contains("--autotest") {+ AutoTestView()+ } else if CommandLine.arguments.contains("--autotest-signin") {+ AccountView()+ } else if CommandLine.arguments.contains("--autotest-sandboxes") {+ // Headless spin-down check: list the account's sandboxes and stop+ // the first started one, so the flow is verifiable without taps.+ NavigationStack { SandboxesView(onSignOut: {}, autoStopFirstStarted: true) }+ } else if CommandLine.arguments.contains("--autotest-keychain") {+ KeychainCheckView()+ } else if CommandLine.arguments.contains("--autotest-cube") {+ // Headless "build for me" proof: broker a cube, have the agent+ // create a file in it via bash, verify through gateway exec.+ CubeAutoTestView()+ } else if CommandLine.arguments.contains("--autotest-compose") {+ // Render the new-session compose sheet standalone for visual QA.+ NewSessionView { _ in }+ } else {+ SessionsListView()+ }+ }+ }+}++// Launch with `--autotest-keychain` (+ GRAFF_GATEWAY_KEY in the env) to seed+// the Keychain through the real signIn path and read it straight back —+// proves credential persistence across launches without a device approval.+struct KeychainCheckView: View {+ var body: some View {+ Text(Self.result)+ .font(.system(.body, design: .monospaced))+ .padding()+ }+ static var result: String {+ guard let k = ProcessInfo.processInfo.environment["GRAFF_GATEWAY_KEY"] else {+ return "no GRAFF_GATEWAY_KEY in env"+ }+ Gateway.signIn(key: k)+ guard let back = KeychainStore.get("codegraff-api-key") else { return "keychain store FAILED" }+ return "keychain ok: \(back.prefix(9))… persisted"+ }+}++// Launch with `--autotest` to open the first session and fire one real turn+// through `graff serve` on appear - verifies the live transport on the simulator+// without manual tapping. Harmless in normal runs (gated by the arg).+struct AutoTestView: View {+ @State private var session = sampleSessions[0]+ var body: some View {+ NavigationStack {+ ChatView(session: $session,+ autoSend: "Reply with one short sentence confirming the serve transport works.")+ }+ }+}++// MARK: - Liquid Glass helpers+extension View {+ func glassPanel(_ radius: CGFloat = 22) -> some View {+ self.glassEffect(.regular, in: RoundedRectangle(cornerRadius: radius, style: .continuous))+ }+ func glassCapsule() -> some View {+ self.glassEffect(.regular, in: Capsule())+ }+}++// MARK: - Model+enum Role { case user, assistant }++struct ChatMessage: Identifiable {+ let id = UUID()+ let role: Role+ var text: String+ var reasoning: String? = nil+}++enum TodoStatus {+ case pending, inProgress, completed+ var symbol: String {+ switch self {+ case .pending: return "circle"+ case .inProgress: return "circle.dotted"+ case .completed: return "checkmark.circle.fill"+ }+ }+ var tint: Color {+ switch self {+ case .pending: return .secondary+ case .inProgress: return .blue+ case .completed: return .green+ }+ }+}++struct TodoItem: Identifiable {+ let id = UUID()+ let title: String+ var status: TodoStatus+}++enum SessionStatus: String {+ case working, waiting, idle, done+ var label: String {+ switch self {+ case .working: return "Working"+ case .waiting: return "Waiting on you"+ case .idle: return "Idle"+ case .done: return "Done"+ }+ }+ var symbol: String {+ switch self {+ case .working: return "circle.dotted"+ case .waiting: return "exclamationmark.circle.fill"+ case .idle: return "pause.circle"+ case .done: return "checkmark.circle.fill"+ }+ }+ var tint: Color {+ switch self {+ case .working: return .blue+ case .waiting: return .orange+ case .idle: return .secondary+ case .done: return .green+ }+ }+}++struct AgentSession: Identifiable {+ // Settable so history rows keep their server id across launches; sessions+ // synced from the account are hydrated (transcript fetched) on first open.+ var id = UUID()+ var needsHydration = false+ var title: String+ var model: String+ var status: SessionStatus+ var lastActivity: String+ var todos: [TodoItem]+ var messages: [ChatMessage]+ var planPending: Bool = false+ // Set for sessions running in a cloud sandbox (the cube transport);+ // nil means the env/loopback serve default.+ var cube: CubeConnection? = nil+ var progress: (done: Int, total: Int) {+ (todos.filter { $0.status == .completed }.count, todos.count)+ }+}++let sampleSessions: [AgentSession] = [+ AgentSession(+ title: "Add cube transport to client",+ model: "deepseek-v4-pro",+ status: .working,+ lastActivity: "just now",+ todos: [+ TodoItem(title: "Factor desktop client behind a transport interface", status: .completed),+ TodoItem(title: "Add local serve transport", status: .completed),+ TodoItem(title: "Add cube transport via gateway host-port proxy", status: .inProgress),+ TodoItem(title: "Send required User-Agent header (CF WAF)", status: .pending),+ TodoItem(title: "Decode reasoning / text / turn events", status: .pending),+ ],+ messages: [+ ChatMessage(role: .user, text: "Wire up the cube transport so the app streams from a sandbox."),+ ChatMessage(role: .assistant, text: "On it. I'll add a third transport alongside tauri and serve, routing HTTP/NDJSON through the gateway host-port proxy with a tenant-scoped capability header.", reasoning: "serve and cube share the NDJSON contract - only base URL + auth header differ."),+ ]+ ),+ AgentSession(+ title: "Extend graff serve exec timeout",+ model: "deepseek-v4-pro",+ status: .waiting,+ lastActivity: "2m ago",+ todos: [+ TodoItem(title: "Locate the ~100s exec timeout", status: .completed),+ TodoItem(title: "Make it configurable", status: .inProgress),+ TodoItem(title: "Plumb through to the orchestrator", status: .pending),+ ],+ messages: [+ ChatMessage(role: .user, text: "The persistent serve session dies at ~100s. Extend it."),+ ChatMessage(role: .assistant, text: "I've drafted a plan to make the exec timeout configurable and raise the default for serve. Implement it?"),+ ],+ planPending: true+ ),+ AgentSession(+ title: "Notarize v0.0.16 build",+ model: "deepseek-v4-pro",+ status: .done,+ lastActivity: "1h ago",+ todos: [+ TodoItem(title: "Sign the .app", status: .completed),+ TodoItem(title: "Submit to notary", status: .completed),+ TodoItem(title: "Staple the ticket", status: .completed),+ ],+ messages: [+ ChatMessage(role: .user, text: "Notarize the release build."),+ ChatMessage(role: .assistant, text: "Done - signed, notarized (Accepted), stapled. spctl assessment passes."),+ ]+ ),+]diff --git a/apps/ios/Graff/Sources/GraffServeClient.swift b/apps/ios/Graff/Sources/GraffServeClient.swiftnew file mode 100644index 00000000..836c671a--- /dev/null+++ b/apps/ios/Graff/Sources/GraffServeClient.swift@@ -0,0 +1,116 @@+import Foundation++// Events decoded from the graff serve NDJSON stream (one JSON object per line).+enum GraffEvent {+ case reasoning(String)+ case text(String)+ case toolCall(name: String)+ case turn(text: String, contextTokens: Int, costUSD: Double)+ case error(String)+ case other(String)+}++enum GraffError: LocalizedError {+ case badResponse(String)+ var errorDescription: String? {+ switch self { case .badResponse(let s): return s }+ }+}++// Local `serve` transport: POST /v1/sessions -> session_id, then+// POST /v1/sessions/{id} with a stdio-protocol request, streamed back as NDJSON.+// The simulator's localhost maps to the host Mac, so 127.0.0.1:8787 reaches+// `graff serve`. The `cube` transport is this same client with a different base+// URL + token: the launch environment overrides the loopback defaults so the+// app can point at a remote serve (e.g. a sandbox preview URL) without a rebuild.+struct GraffServeClient {+ var base: String = ProcessInfo.processInfo.environment["GRAFF_SERVE_BASE"] ?? "http://127.0.0.1:8787"+ var token: String? = ProcessInfo.processInfo.environment["GRAFF_SERVE_TOKEN"]+ var previewToken: String? = ProcessInfo.processInfo.environment["GRAFF_SERVE_PREVIEW_TOKEN"]++ init() {}+ // The cube transport proper: same NDJSON contract, pointed at a sandbox+ // preview URL with the Daytona token alongside the serve bearer.+ init(cube: CubeConnection) {+ base = cube.base+ token = cube.serveToken+ previewToken = cube.previewToken+ }++ private func makeRequest(_ path: String, method: String, json: [String: Any]? = nil) -> URLRequest {+ var r = URLRequest(url: URL(string: base + path)!)+ r.httpMethod = method+ r.setValue("application/json", forHTTPHeaderField: "Content-Type")+ r.setValue("Graff-iOS/0.1", forHTTPHeaderField: "User-Agent") // CF WAF rejects empty UA on the gateway path+ if let token { r.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }+ if let previewToken { r.setValue(previewToken, forHTTPHeaderField: "x-daytona-preview-token") }+ if let json { r.httpBody = try? JSONSerialization.data(withJSONObject: json) }+ return r+ }++ // serve answers 201 for session create and 200 for the turn stream - accept any 2xx.+ private static func ok(_ resp: URLResponse?) -> Bool {+ (200...299).contains((resp as? HTTPURLResponse)?.statusCode ?? 0)+ }+ private static func status(_ resp: URLResponse?) -> Int {+ (resp as? HTTPURLResponse)?.statusCode ?? -1+ }++ // yolo=true asks serve for a session whose tools run without approval+ // prompts — right for cube sessions in a disposable sandbox, never for+ // a serve on your own machine.+ func createSession(model: String, yolo: Bool = false, appendSystemPrompt: String? = nil) async throws -> String {+ var body: [String: Any] = ["model": model]+ if yolo { body["yolo"] = true }+ if let appendSystemPrompt { body["append_system_prompt"] = appendSystemPrompt }+ let (data, resp) = try await URLSession.shared.data(for: makeRequest("/v1/sessions", method: "POST", json: body))+ guard Self.ok(resp),+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let id = obj["session_id"] as? String else {+ throw GraffError.badResponse("create HTTP \(Self.status(resp))")+ }+ return id+ }++ func streamTurn(sessionID: String, text: String) -> AsyncThrowingStream<GraffEvent, Error> {+ var req = makeRequest("/v1/sessions/" + sessionID, method: "POST", json: ["type": "user", "text": text])+ req.timeoutInterval = 600 // build turns can run for minutes between events+ return AsyncThrowingStream { continuation in+ let task = Task {+ do {+ let (bytes, resp) = try await URLSession.shared.bytes(for: req)+ guard Self.ok(resp) else {+ continuation.finish(throwing: GraffError.badResponse("turn HTTP \(Self.status(resp))"))+ return+ }+ for try await line in bytes.lines {+ guard !line.isEmpty, let ev = Self.decode(line) else { continue }+ continuation.yield(ev)+ if case .turn = ev { break }+ if case .error = ev { break }+ }+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ continuation.onTermination = { _ in task.cancel() }+ }+ }++ static func decode(_ line: String) -> GraffEvent? {+ guard let data = line.data(using: .utf8),+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let type = obj["type"] as? String else { return nil }+ switch type {+ case "reasoning": return .reasoning(obj["text"] as? String ?? "")+ case "text": return .text(obj["text"] as? String ?? "")+ case "tool_call": return .toolCall(name: obj["name"] as? String ?? "tool")+ case "turn": return .turn(text: obj["text"] as? String ?? "",+ contextTokens: obj["context_tokens"] as? Int ?? 0,+ costUSD: obj["cost_usd"] as? Double ?? 0)+ case "error": return .error(obj["message"] as? String ?? "error")+ default: return .other(type)+ }+ }+}diff --git a/apps/ios/Graff/Sources/NewSessionView.swift b/apps/ios/Graff/Sources/NewSessionView.swiftnew file mode 100644index 00000000..8e773c40--- /dev/null+++ b/apps/ios/Graff/Sources/NewSessionView.swift@@ -0,0 +1,204 @@+import SwiftUI++// "+" on Sessions: describe the task, watch the cube spin up (sandbox ->+// install -> serve -> preview), then chat with graff building in YOUR+// sandbox. The broker is the same one `graff cube new` runs in the CLI.+struct NewSessionView: View {+ var onCreated: (AgentSession) -> Void+ @Environment(\.dismiss) private var dismiss++ private enum Phase { case compose, launching, chat, failed(String) }+ @State private var phase: Phase = .compose+ @State private var prompt = ""+ @State private var steps: [String] = []+ @State private var session = AgentSession(title: "New session", model: "codegraff", status: .working,+ lastActivity: "now", todos: [], messages: [])+ @State private var signedIn = Gateway.apiKey != nil+ @State private var showAccount = false+ @State private var handedOff = false++ var body: some View {+ NavigationStack {+ Group {+ switch phase {+ case .compose: compose+ case .launching: launching+ case .chat:+ ChatView(session: $session, autoSend: prompt)+ .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Done") { finish() } } }+ case .failed(let msg): failedView(msg)+ }+ }+ }+ .onDisappear { finish() }+ }++ private var compose: some View {+ VStack(spacing: 18) {+ Image(systemName: "shippingbox").font(.system(size: 44)).foregroundStyle(.tint)+ Text("Build in a cube").font(.title2.bold())+ Text("graff gets a fresh cloud sandbox on your account and starts working on this.")+ .font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center)+ TextField("What should graff build?", text: $prompt, axis: .vertical)+ .lineLimit(2...5)+ .padding(14)+ .glassPanel(18)+ if signedIn {+ Button {+ phase = .launching+ Task { await launch() }+ } label: {+ Label("Start building", systemImage: "play.fill").frame(maxWidth: .infinity)+ }+ .buttonStyle(.glassProminent)+ .disabled(prompt.trimmingCharacters(in: .whitespaces).isEmpty)+ } else {+ Button("Sign in to codegraff first") { showAccount = true }+ .buttonStyle(.borderedProminent)+ }+ }+ .padding()+ .navigationTitle("New session")+ .navigationBarTitleDisplayMode(.inline)+ .sheet(isPresented: $showAccount, onDismiss: { signedIn = Gateway.apiKey != nil }) { AccountView() }+ }++ private var launching: some View {+ VStack(alignment: .leading, spacing: 14) {+ ForEach(Array(steps.enumerated()), id: \.offset) { i, s in+ HStack(spacing: 10) {+ if i == steps.count - 1 {+ ProgressView()+ } else {+ Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)+ }+ Text(s).font(.callout)+ }+ }+ }+ .padding(20)+ .glassPanel(22)+ .padding()+ .navigationTitle("Spinning up")+ .navigationBarTitleDisplayMode(.inline)+ }++ private func failedView(_ msg: String) -> some View {+ VStack(spacing: 16) {+ Image(systemName: "exclamationmark.triangle.fill").font(.largeTitle).foregroundStyle(.orange)+ Text("Spin-up failed").font(.headline)+ Text(msg).font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center)+ Button("Try again") { phase = .compose }.buttonStyle(.borderedProminent)+ }+ .padding()+ }++ @MainActor+ private func launch() async {+ do {+ let conn = try await CubeBroker.launch(purpose: "graff-ios") { msg in steps.append(msg) }+ let trimmed = prompt.trimmingCharacters(in: .whitespacesAndNewlines)+ let title = trimmed.count > 42 ? String(trimmed.prefix(42)) + "…" : trimmed+ session = AgentSession(title: title.isEmpty ? "Cloud session" : title, model: "codegraff",+ status: .working, lastActivity: "now", todos: [], messages: [], cube: conn)+ phase = .chat+ } catch {+ phase = .failed(error.localizedDescription)+ }+ }++ // Hand the session (with whatever transcript it accumulated) back to the+ // list exactly once, whether the user taps Done or swipes the sheet away.+ private func finish() {+ guard !handedOff else { dismiss(); return }+ if case .chat = phase {+ handedOff = true+ onCreated(session)+ }+ dismiss()+ }+}++// Launch with `--autotest-cube` (+ GRAFF_GATEWAY_KEY): brokers a real cube on+// the account, has the agent BUILD something in it (a file, via its bash tool+// in a yolo session), then verifies the artifact from OUTSIDE the serve pipe+// (gateway exec) and prints PASS/FAIL — the whole "phone asks, sandbox+// builds" loop with no taps.+struct CubeAutoTestView: View {+ @State private var lines: [String] = ["cube autotest…"]++ var body: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 6) {+ ForEach(Array(lines.enumerated()), id: \.offset) { _, l in+ Text(l).font(.system(.footnote, design: .monospaced))+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding()+ }+ .task { await run() }+ }++ @MainActor+ private func run() async {+ guard let k = ProcessInfo.processInfo.environment["GRAFF_GATEWAY_KEY"] else {+ lines.append("FAIL: no GRAFF_GATEWAY_KEY in env")+ return+ }+ Gateway.signIn(key: k)+ do {+ let conn = try await CubeBroker.launch(purpose: "ios-cube-autotest") { msg in lines.append(msg) }+ lines.append("cube ready: \(conn.sandboxID)")+ lines.append("base: \(conn.base)")+ let client = GraffServeClient(cube: conn)+ let sid = try await client.createSession(model: "codegraff", yolo: true)+ lines.append("session: \(sid)")+ lines.append("asking graff to build…")+ for try await ev in client.streamTurn(sessionID: sid,+ text: "Using bash, write the exact text BUILT-FROM-IOS into /tmp/built-from-ios.txt. Then reply DONE.") {+ switch ev {+ case .toolCall(let name): lines.append(" tool: \(name)")+ case .turn(let text, _, _): lines.append(" turn: \(String(text.prefix(80)))")+ case .error(let m): lines.append(" error: \(m)")+ default: break+ }+ }+ let check = try await Gateway.exec(conn.sandboxID, command: "cat /tmp/built-from-ios.txt", timeoutSeconds: 20)+ let content = (check.result ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+ lines.append("sandbox file: \(content)")+ lines.append(content == "BUILT-FROM-IOS" ? "CUBE-BUILD-PASS" : "CUBE-BUILD-FAIL")++ // GitHub: prove the cube carries the account's repo access — the+ // same check the CLI verify runs, from the app's own pipeline.+ if let login = conn.githubLogin {+ let gh = try await Gateway.exec(conn.sandboxID,+ command: "GH_TOKEN=$(cat $HOME/.cube-github-token) $HOME/bin/gh api /installation/repositories -q .total_count",+ timeoutSeconds: 30)+ let n = (gh.result ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+ lines.append("gh sees \(n) repos as \(login)")+ lines.append(Int(n) != nil ? "CUBE-GH-PASS" : "CUBE-GH-FAIL")+ } else {+ lines.append("CUBE-GH-SKIP (github not connected)")+ }++ // History: round-trip a transcript through the account store.+ let hist = AgentSession(title: "cube autotest", model: "codegraff", status: .done,+ lastActivity: "now", todos: [],+ messages: [ChatMessage(role: .user, text: "autotest build"),+ ChatMessage(role: .assistant, text: "DONE")],+ cube: conn)+ let hid = hist.id.uuidString.lowercased()+ try await Gateway.putAppSession(id: hid, title: hist.title, model: hist.model,+ sandboxID: conn.sandboxID,+ transcript: AppSessionSync.transcriptJSON(hist.messages))+ let back = try await Gateway.fetchAppSession(hid)+ let msgs = AppSessionSync.messages(fromTranscript: back.transcript)+ lines.append("history: \(msgs.count) msgs round-tripped")+ lines.append(msgs.count == 2 && msgs[1].text == "DONE" ? "CUBE-HIST-PASS" : "CUBE-HIST-FAIL")+ try? await Gateway.deleteAppSession(hid)+ } catch {+ lines.append("FAIL: \(error.localizedDescription)")+ }+ }+}diff --git a/apps/ios/Graff/Sources/SessionsListView.swift b/apps/ios/Graff/Sources/SessionsListView.swiftnew file mode 100644index 00000000..d13e7a22--- /dev/null+++ b/apps/ios/Graff/Sources/SessionsListView.swift@@ -0,0 +1,146 @@+import SwiftUI++struct SessionsListView: View {+ // Signed in → the account's synced history; signed out → demo scaffolding.+ @State private var sessions = Gateway.apiKey != nil ? [] : sampleSessions+ @State private var showAccount = false+ @State private var showNewSession = false+ @State private var loadNote = ""++ var body: some View {+ NavigationStack {+ List {+ if !loadNote.isEmpty {+ Text(loadNote).font(.footnote).foregroundStyle(.secondary)+ }+ ForEach($sessions) { $session in+ NavigationLink {+ ChatView(session: $session)+ } label: {+ SessionRow(session: session)+ }+ }+ .onDelete { offsets in+ let doomed = offsets.map { sessions[$0] }+ sessions.remove(atOffsets: offsets)+ for s in doomed {+ let id = s.id.uuidString.lowercased()+ Task.detached { try? await Gateway.deleteAppSession(id) }+ }+ }+ }+ .navigationTitle("Sessions")+ .toolbar {+ ToolbarItem(placement: .topBarLeading) {+ Button { showAccount = true } label: { Image(systemName: "person.crop.circle") }+ .buttonStyle(.glass)+ }+ ToolbarItem(placement: .topBarTrailing) {+ Button { showNewSession = true } label: { Image(systemName: "plus") }+ .buttonStyle(.glass)+ }+ }+ .sheet(isPresented: $showAccount, onDismiss: { Task { await loadHistory() } }) { AccountView() }+ .sheet(isPresented: $showNewSession) {+ NewSessionView { newSession in+ sessions.insert(newSession, at: 0)+ AppSessionSync.save(newSession)+ }+ }+ .refreshable { await loadHistory() }+ .task { await loadHistory() }+ }+ }++ // Rebuild the list from /v1/app/sessions. Rows carry no transcript — they+ // hydrate when opened. A row whose cube matches the locally stored+ // connection is fully attachable; otherwise it keeps just the sandbox id+ // (ChatView offers a resume, which re-keys or respins as needed).+ @MainActor+ private func loadHistory() async {+ guard Gateway.apiKey != nil else { return }+ do {+ let rows = try await Gateway.listAppSessions()+ let live = (try? await Gateway.sandboxes()) ?? []+ let started = Set(live.filter { $0.state == "started" }.map(\.id))+ let localCube = CubeConnection.stored()+ sessions = rows.map { row in+ var s = AgentSession(title: row.title.isEmpty ? "Session" : row.title,+ model: row.model.isEmpty ? "codegraff" : row.model,+ status: .idle,+ lastActivity: Self.relative(row.updated_at),+ todos: [], messages: [])+ s.id = UUID(uuidString: row.id) ?? UUID()+ s.needsHydration = true+ if let sb = row.sandbox_id {+ if let lc = localCube, lc.sandboxID == sb {+ s.cube = lc+ } else {+ // Known cube, no local credentials (e.g. new device):+ // resumable via re-key, never via these empty fields.+ s.cube = CubeConnection(sandboxID: sb, base: "", serveToken: "",+ previewToken: nil, githubLogin: nil)+ }+ s.status = started.contains(sb) ? .idle : .done+ }+ return s+ }+ loadNote = sessions.isEmpty ? "No sessions yet — tap + to build something." : ""+ } catch {+ loadNote = error.localizedDescription+ }+ }++ private static func relative(_ epoch: Int) -> String {+ let f = RelativeDateTimeFormatter()+ f.unitsStyle = .abbreviated+ return f.localizedString(for: Date(timeIntervalSince1970: TimeInterval(epoch)), relativeTo: Date())+ }+}++struct SessionRow: View {+ let session: AgentSession++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text(session.title).font(.headline).lineLimit(1)+ Spacer()+ StatusChip(status: session.status)+ }+ HStack(spacing: 10) {+ Label(session.model, systemImage: "cpu")+ .font(.caption).foregroundStyle(.secondary).lineLimit(1)+ if session.cube != nil {+ Label("cube", systemImage: "shippingbox")+ .font(.caption).foregroundStyle(.secondary)+ }+ Spacer()+ if !session.todos.isEmpty {+ Text("\(session.progress.done)/\(session.progress.total)")+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ Text(session.lastActivity).font(.caption2).foregroundStyle(.tertiary)+ }+ if !session.todos.isEmpty {+ ProgressView(value: Double(session.progress.done),+ total: Double(max(session.progress.total, 1)))+ .tint(session.status.tint)+ }+ }+ .padding(.vertical, 4)+ }+}++struct StatusChip: View {+ let status: SessionStatus+ var body: some View {+ Label(status.label, systemImage: status.symbol)+ .font(.caption2.weight(.medium))+ .foregroundStyle(status.tint)+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .glassCapsule()+ }+}diff --git a/apps/ios/autotest.sh b/apps/ios/autotest.shnew file mode 100755index 00000000..4b34fac2--- /dev/null+++ b/apps/ios/autotest.sh@@ -0,0 +1,12 @@+#!/bin/bash+# Relaunch the installed app with --autotest (auto-fires one live serve turn),+# wait for the stream, and screenshot. Run ./build-sim.sh first to install.+set -euo pipefail+cd "$(dirname "$0")"+SIM="${SIM:-iPhone 17 Pro}"+BUNDLE=com.codegraff.graff+xcrun simctl terminate "$SIM" "$BUNDLE" 2>/dev/null || true+xcrun simctl launch "$SIM" "$BUNDLE" --autotest+sleep 16+xcrun simctl io "$SIM" screenshot build/autotest.png >/dev/null 2>&1 || true+echo "shot: $(pwd)/build/autotest.png"diff --git a/apps/ios/build-sim.sh b/apps/ios/build-sim.shnew file mode 100755index 00000000..61909d9d--- /dev/null+++ b/apps/ios/build-sim.sh@@ -0,0 +1,54 @@+#!/bin/bash+# Build the Graff iOS app and run it on a simulator — no Xcode project required.+# ./build-sim.sh # uses "iPhone 17 Pro"+# SIM="iPhone Air" ./build-sim.sh+set -euo pipefail+cd "$(dirname "$0")"++APP=Graff+BUNDLE=com.codegraff.graff+SIM="${SIM:-iPhone 17 Pro}"+SDK="$(xcrun --sdk iphonesimulator --show-sdk-path)"+TARGET=arm64-apple-ios26.0-simulator+OUT="build/${APP}.app"++echo "==> compiling ($TARGET)"+rm -rf build && mkdir -p "$OUT"++# Simulator entitlements, embedded at LINK time (__TEXT,__entitlements): the+# sim's securityd reads them from there, and without an application-identifier+# it rejects Keychain writes (errSecMissingEntitlement, -34018), which breaks+# codegraff sign-in persistence. Do NOT sign these in with codesign instead —+# SpringBoard then refuses to launch the app; the linker section is the sim way.+cat > build/ent.plist <<'PLIST'+<?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>application-identifier</key>+ <string>GRAFFSIM.com.codegraff.graff</string>+ <key>keychain-access-groups</key>+ <array>+ <string>GRAFFSIM.com.codegraff.graff</string>+ </array>+</dict>+</plist>+PLIST+xcrun -sdk iphonesimulator swiftc \+ -target "$TARGET" -sdk "$SDK" \+ -emit-executable \+ -Xlinker -sectcreate -Xlinker __TEXT -Xlinker __entitlements -Xlinker build/ent.plist \+ -o "$OUT/$APP" \+ Graff/Sources/*.swift+cp Graff/Info.plist "$OUT/Info.plist"++echo "==> booting $SIM"+xcrun simctl boot "$SIM" 2>/dev/null || true+open -a Simulator >/dev/null 2>&1 || true++echo "==> installing + launching"+xcrun simctl install "$SIM" "$OUT"+xcrun simctl launch "$SIM" "$BUNDLE" || true+sleep 4+xcrun simctl io "$SIM" screenshot build/launch.png >/dev/null 2>&1 || true+echo "==> done — screenshot: $(pwd)/build/launch.png"diff --git a/apps/ios/project.yml b/apps/ios/project.ymlnew file mode 100644index 00000000..18e571ef--- /dev/null+++ b/apps/ios/project.yml@@ -0,0 +1,24 @@+# xcodegen spec — `brew install xcodegen && xcodegen generate` then open Graff.xcodeproj.+# The CLI build (build-sim.sh) does not need this; it's here for ongoing Xcode work.+name: Graff+options:+ bundleIdPrefix: com.codegraff+ deploymentTarget:+ iOS: "26.0"+targets:+ Graff:+ type: application+ platform: iOS+ sources:+ - Graff/Sources+ info:+ path: Graff/Info.plist+ properties:+ CFBundleDisplayName: Graff+ UILaunchScreen: {}+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: com.codegraff.graff+ GENERATE_INFOPLIST_FILE: NO+ SWIFT_VERSION: "6.0"+ TARGETED_DEVICE_FAMILY: "1"diff --git a/apps/ios/recap.sh b/apps/ios/recap.shnew file mode 100755index 00000000..e7970824--- /dev/null+++ b/apps/ios/recap.sh@@ -0,0 +1,12 @@+#!/bin/bash+# Relaunch --autotest and capture the in-flight typing indicator + the reply.+set -euo pipefail+cd "$(dirname "$0")"+SIM="${SIM:-iPhone 17 Pro}"+BUNDLE=com.codegraff.graff+xcrun simctl terminate "$SIM" "$BUNDLE" 2>/dev/null || true+xcrun simctl launch "$SIM" "$BUNDLE" --autotest+sleep 5; xcrun simctl io "$SIM" screenshot build/cap_typing.png >/dev/null 2>&1 || true+sleep 3; xcrun simctl io "$SIM" screenshot build/cap_mid.png >/dev/null 2>&1 || true+sleep 8; xcrun simctl io "$SIM" screenshot build/cap_reply.png >/dev/null 2>&1 || true+echo "captured: cap_typing.png cap_mid.png cap_reply.png"