Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/node/services/taskService.reawakening.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TaskHandleStore } from "@/node/services/taskHandleStore";
import { WorkflowRunStore } from "@/node/services/workflows/WorkflowRunStore";
import { recordAgentWorkflowRunReference } from "@/node/services/agentWorkflowRunReferences";
import { Ok, Err, type Result } from "@/common/types/result";
import { isWorkspaceArchived } from "@/common/utils/archive";
import { formatSubagentReportEnvelope } from "@/common/utils/subagentReportEnvelope";
import type { SendMessageError } from "@/common/types/errors";
import { createMuxMessage, type MuxMessage, type MuxMessageMetadata } from "@/common/types/message";
Expand Down Expand Up @@ -1099,6 +1100,101 @@ describe("TaskService", () => {
]);
});

// F203 (drift scan of F54): the user archives the child while a deferred parent message waits
// for its stream to end. The archive is the later user decision, so the redelivery must not
// unarchive the child. A send to an already archived child still restores it on purpose.
const f203Cases = [
{
name: "does not unarchive a child the user archived during the wait",
archivedAtSend: undefined,
duringWait: { archivedAt: "2026-08-09T00:00:00.000Z" },
archivedAfter: true,
},
{
name: "does not unarchive a child the user unarchived and archived again during the wait",
archivedAtSend: "2026-08-01T00:00:00.000Z",
duringWait: {
unarchivedAt: "2026-08-05T00:00:00.000Z",
archivedAt: "2026-08-09T00:00:00.000Z",
},
archivedAfter: true,
},
{
name: "still unarchives a child that was archived at the send",
archivedAtSend: "2026-08-01T00:00:00.000Z",
duringWait: {},
archivedAfter: false,
},
] as const;
for (const f203 of f203Cases) {
test(`a deferred parent message ${f203.name}`, async () => {
const config = await createTestConfig(rootDir);
const projectPath = path.join(rootDir, "repo");
const parentWorkspaceId = "parent-deferred-archived";
const childTaskId = "child-deferred-archived";
await saveWorkspaces(
config,
projectPath,
[
projectWorkspace(projectPath, "parent", parentWorkspaceId),
projectWorkspace(projectPath, "child", childTaskId, {
runtimeConfig: { type: "local" },
parentWorkspaceId,
taskStatus: "reported",
...(f203.archivedAtSend != null ? { archivedAt: f203.archivedAtSend } : {}),
}),
],
testTaskSettings()
);
let streaming = true;
let releaseIdle: () => void = () => undefined;
const idle = new Promise<void>((resolve) => {
releaseIdle = resolve;
});
const setChildField = (field: "archivedAt" | "unarchivedAt", value: string) =>
config.editConfig((cfg) => {
const workspace = Array.from(cfg.projects.values())
.flatMap((project) => project.workspaces)
.find((candidate) => candidate.id === childTaskId);
if (workspace) workspace[field] = value;
return cfg;
});
const unarchive = mock(async (workspaceId: string): Promise<Result<void>> => {
if (workspaceId === childTaskId)
await setChildField("unarchivedAt", "2026-08-10T00:00:00.000Z");
return Ok(undefined);
});
const { workspaceService } = createWorkspaceServiceMocks({
waitForIdleAndNoQueuedMessages: mock(() => idle),
unarchiveWhileTaskTreeLocked: unarchive,
});
const { aiService } = createAIServiceMocks(config, {
isStreaming: mock((workspaceId: string) => streaming && workspaceId === childTaskId),
});
const { taskService } = createTaskServiceHarness(config, { workspaceService, aiService });

const sent = await taskService.sendMessageToDescendantAgentTask(
parentWorkspaceId,
childTaskId,
"Late decision",
"tool-end"
);
expect(sent.success ? sent.data.delivery : sent.error).toBe("queued");

// What the user does while the message waits.
for (const [field, value] of Object.entries(f203.duringWait)) {
await setChildField(field as "archivedAt" | "unarchivedAt", value);
}
streaming = false;
releaseIdle();
await flushTerminalAttentionDrains(taskService);

const child = findWorkspaceInConfig(config, childTaskId);
expect(isWorkspaceArchived(child?.archivedAt, child?.unarchivedAt)).toBe(f203.archivedAfter);
expect(unarchive.mock.calls.length > 0).toBe(!f203.archivedAfter);
});
}

