From ce7b58fa0574adf0936435da84206ff1ec18edf6 Mon Sep 17 00:00:00 2001 From: Dawid Buszta <344369893+MF-DEEV@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:14:19 +0200 Subject: [PATCH] fix(sessions): subagents sent to the background are not done Claude Code ends the turn that sends subagents to the background, with its Stop hook, but its registry stays "busy" until they finish. The island took the end for the last word and showed the session idle, with a notice that it finished, while Claude waited for them. A subagent launched in the background is now followed like a command left running there, from its launch to the notice of its end, and keeps the session In background, named by what it does, while the registry says busy. The Stop hook reads the session's latest lines first, so an agent sent off just before it is seen. A background command refused before it ran no longer counts as running. --- .../ClaudeSessions/ClaudeSessionEngine.swift | 20 +++--- .../ClaudeSessions/ClaudeSessionModels.swift | 11 +-- .../ClaudeSessions/ClaudeSessionService.swift | 6 ++ .../ClaudeTranscriptReader.swift | 11 ++- Tests/ClaudeSessionEngineTests.swift | 67 +++++++++++++++++++ Tests/ClaudeSessionReaderTests.swift | 12 ++++ docs/claude-sessions-spike.md | 1 + 7 files changed, 114 insertions(+), 14 deletions(-) diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift index 4a20cbc4d..e1fe9699a 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift @@ -36,7 +36,8 @@ final class ClaudeSessionEngine { /// Subagents reported done before anything else was known of them; /// the end applies once they are. var endedAgents: [String: Date] = [:] - /// Commands left running in the background, by the call that started them. + /// Commands and subagents left running in the background, by the call + /// that started them. var background: [String: Background] = [:] var tasks: ClaudeTaskProgress? var usage: [String: (tokens: AgentTokens, cost: Double)] = [:] @@ -242,11 +243,12 @@ final class ClaudeSessionEngine { // Claude Code says "shell" for a session at rest with a command of its // own still running in the background. The work is not done while one // it waits for runs; a dev server or an emulator left running is not - // work, and when nothing was seen start, it counts as work. - if record.status == .shell { - let running = entry.runningBackground - if running.isEmpty || running.contains(where: { !$0.service }) { return .background } - } + // work, and when nothing was seen start, it counts as work. While a + // subagent it sent to the background works, it says "busy" though + // the turn ended. + let running = entry.runningBackground + if record.status == .shell, running.isEmpty || running.contains(where: { !$0.service }) { return .background } + if record.status == .busy, running.contains(where: { !$0.service && $0.task != nil }) { return .background } if let ended = entry.turnEnded, entry.completed, now.timeIntervalSince(ended) < finishedFor, (entry.acknowledged ?? .distantPast) < ended { return .finished @@ -288,7 +290,7 @@ final class ClaudeSessionEngine { title: previews ? entry.title : nil, lastText: previews ? entry.lastText : nil, hooked: entry.hooked, chat: previews ? entry.chat : [], backgroundLabel: previews ? entry.runningBackground.last { !$0.service }?.label : nil, - services: record.status == .shell ? entry.runningBackground.filter(\.service).count : 0) + services: record.status == .shell || phase == .background ? entry.runningBackground.filter(\.service).count : 0) } // MARK: Rules @@ -359,7 +361,7 @@ final class ClaudeSessionEngine { /// The notice and the registry's change are written apart. static let askedSlack: TimeInterval = 5 - /// Background commands kept per session, the ended ones going first. + /// Background commands and subagents kept per session, the ended ones going first. static let backgroundKept = 40 /// The conversation keeps its latest messages. @@ -504,6 +506,8 @@ final class ClaudeSessionEngine { } // The tool that asked ran or was refused, here or in the terminal. entry.permissions.removeAll { $0.toolID == id } + // A background command refused before it ran got no id and never ends. + if failed, let job = entry.background[id], job.task == nil, job.ended == nil { entry.background[id]?.ended = date } touch(date, in: &entry) } diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift index 61260377b..969fa88e8 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift @@ -14,8 +14,8 @@ enum ClaudeSessionPhase: String, Equatable { case waitingPermission /// A question, dialog or other prompt waits for the person. case waitingInput - /// The turn ended but a command it started, like a render, still runs - /// in the background; Claude Code hears when it ends. + /// The turn ended but a command it started, like a render, or a subagent + /// it sent off still runs in the background; Claude Code hears when it ends. case background /// The turn ended and the person has not looked at it yet. case finished @@ -322,10 +322,11 @@ enum ClaudeTranscriptFact: Equatable { case usage(key: String, tokens: AgentTokens, cost: Double) case subagentActivity(id: String, at: Date) case subagentEnded(id: String, at: Date) - /// A command the model left running in the background; a service, like - /// a dev server or an emulator, is meant to keep running. + /// A command the model left running in the background, or a subagent it + /// sent there; a service, like a dev server or an emulator, is meant to + /// keep running. case backgroundStarted(toolID: String, service: Bool, label: String?, at: Date) - /// The id Claude Code gave that command, which its end notice names. + /// The id Claude Code gave that command or subagent, which its end notice names. case backgroundTask(toolID: String, task: String) case subagentInfo(id: String, type: String, description: String?) case tasks(ClaudeTaskProgress) diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift index 446148780..9d5e5751b 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift @@ -322,6 +322,12 @@ final class ClaudeSessionService: ObservableObject { } else { connection.finish() } + // A turn's lines are written before its Stop hook runs; reading them + // first tells whether it left work in the background, before a notice + // calls it done. + if case .stopped = message.fact.event, let path = transcripts[message.fact.sessionID] { + read(path, session: message.fact.sessionID, now: now) + } engine.ingest(hook: message.fact, now: now) publish(now: now) } diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeTranscriptReader.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeTranscriptReader.swift index 8ad6e2de0..d767e34b2 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeTranscriptReader.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeTranscriptReader.swift @@ -107,9 +107,18 @@ struct ClaudeTranscriptReader { for result in results { guard let id = result["tool_use_id"] as? String else { continue } facts.append(.toolFinished(id: id, at: date, failed: result["is_error"] as? Bool == true)) - if let task = (json["toolUseResult"] as? [String: Any])?["backgroundTaskId"] as? String, !task.isEmpty { + let outcome = json["toolUseResult"] as? [String: Any] + if let task = outcome?["backgroundTaskId"] as? String, !task.isEmpty { facts.append(.backgroundTask(toolID: id, task: task)) } + // A subagent sent to the background answers at once with + // its id; Claude waits for it as for a render. + if outcome?["isAsync"] as? Bool == true || outcome?["status"] as? String == "async_launched", + let agent = outcome?["agentId"] as? String, !agent.isEmpty { + let label = policy.previews ? preview(outcome?["description"] as? String) : nil + facts.append(.backgroundStarted(toolID: id, service: false, label: label, at: date)) + facts.append(.backgroundTask(toolID: id, task: agent)) + } } if json["toolEndsTurn"] as? Bool == true { facts.append(.turnEnded(date, completed: true)) } break diff --git a/Tests/ClaudeSessionEngineTests.swift b/Tests/ClaudeSessionEngineTests.swift index 1864b6a7f..c0f58679c 100644 --- a/Tests/ClaudeSessionEngineTests.swift +++ b/Tests/ClaudeSessionEngineTests.swift @@ -159,6 +159,73 @@ enum ClaudeSessionEngineTests { "work it waits for keeps it in the background, saying what") services.ingest(sessionID: "s1", facts: [.subagentEnded(id: "b3", at: at(9))], now: at(9)) suite.expect(only(services, 10)?.phase != .background, "once that work ends, the services alone do not hold it there") + // Claude Code stays "busy" while subagents it sent to the background + // work, and the turn that sent them still ends with its Stop hook. + let explore = ClaudeSessionEngine(policy: ClaudeContentPolicy(previews: true)) + explore.ingest(records: [record(status: .busy, changed: 0)], now: at(0)) + explore.ingest(sessionID: "s1", facts: [ + .turnBegan(at(1)), + .backgroundStarted(toolID: "t1", service: false, label: "Map friends tab", at: at(2)), .backgroundTask(toolID: "t1", task: "a1"), + .backgroundStarted(toolID: "t2", service: false, label: "Map poll design", at: at(3)), .backgroundTask(toolID: "t2", task: "a2"), + ], now: at(2)) + _ = explore.snapshot(now: at(3)) + explore.ingest(sessionID: "s1", facts: [.turnEnded(at(10), completed: true)], now: at(10)) + explore.ingest(hook: hook(.stopped(lastText: "Waiting for both agents"), 10), now: at(10)) + let sentOffSnapshot = explore.snapshot(now: at(11)) + let sentOff: ClaudeSession? = sentOffSnapshot.sessions.first + suite.expect(sentOff?.phase == .background, "a turn that left subagents working in the background is not done") + suite.expect(sentOff?.backgroundLabel == "Map poll design", "and says what it waits for") + suite.expect(sentOffSnapshot.events.isEmpty, "so no notice says it finished") + explore.ingest(sessionID: "s1", facts: [.subagentEnded(id: "a1", at: at(100)), .turnBegan(at(100))], now: at(100)) + suite.expect(only(explore, 101)?.phase == .generating, "the first one's end takes the turn up again") + explore.ingest(sessionID: "s1", facts: [.turnEnded(at(105), completed: true)], now: at(105)) + let second = explore.snapshot(now: at(106)) + let left2: ClaudeSession? = second.sessions.first + suite.expect(left2?.phase == .background && second.events.isEmpty, "while the other still works it stays in the background") + explore.ingest(sessionID: "s1", facts: [.subagentEnded(id: "a2", at: at(200)), .turnBegan(at(200))], now: at(200)) + _ = explore.snapshot(now: at(201)) + explore.ingest(sessionID: "s1", facts: [.turnEnded(at(230), completed: true)], now: at(230)) + explore.ingest(records: [record(status: .idle, changed: 230)], now: at(230)) + let done = explore.snapshot(now: at(231)) + let noticed = done.events.contains { if case .finished = $0 { return true }; return false } + suite.expect(done.sessions.first?.phase == .finished && noticed, "once both are done and the turn ends, it finished, with a notice") + let served = ClaudeSessionEngine() + served.ingest(records: [record(status: .busy, changed: 0)], now: at(0)) + served.ingest(sessionID: "s1", facts: [ + .turnBegan(at(1)), + .backgroundStarted(toolID: "t1", service: true, label: "Run own Metro", at: at(2)), .backgroundTask(toolID: "t1", task: "b1"), + .turnEnded(at(10), completed: true), + ], now: at(10)) + suite.expect(only(served, 11)?.phase == .finished, "while the registry trails the end, a service alone does not hold it") + served.ingest(sessionID: "s1", facts: [ + .backgroundStarted(toolID: "t2", service: false, label: "Map the app", at: at(12)), .backgroundTask(toolID: "t2", task: "a1"), + ], now: at(12)) + suite.expect(only(served, 13)?.services == 1, "beside a subagent in the background it says what else runs") + // A background command refused before it ran gets no id and never ends. + let refused = ClaudeSessionEngine() + refused.ingest(records: [record(status: .busy, changed: 0)], now: at(0)) + refused.ingest(sessionID: "s1", facts: [ + .turnBegan(at(1)), .toolStarted(tool("b1", 2)), + .backgroundStarted(toolID: "b1", service: false, label: "Submit the build", at: at(2)), + .toolFinished(id: "b1", at: at(3), failed: true), + ], now: at(3)) + _ = refused.snapshot(now: at(5)) + refused.ingest(sessionID: "s1", facts: [.turnEnded(at(10), completed: true)], now: at(10)) + let trailing = refused.snapshot(now: at(10.5)) + refused.ingest(records: [record(status: .idle, changed: 11)], now: at(11)) + let refusedNoticed = (trailing.events + refused.snapshot(now: at(11.5)).events).contains { if case .finished = $0 { return true }; return false } + suite.expect(trailing.sessions.first?.phase != .background && refusedNoticed, + "a background command refused before it ran holds nothing, and the turn's end is still told") + let lostEnd = ClaudeSessionEngine() + lostEnd.ingest(records: [record(status: .busy, changed: 0)], now: at(0)) + lostEnd.ingest(sessionID: "s1", facts: [ + .turnBegan(at(1)), + .backgroundStarted(toolID: "t1", service: false, label: nil, at: at(2)), .backgroundTask(toolID: "t1", task: "a1"), + .turnEnded(at(10), completed: true), + ], now: at(10)) + lostEnd.ingest(records: [record(status: .idle, changed: 20)], now: at(20)) + suite.expect(only(lostEnd, 21)?.phase == .finished, "an end not read does not hold it once the registry goes idle") + let unseen = ClaudeSessionEngine() unseen.ingest(records: [record(status: .shell, changed: 0)], now: at(0)) suite.expect(only(unseen, 1)?.phase == .background, "a command running that was never seen start counts as work") diff --git a/Tests/ClaudeSessionReaderTests.swift b/Tests/ClaudeSessionReaderTests.swift index 6b90d3a23..2a4e2e933 100644 --- a/Tests/ClaudeSessionReaderTests.swift +++ b/Tests/ClaudeSessionReaderTests.swift @@ -163,6 +163,18 @@ enum ClaudeSessionReaderTests { suite.expect(parse([started], previews: false).contains(.backgroundStarted(toolID: "tb1", service: true, label: nil, at: date("2026-10-22T10:00:00.000Z"))), "with previews off it is still told apart, without its words") + let sent = #"{"type":"user","timestamp":"2026-10-22T13:14:15.571Z","toolUseResult":{"isAsync":true,"status":"async_launched","agentId":"a758ef93113160fa0","description":"Map friends tab and add flow"},"message":{"role":"user","content":[{"tool_use_id":"ta1","type":"tool_result","content":[{"type":"text","text":"Async agent launched successfully."}]}]}}"# + let waited = #"{"type":"user","timestamp":"2026-10-22T13:14:20.000Z","toolUseResult":{"status":"completed","agentId":"a1","description":"Look around"},"message":{"role":"user","content":[{"tool_use_id":"ta2","type":"tool_result","content":"Done."}]}}"# + let agents = parse([sent, waited], previews: true) + suite.expect(agents.contains(.backgroundStarted(toolID: "ta1", service: false, label: "Map friends tab and add flow", + at: date("2026-10-22T13:14:15.571Z"))) + && agents.contains(.backgroundTask(toolID: "ta1", task: "a758ef93113160fa0")), + "a subagent sent to the background is work Claude waits for, under its own id") + suite.expect(!agents.contains { if case .backgroundStarted(let id, _, _, _) = $0 { return id == "ta2" }; return false }, + "a subagent that answered before the turn went on is not") + suite.expect(parse([sent], previews: false).contains(.backgroundStarted(toolID: "ta1", service: false, label: nil, + at: date("2026-10-22T13:14:15.571Z"))), + "with previews off without what it does") let notice = #"{"type":"user","origin":{"kind":"task-notification"},"timestamp":"2026-10-21T19:06:34.760Z","message":{"role":"user","content":"\na05df\ncompleted\n"},"sessionId":"s1"}"# let queued = #"{"type":"queue-operation","operation":"enqueue","timestamp":"2026-10-21T19:06:30.000Z","content":"b77failed"}"# diff --git a/docs/claude-sessions-spike.md b/docs/claude-sessions-spike.md index 17eafa30b..e85bb43c0 100644 --- a/docs/claude-sessions-spike.md +++ b/docs/claude-sessions-spike.md @@ -49,6 +49,7 @@ Not run end to end: the Always answer, which hands back `permission_suggestions` ## Later findings (2.1.307) - The registry says `"shell"` for a session at rest while a command it started in the background still runs (`status === "idle" && ? "shell"`). The island shows it as working in the background, not done. +- While a subagent sent to the background works, the registry stays `"busy"` (`isLoading || delegatedActive`) though the turn that sent it ended with `end_turn` and the Stop hook (2.1.308). Its `Agent` result carries `toolUseResult` `isAsync: true`, `status: "async_launched"`, `agentId` and `description`, and its end comes as a `` naming that `agentId`. The island shows the session in the background until then; the registry going idle releases it if the end was missed. - `"dialog open"` covers every dialog in the terminal, including ones the person opens, like `/usage`. Only dialogs Claude Code raises itself send a Notification hook. - Claude Code attaches an image when a paste is nothing but the path of a PNG, JPEG, GIF or WebP file, and reads the file a moment later. A return sent at once goes out without it. Terminal adds a return after every `do script`, so the image paths go first with a paste left open, which that return joins as a line break; after a pause the text closes the paste and its return sends the reply. Confirmed in a throwaway session: the transcript held the image block and the model described the picture.