diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index 5ec8d2b372..b87e33e5a6 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -254,6 +254,56 @@ public TaskRepository getTaskRepository() { return taskRepository; } + /** + * Formats the inbox hint pushed when a background subagent task settles. + * + *

Failed tasks must not be announced with completion wording: the parent model would treat + * the run as a delivered (empty) business result instead of an infrastructure failure to retry + * or escalate. Mirrors the task-delivery reminder's {@code } semantics.

+ * + *

Automatic notifications identify the task and its terminal state with a fixed error + * category — they never embed the raw exception message, which can leak internals (paths, + * endpoints, credentials) into the conversation. The full message stays in the durable task + * record, reachable via {@code task_output}.

+ * + *

A non-terminal {@code status} means the task finished but its terminal state could not be + * persisted; the in-memory result is delivered once so it is not lost.

+ */ + public static String taskSettledHintContent( + String taskId, String subAgentId, TaskStatus status, String result) { + if (!status.isTerminal()) { + return String.format( + "Background subagent task '%s' (agent=%s) finished and" + + " produced a result, but its terminal state could not be persisted," + + " so task queries may still report it as running. Do not start it" + + " again.\n\nResult:\n\n%s", + taskId, subAgentId, result != null ? result : "(no output)"); + } + if (status == TaskStatus.FAILED) { + return String.format( + "Background subagent task '%s' (agent=%s) FAILED and" + + " produced no result. Error category: execution failure. This is an" + + " execution failure, not a business conclusion; error details are" + + " omitted from notifications because they may contain sensitive" + + " data. Use task_output(task_id=..., block=false) or task_list() to" + + " retrieve the full task record and error" + + " details.", + taskId, subAgentId); + } + if (status == TaskStatus.CANCELLED) { + return String.format( + "Background subagent task '%s' (agent=%s) was CANCELLED and" + + " produced no result. Use task_output(task_id=..., block=false) or" + + " task_list() if you need the task" + + " record.", + taskId, subAgentId); + } + return String.format( + "Background subagent task '%s' (agent=%s) has completed." + + "\n\nResult:\n\n%s", + taskId, subAgentId, result != null ? result : "(no output)"); + } + /** * Wires a {@link MessageBus} so that background task completions signal the session inbox and * enqueue a wakeup. This enables the {@link @@ -276,49 +326,51 @@ public SubagentsMiddleware wireMessageBus(MessageBus messageBus, String agentId) public static void wireMessageBus(TaskRepository repository, MessageBus bus, String agentId) { if (bus == null) return; repository.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, result) -> { - String userId = rc != null ? rc.getUserId() : null; - Map payload = - Map.of( - "type", - "hint", - "id", - UUID.randomUUID().toString().replace("-", ""), - "source", - TASK_HINT_SOURCE, - "taskId", - taskId != null ? taskId : "", - "hint", - TASK_HINT_HEADER - + taskId - + TASK_HINT_AGENT - + subAgentId - + ") has completed.\n\nResult:\n\n" - + (result != null ? result : "(no output)") - + ""); - bus.inboxPush(sessionId, payload) - .onErrorResume( - error -> { - log.warn( - "Failed to signal task {} in the inbox", - taskId, - error); - return Mono.empty(); - }) - .then( - bus.enqueueWakeup( - userId != null ? userId : "", - sessionId, - agentId != null ? agentId : "")) - .subscribe( - unused -> {}, - err -> - log.warn( - "Failed to enqueue wakeup after task {}" - + " completion: {}", - taskId, - err.getMessage())); - }); + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { + String userId = rc != null ? rc.getUserId() : null; + Map payload = + Map.of( + "type", + "hint", + "id", + UUID.randomUUID().toString().replace("-", ""), + "source", + TASK_HINT_SOURCE, + "taskId", + taskId != null ? taskId : "", + "hint", + taskSettledHintContent( + taskId, subAgentId, status, result)); + bus.inboxPush(sessionId, payload) + .onErrorResume( + error -> { + log.warn( + "Failed to signal task {} in the inbox", + taskId, + error); + return Mono.empty(); + }) + .then( + bus.enqueueWakeup( + userId != null ? userId : "", + sessionId, + agentId != null ? agentId : "")) + .subscribe( + unused -> {}, + err -> + log.warn( + "Failed to enqueue wakeup after task {}" + + " completion: {}", + taskId, + err.getMessage())); + log.info( + "Subagent task {} settled (status={}), pushed to inbox and" + + " enqueued wakeup: session={}", + taskId, + status, + sessionId); + }); } /** @@ -569,7 +621,10 @@ private static String renderTaskResults(List deliveries) { } case FAILED -> { sb.append("\n"); - sb.append(d.errorMessage() != null ? d.errorMessage() : "(no error message)"); + sb.append( + "execution failure; error details are omitted from notifications" + + " because they may contain sensitive data — call" + + " task_output for the full record"); sb.append("\n\n"); } case CANCELLED -> sb.append("Task was cancelled before producing a result.\n"); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java index 95bd619a0d..427adde087 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java @@ -126,10 +126,15 @@ default boolean isDelivered(RuntimeContext rc, String sessionId, String taskId) } /** - * Registers a callback invoked when any task reaches a terminal state (COMPLETED or FAILED). - * Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to push results - * to the session inbox and enqueue a wakeup signal. The {@code result} argument is {@code null} - * for failed tasks. + * Registers a callback invoked when any task reaches a terminal state (COMPLETED, FAILED, or + * CANCELLED). Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to + * push results to the session inbox and enqueue a wakeup signal. The {@code result} argument is + * {@code null} for failed and cancelled tasks. Use {@link TaskSettledCallback} to also receive + * terminal status and errors. + * + *

Through {@link TaskSettledCallback}, {@code status} is always the status on record. When + * a completed task's terminal state cannot be persisted, the callback reports the non-terminal + * status on record together with the result, so the in-memory result is not lost. * *

Callers retaining execution ownership can set {@link #SUPPRESS_COMPLETION_CALLBACK} * in their RuntimeContext to suppress inbox/wakeup callbacks while preserving durable results. @@ -145,10 +150,7 @@ default void shutdown() { // no-op } - /** - * Callback invoked when a background task reaches a terminal state (COMPLETED or FAILED). - * {@code result} is {@code null} when the task failed. - */ + /** Callback for completed or failed tasks; {@code result} is null on failure. */ @FunctionalInterface interface TaskCompletionCallback { void onCompleted( @@ -157,5 +159,49 @@ void onCompleted( String subAgentId, String sessionId, String result); + + /** Delivers terminal details while preserving the five-argument callback contract. */ + default void onSettled( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + TaskStatus status, + String result, + String errorMessage) { + onCompleted(rc, taskId, subAgentId, sessionId, result); + } + } + + /** Terminal callback; register through {@link TaskRepository#setCompletionCallback}. */ + @FunctionalInterface + interface TaskSettledCallback extends TaskCompletionCallback { + @Override + void onSettled( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + TaskStatus status, + String result, + String errorMessage); + + /** Legacy repositories only distinguish failures by a null result and provide no error. */ + @Override + default void onCompleted( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + String result) { + onSettled( + rc, + taskId, + subAgentId, + sessionId, + result != null ? TaskStatus.COMPLETED : TaskStatus.FAILED, + result, + null); + } } } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index 91036da72b..d717794e12 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -308,16 +308,32 @@ public BackgroundTask putTask( future.whenComplete( (result, err) -> { if (adopted.future().isCancelled()) { - markCancelled(capturedRc, sid, taskId); - fireCompletionCallback(capturedRc, taskId, subAgentId, sid, null); + settleAndNotify( + capturedRc, + sid, + taskId, + subAgentId, + TaskStatus.CANCELLED, + null, + null); } else if (err != null) { - String errMsg = failureMessage(err); - updateStatus(capturedRc, sid, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(capturedRc, taskId, subAgentId, sid, null); + settleAndNotify( + capturedRc, + sid, + taskId, + subAgentId, + TaskStatus.FAILED, + null, + failureMessage(err)); } else { - updateStatus( - capturedRc, sid, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback(capturedRc, taskId, subAgentId, sid, result); + settleAndNotify( + capturedRc, + sid, + taskId, + subAgentId, + TaskStatus.COMPLETED, + result, + null); } }); } else if (spec instanceof TaskRunSpec.LocalTaskRunSpec local) { @@ -387,15 +403,19 @@ private String runLocalSupplier( markCancelled(rc, sessionId, taskId); return null; } - updateStatus(rc, sessionId, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, result); + settleAndNotify(rc, sessionId, taskId, subAgentId, TaskStatus.COMPLETED, result, null); return result; } catch (Exception e) { RuntimeException failure = e instanceof RuntimeException re ? re : new RuntimeException(e); - String errMsg = failureMessage(failure); - updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, null); + settleAndNotify( + rc, + sessionId, + taskId, + subAgentId, + TaskStatus.FAILED, + null, + failureMessage(failure)); throw failure; } } @@ -423,15 +443,21 @@ private String runRemoteTask( } String result = pollRemoteUntilDone(rc, sessionId, taskId, target); if (result != null) { - fireCompletionCallback(rc, taskId, subAgentId, sessionId, result); + settleAndNotify( + rc, sessionId, taskId, subAgentId, TaskStatus.COMPLETED, result, null); } return result; } catch (Exception e) { RuntimeException failure = e instanceof RuntimeException re ? re : new RuntimeException(e); - String errMsg = failureMessage(failure); - updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, null); + settleAndNotify( + rc, + sessionId, + taskId, + subAgentId, + TaskStatus.FAILED, + null, + failureMessage(failure)); throw failure; } } @@ -864,7 +890,12 @@ record -> { return existing; } - private synchronized void updateStatus( + /** + * Returns the status on record after the call: the existing status when a guard applies or + * {@link WorkspaceManager#writeTaskRecord} fails, {@code status} once the write lands, or + * {@code null} when no record is readable. + */ + private synchronized TaskStatus updateStatus( RuntimeContext rc, String sessionId, String taskId, @@ -879,14 +910,14 @@ private synchronized void updateStatus( if (existing.isPresent() && existing.get().getStatus() != null && existing.get().getStatus().isTerminal()) { - return; + return existing.get().getStatus(); } // Guard 2: if cancellation has been requested but the workspace record has not yet reached // a terminal state (e.g. heartbeat races cancelTask()), refuse to persist non-terminal // updates. This stops the heartbeat from writing RUNNING back over a record whose // cancelRequested flag was just set by cancelTask(). if (!status.isTerminal() && existing.isPresent() && existing.get().isCancelRequested()) { - return; + return existing.get().getStatus(); } TaskRecord record = existing.orElseGet( @@ -905,6 +936,61 @@ private synchronized void updateStatus( record.setErrorMessage(error); } persistRecord(rc, sessionId, record); + // writeTaskRecord is best-effort: storage failures are logged and swallowed, so only a + // read-back proves which status the task now exposes. + return workspaceManager + .readTaskRecord(rc, parentAgentId, sessionId, taskId) + .map(TaskRecord::getStatus) + .orElse(null); + } + + /** + * Persists a terminal state and reports the status that is actually on record. When + * cancellation races a settlement, {@link #updateStatus} keeps the record's CANCELLED status, + * so the callback must also report CANCELLED — announcing FAILED for a task the user just + * cancelled would invite the parent agent to retry it. When the terminal write does not land, + * no terminal status is announced: the result of a completed task exists only in memory and is + * handed over with the on-record status, while an unrecorded failure or cancellation has + * nothing to deliver and stays silent. + */ + private void settleAndNotify( + RuntimeContext rc, + String sessionId, + String taskId, + String subAgentId, + TaskStatus status, + String result, + String errorMessage) { + TaskStatus effective = updateStatus(rc, sessionId, taskId, status, result, errorMessage); + if (effective == null) { + log.warn( + "Task {} settlement notification withheld for session {}: no record is" + + " readable", + taskId, + sessionId); + return; + } + if (!effective.isTerminal()) { + log.warn( + "Task {} status {} was not persisted for session {} (on record: {})", + taskId, + status, + sessionId, + effective); + if (status == TaskStatus.COMPLETED) { + fireCompletionCallback(rc, taskId, subAgentId, sessionId, effective, result, null); + } + return; + } + boolean asPersisted = effective == status; + fireCompletionCallback( + rc, + taskId, + subAgentId, + sessionId, + effective, + asPersisted ? result : null, + asPersisted ? errorMessage : null); } private void markCancelled(RuntimeContext rc, String sessionId, String taskId) { @@ -984,14 +1070,20 @@ private BackgroundTask syntheticTask(RuntimeContext rc, TaskRecord record) { } private void fireCompletionCallback( - RuntimeContext rc, String taskId, String subAgentId, String sessionId, String result) { + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + TaskStatus status, + String result, + String errorMessage) { TaskCompletionCallback cb = this.completionCallback; if (cb == null || (rc != null && Boolean.TRUE.equals(rc.get(SUPPRESS_COMPLETION_CALLBACK)))) { return; } try { - cb.onCompleted(rc, taskId, subAgentId, sessionId, result); + cb.onSettled(rc, taskId, subAgentId, sessionId, status, result, errorMessage); } catch (Exception e) { log.warn("TaskCompletionCallback failed for task {}: {}", taskId, e.getMessage(), e); } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java index b19b8efbb4..b8286e8d8a 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java @@ -16,6 +16,7 @@ package io.agentscope.harness.agent.middleware; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -150,7 +151,7 @@ private static String textOf(Msg m) { // ---- buildDeliveryReminder static formatting --------------------------------------------- @Test - void deliveryPreservesLargeResultsAndErrorsWithTaskOutputAvailable() { + void deliveryPreservesLargeResultsAndDefersErrorsToTaskOutput() { var repo = new StubRepo(); String payload = "status: max_iterations\n" + "evidence ".repeat(5000) + "REQUIRED_TAIL"; String failure = "details ".repeat(5000) + "FAILURE_TAIL"; @@ -180,7 +181,10 @@ void deliveryPreservesLargeResultsAndErrorsWithTaskOutputAvailable() { .findFirst() .orElseThrow(); assertTrue(notification.contains(payload)); - assertTrue(notification.contains(failure)); + // Raw errors never enter the conversation; task_output serves the full record. + assertFalse(notification.contains(failure)); + assertTrue(notification.contains(""), notification); + assertTrue(notification.contains("task_output"), notification); assertEquals(List.of("full", "failed"), repo.markCalls); } } @@ -200,14 +204,22 @@ void reminder_singleCompleted_rendersTaskResultBlock() { } @Test - void reminder_failedRendersTaskErrorBlock() { + void reminder_failedRendersFixedCategoryTaskErrorBlock() { Msg msg = SubagentsMiddleware.buildDeliveryReminder( - List.of(delivery("tx", TaskStatus.FAILED, null, "boom"))); + List.of( + delivery( + "tx", + TaskStatus.FAILED, + null, + "auth failed: token=sk-live-secret-1234567890"))); String text = textOf(msg); assertTrue(text.contains("state=\"error\"")); assertTrue(text.contains("")); - assertTrue(text.contains("boom")); + assertTrue(text.contains("execution failure"), text); + assertTrue(text.contains("task_output"), text); + assertFalse(text.contains("boom")); + assertFalse(text.contains("sk-live-secret"), text); } @Test diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java new file mode 100644 index 0000000000..4f8d67aae7 --- /dev/null +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -0,0 +1,373 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.middleware; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; + +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.model.Model; +import io.agentscope.harness.agent.HarnessAgent; +import io.agentscope.harness.agent.bus.MessageBus; +import io.agentscope.harness.agent.filesystem.local.LocalFilesystem; +import io.agentscope.harness.agent.subagent.task.BackgroundTask; +import io.agentscope.harness.agent.subagent.task.TaskRecord; +import io.agentscope.harness.agent.subagent.task.TaskRepository; +import io.agentscope.harness.agent.subagent.task.TaskRunSpec.LocalTaskRunSpec; +import io.agentscope.harness.agent.subagent.task.TaskStatus; +import io.agentscope.harness.agent.subagent.task.WorkspaceTaskRepository; +import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import reactor.core.publisher.Mono; + +/** Subagent task hints preserve terminal status and errors through every message-bus wiring path. */ +class SubagentTaskSettledHintTest { + + private static final String PARENT_ID = "parent"; + private static final String USER_ID = "original-user"; + private static final String SESSION_ID = "original-session"; + private static final String TASK_ID = "task_settled"; + private static final String SUBAGENT_ID = "image-reader"; + private static final String ERROR = "auth failed: token=sk-live-secret-1234567890"; + private static final String OUTPUT = "done: 3 findings"; + + @TempDir Path tempDir; + + private HarnessAgent agent; + private WorkspaceManager workspaceManager; + private WorkspaceTaskRepository repo; + private RecordingBus recordingBus; + + @AfterEach + void closeResources() { + try { + if (agent != null) { + agent.close(); + } + } finally { + if (repo != null) { + repo.shutdown(); + } + if (workspaceManager != null) { + workspaceManager.close(); + } + } + } + + @Test + void failedTaskIsAnnouncedWithFixedCategoryNotRawError() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "image-reader", TaskStatus.FAILED, null); + + assertTrue(hint.contains("FAILED"), hint); + assertTrue(hint.contains("Error category: execution failure"), hint); + assertTrue(hint.contains("execution failure, not a business conclusion"), hint); + assertTrue(hint.contains("task_output(task_id=..., block=false)"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); + } + + @Test + void cancelledTaskIsAnnouncedAsCancelled() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "image-reader", TaskStatus.CANCELLED, null); + + assertTrue(hint.contains("CANCELLED"), hint); + assertFalse(hint.contains("FAILED"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); + } + + @Test + void completedTaskKeepsCompletionWording() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "image-reader", TaskStatus.COMPLETED, "done: 3 findings"); + + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains("done: 3 findings"), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void failedTaskWiringNotifiesFixedCategoryAndWakesOriginalSession(EntryMode mode) + throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitFailingTask(rc); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.FAILED, task.getTaskStatus()); + assertEquals(ERROR, task.getError().getMessage()); + assertDurableResult(rc, TaskStatus.FAILED, null, ERROR); + assertTrue(hint.contains("FAILED"), hint); + assertTrue(hint.contains("Error category: execution failure"), hint); + assertFalse(hint.contains(ERROR), hint); + assertFalse(hint.contains("sk-live"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void completedTaskWiringPushesOutputAndWakesOriginalSession(EntryMode mode) throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> OUTPUT); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.COMPLETED, task.getTaskStatus()); + assertDurableResult(rc, TaskStatus.COMPLETED, OUTPUT, null); + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains(OUTPUT), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void nullResultTaskWiringStillAnnouncesCompletion(EntryMode mode) throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> null); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.COMPLETED, task.getTaskStatus()); + assertDurableResult(rc, TaskStatus.COMPLETED, null, null); + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains("(no output)"), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void suppressedFailedTaskPreservesDurableErrorWithoutNotifications(EntryMode mode) + throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(true); + BackgroundTask task = submitFailingTask(rc); + + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + assertEquals(TaskStatus.FAILED, task.getTaskStatus()); + assertEquals(ERROR, task.getError().getMessage()); + assertDurableResult(rc, TaskStatus.FAILED, null, ERROR); + assertEquals(List.of(), recordingBus.queued); + assertEquals(List.of(), recordingBus.published); + } + + @Test + void unpersistedCompletionHintCarriesResultAndWakesOriginalSession() throws Exception { + dropTerminalWrites(); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> OUTPUT); + + String hint = awaitHintAndWakeup(task); + + assertTrue(hint.contains(OUTPUT), hint); + assertTrue(hint.contains("could not be persisted"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("FAILED"), hint); + assertDurableResult(rc, TaskStatus.RUNNING, null, null); + } + + @Test + void unpersistedFailureQueuesNeitherHintNorWakeup() throws Exception { + dropTerminalWrites(); + BackgroundTask task = submitFailingTask(runtimeContext(false)); + + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + assertEquals(List.of(), recordingBus.queued); + assertEquals(List.of(), recordingBus.published); + } + + /** WorkspaceManager swallows storage failures, so a dropped write is how a failed one looks. */ + private void dropTerminalWrites() { + workspaceManager = + new WorkspaceManager(tempDir) { + @Override + public void writeTaskRecord( + RuntimeContext rc, + String agentId, + String sessionId, + TaskRecord record) { + if (record.getStatus() == null || !record.getStatus().isTerminal()) { + super.writeTaskRecord(rc, agentId, sessionId, record); + } + } + }; + repo = WorkspaceTaskRepository.forTests(workspaceManager, PARENT_ID); + recordingBus = new RecordingBus(); + new SubagentsMiddleware(List.of(), repo, workspaceManager) + .wireMessageBus(recordingBus.bus, PARENT_ID); + } + + private void wire(EntryMode mode) { + workspaceManager = new WorkspaceManager(tempDir); + repo = WorkspaceTaskRepository.forTests(workspaceManager, PARENT_ID); + recordingBus = new RecordingBus(); + if (mode == EntryMode.DIRECT) { + new SubagentsMiddleware(List.of(), repo, workspaceManager) + .wireMessageBus(recordingBus.bus, PARENT_ID); + return; + } + Model model = mock(Model.class); + HarnessAgent.Builder builder = + HarnessAgent.builder() + .name(PARENT_ID) + .agentId(PARENT_ID) + .model(model) + .workspace(tempDir) + .abstractFilesystem(new LocalFilesystem(tempDir)) + .taskRepository(repo) + .messageBus(recordingBus.bus) + .disableMemoryTools() + .disableMemoryHooks(); + if (mode == EntryMode.BUILDER_STATIC) { + builder.disableDynamicSubagents(); + } + agent = builder.build(); + } + + private static RuntimeContext runtimeContext(boolean suppress) { + return RuntimeContext.builder() + .userId(USER_ID) + .sessionId(SESSION_ID) + .put(TaskRepository.SUPPRESS_COMPLETION_CALLBACK, suppress) + .build(); + } + + private BackgroundTask submitTask(RuntimeContext rc, Supplier execution) { + return repo.putTask(rc, TASK_ID, SUBAGENT_ID, SESSION_ID, new LocalTaskRunSpec(execution)); + } + + private BackgroundTask submitFailingTask(RuntimeContext rc) { + return submitTask( + rc, + () -> { + throw new IllegalStateException(ERROR); + }); + } + + private String awaitHintAndWakeup(BackgroundTask task) throws Exception { + recordingBus.notified.get(5, TimeUnit.SECONDS); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + assertEquals( + List.of("agentscope:inbox:" + SESSION_ID, "agentscope:wakeups"), + recordingBus.queued.stream().map(BusCall::key).toList()); + Map payload = recordingBus.queued.get(0).payload(); + assertEquals("hint", payload.get("type")); + assertEquals("subagent_task", payload.get("source")); + String hint = (String) payload.get("hint"); + assertTrue(hint.contains(TASK_ID), hint); + assertTrue(hint.contains(SUBAGENT_ID), hint); + assertEquals( + Map.of("userId", USER_ID, "sessionId", SESSION_ID, "agentId", PARENT_ID), + recordingBus.queued.get(1).payload()); + assertEquals( + List.of(new BusCall("agentscope:wakeup_signal", Map.of())), recordingBus.published); + return hint; + } + + private void assertDurableResult( + RuntimeContext rc, TaskStatus status, String result, String errorMessage) { + var record = + workspaceManager.readTaskRecord(rc, PARENT_ID, SESSION_ID, TASK_ID).orElseThrow(); + assertEquals(TASK_ID, record.getTaskId()); + assertEquals(SUBAGENT_ID, record.getSubAgentId()); + assertEquals(PARENT_ID, record.getParentAgentId()); + assertEquals(SESSION_ID, record.getParentSessionId()); + assertEquals(status, record.getStatus()); + assertEquals(result, record.getResult()); + assertEquals(errorMessage, record.getErrorMessage()); + } + + enum EntryMode { + DIRECT, + BUILDER_DYNAMIC, + BUILDER_STATIC + } + + private record BusCall(String key, Map payload) {} + + private static final class RecordingBus { + private final MessageBus bus = mock(MessageBus.class, CALLS_REAL_METHODS); + private final List queued = new CopyOnWriteArrayList<>(); + private final List published = new CopyOnWriteArrayList<>(); + private final CompletableFuture notified = new CompletableFuture<>(); + + private RecordingBus() { + doAnswer( + invocation -> { + String key = invocation.getArgument(0); + Map payload = invocation.getArgument(1); + return Mono.fromSupplier( + () -> { + queued.add(new BusCall(key, Map.copyOf(payload))); + completeIfNotified(); + return "entry-" + queued.size(); + }); + }) + .when(bus) + .queuePush(anyString(), anyMap()); + doAnswer( + invocation -> { + String key = invocation.getArgument(0); + Map payload = invocation.getArgument(1); + return Mono.defer( + () -> { + published.add(new BusCall(key, Map.copyOf(payload))); + completeIfNotified(); + return Mono.empty(); + }); + }) + .when(bus) + .publish(anyString(), anyMap()); + } + + private void completeIfNotified() { + if (queued.stream().anyMatch(call -> call.key().startsWith("agentscope:inbox:")) + && queued.stream().anyMatch(call -> call.key().equals("agentscope:wakeups")) + && published.stream() + .anyMatch(call -> call.key().equals("agentscope:wakeup_signal"))) { + notified.complete(null); + } + } + } +} diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java index 203e64a6f4..bcaa40684f 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java @@ -17,7 +17,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import io.agentscope.core.agent.RuntimeContext; import io.agentscope.harness.agent.subagent.protocol.RemoteAgentEvent; @@ -29,7 +34,9 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @@ -62,6 +69,36 @@ void tearDown() { } } + @Test + void remoteFailureDeliversStatusAndError() throws Exception { + RemoteSubagentTransport transport = mock(RemoteSubagentTransport.class); + when(transport.getStatus(any(), anyString())) + .thenReturn(new RemoteTaskStatus("failed", "remote execution error")); + repo.setTransport(transport); + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callback.complete( + new TaskDelivery( + taskId, agentId, status, result, error, null))); + repo.putTask( + RuntimeContext.empty(), + "remote-failure", + "remote-worker", + "remote-session", + new TaskRunSpec.RemoteTaskRunSpec( + "http://remote.test", + Map.of(), + "remote-worker", + "do work", + RemoteSubmitContext.empty())); + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertEquals("remote execution error", delivery.errorMessage()); + assertNull(delivery.result()); + } + @Test void remoteTask_togglesAwaitingConfirm_thenFiresCompletionOnSuccess() throws Exception { AtomicInteger statusCalls = new AtomicInteger(); diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 09798523be..3cf977f208 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -29,6 +29,10 @@ import io.agentscope.harness.agent.filesystem.remote.store.NamespaceFactory; import io.agentscope.harness.agent.filesystem.spec.RemoteFilesystemSpec; import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URL; +import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; @@ -37,14 +41,21 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.tools.ToolProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests for {@link WorkspaceTaskRepository}: @@ -172,6 +183,420 @@ void putTask_writesFailedOnException() throws Exception { assertTrue(record.get().getErrorMessage().contains("intentional failure")); } + @Test + @DisplayName("completion callback receives FAILED status and error message when task throws") + void completionCallback_receivesFailedStatusAndError() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + + repo.putTask( + RuntimeContext.empty(), + "task-callback-fail", + "sub-agent-fail", + "sess-callback", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new RuntimeException("callback failure detail"); + })); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertNull(delivery.result()); + assertEquals("callback failure detail", delivery.errorMessage()); + } + + @Test + @DisplayName("completion callback receives COMPLETED status and result on success") + void completionCallback_receivesCompletedStatusAndResult() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + + repo.putTask( + RuntimeContext.empty(), + "task-callback-ok", + "sub-agent-ok", + "sess-callback", + new TaskRunSpec.LocalTaskRunSpec(() -> "delivered")); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.COMPLETED, delivery.status()); + assertEquals("delivered", delivery.result()); + assertNull(delivery.errorMessage()); + } + + @Test + void legacyCallbackReceivesSuccessAndFailure() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, result) -> callback.complete(result)); + repo.putTask( + RuntimeContext.empty(), + "legacy-success", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec(() -> "legacy result")); + assertEquals("legacy result", callback.get(5, TimeUnit.SECONDS)); + + CompletableFuture failure = new CompletableFuture<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, result) -> failure.complete(result)); + repo.putTask( + RuntimeContext.empty(), + "legacy-failure", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new IllegalStateException("legacy error"); + })); + assertNull(failure.get(5, TimeUnit.SECONDS)); + } + + @Test + void callbacksCompiledAgainstFiveArgumentApiRemainBinaryCompatible() throws Exception { + Path source = Files.createDirectories(tempDir.resolve("legacy-source")); + Path output = Files.createDirectories(tempDir.resolve("legacy-classes")); + Path api = source.resolve("TaskRepository.java"); + Files.writeString( + api, + """ + package io.agentscope.harness.agent.subagent.task; + import io.agentscope.core.agent.RuntimeContext; + public interface TaskRepository { + @FunctionalInterface + interface TaskCompletionCallback { + void onCompleted(RuntimeContext rc, String taskId, String subAgentId, + String sessionId, String result); + } + } + """); + Path client = source.resolve("LegacyCallbacks.java"); + Files.writeString( + client, + """ + package compat; + import io.agentscope.core.agent.RuntimeContext; + import io.agentscope.harness.agent.subagent.task.TaskRepository.TaskCompletionCallback; + public class LegacyCallbacks { + public static String result; + public static TaskCompletionCallback callback() { + return (rc, taskId, agentId, sessionId, value) -> result = value; + } + public static void invoke(TaskCompletionCallback callback, String value) { + callback.onCompleted(RuntimeContext.empty(), "task", "worker", "session", value); + } + } + """); + assertEquals( + 0, + ToolProvider.getSystemJavaCompiler() + .run( + null, + null, + null, + "--release", + "17", + "-classpath", + System.getProperty("java.class.path"), + "-d", + output.toString(), + api.toString(), + client.toString())); + try (var loader = + new URLClassLoader( + new URL[] {output.toUri().toURL()}, getClass().getClassLoader())) { + Class legacy = loader.loadClass("compat.LegacyCallbacks"); + var callback = + (TaskRepository.TaskCompletionCallback) + legacy.getMethod("callback").invoke(null); + callback.onSettled( + RuntimeContext.empty(), + "task", + "worker", + "session", + TaskStatus.COMPLETED, + "new result", + null); + assertEquals("new result", legacy.getField("result").get(null)); + callback.onSettled( + RuntimeContext.empty(), + "task", + "worker", + "session", + TaskStatus.FAILED, + null, + "new error"); + assertNull(legacy.getField("result").get(null)); + + AtomicReference status = new AtomicReference<>(); + TaskRepository.TaskSettledCallback settled = + (rc, taskId, agentId, sessionId, state, result, error) -> status.set(state); + var invoke = + legacy.getMethod( + "invoke", TaskRepository.TaskCompletionCallback.class, String.class); + invoke.invoke(null, settled, "old result"); + assertEquals(TaskStatus.COMPLETED, status.get()); + invoke.invoke(null, settled, null); + assertEquals(TaskStatus.FAILED, status.get()); + } + } + + @Test + void adoptedFutureDeliversAuthoritativeFailureAndEmptySuccess() throws Exception { + for (boolean fails : List.of(false, true)) { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CompletableFuture future = new CompletableFuture<>(); + repo.putTask( + RuntimeContext.empty(), + "adopted-" + fails, + "worker", + "session", + new TaskRunSpec.AdoptedTaskRunSpec(future)); + if (fails) { + future.completeExceptionally(new IllegalStateException("adopted error")); + } else { + future.complete(null); + } + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(fails ? TaskStatus.FAILED : TaskStatus.COMPLETED, delivery.status()); + assertNull(delivery.result()); + assertEquals(fails ? "adopted error" : null, delivery.errorMessage()); + } + } + + @Test + void cancelledAdoptedTaskNotifiesCancelledNotFailed() throws Exception { + // Reviewer repro: cancelling an adopted future enters whenComplete's exception branch, + // but the callback must report the persisted CANCELLED terminal state, never FAILED. + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CompletableFuture future = new CompletableFuture<>(); + BackgroundTask task = + repo.putTask( + RuntimeContext.empty(), + "adopted-cancel", + "worker", + "session", + new TaskRunSpec.AdoptedTaskRunSpec(future)); + + assertTrue(repo.cancelTask(RuntimeContext.empty(), "session", "adopted-cancel")); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.CANCELLED, delivery.status()); + assertNull(delivery.result()); + assertNull(delivery.errorMessage()); + var record = + workspaceManager + .readTaskRecord( + RuntimeContext.empty(), "test-agent", "session", "adopted-cancel") + .orElseThrow(); + assertEquals(TaskStatus.CANCELLED, record.getStatus()); + } + + @Test + void cancelledLocalTaskNotifiesCancelledNotFailed() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + BackgroundTask task = + repo.putTask( + RuntimeContext.empty(), + "local-cancel", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + started.countDown(); + // The supplier is not interrupted on cancel — it can only + // observe cancellation after its own failure, which must not + // be reported as FAILED. + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + throw new IllegalStateException("post-cancel failure"); + })); + + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertTrue(repo.cancelTask(RuntimeContext.empty(), "session", "local-cancel")); + release.countDown(); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.CANCELLED, delivery.status()); + assertNull(delivery.result()); + var record = + workspaceManager + .readTaskRecord( + RuntimeContext.empty(), "test-agent", "session", "local-cancel") + .orElseThrow(); + assertEquals(TaskStatus.CANCELLED, record.getStatus()); + } + + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + void unpersistedTerminalStateIsNeverAnnounced(boolean taskFails, boolean writeThrows) + throws Exception { + // Storage may fail loudly (writeTaskRecord raises) or silently (WorkspaceManager logs the + // I/O error and returns normally). The record stays RUNNING either way, so the callback + // must never report a terminal status; only a completed result is handed over. + repo.shutdown(); + workspaceManager = + new WorkspaceManager(tempDir) { + @Override + public void writeTaskRecord( + RuntimeContext rc, + String agentId, + String sessionId, + TaskRecord record) { + if (record.getStatus() != null && record.getStatus().isTerminal()) { + if (writeThrows) { + throw new UncheckedIOException(new IOException("disk full")); + } + return; + } + super.writeTaskRecord(rc, agentId, sessionId, record); + } + }; + repo = WorkspaceTaskRepository.forTests(workspaceManager, "test-agent"); + List callbacks = new CopyOnWriteArrayList<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callbacks.add( + new TaskDelivery( + taskId, agentId, status, result, error, null))); + RuntimeContext rc = RuntimeContext.empty(); + + BackgroundTask task = + repo.putTask( + rc, + "unpersisted", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + if (taskFails) { + throw new IllegalStateException("boom"); + } + return "done"; + })); + + assertTrue(task.waitForCompletion(5_000), "task did not finish within 5 seconds"); + + assertEquals( + TaskStatus.RUNNING, + workspaceManager + .readTaskRecord(rc, "test-agent", "session", "unpersisted") + .orElseThrow() + .getStatus()); + assertTrue(repo.findPendingDeliveries(rc, "session").isEmpty()); + if (taskFails) { + assertEquals(List.of(), callbacks); + } else { + assertEquals(1, callbacks.size()); + assertEquals(TaskStatus.RUNNING, callbacks.get(0).status()); + assertEquals("done", callbacks.get(0).result()); + assertNull(callbacks.get(0).errorMessage()); + } + } + + @Test + void suppressedSettledFailuresRetainDurableErrors() throws Exception { + AtomicInteger callbacks = new AtomicInteger(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callbacks.incrementAndGet()); + for (boolean adopted : List.of(false, true)) { + String sessionId = "suppressed-failure-" + adopted; + RuntimeContext context = + RuntimeContext.builder() + .sessionId(sessionId) + .put(TaskRepository.SUPPRESS_COMPLETION_CALLBACK, true) + .build(); + CompletableFuture future = new CompletableFuture<>(); + TaskRunSpec spec = + adopted + ? new TaskRunSpec.AdoptedTaskRunSpec(future) + : new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new IllegalStateException( + "suppressed execution error"); + }); + BackgroundTask task = + repo.putTask(context, "suppressed-task", "worker", sessionId, spec); + if (adopted) { + future.completeExceptionally( + new IllegalStateException("suppressed execution error")); + } + assertTrue(task.waitForCompletion(5000)); + assertEquals(0, callbacks.get()); + List deliveries = repo.findPendingDeliveries(context, sessionId); + assertEquals(1, deliveries.size()); + TaskDelivery delivery = deliveries.get(0); + assertEquals("suppressed-task", delivery.taskId()); + assertEquals("worker", delivery.agentId()); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertNull(delivery.result()); + assertEquals("suppressed execution error", delivery.errorMessage()); + } + } + // ------------------------------------------------------------------ // Cross-node fallback: no local future // ------------------------------------------------------------------ diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index 06cad4bb03..fc26fe0eb0 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -172,6 +172,8 @@ Automatic delivery and wait barriers include the full output of each result they `task_output` returns the full result of a completed task. +Message-bus notifications distinguish `FAILED` tasks from successful completion and report a fixed error category (execution failure) instead of the raw exception message, which may contain sensitive data; the full error remains available through the task record via `task_output`. Cancelled tasks are announced as `CANCELLED`, matching the persisted terminal state. When the terminal state could not be persisted, no terminal status is announced: a completed result is still delivered once with a notice that it is not on record, while an unrecorded failure or cancellation is not announced. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. + ### Background task tools Behind the scenes, subagent lifecycle is split across two groups of tools: diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index d6c4a3a902..92f0ecaab6 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -168,6 +168,8 @@ RuntimeContext ctx = RuntimeContext.builder() 自动交付和等待屏障会附上此次返回的完整结果。任务状态摘要用于查看执行状态。需要实际输出时,可以用 `task_output` 获取完整结果。 +消息总线通知会区分 `FAILED` 任务和正常完成,并报告固定的错误类别(执行失败),而非可能包含敏感数据的原始异常消息;完整错误仍可通过 `task_output` 从任务记录中获取。取消的任务会按持久化的终态播报为 `CANCELLED`。终态未能持久化时不播报任何终态:已完成任务的结果仍会附带"未落盘"提示送达一次,未落盘的失败或取消则不播报。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 + ### 后台任务工具 子 agent 的生命周期背后由两组工具配合完成: