Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6067028
Add failing coverage for Claude TaskCreate/TaskUpdate todo ingestion
austinywang Aug 3, 2026
ad73eaf
Populate workspace todos from Claude's TaskCreate/TaskUpdate calls
austinywang Aug 3, 2026
5c18a43
Address review: authoritative task ids, per-workstream row ownership,…
austinywang Aug 3, 2026
4e61c29
Retire the provisional checklist row when a task adopts its real id
austinywang Aug 3, 2026
1d0c06a
Address review feedback: unknown statuses, ordering docs, resume cove…
austinywang Aug 3, 2026
86d8e26
Claim a task id only when the update actually keeps a row
austinywang Aug 3, 2026
07b8a65
Drive the checklist from completed task calls, not pre-execution intent
austinywang Aug 3, 2026
dc04fd7
Keep ownership across resumable sessions; fix empty snapshots and det…
austinywang Aug 3, 2026
d0db71a
Persist each agent checklist row's owning task so ownership survives …
austinywang Aug 4, 2026
7995a11
Harden whole-list todo snapshots: stable ids, cancelled tasks, parse …
austinywang Aug 4, 2026
e003e1c
Order task deltas and keep duplicate id-less entries distinct
austinywang Aug 4, 2026
a4594a1
Reject self-reported task failures and protect whole-list snapshots
austinywang Aug 4, 2026
6c1143d
Keep id-less task identity across a reword; bound seeded workstreams
austinywang Aug 4, 2026
14b2c2b
Re-home task events to the surface's current workspace; recover id-le…
austinywang Aug 4, 2026
b78f7ab
Fail closed on id-less reidentification; retire rows in a workspace l…
austinywang Aug 4, 2026
9ebd6b0
Acknowledge task deltas, re-home them for real, and retire rows from …
austinywang Aug 4, 2026
9ea7999
Widen retirement and recovery to every window; validate the push ackn…
austinywang Aug 4, 2026
58a1a93
Reject stale concurrent TaskUpdates that would un-complete a task
austinywang Aug 4, 2026
a928107
Skip the retirement sweep when the workstream has not moved
austinywang Aug 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public final class WorkstreamStore {
/// carries forward prompt/preamble context from nearby telemetry rows.
private var lastContextByWorkstream: [String: WorkstreamContext] = [:]

/// Running task list per workstream, accumulated from the agent's
/// per-task tool calls (`TaskCreate` / `TaskUpdate`), which report one
/// task at a time rather than the whole list.
private var taskToolTodosByWorkstream: [String: WorkstreamTaskToolTodos] = [:]

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/// Creates a store for Feed workstream items.
///
/// - Parameters:
Expand Down Expand Up @@ -308,7 +313,19 @@ public final class WorkstreamStore {
)
)
case .preToolUse:
return (.toolUse, .toolUse(toolName: event.toolName ?? "", toolInputJSON: toolInput))
let toolName = event.toolName ?? ""
// Claude's task tools (and the legacy whole-list TodoWrite) reach
// us as ordinary PreToolUse calls; fold them into the workstream's
// running checklist instead of anonymous tool telemetry.
if WorkstreamTaskToolTodos.handles(toolName: toolName) {
var accumulator = taskToolTodosByWorkstream[event.sessionId] ?? WorkstreamTaskToolTodos()
let todos = accumulator.apply(toolName: toolName, toolInputJSON: event.toolInputJSON)
taskToolTodosByWorkstream[event.sessionId] = accumulator
if let todos {
return (.todos, .todos(todos))
}
}
return (.toolUse, .toolUse(toolName: toolName, toolInputJSON: toolInput))
case .postToolUse:
return (
.toolResult,
Expand Down Expand Up @@ -341,7 +358,9 @@ public final class WorkstreamStore {
case .stop:
return (.stop, .stop(reason: Self.stopReason(from: event.toolInputJSON)))
case .todoWrite:
return (.todos, .todos(Self.todos(from: event.toolInputJSON)))
let todos = WorkstreamTaskToolTodos.parseTodoWriteList(event.toolInputJSON)
taskToolTodosByWorkstream[event.sessionId] = nil
return (.todos, .todos(todos))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
case .notification:
return (.toolResult, .toolResult(toolName: "notification", resultJSON: toolInput, isError: false))
}
Expand Down Expand Up @@ -489,38 +508,4 @@ public final class WorkstreamStore {
}
return nil
}

