Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Remove the in-repo iOS app

justrach6d6511c9d7b3
diff --git a/README.md b/README.md
index 0d45f329..b185fb73 100644
--- a/README.md
+++ b/README.md
@@ -414,7 +414,7 @@ The repository is organized as follows:
| path | what it is |
|---|---|
| `src/`, `TUI/` | harness + terminal |
-| `apps/` | iOS and Chrome extensions |
+| `apps/` | Chrome native-messaging extension |
| `graff-evals/` | live, in-house, FrontierHarness |
| `docs/` | ADRs, architecture, images, install, embedding |
| `sdk/` | generated TypeScript / Python |
diff --git a/apps/ios/.gitignore b/apps/ios/.gitignore
deleted file mode 100644
index e3095337..00000000
--- a/apps/ios/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-build/
-DerivedData/
-*.xcodeproj
-.DS_Store
diff --git a/apps/ios/Graff/Info.plist b/apps/ios/Graff/Info.plist
deleted file mode 100644
index c6a05101..00000000
--- a/apps/ios/Graff/Info.plist
+++ /dev/null
@@ -1,28 +0,0 @@
-<?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.swift
deleted file mode 100644
index fa276bfd..00000000
--- a/apps/ios/Graff/Sources/AccountView.swift
+++ /dev/null
@@ -1,179 +0,0 @@
-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.swift
deleted file mode 100644
index c12521cf..00000000
--- a/apps/ios/Graff/Sources/ChatView.swift
+++ /dev/null
@@ -1,452 +0,0 @@
-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
- // #59: the streaming task was discarded, so the composer's "working" glyph
- // was a dead button. Holding it makes stop a real action.
- @State private var turnTask: Task<Void, Never>?
-
- 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) }
- }
- }
- // A turn that ends with no new text still changes what the row
- // says (#307/#285): scroll so the failure notice is not left
- // hidden behind the composer.
- .onChange(of: session.messages.last?.state) {
- 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, onStop: stop)
- .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
- announce("Message sent. Assistant is responding.")
- turnTask = Task { await runTurn(t) }
- }
-
- // #59: cancelling the turn task terminates the NDJSON stream (the client
- // already wires onTermination) and runTurn records .cancelled on the turn.
- private func stop() { turnTask?.cancel() }
-
- // #317: VoiceOver gets nothing out of an animated dot row, so the start and
- // the terminal state of a turn are spoken once each - not per token.
- private func announce(_ message: String) {
- AccessibilityNotification.Announcement(message).post()
- }
-
- // 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; turnTask = nil }
- var turnID: UUID?
- var outcome: TurnState = .completed
- do {
- if serveSessionID == nil {
- serveSessionID = try await client.createSession(model: session.model,
- yolo: session.cube != nil,
- appendSystemPrompt: cubeSystemNote)
- }
- // #309: the row is addressed by its stable id for the rest of the
- // turn - hydration may rewrite session.messages under us.
- let placeholder = ChatMessage(role: .assistant, text: "", state: .streaming)
- let id = placeholder.id
- turnID = id
- session.messages.append(placeholder)
- for try await ev in client.streamTurn(sessionID: serveSessionID!, text: text) {
- switch ev {
- case .reasoning(let r):
- session.messages.updateTurn(id) { $0.reasoning = ($0.reasoning ?? "") + r }
- case .text(let d):
- session.messages.updateTurn(id) { $0.text += d }
- case .turn(let final, _, _):
- session.messages.updateTurn(id) { $0.text = final }
- case .error(let m):
- // #285: a server-reported error is not model prose, so it
- // lands on the turn's state rather than in its text.
- outcome = .failed(m)
- case .toolCall(let name):
- session.messages.updateTurn(id) {
- $0.reasoning = (($0.reasoning ?? "") + "\n⚙️ \(name)")
- .trimmingCharacters(in: .whitespacesAndNewlines)
- }
- case .other:
- break
- }
- }
- // Falling out of the loop without a throw means a terminal event
- // arrived - the client reports a bare EOF as prematureEnd (#307).
- // A cancelled consumer ends the stream quietly, so ask (#59).
- if Task.isCancelled { outcome = .cancelled }
- } catch {
- outcome = Task.isCancelled ? .cancelled : .failed(error.localizedDescription)
- }
- if let turnID {
- // #285: one submission, one assistant record - the failure updates
- // the turn it belongs to instead of appending a second bubble.
- session.messages.updateTurn(turnID) { $0.state = outcome }
- } else if case .failed(let why) = outcome {
- // createSession failed before any placeholder existed; the failure
- // still needs exactly one record to sit on.
- session.messages.append(ChatMessage(role: .assistant, text: "", state: .failed(why)))
- }
- switch outcome {
- case .failed(let why): announce("Turn failed. \(why)")
- case .cancelled: announce("Turn stopped.")
- case .completed, .streaming: announce("Assistant finished responding.")
- }
- // #286: the row's status is the turn's actual outcome. A failed turn
- // used to fall back to .idle and then be relabelled Done by the history
- // list purely because its sandbox had stopped.
- switch outcome {
- case .failed: session.status = .failed
- case .cancelled: session.status = .ended
- case .completed: session.status = .done
- case .streaming: session.status = .idle
- }
- session.lastActivity = "just now"
- AppSessionSync.save(session)
- }
-
- @MainActor
- private func hydrateIfNeeded() async {
- guard session.needsHydration, !didHydrate else { return }
- didHydrate = true
- let localCount = session.messages.count
- if let full = try? await Gateway.fetchAppSession(session.id.uuidString.lowercased()) {
- // #309: the composer stays live while this request is in flight, so
- // anything appended meanwhile belongs to the running turn. History
- // is restored in front of it instead of replacing the array
- // wholesale, which used to erase a just-sent message.
- let live = session.messages.count > localCount
- ? Array(session.messages[localCount...])
- : []
- session.messages = AppSessionSync.messages(fromTranscript: full.transcript) + live
- session.needsHydration = false
- // #286: now that the transcript is here, the row can show the
- // outcome it actually records instead of a liveness guess. A live
- // turn owns the status, so never overwrite one mid-flight.
- if live.isEmpty, !streaming,
- let outcome = AppSessionSync.outcome(fromTranscript: full.transcript) {
- session.status = outcome
- }
- }
- }
-
- @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) }
- // #307: only a turn that is actually streaming may animate. Emptiness is
- // not evidence of progress - a failed turn, or a blank record reloaded from
- // history, used to keep the dots pulsing forever.
- private var isTyping: Bool {
- message.role == .assistant && message.state == .streaming && isBlank
- }
-
- // #317: the whole bubble is one VoiceOver element that says who spoke, what
- // was said, and how the turn ended - not three decorative circles.
- private var voiceOverLabel: String {
- var parts = [message.role == .user ? "You said" : "Assistant"]
- if let r = message.reasoning, !r.isEmpty { parts.append("Reasoning: \(r)") }
- if !message.text.isEmpty { parts.append(message.text) }
- switch message.state {
- case .streaming: if isBlank { parts.append("Responding") }
- case .failed(let why): parts.append("Turn failed: \(why)")
- case .cancelled: parts.append("Turn stopped")
- case .completed: break
- }
- return parts.joined(separator: ". ")
- }
-
- 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 isTyping {
- TypingIndicator()
- }
- // #285: the failure reason is turn metadata, rendered as such,
- // so it can never be mistaken for model-authored text.
- if case .failed(let why) = message.state {
- Label(why, systemImage: "exclamationmark.triangle.fill")
- .font(.caption)
- .foregroundStyle(.red)
- } else if message.state == .cancelled {
- Label("Stopped", systemImage: "stop.circle")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- }
- .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) }
- }
- .accessibilityElement(children: .ignore)
- .accessibilityLabel(voiceOverLabel)
- .accessibilityAddTraits(message.state == .streaming ? .updatesFrequently : [])
- }
-}
-
-// 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. Shown only for a
-// .streaming turn (#307), and spoken as one status element (#317).
-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 }
- .accessibilityElement(children: .ignore)
- .accessibilityLabel("Assistant is responding")
- .accessibilityAddTraits(.updatesFrequently)
- }
-}
-
-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
- // #59: while a turn streams the button is a live stop, not a greyed-out
- // ellipsis whose action is still onSend.
- var onStop: () -> 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)
- .accessibilityLabel("Message")
- .accessibilityHint(streaming
- ? "Unavailable while the assistant is responding"
- : "Write a message to the assistant")
- Button(action: streaming ? onStop : onSend) {
- Image(systemName: streaming ? "stop.fill" : "arrow.up")
- .font(.headline.weight(.bold))
- }
- .buttonStyle(.glassProminent)
- .tint(streaming ? .red : nil)
- .disabled(!streaming && (disabled || draft.trimmingCharacters(in: .whitespaces).isEmpty))
- .accessibilityLabel(streaming ? "Stop responding" : "Send message")
- }
- }
-}
-
-// 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.swift
deleted file mode 100644
index 9ae0552d..00000000
--- a/apps/ios/Graff/Sources/CubeBroker.swift
+++ /dev/null
@@ -1,248 +0,0 @@
-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
- // When the installation token wired into this cube dies. A cube outlives
- // its 1-hour token, and the reuse fast path used to hand the connection
- // straight back (#314) — so git/gh inside kept running on dead credentials
- // while the chat still told the model GitHub was wired up.
- var githubTokenExpiry: Date? = nil
-
- // Re-mint a few minutes early: a turn that starts on a nearly-dead token
- // still has to finish its clone/push.
- static let githubRefreshSkew: TimeInterval = 5 * 60
-
- // Nothing to refresh when the cube never carried repo access. An expiry we
- // never recorded (a connection stored before #314) counts as expired — its
- // real age is unknowable, so assume the worst and re-key once.
- func githubNeedsRefresh(asOf now: Date = Date()) -> Bool {
- guard githubLogin != nil else { return false }
- guard let expiry = githubTokenExpiry else { return true }
- return expiry.timeIntervalSince(now) <= Self.githubRefreshSkew
- }
-
- 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
-
- // #314: the wire carries an ISO-8601 instant; the stored connection needs a
- // Date it can compare against on reuse. An unparseable stamp falls back to
- // an hour out, which is what the endpoint promises anyway.
- var expiry: Date {
- let f = ISO8601DateFormatter()
- if let d = f.date(from: expires_at) { return d }
- f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
- if let d = f.date(from: expires_at) { return d }
- return Date().addingTimeInterval(3600)
- }
-}
-
-// 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
- var refreshingGitHub = false
- if let old = CubeConnection.stored() {
- await onStep("Checking the last cube…")
- let state = (try? await Gateway.sandboxInfo(old.sandboxID))?.state ?? "gone"
- let staleGitHub = old.githubNeedsRefresh()
- if state == "started" && !old.base.isEmpty && !old.serveToken.isEmpty && !staleGitHub {
- 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.
- // A running cube whose installation token has aged out lands here
- // too (#314): the token is baked into the serve process environment
- // as much as into the credential files, so a re-key — mint, rewrite,
- // restart serve — is what makes the "fresh token every bring-up"
- // promise above true on the reuse path. Still no reinstall, so this
- // stays the cheap rung of the ladder.
- if state == "started" || state == "stopped" {
- resumeID = old.sandboxID
- wasRunning = state == "started"
- refreshingGitHub = wasRunning && staleGitHub
- } else {
- CubeConnection.clearStored()
- }
- }
-
- // #312: what this launch is on the hook for. The New Session sheet can
- // be dismissed mid-provisioning; the cube this launch paid to bring up
- // then has to go back down (Gateway.createSandbox's autoStopMinutes: 30
- // caps the bleed, it never undoes the spin-up). A cube that was already
- // running when we found it is not ours to stop.
- var broughtUp: String? = nil
- do {
- let id: String
- if let rid = resumeID {
- await onStep(refreshingGitHub
- ? "GitHub token expired — re-keying the cube (no reinstall)…"
- : wasRunning ? "Re-keying the running cube (no reinstall)…"
- : "Waking the stopped cube (cheaper — no reinstall)…")
- if !wasRunning {
- _ = try await Gateway.startSandbox(rid)
- broughtUp = rid
- }
- id = rid
- } else {
- // #312: never buy a cube for a sheet that is already gone.
- try Task.checkCancellation()
- await onStep("Creating sandbox (full spin-up)…")
- id = try await Gateway.createSandbox(purpose: purpose).id
- broughtUp = 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)
- // provisionGitHub swallows its own errors, cancellation included, so
- // ask again before spending anything more on an abandoned launch (#312).
- try Task.checkCancellation()
-
- // 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,
- githubTokenExpiry: github?.expiry)
- conn.store()
- return conn
- } catch {
- // #312: put back only what this launch brought up, and only when the
- // caller walked away — a genuine spin-up failure keeps its sandbox so
- // the next attempt can resume it instead of paying again.
- if Task.isCancelled, let id = broughtUp {
- await onStep("Cancelled — stopping the cube…")
- // Detached on purpose: every URLSession call made from a
- // cancelled task fails instantly, and this rollback is the one
- // thing that still has to happen.
- await Task.detached { _ = try? await Gateway.stopSandbox(id) }.value
- }
- throw error
- }
- }
-
- // 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.swift
deleted file mode 100644
index d486f7db..00000000
--- a/apps/ios/Graff/Sources/GraffAccount.swift
+++ /dev/null
@@ -1,506 +0,0 @@
-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)" }
- }
-
- var isInsufficientSessionScope: Bool {
- switch self {
- case .http(403, let message): return message.localizedCaseInsensitiveContains("sessions")
- default: return false
- }
- }
-}
-
-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?
- // #286: how the turn ended, persisted alongside it. Without this a failed
- // or interrupted turn reloads indistinguishable from a successful one, and
- // the history list has no outcome to show but sandbox liveness. Absent on
- // transcripts written before this field existed — absence means "unlabelled",
- // not "succeeded".
- var state: String? = nil
- var failure: String? = nil
-}
-
-enum AppSessionSync {
- private static func wire(_ state: TurnState) -> (state: String, failure: String?) {
- switch state {
- case .streaming: return ("streaming", nil)
- case .completed: return ("completed", nil)
- case .cancelled: return ("cancelled", nil)
- case .failed(let why): return ("failed", why)
- }
- }
-
- // A turn persisted as `streaming` never reached a terminal event — the app
- // was killed or the transport died mid-turn — so it reloads as interrupted
- // rather than as a silent success (#286).
- private static func turnState(_ dto: MessageDTO) -> TurnState {
- switch dto.state {
- case "failed": return .failed(dto.failure ?? "Turn failed.")
- case "cancelled": return .cancelled
- case "streaming": return .failed(dto.failure ?? "Interrupted before the turn finished.")
- default: return .completed
- }
- }
-
- static func transcriptJSON(_ messages: [ChatMessage]) -> String {
- let dtos = messages.map { m -> MessageDTO in
- let w = wire(m.state)
- return MessageDTO(role: m.role == .user ? "user" : "assistant",
- text: m.text, reasoning: m.reasoning,
- state: w.state, failure: w.failure)
- }
- 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,
- state: turnState($0)) }
- }
-
- // #286: the outcome the transcript actually records, or nil when it records
- // none (an unlabelled or empty transcript is not evidence of success). The
- // caller falls back to a neutral liveness-derived state instead of Done.
- static func outcome(fromTranscript json: String) -> SessionStatus? {
- guard let data = json.data(using: .utf8),
- let dtos = try? JSONDecoder().decode([MessageDTO].self, from: data),
- let last = dtos.last(where: { $0.role != "user" }),
- let state = last.state else { return nil }
- switch state {
- case "completed": return .done
- case "failed", "streaming": return .failed
- case "cancelled": return .ended
- default: return nil
- }
- }
-
- // #310: every write is stamped with a monotonic revision HERE, on the main
- // actor, in the order the caller made it. Detaching first and numbering
- // later would let two saves reach the sync engine in either order, which
- // is the bug this is guarding against.
- @MainActor private static var revisionCounter: UInt64 = 0
- @MainActor private static func nextRevision() -> UInt64 {
- revisionCounter += 1
- return revisionCounter
- }
-
- // Still fire-and-forget from the caller's point of view — history sync must
- // never block or break the chat — but no longer unordered (#310).
- @MainActor
- 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
- let revision = nextRevision()
- Task {
- await AppSessionSyncEngine.shared.save(id: id, revision: revision, title: title,
- model: model, sandboxID: sandboxID,
- transcript: transcript)
- }
- }
-
- @MainActor
- static func delete(_ sessionID: UUID) {
- guard Gateway.apiKey != nil else { return }
- let id = sessionID.uuidString.lowercased()
- let revision = nextRevision()
- Task { await AppSessionSyncEngine.shared.delete(id: id, revision: revision) }
- }
-}
-
-// #310: session persistence used to be a bare `Task.detached` per save, with no
-// ordering, no revision and no relationship to the equally detached DELETE. An
-// older PUT could land after a newer one and roll the synced transcript
-// backward, and a delayed PUT could land after a DELETE and resurrect a session
-// the user had removed. The gateway's /v1/app/sessions PUT takes no If-Match or
-// version — there is nothing to make conditional — so the invariant is enforced
-// entirely on this side:
-//
-// * writes for one session id run strictly one at a time, in issue order;
-// * a payload that has been superseded while it waited its turn is dropped
-// rather than sent, so an older transcript never reaches the gateway;
-// * a deleted id is tombstoned with the revision of its DELETE, which drops
-// every write older than that delete, and the DELETE itself is chained
-// behind any PUT already in flight so the row cannot come back.
-//
-// The tombstone is deliberately scoped to *older* writes. It is not a
-// permanent ban on the id: the DELETE is fire-and-forget (`try?`), so it can
-// fail offline or 5xx, the row survives on the gateway, and the next refresh
-// hands the session straight back to the user. A save issued strictly after
-// the delete is that revived session being used again — refusing it forever
-// would silently discard every later turn for the life of the process, which
-// is worse than the resurrection it was meant to prevent.
-//
-// Server-side gap: without a conditional PUT, a second device racing this one
-// is still last-writer-wins. That needs a gateway revision/If-Match, which does
-// not exist yet.
-// One write as it reaches the wire. `transcript == nil` is a delete.
-struct AppSessionWrite: Sendable {
- let id: String
- let title: String
- let model: String
- let sandboxID: String?
- let transcript: String?
-}
-
-actor AppSessionSyncEngine {
- static let shared = AppSessionSyncEngine()
-
- // The gateway leg, injectable so the ordering invariants can be asserted
- // against a deterministically delayed transport (--autotest-sync).
- static let gatewayTransport: @Sendable (AppSessionWrite) async -> Void = { w in
- if let transcript = w.transcript {
- try? await Gateway.putAppSession(id: w.id, title: w.title, model: w.model,
- sandboxID: w.sandboxID, transcript: transcript)
- } else {
- try? await Gateway.deleteAppSession(w.id)
- }
- }
-
- private let transport: @Sendable (AppSessionWrite) async -> Void
- init(transport: @escaping @Sendable (AppSessionWrite) async -> Void = AppSessionSyncEngine.gatewayTransport) {
- self.transport = transport
- }
-
- // Newest revision issued per session id; anything older is obsolete.
- private var latest: [String: UInt64] = [:]
- // Tail of each session's serial chain, so the next operation can await it.
- private var chain: [String: Task<Void, Never>] = [:]
- private var chainGeneration: [String: UInt64] = [:]
- private var generationCounter: UInt64 = 0
- // Revision of the newest DELETE seen per id, not a bare set: the tombstone
- // has to be comparable against later writes, not applied to all of them.
- private var tombstones: [String: UInt64] = [:]
-
- func save(id: String, revision: UInt64, title: String, model: String,
- sandboxID: String?, transcript: String) {
- // Out-of-order arrival at the actor is fine: revisions were stamped in
- // call order, so an older one simply never becomes the latest. A delete
- // stamps `latest` too, so this one check also refuses every save older
- // than the delete — which is all #310 asks for.
- guard revision > (latest[id] ?? 0) else { return }
- latest[id] = revision
- // Strictly newer than any delete for this id, so the tombstone no
- // longer applies: this is a live session being written again, not a
- // stale PUT trying to undo a delete.
- tombstones[id] = nil
- let write = AppSessionWrite(id: id, title: title, model: model,
- sandboxID: sandboxID, transcript: transcript)
- let send = transport
- link(id) { [self] in
- // Superseded while queued — sending it would roll the gateway back.
- guard await isCurrent(id, revision) else { return }
- await send(write)
- }
- }
-
- func delete(id: String, revision: UInt64) {
- // Tombstone first: every write issued before this delete is now
- // obsolete, whether it is queued or still on its way to the actor.
- tombstones[id] = revision
- // Never downgrade: a save that outranks this delete was issued after it
- // and keeps its claim on the chain.
- latest[id] = max(latest[id] ?? 0, revision)
- let write = AppSessionWrite(id: id, title: "", model: "", sandboxID: nil, transcript: nil)
- let send = transport
- link(id) { await send(write) }
- }
-
- // Wait until every queued write has run. Only the in-process harness needs
- // this; the app never blocks on sync.
- func quiesce() async {
- while let task = chain.values.first { await task.value }
- }
-
- private func isCurrent(_ id: String, _ revision: UInt64) -> Bool {
- revision > (tombstones[id] ?? 0) && latest[id] == revision
- }
-
- // Append to this session's serial chain. Different sessions still overlap;
- // only same-id writes are ordered against each other.
- private func link(_ id: String, _ work: @escaping @Sendable () async -> Void) {
- let previous = chain[id]
- generationCounter += 1
- let generation = generationCounter
- chainGeneration[id] = generation
- chain[id] = Task { [self] in
- await previous?.value
- await work()
- release(id, generation)
- }
- }
-
- private func release(_ id: String, _ generation: UInt64) {
- guard chainGeneration[id] == generation else { return } // a newer write owns the chain
- chain[id] = nil
- chainGeneration[id] = nil
- }
-}
diff --git a/apps/ios/Graff/Sources/GraffApp.swift b/apps/ios/Graff/Sources/GraffApp.swift
deleted file mode 100644
index bb018d12..00000000
--- a/apps/ios/Graff/Sources/GraffApp.swift
+++ /dev/null
@@ -1,485 +0,0 @@
-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-turnstate") {
- // Turn-model invariants (#307/#285/#309) checked in memory —
- // no network, no taps, so it runs anywhere the app launches.
- TurnStateCheckView()
- } else if CommandLine.arguments.contains("--autotest-sync") {
- // Session-sync ordering invariants (#310) against a delayed
- // in-memory transport — deterministic, no network, no taps.
- SyncOrderCheckView()
- } 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.")
- }
- }
-}
-
-// Launch with `--autotest-turnstate` to assert the turn model's invariants
-// in-process — the only regression guard these views have, since the app has no
-// test target and CI does not build it. Every line is also printed, so
-// `xcrun simctl launch --console-pty … --autotest-turnstate` can gate on
-// TURNSTATE-PASS.
-struct TurnStateCheckView: View {
- var body: some View {
- Text(Self.report)
- .font(.system(.footnote, design: .monospaced))
- .padding()
- }
-
- static var report: String {
- var lines: [String] = []
- func check(_ name: String, _ ok: Bool) { lines.append((ok ? "ok " : "FAIL ") + name) }
-
- let user = ChatMessage(role: .user, text: "hi")
- let turn = ChatMessage(role: .assistant, text: "", state: .streaming)
- let capturedIndex = [user, turn].count - 1 // what runTurn used to keep
-
- // #309: hydration lands mid-turn and rewrites the transcript. The live
- // row has moved, so only its id can still find it.
- let history = (0..<4).map { ChatMessage(role: .assistant, text: "old \($0)") }
- var hydrated = history + [user, turn]
- check("hydration invalidates the captured index",
- hydrated[capturedIndex].id != turn.id)
- hydrated.updateTurn(turn.id) { $0.text += "streamed" }
- check("update by id reaches the live turn",
- hydrated.last?.id == turn.id && hydrated.last?.text == "streamed")
- check("update by id touches nothing else",
- hydrated.filter { $0.text == "streamed" }.count == 1)
-
- // A shorter hydrated array is where the captured index used to trap.
- var dropped = [ChatMessage(role: .user, text: "only")]
- check("captured index is out of bounds after hydration",
- capturedIndex >= dropped.count)
- dropped.updateTurn(turn.id) { $0.text = "must not appear" }
- check("update by id on a dropped turn is a safe no-op",
- dropped.count == 1 && dropped[0].text == "only")
-
- // #285: a failure updates the turn it belongs to, never appends.
- var failing = [user, turn]
- failing.updateTurn(turn.id) { $0.state = .failed("The network connection was lost.") }
- check("failure stays on one assistant record",
- failing.count == 2 && failing[1].state == .failed("The network connection was lost."))
- check("failure reason is not model prose", failing[1].text.isEmpty)
-
- // #307: a blank record reloaded from history is finished, not typing.
- check("history defaults to completed",
- ChatMessage(role: .assistant, text: "").state == .completed)
- check("garbage NDJSON does not decode",
- GraffServeClient.decode("<html>502 Bad Gateway</html>") == nil)
- var sawTurn = false
- if case .some(.turn) = GraffServeClient.decode("{\"type\":\"turn\",\"text\":\"done\"}") { sawTurn = true }
- check("a terminal turn record decodes", sawTurn)
-
- // #286: sandbox liveness must never be read as a task outcome.
- let sb = "sandbox-1"
- check("a stopped/gone sandbox is Ended, not Done",
- SessionsListView.rowStatus(prior: nil, sandbox: sb, started: []) == .ended)
- check("a started sandbox is idle",
- SessionsListView.rowStatus(prior: nil, sandbox: sb, started: [sb]) == .idle)
- check("a failed sandbox listing is Unknown, not Done",
- SessionsListView.rowStatus(prior: nil, sandbox: sb, started: nil) == .unknown)
- check("a failed sandbox listing keeps the prior status",
- SessionsListView.rowStatus(prior: .working, sandbox: sb, started: nil) == .working)
- check("a known failure survives a stopped sandbox",
- SessionsListView.rowStatus(prior: .failed, sandbox: sb, started: []) == .failed)
- check("no sandbox means no liveness verdict",
- SessionsListView.rowStatus(prior: nil, sandbox: nil, started: []) == .idle)
-
- // #286: the outcome round-trips through the synced transcript.
- let failedTurn = [ChatMessage(role: .user, text: "go"),
- ChatMessage(role: .assistant, text: "",
- state: .failed("The network connection was lost."))]
- let failedJSON = AppSessionSync.transcriptJSON(failedTurn)
- check("a failed turn reloads as failed",
- AppSessionSync.messages(fromTranscript: failedJSON).last?.state
- == .failed("The network connection was lost."))
- check("a failed transcript is not a Done session",
- AppSessionSync.outcome(fromTranscript: failedJSON) == .failed)
- let okJSON = AppSessionSync.transcriptJSON([ChatMessage(role: .assistant, text: "shipped")])
- check("a completed transcript is Done",
- AppSessionSync.outcome(fromTranscript: okJSON) == .done)
- check("an interrupted turn is not silently successful",
- AppSessionSync.outcome(fromTranscript:
- AppSessionSync.transcriptJSON([ChatMessage(role: .assistant, text: "",
- state: .streaming)])) == .failed)
- check("an unlabelled (pre-#286) transcript claims no outcome",
- AppSessionSync.outcome(fromTranscript:
- "[{\"role\":\"assistant\",\"text\":\"Transport error\"}]") == nil)
-
- let failures = lines.filter { $0.hasPrefix("FAIL") }.count
- let summary = failures == 0 ? "TURNSTATE-PASS" : "TURNSTATE-FAIL (\(failures))"
- print(summary)
- for l in lines { print(l) }
- return ([summary] + lines).joined(separator: "\n")
- }
-}
-
-// Launch with `--autotest-sync` to reproduce #310's delayed-response scenarios
-// against an in-memory transport that stalls the FIRST write it receives — the
-// exact "delay the PUT produced after turn 1" setup from the issue — and assert
-// what actually reached the wire. Gates on SYNCORDER-PASS.
-struct SyncOrderCheckView: View {
- @State private var report = "running…"
- var body: some View {
- Text(report)
- .font(.system(.footnote, design: .monospaced))
- .padding()
- .task { report = await Self.run() }
- }
-
- // Records every write in the order it reached the transport, holding the
- // first one open long enough that anything issued after it must queue.
- private actor Recorder {
- private var seen = 0
- private var log: [String] = []
- func apply(_ write: AppSessionWrite) async {
- seen += 1
- if seen == 1 { try? await Task.sleep(nanoseconds: 200_000_000) }
- log.append(write.transcript ?? "DELETE")
- }
- func applied() -> [String] { log }
- }
-
- static func run() async -> String {
- var lines: [String] = []
- func check(_ name: String, _ ok: Bool) { lines.append((ok ? "ok " : "FAIL ") + name) }
-
- func harness() -> (Recorder, AppSessionSyncEngine) {
- let recorder = Recorder()
- return (recorder, AppSessionSyncEngine(transport: { await recorder.apply($0) }))
- }
- func put(_ engine: AppSessionSyncEngine, _ rev: UInt64, _ body: String) async {
- await engine.save(id: "s1", revision: rev, title: "t", model: "m",
- sandboxID: nil, transcript: body)
- }
-
- // save/save: the delayed turn-1 PUT must not be the last word.
- var (recorder, engine) = harness()
- await put(engine, 1, "turn-1")
- await put(engine, 2, "turn-2")
- await engine.quiesce()
- var applied = await recorder.applied()
- check("the newer transcript wins the save/save race", applied.last == "turn-2")
- check("writes reach the gateway in issue order", applied == ["turn-1", "turn-2"])
-
- // An obsolete save queued behind a slow one is dropped, not sent.
- (recorder, engine) = harness()
- await put(engine, 1, "turn-1")
- await put(engine, 2, "turn-2")
- await put(engine, 3, "turn-3")
- await engine.quiesce()
- applied = await recorder.applied()
- check("a superseded queued save is never sent", applied == ["turn-1", "turn-3"])
-
- // An out-of-order arrival (older revision, later call) is refused.
- (recorder, engine) = harness()
- await put(engine, 5, "newer")
- await put(engine, 2, "older")
- await engine.quiesce()
- applied = await recorder.applied()
- check("an older revision never clobbers a newer one", applied == ["newer"])
-
- // save/delete: the DELETE waits for the PUT it was issued behind.
- (recorder, engine) = harness()
- await put(engine, 1, "turn-1")
- await engine.delete(id: "s1", revision: 2)
- await engine.quiesce()
- applied = await recorder.applied()
- check("DELETE is ordered after the in-flight PUT", applied == ["turn-1", "DELETE"])
-
- // The tombstone covers writes issued BEFORE the delete, whichever order
- // they reach the actor in — that is the resurrection #310 is about.
- (recorder, engine) = harness()
- await put(engine, 1, "turn-1")
- await engine.delete(id: "s1", revision: 3)
- await put(engine, 2, "stale-save")
- await engine.quiesce()
- applied = await recorder.applied()
- check("a save older than the delete never resurrects the session",
- !applied.contains("stale-save"))
-
- // …but it is not a permanent ban on the id. The DELETE is best-effort;
- // when it fails the row comes back on the next refresh, and using that
- // session again must still sync instead of being dropped forever.
- (recorder, engine) = harness()
- await put(engine, 1, "turn-1")
- await engine.delete(id: "s1", revision: 2)
- await put(engine, 3, "revived")
- await engine.quiesce()
- applied = await recorder.applied()
- check("a save issued after the delete is still written",
- applied == ["turn-1", "DELETE", "revived"])
-
- // And the revived session keeps its ordering guarantees afterwards.
- (recorder, engine) = harness()
- await engine.delete(id: "s1", revision: 1)
- await put(engine, 3, "revived-newer")
- await put(engine, 2, "revived-older")
- await engine.quiesce()
- applied = await recorder.applied()
- check("a revived session still refuses out-of-order writes",
- applied == ["DELETE", "revived-newer"])
-
- // Different sessions are independent — serialization is per id.
- (recorder, engine) = harness()
- await put(engine, 1, "a")
- await engine.save(id: "s2", revision: 2, title: "t", model: "m",
- sandboxID: nil, transcript: "b")
- await engine.quiesce()
- applied = await recorder.applied()
- check("a second session is not blocked by the first",
- applied.sorted() == ["a", "b"])
-
- let failures = lines.filter { $0.hasPrefix("FAIL") }.count
- let summary = failures == 0 ? "SYNCORDER-PASS" : "SYNCORDER-FAIL (\(failures))"
- print(summary)
- for l in lines { print(l) }
- return ([summary] + lines).joined(separator: "\n")
- }
-}
-
-// 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 }
-
-// How a turn ended. The assistant row has to carry this itself: an empty
-// bubble is not evidence that work is still in flight (#307), and a transport
-// failure belongs ON the turn instead of becoming a second assistant record
-// (#285) or having nowhere to land when the turn is stopped (#59).
-enum TurnState: Equatable {
- case streaming
- case completed
- case failed(String)
- case cancelled
-}
-
-struct ChatMessage: Identifiable {
- let id = UUID()
- let role: Role
- var text: String
- var reasoning: String? = nil
- // Defaults to .completed so history (samples, hydrated transcripts) is
- // never mistaken for an in-flight turn; runTurn passes .streaming
- // explicitly for the row it is filling in.
- var state: TurnState = .completed
-}
-
-extension Array where Element == ChatMessage {
- // #309: the only way to touch an in-flight turn. Addressing it by its
- // stable id means a hydration that replaces the transcript mid-stream can
- // no longer misapply an event to a historical row - or trap, when the
- // hydrated array is shorter than the index the turn captured.
- mutating func updateTurn(_ id: UUID, _ mutate: (inout ChatMessage) -> Void) {
- guard let i = firstIndex(where: { $0.id == id }) else { return }
- mutate(&self[i])
- }
-}
-
-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
-}
-
-// #286: sandbox liveness is not a task outcome. `done` means a persisted
-// successful terminal turn and nothing else; a sandbox that merely stopped is
-// `ended` (neutral — the work may or may not have succeeded), a turn that
-// failed or was interrupted is `failed`, and a sandbox whose state could not
-// be fetched is `unknown` rather than silently optimistic.
-enum SessionStatus: String {
- case working, waiting, idle, done, ended, failed, unknown
-
- // Outcomes read from the session's own transcript. Sandbox liveness must
- // never overwrite one of these with a guess (#286).
- var isTranscriptOutcome: Bool { self == .done || self == .failed }
-
- var label: String {
- switch self {
- case .working: return "Working"
- case .waiting: return "Waiting on you"
- case .idle: return "Idle"
- case .done: return "Done"
- case .ended: return "Ended"
- case .failed: return "Failed"
- case .unknown: return "Unknown"
- }
- }
- 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"
- case .ended: return "stop.circle"
- case .failed: return "exclamationmark.triangle.fill"
- case .unknown: return "questionmark.circle"
- }
- }
- var tint: Color {
- switch self {
- case .working: return .blue
- case .waiting: return .orange
- case .idle: return .secondary
- case .done: return .green
- case .ended: return .secondary
- case .failed: return .red
- case .unknown: return .secondary
- }
- }
-}
-
-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)
- }
-}
-
-// #316: test/demo fixtures ONLY. These are deliberately realistic, so they
-// must never be shown as account history — the signed-out Sessions list used
-// to open on them and read as retained user data. Their only reachable use is
-// `--autotest`, which drives a real turn through one of them.
-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.swift
deleted file mode 100644
index 8c18c93e..00000000
--- a/apps/ios/Graff/Sources/GraffServeClient.swift
+++ /dev/null
@@ -1,136 +0,0 @@
-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)
- // #307: a 200 whose NDJSON body ends without a terminal `turn`/`error`
- // record is a truncated turn, not a successful one.
- case prematureEnd
- // #307: an undecodable line means the protocol broke mid-stream; skipping
- // it let a truncated stream take the same false-success path.
- case malformedEvent(String)
- var errorDescription: String? {
- switch self {
- case .badResponse(let s): return s
- case .prematureEnd: return "The turn stream ended before the agent finished."
- case .malformedEvent(let s): return "Unreadable turn stream record: \(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
- }
- // #307: exactly one terminal `turn`/`error` record ends a
- // turn. Anything else that stops the line loop - EOF, a
- // truncated or malformed record - is a transport failure,
- // so a caller can never read silence as success.
- var sawTerminal = false
- for try await line in bytes.lines {
- if line.isEmpty { continue } // NDJSON keepalive padding
- guard let ev = Self.decode(line) else {
- continuation.finish(throwing:
- GraffError.malformedEvent(String(line.prefix(80))))
- return
- }
- continuation.yield(ev)
- if case .turn = ev { sawTerminal = true; break }
- if case .error = ev { sawTerminal = true; break }
- }
- continuation.finish(throwing: sawTerminal ? nil : GraffError.prematureEnd)
- } 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.swift
deleted file mode 100644
index c37e2498..00000000
--- a/apps/ios/Graff/Sources/NewSessionView.swift
+++ /dev/null
@@ -1,272 +0,0 @@
-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
- // #312: the launch used to run in an untracked Task, so tearing the sheet
- // down left it provisioning a cube nobody would ever see. Hold the handle
- // so dismissal can cancel it, and remember that we walked away.
- @State private var launchTask: Task<Void, Never>? = nil
- @State private var abandoned = false
-
- var body: some View {
- NavigationStack {
- Group {
- switch phase {
- case .compose: compose
- case .launching:
- // Cancelling is the point of this button (#312): it stops the
- // cube coming up rather than just hiding the progress.
- launching
- .toolbar { ToolbarItem(placement: .topBarLeading) { Button("Cancel") { finish() } } }
- 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
- launchTask = Task { await launch() }
- } label: {
- Label("Start building", systemImage: "play.fill").frame(maxWidth: .infinity)
- }
- .buttonStyle(.glassProminent)
- // .whitespaces excludes newlines, so a return-only prompt read as
- // non-empty here and bought a cube it could never use (#315).
- .disabled(prompt.trimmingCharacters(in: .whitespacesAndNewlines).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 {
- // Validate BEFORE spending. CubeBroker.launch provisions a PAID sandbox,
- // and the prompt was only checked afterwards — so a whitespace/newline
- // prompt bought a cube, then ChatView.send refused to send it, leaving a
- // billed session with an empty transcript titled "Cloud session" (#315).
- let trimmed = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else {
- phase = .compose
- return
- }
- do {
- let conn = try await CubeBroker.launch(purpose: "graff-ios") { msg in steps.append(msg) }
- let title = trimmed.count > 42 ? String(trimmed.prefix(42)) + "…" : trimmed
- let created = AgentSession(title: title.isEmpty ? "Cloud session" : title, model: "codegraff",
- status: .working, lastActivity: "now", todos: [], messages: [], cube: conn)
- session = created
- // #312: the sheet can go away in the gap between the cube coming up
- // and this line. The cube is real and already billed, so hand it to
- // the Sessions list instead of orphaning it — rollback only covers
- // launches cancellation actually caught in flight.
- guard !abandoned else {
- if !handedOff { handedOff = true; onCreated(created) }
- return
- }
- phase = .chat
- } catch {
- // A cancelled launch is not a failure — the sheet is already gone,
- // and CubeBroker has stopped whatever it brought up (#312).
- if !Task.isCancelled { 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)
- } else {
- // #312: leaving mid-provisioning used to bill a cube into the void.
- // Cancelling lets CubeBroker unwind and stop what it brought up.
- abandoned = true
- launchTask?.cancel()
- launchTask = nil
- }
- 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() }
- }
-
- // Pure-logic leg: the token-expiry rule that decides whether a running cube
- // may be reused as-is (#314). No network and no key, so it runs on every
- // autotest launch — the closest thing this app has to a unit test.
- @MainActor
- private func checkTokenExpiry() {
- let now = Date()
- func conn(_ login: String?, _ expiry: Date?) -> CubeConnection {
- CubeConnection(sandboxID: "s", base: "b", serveToken: "t", previewToken: nil,
- githubLogin: login, githubTokenExpiry: expiry)
- }
- var ok = conn("octo", now.addingTimeInterval(3600)).githubNeedsRefresh(asOf: now) == false
- ok = ok && conn("octo", now.addingTimeInterval(-60)).githubNeedsRefresh(asOf: now)
- ok = ok && conn("octo", now.addingTimeInterval(120)).githubNeedsRefresh(asOf: now)
- ok = ok && conn("octo", nil).githubNeedsRefresh(asOf: now) // stored before #314
- ok = ok && conn(nil, nil).githubNeedsRefresh(asOf: now) == false // no repo access to refresh
- // A connection stored before #314 still has to decode, expiry-less.
- let legacy = #"{"sandboxID":"s","base":"b","serveToken":"t","githubLogin":"octo"}"#
- let old = try? JSONDecoder().decode(CubeConnection.self, from: Data(legacy.utf8))
- ok = ok && old?.githubNeedsRefresh(asOf: now) == true
- // ...and the expiry has to survive the Keychain round-trip.
- let rt = (try? JSONEncoder().encode(conn("octo", now.addingTimeInterval(3600))))
- .flatMap { try? JSONDecoder().decode(CubeConnection.self, from: $0) }
- ok = ok && rt?.githubNeedsRefresh(asOf: now) == false
- // The mint-token wire hands the expiry over as an ISO-8601 stamp.
- let iso = "2026-07-31T12:00:00Z"
- let parsed = MintedGitHub(token: "x", expires_at: iso, account_login: "octo").expiry
- ok = ok && ISO8601DateFormatter().date(from: iso)
- .map { abs(parsed.timeIntervalSince($0)) < 0.5 } == true
- lines.append(ok ? "CUBE-TOKEN-EXPIRY-PASS" : "CUBE-TOKEN-EXPIRY-FAIL")
- }
-
- @MainActor
- private func run() async {
- checkTokenExpiry()
- 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.swift
deleted file mode 100644
index adf52715..00000000
--- a/apps/ios/Graff/Sources/SessionsListView.swift
+++ /dev/null
@@ -1,220 +0,0 @@
-import SwiftUI
-
-struct SessionsListView: View {
- // #316: this list only ever holds the signed-in account's real history.
- // It used to open on `sampleSessions` when signed out — fabricated rows
- // with realistic titles, models, progress and timestamps, and nothing
- // marking them as examples, so a fresh install looked like it had
- // retained someone's account data. Signed out now means an empty list and
- // a sign-in call to action; the fixtures stay behind `--autotest`.
- @State private var sessions: [AgentSession] = []
- @State private var signedIn = Gateway.apiKey != nil
- @State private var showAccount = false
- @State private var showNewSession = false
- @State private var loadNote = ""
- @State private var needsSessionRelogin = false
-
- var body: some View {
- NavigationStack {
- List {
- if !signedIn {
- VStack(alignment: .leading, spacing: 10) {
- Text("You're not signed in").font(.headline)
- Text("Sign in with your codegraff account to see your sessions here. Nothing is shown until then — this list only ever contains your own history.")
- .font(.footnote).foregroundStyle(.secondary)
- Button("Sign in") { showAccount = true }
- .buttonStyle(.borderedProminent)
- }
- .padding(.vertical, 6)
- }
- if !loadNote.isEmpty {
- VStack(alignment: .leading, spacing: 10) {
- Text(loadNote).font(.footnote).foregroundStyle(.secondary)
- if needsSessionRelogin {
- Button("Sign in again") {
- Gateway.signOut()
- sessions = []
- signedIn = false
- showAccount = true
- }
- .buttonStyle(.borderedProminent)
- }
- }
- }
- 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)
- // #310: routed through the sync engine so the DELETE is
- // ordered against this session's in-flight saves and the id
- // is tombstoned — an older PUT can no longer resurrect it.
- for s in doomed { AppSessionSync.delete(s.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 {
- // #316: signed out is an honest empty state, not a fixture gallery.
- guard Gateway.apiKey != nil else {
- signedIn = false
- sessions = []
- loadNote = ""
- needsSessionRelogin = false
- return
- }
- signedIn = true
- do {
- let rows = try await Gateway.listAppSessions()
- // #286: a failed sandbox listing is not evidence that anything
- // finished. Keep it nil so rows fall back to what we already knew,
- // or to Unknown — never to a manufactured Done.
- var started: Set<String>? = nil
- var livenessNote = ""
- do {
- started = Set(try await Gateway.sandboxes().filter { $0.state == "started" }.map(\.id))
- } catch {
- livenessNote = "Sandbox state unavailable — cube status may be out of date."
- }
- // Outcomes already read from a transcript survive a reload; only
- // liveness-derived guesses are recomputed.
- let priorStatus = Dictionary(sessions.map { ($0.id, $0.status) },
- uniquingKeysWith: { first, _ in first })
- 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
- let prior = priorStatus[s.id]
- 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 = Self.rowStatus(prior: prior, sandbox: row.sandbox_id, started: started)
- return s
- }
- needsSessionRelogin = false
- let emptyNote = sessions.isEmpty ? "No sessions yet — tap + to build something." : ""
- loadNote = [emptyNote, livenessNote].filter { !$0.isEmpty }.joined(separator: "\n")
- } catch {
- if let gatewayError = error as? GatewayError,
- gatewayError.isInsufficientSessionScope {
- needsSessionRelogin = true
- loadNote = "This sign-in predates session sync. Sign in again to renew access."
- } else {
- needsSessionRelogin = false
- loadNote = error.localizedDescription
- }
- }
- }
-
- // #286: the whole liveness→status decision, kept pure so the invariant is
- // checkable in-process (--autotest-turnstate) without a network or a tap.
- //
- // * an outcome already read from the transcript always wins;
- // * `started == nil` means the sandbox listing FAILED — that is unknown,
- // never Done;
- // * a stopped/gone sandbox has only Ended: the gateway exposes no task
- // outcome on the sandbox (only a liveness `state`), so success must not
- // be inferred from a sandbox that is no longer running.
- static func rowStatus(prior: SessionStatus?, sandbox: String?, started: Set<String>?) -> SessionStatus {
- if let prior, prior.isTranscriptOutcome { return prior }
- guard let sandbox else { return prior ?? .idle }
- guard let started else { return prior ?? .unknown }
- return started.contains(sandbox) ? .idle : .ended
- }
-
- 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.sh
deleted file mode 100755
index 88105036..00000000
--- a/apps/ios/autotest.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/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-lib.sh # #407: UDID + boot-state aware cleanup trap (KEEP=1 / SIM_GUI=1)
-sim_boot
-xcrun simctl terminate "$sim_udid" "$BUNDLE" 2>/dev/null || true
-xcrun simctl launch "$sim_udid" "$BUNDLE" --autotest
-sleep 16
-xcrun simctl io "$sim_udid" 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.sh
deleted file mode 100755
index 8a9cd4ae..00000000
--- a/apps/ios/build-sim.sh
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/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
-. ./sim-lib.sh # #407: UDID + boot-state aware cleanup trap (KEEP=1 / SIM_GUI=1)
-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"
-sim_boot
-
-echo "==> installing + launching"
-xcrun simctl install "$sim_udid" "$OUT"
-xcrun simctl launch "$sim_udid" "$BUNDLE" || true
-sleep 4
-xcrun simctl io "$sim_udid" screenshot build/launch.png >/dev/null 2>&1 || true
-echo "==> done — screenshot: $(pwd)/build/launch.png"
diff --git a/apps/ios/build/Graff.app/Graff b/apps/ios/build/Graff.app/Graff
deleted file mode 100755
index e4befc1d..00000000
Binary files a/apps/ios/build/Graff.app/Graff and /dev/null differ
diff --git a/apps/ios/build/Graff.app/Info.plist b/apps/ios/build/Graff.app/Info.plist
deleted file mode 100644
index c6a05101..00000000
--- a/apps/ios/build/Graff.app/Info.plist
+++ /dev/null
@@ -1,28 +0,0 @@
-<?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/build/launch.png b/apps/ios/build/launch.png
deleted file mode 100644
index ba324d2e..00000000
Binary files a/apps/ios/build/launch.png and /dev/null differ
diff --git a/apps/ios/project.yml b/apps/ios/project.yml
deleted file mode 100644
index 18e571ef..00000000
--- a/apps/ios/project.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-# 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.sh
deleted file mode 100755
index 77f6fc93..00000000
--- a/apps/ios/recap.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash
-# Relaunch --autotest and capture the in-flight typing indicator + the reply.
-set -euo pipefail
-cd "$(dirname "$0")"
-. ./sim-lib.sh # #407: UDID + boot-state aware cleanup trap (KEEP=1 / SIM_GUI=1)
-sim_boot
-xcrun simctl terminate "$sim_udid" "$BUNDLE" 2>/dev/null || true
-xcrun simctl launch "$sim_udid" "$BUNDLE" --autotest
-sleep 5; xcrun simctl io "$sim_udid" screenshot build/cap_typing.png >/dev/null 2>&1 || true
-sleep 3; xcrun simctl io "$sim_udid" screenshot build/cap_mid.png >/dev/null 2>&1 || true
-sleep 8; xcrun simctl io "$sim_udid" screenshot build/cap_reply.png >/dev/null 2>&1 || true
-echo "captured: cap_typing.png cap_mid.png cap_reply.png"
diff --git a/apps/ios/sim-lib.sh b/apps/ios/sim-lib.sh
deleted file mode 100755
index b1c6e0bc..00000000
--- a/apps/ios/sim-lib.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/bin/bash
-# Shared simulator lifecycle (#407). Source this after (optionally) setting
-# SIM/BUNDLE. It resolves $SIM to a UDID once, boots only when needed, and
-# a trap tears down what this run started: the launched app always, the
-# device only if this run booted it. A pre-booted device is left alone.
-# KEEP=1 keep app + device running on exit (interactive debugging)
-# SIM_GUI=1 open the Simulator window — headless is the default; simctl
-# install/launch/io screenshot all work without the GUI.
-
-SIM="${SIM:-iPhone 17 Pro}"
-BUNDLE="${BUNDLE:-com.codegraff.graff}"
-
-sim_udid="$(xcrun simctl list devices available | awk -v n="$SIM" -F '[()]' 'index($0, n" (") {print $2; exit}')"
-[ -n "$sim_udid" ] || { echo "no available simulator named '$SIM'" >&2; exit 1; }
-
-sim_booted_by_us=0
-sim_cleanup() {
- [ "${KEEP:-0}" = 1 ] && return 0
- xcrun simctl terminate "$sim_udid" "$BUNDLE" 2>/dev/null || true
- [ "$sim_booted_by_us" = 1 ] && xcrun simctl shutdown "$sim_udid" 2>/dev/null || true
-}
-trap sim_cleanup EXIT INT TERM
-
-sim_boot() {
- xcrun simctl list devices | grep "$sim_udid" | grep -q '(Booted)' && return 0
- xcrun simctl boot "$sim_udid"
- sim_booted_by_us=1
- [ "${SIM_GUI:-0}" = 1 ] && open -a Simulator >/dev/null 2>&1 || true
-}
diff --git a/docs/yxlyx-leftovers.md b/docs/yxlyx-leftovers.md
index ddc9b6d2..faf4d0cb 100644
--- a/docs/yxlyx-leftovers.md
+++ b/docs/yxlyx-leftovers.md
@@ -16,7 +16,7 @@ of the same head and is closed as duplicate), `#679` MCP TLS reuse
| [#217](https://github.com/justrach/codegraff/issues/217) governed run budget | `src/run_budget.zig`: invocation-wide `--max-model-calls` (default unlimited), concurrency 8, depth 1. Charged across root / children / title / judges / compaction. Exhaustion is a structured stop, not a model plea. `--max-tool-calls` is still root-only. | Partial. **Parked:** finite defaults for `/goal`/`/loop`, wall-time, token, and USD ceilings, descendant tool accounting, slash widening-with-approval. |
| [#220](https://github.com/justrach/codegraff/issues/220) protected verifiers | `--eval` / `--until` scores a command the agent can invoke. ADR [0008](adr/0008-synthetic-evals-use-external-verifiers.md) is the eval-suite rule, not a `/goal` acceptance contract. | **Parked.** Independent verifier stages and hidden tests are a new controller, not a docs tweak. |
| [#306](https://github.com/justrach/codegraff/issues/306) review runaway | Same budget knobs as #217. `/review` is one isolated pass (catalog). No review-specific cycle cap or "confirm before implementing" gate. | **Parked** on the #217 remainder. |
-| [#283](https://github.com/justrach/codegraff/issues/283) cube NDJSON buffer | `graff serve` already emits NDJSON as events happen. The failure is Daytona preview buffering the response and iOS `URLSession` idling out. `graff cube` / `src/cube.zig` is the sandbox+serve CLI. | **Parked** (ingress + iOS client). Not a new harness mode. |
+| [#283](https://github.com/justrach/codegraff/issues/283) cube NDJSON buffer | `graff serve` already emits NDJSON as events happen. The failure is Daytona preview buffering the response and iOS `URLSession` idling out. `graff cube` / `src/cube.zig` is the sandbox+serve CLI. | **Closed, not planned** (the in-repo iOS app was removed). |
| [#199](https://github.com/justrach/codegraff/issues/199) idle localhost servers | No `graff processes` / idle supervisor. Jobs exist for tool-started bash; they do not pause forgotten `next dev` trees. PR #200 closed as abandoned vs tip. | **Parked.** Do not start a process-supervisor product on this branch. |
| [#106](https://github.com/justrach/codegraff/issues/106) representative Ultracode sims | Unit suite + `TUI/sim.zig` Term + tier-2 harness cases. Not a multi-turn human Ultracode drama. | **Parked** (eval/tier-2 work, not 279 continuation). |
diff --git a/scripts/e2e-cube-serve.py b/scripts/e2e-cube-serve.py
index c8ffbbf3..0f0f428e 100755
--- a/scripts/e2e-cube-serve.py
+++ b/scripts/e2e-cube-serve.py
@@ -1,12 +1,12 @@
#!/usr/bin/env python3
"""Cube transport proof: run `graff serve` inside a Daytona sandbox (via the
codegraff gateway) and stream a real agent turn from this Mac through the
-Daytona preview URL — the exact pipe the iOS app will use.
+Daytona preview URL — the pipe a remote client uses.
Steps: create sandbox -> install graff -> start serve (async exec, detached)
-> mint preview URL -> create session + stream one NDJSON turn from outside
-> report cost meter. Leaves the sandbox running (autoStop reaps it) so a
-client (e.g. the iOS app via GRAFF_SERVE_BASE/GRAFF_SERVE_TOKEN) can reuse
+client (via GRAFF_SERVE_BASE/GRAFF_SERVE_TOKEN) can reuse
it via .graff/cube-state.json. Run from the repo root:
python3 scripts/e2e-cube-serve.py