Skip to content

Open source CapCut alternative.

TypeScript

fix(app): remove the empty workspace folder when a run ends without producing files

David Le70ac8959c950
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
index 766b7c76..d34c72c7 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
@@ -735,6 +735,62 @@ public actor HarnessAgentCoordinator {
await store.upsertConversation(convo)
}
+ /// Remove the conversation's working directory when a run ends having never put a file in it, so a
+ /// task that answered in words (or failed before producing anything) leaves no empty folder in the
+ /// user's Downloads. The inverse of `ensureWorkspaceRoot`, and the reason eager seeding is safe: the
+ /// folder exists while the run might need it and is gone the moment the run ends without using it.
+ /// Runs only on a terminal status — a gate (clarify, permission) keeps the folder for the resumed run.
+ /// Deletion requires the directory to be genuinely empty (Finder's `.DS_Store` aside); a read failure
+ /// keeps the folder. Clears the workspace record and the projected facts so a later turn in the same
+ /// conversation re-seeds a fresh working directory instead of resolving into the deleted one.
+ public func removeWorkspaceRootIfEmpty(agentID: String) async {
+ guard let store = conversationStore else { return }
+ let existing: HarnessAgentState?
+ if let cached = tasksByID[agentID] {
+ existing = cached
+ } else {
+ existing = await store.agentSnapshot(id: agentID)
+ }
+ guard var task = existing else { return }
+ switch task.status {
+ case .completed, .failedSafe, .cancelled, .timedOut:
+ break
+ default:
+ return
+ }
+ guard var convo = await store.conversation(id: task.conversationID),
+ var workspace = ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey]),
+ let root = workspace.root, !root.isEmpty else { return }
+ var isDirectory: ObjCBool = false
+ if FileManager.default.fileExists(atPath: root, isDirectory: &isDirectory) {
+ guard isDirectory.boolValue,
+ let contents = try? FileManager.default.contentsOfDirectory(atPath: root),
+ contents.allSatisfy({ $0 == ".DS_Store" }) else { return }
+ do {
+ try FileManager.default.removeItem(atPath: root)
+ } catch {
+ return
+ }
+ }
+ workspace.root = nil
+ let insideRoot: (String?) -> Bool = { $0 == root || ($0?.hasPrefix(root + "/") ?? false) }
+ if insideRoot(workspace.anchorBase) { workspace.anchorBase = nil }
+ if insideRoot(workspace.folderPath) { workspace.folderPath = nil }
+ convo.metadata[ConversationWorkspace.metadataKey] = workspace.encodedJSON()
+ convo.updatedAt = Date()
+ await store.upsertConversation(convo)
+ // Clear the projected facts and the attempt mark so `ensureWorkspaceRoot`'s fast path doesn't
+ // resolve a follow-up turn into the deleted directory.
+ workspaceRootAttempted.remove(agentID)
+ task.worldModel.facts[ConversationWorkspace.summaryFactKey] = nil
+ task.worldModel.facts[ConversationWorkspace.baseDirFactKey] = nil
+ task.worldModel.facts[ConversationWorkspace.rootDirFactKey] = nil
+ task.worldModel.facts[ConversationWorkspace.fileContentsFactKey] = nil
+ task.updatedAt = Date()
+ tasksByID[agentID] = task
+ await store.upsertAgentSnapshot(task)
+ }
+
/// Project the conversation workspace into the agent's world model facts so the planner sees, every
/// step, what it has produced and where (and executors get the machine-readable resolve directory).
/// Quiet: persists the snapshot without a lifecycle event, since this is per-step bookkeeping, not a
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
index 76012949..4389e06a 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
@@ -286,6 +286,10 @@ public struct GenericHarnessRuntime: Sendable {
}
lastCallSignature = signature
}
+ // A run that ended without ever putting a file in its working directory leaves no folder behind —
+ // an answered-in-words task must not litter Downloads with an empty folder. Terminal-status-gated
+ // inside, so a gate stop (clarify, permission) keeps the folder for the resumed run.
+ await coordinator.removeWorkspaceRootIfEmpty(agentID: agentID)
return results
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
index a325e718..bc32f8f1 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
@@ -571,3 +571,95 @@ struct CommandBackendDestinationTests {
#expect(url.path == "/Users/x/Downloads/summary.pdf")
}
}
+
+/// A run that ends without ever putting a file in its working directory removes that folder, so an
+/// answered-in-words task leaves no empty folder in the user's Downloads. A folder with real content, or
+/// a run merely paused at a gate, keeps its folder.
+@Suite
+struct WorkspaceRootCleanupTests {
+ private func makeRoot() throws -> String {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-root-cleanup-\(UUID().uuidString)", isDirectory: true).path
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ private func seed(
+ store: InMemoryHarnessConversationStore,
+ conversationID: String,
+ root: String
+ ) async {
+ var convo = HarnessConversation(id: conversationID, title: "")
+ let workspace = ConversationWorkspace(root: root, anchorBase: root)
+ convo.metadata[ConversationWorkspace.metadataKey] = workspace.encodedJSON()
+ await store.upsertConversation(convo)
+ }
+
+ @Test
+ func emptyRootIsRemovedWhenTheRunCompletesWithoutFiles() async throws {
+ let root = try makeRoot()
+ let store = InMemoryHarnessConversationStore()
+ let coordinator = HarnessAgentCoordinator(conversationStore: store)
+ _ = await coordinator.createAgent(id: "t1", conversationID: "conv1", goal: "answer a question")
+ await seed(store: store, conversationID: "conv1", root: root)
+ _ = await coordinator.complete(agentID: "t1")
+
+ await coordinator.removeWorkspaceRootIfEmpty(agentID: "t1")
+
+ #expect(!FileManager.default.fileExists(atPath: root))
+ let after = await coordinator.conversationWorkspace(conversationID: "conv1")
+ #expect(after?.root == nil)
+ #expect(after?.anchorBase == nil)
+ }
+
+ @Test
+ func rootWithAFileSurvivesRunEnd() async throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(atPath: root) }
+ FileManager.default.createFile(atPath: root + "/links.md", contents: Data("# Links\n".utf8))
+ let store = InMemoryHarnessConversationStore()
+ let coordinator = HarnessAgentCoordinator(conversationStore: store)
+ _ = await coordinator.createAgent(id: "t2", conversationID: "conv2", goal: "collect links")
+ await seed(store: store, conversationID: "conv2", root: root)
+ _ = await coordinator.complete(agentID: "t2")
+
+ await coordinator.removeWorkspaceRootIfEmpty(agentID: "t2")
+
+ #expect(FileManager.default.fileExists(atPath: root + "/links.md"))
+ let after = await coordinator.conversationWorkspace(conversationID: "conv2")
+ #expect(after?.root == root)
+ }
+
+ @Test
+ func gateStopKeepsTheEmptyRootForTheResumedRun() async throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(atPath: root) }
+ let store = InMemoryHarnessConversationStore()
+ let coordinator = HarnessAgentCoordinator(conversationStore: store)
+ _ = await coordinator.createAgent(id: "t3", conversationID: "conv3", goal: "fill the form")
+ await seed(store: store, conversationID: "conv3", root: root)
+ _ = await coordinator.waitForUser(agentID: "t3", question: "Which account?")
+
+ await coordinator.removeWorkspaceRootIfEmpty(agentID: "t3")
+
+ #expect(FileManager.default.fileExists(atPath: root))
+ let after = await coordinator.conversationWorkspace(conversationID: "conv3")
+ #expect(after?.root == root)
+ }
+
+ @Test
+ func alreadyDeletedRootStillClearsTheRecordOnCompletion() async throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-root-cleanup-gone-\(UUID().uuidString)", isDirectory: true).path
+ let store = InMemoryHarnessConversationStore()
+ let coordinator = HarnessAgentCoordinator(conversationStore: store)
+ _ = await coordinator.createAgent(id: "t4", conversationID: "conv4", goal: "answer")
+ await seed(store: store, conversationID: "conv4", root: root)
+ _ = await coordinator.complete(agentID: "t4")
+
+ await coordinator.removeWorkspaceRootIfEmpty(agentID: "t4")
+
+ let after = await coordinator.conversationWorkspace(conversationID: "conv4")
+ #expect(after?.root == nil)
+ }
+}
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index 4a405878..e334df23 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -212,7 +212,9 @@ The files a task produces are kept together in one named folder per conversation
— created under the user's Downloads by default, and configurable to Desktop,
Documents, or another path. The agent owns that folder, and a write aimed loosely
at the top of Downloads, Desktop, Documents, or the home root is pulled back into
-it, so a task's output lands in one place instead of scattering loose.
+it, so a task's output lands in one place instead of scattering loose. A run that
+ends without putting any file in the folder removes it, so a task answered in
+words leaves nothing behind.
## Shell First, GUI Second