Repository navigation
Populate workspace todos from Claude's TaskCreate/TaskUpdate calls #9475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
6067028
ad73eaf
5c18a43
4e61c29
1d0c06a
86d8e26
07b8a65
dc04fd7
d0db71a
7995a11
e003e1c
a4594a1
6c1143d
14b2c2b
b78f7ab
9ebd6b0
9ea7999
58a1a93
a928107
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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
Suggested change
🤖 Prompt for AI AgentsSource: Path instructions |
||||||||||||||||||||||
| return todos | ||||||||||||||||||||||
|
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 | ||||||||||||||||||||||
| ) | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
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) | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
Uh oh!
There was an error while loading. Please reload this page.