Skip to content

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

Python

fix(ios): stop labelling failed sessions Done from sandbox liveness (#286)

justrachb0cb12494432
diff --git a/apps/ios/Graff/Sources/ChatView.swift b/apps/ios/Graff/Sources/ChatView.swift
index 0ff00cc5..c12521cf 100644
--- a/apps/ios/Graff/Sources/ChatView.swift
+++ b/apps/ios/Graff/Sources/ChatView.swift
@@ -193,7 +193,15 @@ struct ChatView: View {
case .cancelled: announce("Turn stopped.")
case .completed, .streaming: announce("Assistant finished responding.")
}
- session.status = .idle
+ // #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)
}
@@ -213,6 +221,13 @@ struct ChatView: View {
: []
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
+ }
}
}
diff --git a/apps/ios/Graff/Sources/GraffAccount.swift b/apps/ios/Graff/Sources/GraffAccount.swift
index a53ac7be..9c969121 100644
--- a/apps/ios/Graff/Sources/GraffAccount.swift
+++ b/apps/ios/Graff/Sources/GraffAccount.swift
@@ -273,12 +273,44 @@ 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 { MessageDTO(role: $0.role == .user ? "user" : "assistant",
- text: $0.text, reasoning: $0.reasoning) }
+ 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) ?? "[]"
}
@@ -287,7 +319,24 @@ enum AppSessionSync {
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) }
+ 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
+ }
}
// Fire-and-forget: history sync must never block or break the chat.
diff --git a/apps/ios/Graff/Sources/GraffApp.swift b/apps/ios/Graff/Sources/GraffApp.swift
index 3b0f00e1..bb2cff71 100644
--- a/apps/ios/Graff/Sources/GraffApp.swift
+++ b/apps/ios/Graff/Sources/GraffApp.swift
@@ -120,6 +120,42 @@ struct TurnStateCheckView: View {
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)
@@ -198,14 +234,27 @@ struct TodoItem: Identifiable {
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
+ 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 {
@@ -214,6 +263,9 @@ enum SessionStatus: String {
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 {
@@ -222,6 +274,9 @@ enum SessionStatus: String {
case .waiting: return .orange
case .idle: return .secondary
case .done: return .green
+ case .ended: return .secondary
+ case .failed: return .red
+ case .unknown: return .secondary
}
}
}
diff --git a/apps/ios/Graff/Sources/SessionsListView.swift b/apps/ios/Graff/Sources/SessionsListView.swift
index fc5a6a90..c7924cc2 100644
--- a/apps/ios/Graff/Sources/SessionsListView.swift
+++ b/apps/ios/Graff/Sources/SessionsListView.swift
@@ -72,8 +72,20 @@ struct SessionsListView: View {
guard Gateway.apiKey != nil else { return }
do {
let rows = try await Gateway.listAppSessions()
- let live = (try? await Gateway.sandboxes()) ?? []
- let started = Set(live.filter { $0.state == "started" }.map(\.id))
+ // #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,
@@ -83,6 +95,7 @@ struct SessionsListView: View {
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
@@ -92,12 +105,13 @@ struct SessionsListView: View {
s.cube = CubeConnection(sandboxID: sb, base: "", serveToken: "",
previewToken: nil, githubLogin: nil)
}
- s.status = started.contains(sb) ? .idle : .done
}
+ s.status = Self.rowStatus(prior: prior, sandbox: row.sandbox_id, started: started)
return s
}
needsSessionRelogin = false
- loadNote = sessions.isEmpty ? "No sessions yet — tap + to build something." : ""
+ 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 {
@@ -110,6 +124,22 @@ struct SessionsListView: View {
}
}
+ // #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