test("sendMessageToDescendantAgentTask reawakens an inactive child of a scratch parent", async () => {
// Scratch (project-less) chats spawn scratch children in the SCRATCH config bucket; a
// message to an inactive one reawakens it through a mode="existing" workspace turn.
Expand Down
66 changes: 59 additions & 7 deletions src/node/services/taskService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,8 @@ interface DeferredDescendantRedelivery {
attempt: number;
/** Set by the dispatch when the target is still streaming without a task execution. */
deferAgain: boolean;
/** The target's archive at the original send (see DeferredDescendantMessage). */
archivedAtSend: string | null;
}

/** A trusted descendant message whose delivery waits for an idle target (F54). */
Expand All @@ -1306,6 +1308,13 @@ interface DeferredDescendantMessage {
sender: "ancestor" | "sibling";
options: TrustedDescendantMessageOptions | undefined;
stopFence: ReadonlyMap<string, number>;
/**
* F203: the target's archivedAt at the original send, or null when it was not archived. A send
* to an archived task unarchives it on purpose. An archive that lands during the wait (also a
* re-archive after an unarchive) is a later user decision than the message, so, like a Stop, it
* wins over the redelivery.
*/
archivedAtSend: string | null;
}

function resolveDescendantMessageStopFence(
Expand All @@ -1322,6 +1331,22 @@ function isInactiveAgentTaskStatus(
return status === "reported" || status === "interrupted" || legacyArchived;
}

/**
* The target's archive at the original send (F203), or null when the user archived it during the
* wait: that archive is a later user decision than the message and wins, like a Stop. An archive
* is identified by its archivedAt, so a re-archive after an unarchive also counts as new.
*/
function resolveDeferralArchivedAtSend(
redelivery: DeferredDescendantRedelivery | undefined,
target: { archived: boolean; archivedAt: string | undefined }
Comment thread
ThomasK33 marked this conversation as resolved.
Resolved
): { archivedAtSend: string | null } | null {
const current = target.archived ? (target.archivedAt ?? null) : null;
if (redelivery == null) return { archivedAtSend: current };
Comment thread
ThomasK33 marked this conversation as resolved.
Resolved
return current != null && current !== redelivery.archivedAtSend
? null
: { archivedAtSend: redelivery.archivedAtSend };
}

/** After this many idle waits, a deferred message falls back to plain live delivery. */
const MAX_DEFERRED_DESCENDANT_MESSAGE_WAITS = 5;

Expand Down Expand Up @@ -9015,9 +9040,13 @@ export class TaskService implements AgentTaskIntegration {
const inactive =
!continuationActive &&
isInactiveAgentTaskStatus(entry.workspace.taskStatus, legacyArchived);
if (this.deferDescendantMessage(deferral, inactive)) {
return Ok({ delivery: "queued" as const, queueDispatchMode });
}
const deferred = this.deferDescendantMessage(deferral, {
inactive,
archived: legacyArchived,
archivedAt: entry.workspace.archivedAt,
taskStatus: entry.workspace.taskStatus,
});
if (deferred != null) return deferred;
if (inactive && !this.aiService.isStreaming(taskId)) {
return this.reactivateInactiveAgentTask({
ancestorWorkspaceId,
Expand Down Expand Up @@ -9161,15 +9190,33 @@ export class TaskService implements AgentTaskIntegration {
* Send order (F54): while an earlier message to this task waits for the target to go idle, a new
* message queues behind it instead of overtaking it. Redeliveries are the chain itself.
*/
private deferDescendantMessage(params: DeferredDescendantMessage, inactive: boolean): boolean {
private deferDescendantMessage(
deferral: Omit<DeferredDescendantMessage, "archivedAtSend">,
target: {
inactive: boolean;
archived: boolean;
archivedAt: string | undefined;
taskStatus: AgentTaskStatus | undefined;
}
): Result<SendAgentTaskMessageResult, SendAgentTaskMessageError> | null {
const archive = resolveDeferralArchivedAtSend(deferral.options?.redelivery, target);
if (archive == null) {
return Err({
code: "not_active" as const,
taskStatus: target.taskStatus ?? "unknown",
message: "Task workspace was archived while the message waited for its stream to end.",
});
}
const params = { ...deferral, archivedAtSend: archive.archivedAtSend };
const queued = Ok({ delivery: "queued" as const, queueDispatchMode: params.queueDispatchMode });
if (
params.options?.redelivery == null &&
this.deferredDescendantMessagesByTask.has(params.taskId)
) {
this.scheduleDeferredDescendantMessage(params);
return true;
return queued;
}
return inactive && this.deferWhileTargetStreamsWithoutExecution(params);
return target.inactive && this.deferWhileTargetStreamsWithoutExecution(params) ? queued : null;
}

/**
Expand Down Expand Up @@ -9206,7 +9253,12 @@ export class TaskService implements AgentTaskIntegration {
for (let attempt = 0; ; attempt++) {
if (waitForIdle) await this.workspaceService.waitForIdleAndNoQueuedMessages(params.taskId);
waitForIdle = true;
const redelivery = { stopFence: params.stopFence, attempt, deferAgain: false };
const redelivery = {
stopFence: params.stopFence,
attempt,
deferAgain: false,
archivedAtSend: params.archivedAtSend,
};
const result = await this.dispatchTrustedDescendantMessage(
params.ancestorWorkspaceId,
params.taskId,
Expand Down
Loading