private static func todos(from json: String?) -> [WorkstreamTaskTodo] {
let rawTodos: [Any]
if let dict = jsonObject(from: json) as? [String: Any] {
rawTodos = dict["todos"] as? [Any] ?? []
} else {
rawTodos = jsonObject(from: json) as? [Any] ?? []
}
return rawTodos.enumerated().compactMap { idx, raw in
guard let dict = raw as? [String: Any] else { return nil }
let content = (dict["content"] as? String)
?? (dict["text"] as? String)
?? (dict["title"] as? String)
?? ""
guard !content.isEmpty else { return nil }
let rawState = (dict["state"] as? String)
?? (dict["status"] as? String)
?? "pending"
let state: WorkstreamTaskTodo.State
switch rawState {
case "completed", "done":
state = .completed
case "inProgress", "in_progress", "active":
state = .inProgress
default:
state = .pending
}
return WorkstreamTaskTodo(
id: (dict["id"] as? String) ?? "todo\(idx)",
content: content,
state: state
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import Foundation
#if canImport(CryptoKit)
import CryptoKit
#endif

/// Accumulates one workstream's task list from the agent's task-tool calls.
///
/// Claude Code drives its plan through `TaskCreate` / `TaskUpdate`, which
/// mutate **one** task per call and report only that task in the hook payload
/// (older Claude versions, and several other agents, send the whole list in a
/// single `TodoWrite` call instead). The cmux wrapper injects `PreToolUse`
/// with matcher `""`, so every such call reaches us — but only as a delta, so
/// the list has to be carried across events rather than parsed from one
/// payload. See https://github.com/manaflow-ai/cmux/issues/8960.
///
/// `TaskCreate` runs *before* the tool executes, so the payload has no task
/// id yet. Claude numbers tasks sequentially from `"1"` per session, so a
/// created task takes the next id above every id seen so far; a later
/// `TaskUpdate` names its `taskId` explicitly and lines up with it.
public struct WorkstreamTaskToolTodos: Sendable {
/// Tool names this accumulator understands. Anything else is left to the
/// generic tool-use telemetry path.
public static func handles(toolName: String) -> Bool {
switch toolName {
case "TodoWrite", "TaskCreate", "TaskUpdate": return true
default: return false
}
}

private var todos: [WorkstreamTaskTodo] = []
private var nextSyntheticId = 1

/// Applies one task-tool call.
///
/// - Returns: The full accumulated list, or `nil` when the payload
/// carried nothing usable (so the caller can fall back to plain
/// tool-use telemetry rather than publishing an empty checklist).
mutating func apply(toolName: String, toolInputJSON: String?) -> [WorkstreamTaskTodo]? {
let input = Self.object(from: toolInputJSON)
switch toolName {
case "TodoWrite":
let parsed = Self.parseTodoWriteList(toolInputJSON)
guard !parsed.isEmpty else { return nil }
todos = parsed
for todo in parsed { reserve(id: todo.id) }
return todos
case "TaskCreate":
guard let input, let content = Self.content(in: input) else { return nil }
let id = Self.taskId(in: input) ?? mintId()
reserve(id: id)
let state = Self.state(in: input) ?? .pending
if let index = todos.firstIndex(where: { $0.id == id }) {
todos[index] = WorkstreamTaskTodo(id: id, content: content, state: state)
} else {
todos.append(WorkstreamTaskTodo(id: id, content: content, state: state))
}
Comment on lines +131 to +133

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Fail closed when request and response task IDs conflict.

Line 107 selects the request ID before the completed response ID. If the IDs differ, the code can apply response content or a deletion to the request task instead of the task returned by PostToolUse.

When both IDs exist, require them to match. Otherwise, use the response ID when available. Add a regression test for conflicting IDs.

Proposed fix
-            guard let id = input.flatMap(taskId(in:)) ?? resultTask.flatMap(taskId(in:)) else {
+            let inputID = input.flatMap(taskId(in:))
+            let resultID = resultTask.flatMap(taskId(in:))
+            guard inputID == nil || resultID == nil || inputID == resultID,
+                  let id = resultID ?? inputID
+            else {
                 return .ignored
             }

As per path instructions: use authoritative structured signals as the single source of truth and fail closed when they disagree.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
guard let id = input.flatMap(taskId(in:)) ?? resultTask.flatMap(taskId(in:)) else {
return .ignored
}
let inputID = input.flatMap(taskId(in:))
let resultID = resultTask.flatMap(taskId(in:))
guard inputID == nil || resultID == nil || inputID == resultID,
let id = resultID ?? inputID
else {
return .ignored
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/Workstream/WorkstreamTaskToolTodos.swift`
around lines 107 - 109, Update the task ID selection in WorkstreamTaskToolTodos
so that when both input and result IDs are present they must match, returning
.ignored on conflict; otherwise prefer the available response/result ID and fall
back to the request/input ID. Add a regression test covering conflicting IDs and
confirming no task mutation occurs.

Source: Path instructions

return todos
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
case "TaskUpdate":
guard let input, let id = Self.taskId(in: input) else { return nil }
reserve(id: id)
let rawStatus = Self.rawStatus(in: input)
if rawStatus == "deleted" || rawStatus == "removed" {
todos.removeAll { $0.id == id }
// An empty list is a real state here (the agent dropped its
// last task), but publishing it would blank a checklist that
// still has user items in it, so report nothing to apply.
return todos.isEmpty ? nil : todos
}
guard let index = todos.firstIndex(where: { $0.id == id }) else {
// Update for a task we never saw created (resumed session,
// hook installed mid-run). Only adoptable when the payload
// also carries text to show.
guard let content = Self.content(in: input) else { return nil }
todos.append(WorkstreamTaskTodo(
id: id,
content: content,
state: Self.state(in: input) ?? .pending
))
return todos
}
todos[index] = WorkstreamTaskTodo(
id: id,
content: Self.content(in: input) ?? todos[index].content,
state: Self.state(in: input) ?? todos[index].state
)
return todos
default:
return nil
}
}

private mutating func mintId() -> String {
let id = String(nextSyntheticId)
nextSyntheticId += 1
return id
}

/// Keeps the synthetic counter above every id the agent has named, so a
/// create following an explicitly-numbered task cannot collide with it.
private mutating func reserve(id: String) {
guard let numeric = Int(id), numeric >= nextSyntheticId else { return }
nextSyntheticId = numeric + 1
}

// MARK: - Payload parsing

private static func object(from json: String?) -> [String: Any]? {
guard let json, let data = json.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
}

private static func taskId(in dict: [String: Any]) -> String? {
for key in ["taskId", "task_id", "id"] {
if let value = dict[key] as? String, !value.isEmpty { return value }
if let value = dict[key] as? Int { return String(value) }
}
return nil
}

private static func content(in dict: [String: Any]) -> String? {
for key in ["subject", "content", "title", "text", "description"] {
if let value = dict[key] as? String {
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { return trimmed }
}
}
return nil
}

private static func rawStatus(in dict: [String: Any]) -> String? {
(dict["status"] as? String) ?? (dict["state"] as? String)
}

private static func state(in dict: [String: Any]) -> WorkstreamTaskTodo.State? {
guard let raw = rawStatus(in: dict) else { return nil }
return parseState(raw)
}

static func parseState(_ raw: String) -> WorkstreamTaskTodo.State {
switch raw {
case "completed", "done": return .completed
case "inProgress", "in_progress", "active": return .inProgress
default: return .pending
}
}

/// Parses the whole-list `TodoWrite` shape (`{"todos":[…]}` or a bare
/// array).
static func parseTodoWriteList(_ json: String?) -> [WorkstreamTaskTodo] {
guard let json, let data = json.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
else { return [] }
let raw: [Any]
if let dict = root as? [String: Any] {
raw = dict["todos"] as? [Any] ?? []
} else {
raw = root as? [Any] ?? []
}
return raw.enumerated().compactMap { idx, element in
guard let dict = element as? [String: Any],
let content = content(in: dict) else { return nil }
return WorkstreamTaskTodo(
id: taskId(in: dict) ?? "todo\(idx)",
content: content,
state: state(in: dict) ?? .pending
)
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

extension WorkstreamTaskTodo {
/// A stable checklist identity for this todo inside `workstreamId`.
///
/// Agent task ids are per-session counters (`"1"`, `"2"`, …) while the
/// workspace checklist is keyed by `UUID`, so the pair is hashed into a
/// deterministic UUID. Deriving it (instead of keeping a side table)
/// means the same task keeps its checklist row across app restarts and
/// across every entrypoint that syncs the list.
public func stableChecklistItemId(workstreamId: String) -> UUID {
Self.derivedUUID(from: "cmux.workstream.todo\u{0}\(workstreamId)\u{0}\(id)")
}

static func derivedUUID(from seed: String) -> UUID {
let data = Data(seed.utf8)
var bytes: [UInt8]
#if canImport(CryptoKit)
bytes = Array(SHA256.hash(data: data).prefix(16))
#else
bytes = Array(repeating: 0, count: 16)
for (index, byte) in data.enumerated() {
bytes[index % 16] = bytes[index % 16] &+ byte &+ UInt8(truncatingIfNeeded: index)
}
#endif
// RFC 4122 version 4 / variant bits so the value is a well-formed UUID.
bytes[6] = (bytes[6] & 0x0F) | 0x40
bytes[8] = (bytes[8] & 0x3F) | 0x80
return UUID(uuid: (
bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15]
))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import Foundation
import Testing
@testable import CMUXAgentLaunch

/// Regression coverage for https://github.com/manaflow-ai/cmux/issues/8960.
///
/// Claude Code no longer calls `TodoWrite`; it drives a task system through
/// `TaskCreate` / `TaskUpdate`, delivered to cmux as `PreToolUse` events with
/// matcher `""`. Those tools mutate one task per call, so the store has to
/// accumulate a list across events rather than expecting a whole list in one
/// payload.
@MainActor
@Suite("Workstream task-tool todos")
struct WorkstreamTaskToolTodoTests {
private func preToolUse(
_ sessionId: String,
tool: String,
input: String
) -> WorkstreamEvent {
WorkstreamEvent(
sessionId: sessionId,
hookEventName: .preToolUse,
source: "claude",
toolName: tool,
toolInputJSON: input
)
}

private func latestTodos(_ store: WorkstreamStore) -> [WorkstreamTaskTodo]? {
for item in store.items.reversed() {
if case .todos(let todos) = item.payload { return todos }
}
return nil
}

@Test("TaskCreate/TaskUpdate accumulate into a todo list")
func taskToolsAccumulate() {
let store = WorkstreamStore(ringCapacity: 50)
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"Read the code","description":"d"}"#))
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"Write the fix","description":"d"}"#))
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"Open a PR","description":"d"}"#))
store.ingest(preToolUse("s1", tool: "TaskUpdate", input: #"{"taskId":"1","status":"completed"}"#))
store.ingest(preToolUse("s1", tool: "TaskUpdate", input: #"{"taskId":"2","status":"in_progress"}"#))

guard let todos = latestTodos(store) else {
Issue.record("expected a todos payload from the task tools")
return
}
#expect(todos.map(\.id) == ["1", "2", "3"])
#expect(todos.map(\.content) == ["Read the code", "Write the fix", "Open a PR"])
#expect(todos.map(\.state) == [.completed, .inProgress, .pending])
}

@Test("TaskUpdate status deleted removes the item")
func taskUpdateDeleteRemoves() {
let store = WorkstreamStore(ringCapacity: 50)
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"keep"}"#))
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"drop"}"#))
store.ingest(preToolUse("s1", tool: "TaskUpdate", input: #"{"taskId":"2","status":"deleted"}"#))

#expect(latestTodos(store)?.map(\.content) == ["keep"])
}

@Test("Task lists stay separate per workstream")
func taskListsArePerSession() {
let store = WorkstreamStore(ringCapacity: 50)
store.ingest(preToolUse("s1", tool: "TaskCreate", input: #"{"subject":"one"}"#))
store.ingest(preToolUse("s2", tool: "TaskCreate", input: #"{"subject":"two"}"#))

let s1 = store.items.last(where: { $0.workstreamId == "s1" })
let s2 = store.items.last(where: { $0.workstreamId == "s2" })
if case .todos(let todos) = s1?.payload {
#expect(todos.map(\.content) == ["one"])
} else {
Issue.record("expected todos for s1")
}
if case .todos(let todos) = s2?.payload {
#expect(todos.map(\.content) == ["two"])
} else {
Issue.record("expected todos for s2")
}
}

@Test("TodoWrite arriving as a PreToolUse tool name still fills the list")
func todoWriteAsToolName() {
let store = WorkstreamStore(ringCapacity: 50)
store.ingest(preToolUse(
"s1",
tool: "TodoWrite",
input: #"{"todos":[{"id":"a","content":"first","status":"in_progress"},{"id":"b","content":"second","status":"pending"}]}"#
))

#expect(latestTodos(store)?.map(\.content) == ["first", "second"])
#expect(latestTodos(store)?.first?.state == .inProgress)
}

@Test("Non-task PreToolUse events stay tool-use telemetry")
func otherToolsUnaffected() {
let store = WorkstreamStore(ringCapacity: 50)
store.ingest(preToolUse("s1", tool: "Bash", input: #"{"command":"echo hi"}"#))
#expect(store.items.last?.kind == .toolUse)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading