fix(orchestrator): Prevent redundant delegated completion turns (#5311)
This commit is contained in:
1 parent
a6216cf3dc
commit
5133fdbed5
28 files changed
+4784
-255
No files matched your search
@@ -10,6 +10,10 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadProjection } from "../../state/use-thread-detail";
|
||||
import {
|
||||
buildCancelQueuedRunCommand,
|
||||
resolveThreadQueueRowControls,
|
||||
} from "./threadQueueControlPresentation";
|
||||
|
||||
export function ThreadQueueControl(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -22,6 +26,7 @@ export function ThreadQueueControl(props: {
|
||||
);
|
||||
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
|
||||
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
|
||||
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "cancel queued message");
|
||||
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
@@ -52,6 +57,19 @@ export function ThreadQueueControl(props: {
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
const dismiss = async (runId: RunId) => {
|
||||
setBusyRunId(runId);
|
||||
void Haptics.selectionAsync();
|
||||
await cancel(
|
||||
buildCancelQueuedRunCommand({
|
||||
environmentId: props.environmentId,
|
||||
runId,
|
||||
threadId: props.threadId,
|
||||
}),
|
||||
);
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<View className="mx-4 mb-3 overflow-hidden rounded-2xl border border-neutral-300/60 bg-card dark:border-white/[0.1]">
|
||||
<View className="flex-row items-center gap-2 border-b border-neutral-300/50 px-3 py-2 dark:border-white/[0.08]">
|
||||
@@ -62,53 +80,69 @@ export function ThreadQueueControl(props: {
|
||||
</Text>
|
||||
</View>
|
||||
<ScrollView style={{ maxHeight: 156 }} contentContainerStyle={{ paddingVertical: 4 }}>
|
||||
{workflow.queuedRuns.map(({ run, text }, index) => (
|
||||
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
|
||||
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
|
||||
{index + 1}
|
||||
</Text>
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
{text}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message up"
|
||||
disabled={busyRunId !== null || !workflow.canReorder || index === 0}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message down"
|
||||
disabled={
|
||||
busyRunId !== null ||
|
||||
!workflow.canReorder ||
|
||||
index === workflow.queuedRuns.length - 1
|
||||
}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Promote queued message to steer"
|
||||
disabled={busyRunId !== null || !workflow.canPromoteToSteer}
|
||||
onPress={() => void steer(run.id)}
|
||||
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.turn.left.up"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
))}
|
||||
{workflow.queuedRuns.map(({ run, text }, index) => {
|
||||
const controls = resolveThreadQueueRowControls({
|
||||
busy: busyRunId !== null,
|
||||
canPromoteToSteer: workflow.canPromoteToSteer,
|
||||
canReorder: workflow.canReorder,
|
||||
index,
|
||||
queuedCount: workflow.queuedRuns.length,
|
||||
text,
|
||||
});
|
||||
|
||||
return (
|
||||
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
|
||||
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
|
||||
{index + 1}
|
||||
</Text>
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
{controls.displayText}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message up"
|
||||
disabled={!controls.canMoveUp}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message down"
|
||||
disabled={!controls.canMoveDown}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Promote queued message to steer"
|
||||
disabled={!controls.canSteer}
|
||||
onPress={() => void steer(run.id)}
|
||||
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.turn.left.up"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={controls.dismissAccessibilityLabel}
|
||||
disabled={!controls.canDismiss}
|
||||
onPress={() => void dismiss(run.id)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
|
||||
buildCancelQueuedRunCommand,
|
||||
resolveThreadQueueRowControls,
|
||||
} from "./threadQueueControlPresentation";
|
||||
|
||||
describe("threadQueueControlPresentation", () => {
|
||||
it("preserves queue reorder and steer controls with removal", () => {
|
||||
const controls = resolveThreadQueueRowControls({
|
||||
busy: false,
|
||||
canPromoteToSteer: true,
|
||||
canReorder: true,
|
||||
index: 1,
|
||||
queuedCount: 3,
|
||||
text: "Please review the follow-up change.",
|
||||
});
|
||||
|
||||
expect(controls.displayText).toBe("Please review the follow-up change.");
|
||||
expect(controls.canMoveUp).toBe(true);
|
||||
expect(controls.canMoveDown).toBe(true);
|
||||
expect(controls.canSteer).toBe(true);
|
||||
expect(controls.canDismiss).toBe(true);
|
||||
expect(controls.dismissAccessibilityLabel).toBe(REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL);
|
||||
});
|
||||
|
||||
it("disables edge reorder controls and busy dismissal", () => {
|
||||
const first = resolveThreadQueueRowControls({
|
||||
busy: false,
|
||||
canPromoteToSteer: false,
|
||||
canReorder: true,
|
||||
index: 0,
|
||||
queuedCount: 2,
|
||||
text: "First",
|
||||
});
|
||||
const busy = resolveThreadQueueRowControls({
|
||||
busy: true,
|
||||
canPromoteToSteer: true,
|
||||
canReorder: true,
|
||||
index: 0,
|
||||
queuedCount: 1,
|
||||
text: "Queued message",
|
||||
});
|
||||
|
||||
expect(first.canMoveUp).toBe(false);
|
||||
expect(first.canMoveDown).toBe(true);
|
||||
expect(first.canSteer).toBe(false);
|
||||
expect(busy.canDismiss).toBe(false);
|
||||
expect(busy.canMoveUp).toBe(false);
|
||||
expect(busy.canSteer).toBe(false);
|
||||
});
|
||||
|
||||
it("builds cancelQueuedRun command arguments for removal", () => {
|
||||
expect(
|
||||
buildCancelQueuedRunCommand({
|
||||
environmentId: "environment:test" as never,
|
||||
runId: "run:queued" as never,
|
||||
threadId: "thread:test" as never,
|
||||
}),
|
||||
).toEqual({
|
||||
environmentId: "environment:test",
|
||||
input: {
|
||||
runId: "run:queued",
|
||||
threadId: "thread:test",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = "Remove queued message";
|
||||
|
||||
export interface ThreadQueueRowControls {
|
||||
readonly canDismiss: boolean;
|
||||
readonly canMoveDown: boolean;
|
||||
readonly canMoveUp: boolean;
|
||||
readonly canSteer: boolean;
|
||||
readonly dismissAccessibilityLabel: string;
|
||||
readonly displayText: string;
|
||||
}
|
||||
|
||||
export function resolveThreadQueueRowControls(input: {
|
||||
readonly busy: boolean;
|
||||
readonly canPromoteToSteer: boolean;
|
||||
readonly canReorder: boolean;
|
||||
readonly index: number;
|
||||
readonly queuedCount: number;
|
||||
readonly text: string;
|
||||
}): ThreadQueueRowControls {
|
||||
const mutationEnabled = !input.busy;
|
||||
|
||||
return {
|
||||
canDismiss: !input.busy,
|
||||
canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
|
||||
canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
|
||||
canSteer: mutationEnabled && input.canPromoteToSteer,
|
||||
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
|
||||
displayText: input.text,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCancelQueuedRunCommand(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly runId: RunId;
|
||||
readonly threadId: ThreadId;
|
||||
}): {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: {
|
||||
readonly runId: RunId;
|
||||
readonly threadId: ThreadId;
|
||||
};
|
||||
} {
|
||||
return {
|
||||
environmentId: input.environmentId,
|
||||
input: {
|
||||
runId: input.runId,
|
||||
threadId: input.threadId,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
NodeId,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
|
||||
import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
|
||||
import type { McpInvocationScope } from "./McpInvocationContext.ts";
|
||||
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
|
||||
|
||||
describe("OrchestratorMcpService", () => {
|
||||
it.effect("retries terminal acknowledgement with a fresh command id", () =>
|
||||
Effect.gen(function* () {
|
||||
const parentThreadId = ThreadId.make("thread:mcp-ack-parent");
|
||||
const childThreadId = ThreadId.make("thread:mcp-ack-child");
|
||||
const childRunId = RunId.make("run:mcp-ack-child");
|
||||
const taskId = NodeId.make("node:mcp-ack-task");
|
||||
const acknowledgementCommandIds = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const acknowledgementAttempts = yield* Ref.make(0);
|
||||
const parentProjection = {
|
||||
thread: { id: parentThreadId },
|
||||
runs: [],
|
||||
contextTransfers: [],
|
||||
subagents: [
|
||||
{
|
||||
id: taskId,
|
||||
threadId: parentThreadId,
|
||||
origin: "app_owned",
|
||||
childThreadId,
|
||||
driver: "codex",
|
||||
model: "gpt-5.6-terra",
|
||||
result: "terminal result",
|
||||
completionDelivery: { state: "pending" },
|
||||
},
|
||||
],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const childProjection = {
|
||||
thread: { id: childThreadId },
|
||||
runs: [{ id: childRunId, ordinal: 1, status: "completed" }],
|
||||
contextTransfers: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const dependencies = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: (threadId) =>
|
||||
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
|
||||
dispatch: (command) =>
|
||||
Ref.update(acknowledgementCommandIds, (commandIds) => [
|
||||
...commandIds,
|
||||
String(command.commandId),
|
||||
]).pipe(
|
||||
Effect.andThen(Ref.updateAndGet(acknowledgementAttempts, (count) => count + 1)),
|
||||
Effect.flatMap((attempt) =>
|
||||
attempt === 1
|
||||
? Effect.fail(new Error("simulated acknowledgement failure") as never)
|
||||
: Effect.succeed({} as never),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }),
|
||||
Layer.mock(ScheduledTaskService)({}),
|
||||
);
|
||||
const scope: McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment:mcp-ack"),
|
||||
threadId: parentThreadId,
|
||||
providerSessionId: "provider-session:mcp-ack",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["orchestration"]),
|
||||
issuedAt: 1,
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
|
||||
const error = yield* service.taskStatus(scope, taskId).pipe(Effect.flip);
|
||||
assert.equal(error.code, "orchestration_error");
|
||||
|
||||
const result = yield* service.taskStatus(scope, taskId);
|
||||
assert.equal(result.status, "completed");
|
||||
assert.equal(result.summary, "terminal result");
|
||||
const commandIds = yield* Ref.get(acknowledgementCommandIds);
|
||||
assert.equal(commandIds.length, 2);
|
||||
assert.notEqual(commandIds[0], commandIds[1]);
|
||||
}).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies))));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not dispose delivery when a nonterminal task has no active child run", () =>
|
||||
Effect.gen(function* () {
|
||||
const parentThreadId = ThreadId.make("thread:mcp-cancel-parent");
|
||||
const childThreadId = ThreadId.make("thread:mcp-cancel-child");
|
||||
const taskId = NodeId.make("node:mcp-cancel-task");
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
|
||||
const parentProjection = {
|
||||
thread: { id: parentThreadId },
|
||||
runs: [],
|
||||
contextTransfers: [],
|
||||
subagents: [
|
||||
{
|
||||
id: taskId,
|
||||
threadId: parentThreadId,
|
||||
origin: "app_owned",
|
||||
childThreadId,
|
||||
driver: "codex",
|
||||
model: "gpt-5.6-terra",
|
||||
result: null,
|
||||
completionDelivery: { state: "pending" },
|
||||
},
|
||||
],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const childProjection = {
|
||||
thread: { id: childThreadId },
|
||||
runs: [],
|
||||
contextTransfers: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const dependencies = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: (threadId) =>
|
||||
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.as({} as never),
|
||||
),
|
||||
}),
|
||||
Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }),
|
||||
Layer.mock(ScheduledTaskService)({}),
|
||||
);
|
||||
const scope: McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment:mcp-cancel"),
|
||||
threadId: parentThreadId,
|
||||
providerSessionId: "provider-session:mcp-cancel",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["orchestration"]),
|
||||
issuedAt: 1,
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
|
||||
const error = yield* service
|
||||
.cancelTask(scope, { taskId, clientRequestId: "cancel-unstarted-task" })
|
||||
.pipe(Effect.flip);
|
||||
assert.equal(error.code, "task_not_cancellable");
|
||||
assert.deepEqual(yield* Ref.get(dispatched), []);
|
||||
}).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies))));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not dispose delivery when the child interrupt fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent");
|
||||
const childThreadId = ThreadId.make("thread:mcp-cancel-failed-child");
|
||||
const childRunId = RunId.make("run:mcp-cancel-failed-child");
|
||||
const taskId = NodeId.make("node:mcp-cancel-failed-task");
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
|
||||
const parentProjection = {
|
||||
thread: { id: parentThreadId },
|
||||
runs: [],
|
||||
contextTransfers: [],
|
||||
subagents: [
|
||||
{
|
||||
id: taskId,
|
||||
threadId: parentThreadId,
|
||||
origin: "app_owned",
|
||||
childThreadId,
|
||||
driver: "codex",
|
||||
model: "gpt-5.6-terra",
|
||||
result: null,
|
||||
completionDelivery: { state: "pending" },
|
||||
},
|
||||
],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const childProjection = {
|
||||
thread: { id: childThreadId },
|
||||
runs: [{ id: childRunId, status: "running" }],
|
||||
contextTransfers: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const dependencies = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: (threadId) =>
|
||||
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.andThen(Effect.fail(new Error("simulated interrupt failure") as never)),
|
||||
),
|
||||
}),
|
||||
Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }),
|
||||
Layer.mock(ScheduledTaskService)({}),
|
||||
);
|
||||
const scope: McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment:mcp-cancel-failed"),
|
||||
threadId: parentThreadId,
|
||||
providerSessionId: "provider-session:mcp-cancel-failed",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["orchestration"]),
|
||||
issuedAt: 1,
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
|
||||
const error = yield* service
|
||||
.cancelTask(scope, { taskId, clientRequestId: "cancel-failed-task" })
|
||||
.pipe(Effect.flip);
|
||||
assert.equal(error.code, "task_not_cancellable");
|
||||
assert.deepEqual(
|
||||
(yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type),
|
||||
["run.interrupt"],
|
||||
);
|
||||
}).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies))));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns cancel requested when post-interrupt disposal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent");
|
||||
const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-child");
|
||||
const childRunId = RunId.make("run:mcp-cancel-dispose-failed-child");
|
||||
const taskId = NodeId.make("node:mcp-cancel-dispose-failed-task");
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]);
|
||||
const parentProjection = {
|
||||
thread: { id: parentThreadId },
|
||||
runs: [],
|
||||
contextTransfers: [],
|
||||
subagents: [
|
||||
{
|
||||
id: taskId,
|
||||
threadId: parentThreadId,
|
||||
origin: "app_owned",
|
||||
childThreadId,
|
||||
driver: "codex",
|
||||
model: "gpt-5.6-terra",
|
||||
result: null,
|
||||
completionDelivery: { state: "pending" },
|
||||
},
|
||||
],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const childProjection = {
|
||||
thread: { id: childThreadId },
|
||||
runs: [{ id: childRunId, status: "running" }],
|
||||
contextTransfers: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const dependencies = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: (threadId) =>
|
||||
Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.andThen(
|
||||
command.type === "delegated_task.completion-delivery.dispose"
|
||||
? Effect.fail(new Error("simulated disposal failure") as never)
|
||||
: Effect.succeed({} as never),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }),
|
||||
Layer.mock(ScheduledTaskService)({}),
|
||||
);
|
||||
const scope: McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-failed"),
|
||||
threadId: parentThreadId,
|
||||
providerSessionId: "provider-session:mcp-cancel-dispose-failed",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["orchestration"]),
|
||||
issuedAt: 1,
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
|
||||
const result = yield* service.cancelTask(scope, {
|
||||
taskId,
|
||||
clientRequestId: "cancel-dispose-failed-task",
|
||||
});
|
||||
assert.equal(result.status, "cancel_requested");
|
||||
assert.deepEqual(
|
||||
(yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type),
|
||||
["run.interrupt", "delegated_task.completion-delivery.dispose"],
|
||||
);
|
||||
}).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies))));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -328,6 +328,50 @@ function isTerminalTaskStatus(
|
||||
);
|
||||
}
|
||||
|
||||
function directAppOwnedChildTask(
|
||||
parent: OrchestrationV2ThreadProjection,
|
||||
target: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2Subagent | undefined {
|
||||
if (
|
||||
target.thread.lineage.parentThreadId !== parent.thread.id ||
|
||||
target.thread.lineage.relationshipToParent !== "subagent"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return parent.subagents.find(
|
||||
(task) =>
|
||||
task.origin === "app_owned" &&
|
||||
task.threadId === parent.thread.id &&
|
||||
task.childThreadId === target.thread.id,
|
||||
);
|
||||
}
|
||||
|
||||
function pageIncludesTerminalTaskResult(input: {
|
||||
readonly page: ReadonlyArray<OrchestrationV2ThreadProjection["visibleTurnItems"][number]>;
|
||||
readonly task: OrchestrationV2Subagent;
|
||||
readonly target: OrchestrationV2ThreadProjection;
|
||||
readonly maxChars: number;
|
||||
}): boolean {
|
||||
const run = delegatedTaskRun(input.target, input.task);
|
||||
if (run === undefined || !isTerminalTaskStatus(taskStatusForRun(run))) return false;
|
||||
|
||||
const result = subagentResultForRun(input.target, run);
|
||||
if (result.messageId === null && result.turnItemId === null) return false;
|
||||
|
||||
return input.page.some((row) => {
|
||||
if (row.sourceThreadId !== input.target.thread.id) return false;
|
||||
const matchesResult =
|
||||
(result.turnItemId !== null && row.sourceItemId === result.turnItemId) ||
|
||||
(result.messageId !== null &&
|
||||
row.item.type === "assistant_message" &&
|
||||
row.item.messageId === result.messageId);
|
||||
if (!matchesResult) return false;
|
||||
|
||||
const text = turnItemText(row.item);
|
||||
return text !== null && text.length <= input.maxChars;
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeModeRank(mode: RuntimeMode): number {
|
||||
switch (mode) {
|
||||
case "approval-required":
|
||||
@@ -792,6 +836,8 @@ const make = Effect.gen(function* () {
|
||||
scope: McpInvocationScope,
|
||||
taskId: NodeId,
|
||||
waitTimedOut = false,
|
||||
acknowledgeTerminal = false,
|
||||
acknowledgementOperation = "task-status-acknowledge",
|
||||
): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
@@ -824,7 +870,7 @@ const make = Effect.gen(function* () {
|
||||
transfer.sourceThreadId === task.childThreadId &&
|
||||
transfer.targetThreadId === scope.threadId,
|
||||
) ?? null;
|
||||
return {
|
||||
const response = {
|
||||
taskId: task.id,
|
||||
childThreadId: task.childThreadId,
|
||||
childRunId: childRun?.id ?? null,
|
||||
@@ -835,13 +881,46 @@ const make = Effect.gen(function* () {
|
||||
summary: derivedResult,
|
||||
resultContextTransferId: resultTransfer?.id ?? null,
|
||||
waitTimedOut,
|
||||
};
|
||||
} satisfies OrchestratorMcpDelegateTaskResult;
|
||||
if (
|
||||
acknowledgeTerminal &&
|
||||
isTerminalTaskStatus(status) &&
|
||||
task.completionDelivery?.state !== "acknowledged" &&
|
||||
task.completionDelivery?.state !== "disposed"
|
||||
) {
|
||||
const observingRun = latestActiveRun(parentProjection);
|
||||
const acknowledgementRequestKey = yield* requestKey(undefined);
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "delegated_task.completion-delivery.acknowledge",
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: acknowledgementRequestKey,
|
||||
operation: acknowledgementOperation,
|
||||
}),
|
||||
parentThreadId: scope.threadId,
|
||||
taskId,
|
||||
observedByRunId:
|
||||
observingRun?.providerInstanceId === scope.providerInstanceId
|
||||
? observingRun.id
|
||||
: null,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure(
|
||||
"orchestration_error",
|
||||
`Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return response;
|
||||
});
|
||||
|
||||
const waitForTask = (scope: McpInvocationScope, taskId: NodeId, timeoutMs: number) =>
|
||||
Effect.gen(function* () {
|
||||
while (true) {
|
||||
const result = yield* readTask(scope, taskId);
|
||||
const result = yield* readTask(scope, taskId, false, true);
|
||||
if (isTerminalTaskStatus(result.status)) return result;
|
||||
yield* Effect.sleep(Duration.millis(TASK_POLL_INTERVAL_MS));
|
||||
}
|
||||
@@ -1113,7 +1192,7 @@ const make = Effect.gen(function* () {
|
||||
const taskId = taskEvent.event.payload.id;
|
||||
|
||||
if (input.mode !== "wait") {
|
||||
return yield* readTask(scope, taskId);
|
||||
return yield* readTask(scope, taskId, false, true);
|
||||
}
|
||||
const timeoutMs = Math.min(
|
||||
MAX_WAIT_TIMEOUT_MS,
|
||||
@@ -1162,13 +1241,42 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* readTask(scope, taskId, true);
|
||||
return yield* readTask(scope, taskId, true, true);
|
||||
}),
|
||||
taskStatus: (scope, taskId) => readTask(scope, taskId),
|
||||
taskStatus: (scope, taskId) => readTask(scope, taskId, false, true),
|
||||
cancelTask: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* readTask(scope, input.taskId);
|
||||
const key = yield* requestKey(input.clientRequestId);
|
||||
const parentProjection = yield* loadProjection(scope.threadId);
|
||||
const parentTask = parentProjection.subagents.find(
|
||||
(task) => task.id === input.taskId && task.origin === "app_owned",
|
||||
);
|
||||
const disposeCompletionDelivery =
|
||||
parentTask?.completionDelivery?.state === "disposed"
|
||||
? Effect.void
|
||||
: threadManagement
|
||||
.dispatch({
|
||||
type: "delegated_task.completion-delivery.dispose",
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
operation: "cancel-task-completion-delivery",
|
||||
}),
|
||||
parentThreadId: scope.threadId,
|
||||
taskId: input.taskId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError((error) =>
|
||||
failure(
|
||||
"orchestration_error",
|
||||
`Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (isTerminalTaskStatus(current.status)) {
|
||||
yield* disposeCompletionDelivery;
|
||||
return {
|
||||
taskId: input.taskId,
|
||||
status: current.status,
|
||||
@@ -1184,7 +1292,6 @@ const make = Effect.gen(function* () {
|
||||
`Delegated task ${input.taskId} has no interruptible child run.`,
|
||||
);
|
||||
}
|
||||
const key = yield* requestKey(input.clientRequestId);
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "run.interrupt",
|
||||
@@ -1205,6 +1312,14 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* disposeCompletionDelivery.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {
|
||||
taskId: input.taskId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
taskId: input.taskId,
|
||||
status: "cancel_requested",
|
||||
@@ -1393,7 +1508,7 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
readThread: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const { target } = yield* loadScopedThread(scope, input.threadId);
|
||||
const { parent, target } = yield* loadScopedThread(scope, input.threadId);
|
||||
const view = input.view ?? "messages";
|
||||
const afterPosition = input.afterPosition ?? -1;
|
||||
const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
|
||||
@@ -1429,6 +1544,13 @@ const make = Effect.gen(function* () {
|
||||
(projection) => [projection.thread.id, projection.messages] as const,
|
||||
),
|
||||
]);
|
||||
const task = directAppOwnedChildTask(parent, target);
|
||||
if (
|
||||
task !== undefined &&
|
||||
pageIncludesTerminalTaskResult({ page, task, target, maxChars })
|
||||
) {
|
||||
yield* readTask(scope, task.id, false, true, "thread-read-acknowledge");
|
||||
}
|
||||
return {
|
||||
thread: threadDetail(target),
|
||||
recentRuns: target.runs
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -62,7 +62,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", {
|
||||
|
||||
export const TaskStatusTool = Tool.make("task_status", {
|
||||
description:
|
||||
"Read the latest durable state and final summary for a T3-owned delegated task created by this parent thread.",
|
||||
"Read the latest durable state and final summary for a T3-owned delegated task created by this parent thread. Reading a terminal result acknowledges its automatic parent delivery.",
|
||||
parameters: OrchestratorMcpTaskStatusInput,
|
||||
success: OrchestratorMcpDelegateTaskResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
@@ -70,13 +70,13 @@ export const TaskStatusTool = Tool.make("task_status", {
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Get delegated task status")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Readonly, false)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const TaskCancelTool = Tool.make("task_cancel", {
|
||||
description:
|
||||
"Request interruption of an active T3-owned delegated task. Completed tasks are returned unchanged.",
|
||||
"Request interruption of an active T3-owned delegated task and dispose its automatic parent delivery. Completed task results remain available.",
|
||||
parameters: OrchestratorMcpTaskCancelInput,
|
||||
success: OrchestratorMcpTaskCancelResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
@@ -178,7 +178,7 @@ export const ThreadListTool = Tool.make("t3_thread_list", {
|
||||
|
||||
export const ThreadReadTool = Tool.make("t3_thread_read", {
|
||||
description:
|
||||
"Read durable state and a paginated timeline from a T3 thread in the calling project. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Continue with afterPosition=nextPosition.",
|
||||
"Read durable state and a paginated timeline from a T3 thread in the calling project. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition.",
|
||||
parameters: OrchestratorMcpThreadReadInput,
|
||||
success: OrchestratorMcpThreadReadResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
@@ -186,7 +186,7 @@ export const ThreadReadTool = Tool.make("t3_thread_read", {
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Read a T3 thread")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Readonly, false)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
@@ -205,7 +205,7 @@ export const ThreadSendTool = Tool.make("t3_thread_send", {
|
||||
|
||||
export const ThreadWaitTool = Tool.make("t3_thread_wait", {
|
||||
description:
|
||||
"Wait for a T3 thread run to reach a terminal durable state. Without runId, the latest run at call time is selected; an idle thread returns immediately. Timeout does not interrupt work, so call again or use t3_thread_read/list after timedOut=true.",
|
||||
"Wait for a T3 thread run to reach a terminal durable state. Without runId, the latest run at call time is selected; an idle thread returns immediately. Timeout does not interrupt work, so call again or use t3_thread_read/list after timedOut=true. Waiting reports status only and does not acknowledge a delegated result.",
|
||||
parameters: OrchestratorMcpThreadWaitInput,
|
||||
success: OrchestratorMcpThreadWaitResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
|
||||
@@ -712,10 +712,8 @@ export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*";
|
||||
// ClaudeAdapterV2.test.ts cross-checks this list against the toolkit.
|
||||
export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
|
||||
"mcp__t3-code__orchestrator_capabilities",
|
||||
"mcp__t3-code__task_status",
|
||||
"mcp__t3-code__list_scheduled_tasks",
|
||||
"mcp__t3-code__t3_thread_list",
|
||||
"mcp__t3-code__t3_thread_read",
|
||||
"mcp__t3-code__t3_thread_wait",
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
CheckpointId,
|
||||
CheckpointRef,
|
||||
CheckpointScopeId,
|
||||
EventId,
|
||||
MessageId,
|
||||
NodeId,
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2Run,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ProjectionStore from "./ProjectionStore.ts";
|
||||
|
||||
const ProjectionStoreTestLayer = Layer.mergeAll(
|
||||
ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
SqlitePersistenceMemory,
|
||||
);
|
||||
|
||||
const threadId = ThreadId.make("thread:checkpoint-capture-delegated");
|
||||
const projectId = ProjectId.make("project:checkpoint-capture-delegated");
|
||||
const runId = RunId.make("run:checkpoint-capture-delegated");
|
||||
const scopeId = CheckpointScopeId.make("scope:checkpoint-capture-delegated");
|
||||
const rootNodeId = NodeId.make("node:checkpoint-capture-delegated-root");
|
||||
const taskId = NodeId.make("node:checkpoint-capture-task");
|
||||
const deliveryMessageId = MessageId.make("message:checkpoint-capture-delivery");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread:checkpoint-capture-delegated");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const driver = ProviderDriverKind.make("codex");
|
||||
const modelSelection = {
|
||||
instanceId: providerInstanceId,
|
||||
model: "gpt-5.4",
|
||||
} as const;
|
||||
|
||||
it.layer(ProjectionStoreTestLayer)("CheckpointCaptureServiceV2", (it) => {
|
||||
it.effect(
|
||||
"preserves a newer delegatedCompletion cohort when checkpoint run.updated is applied after it",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
|
||||
const now = yield* DateTime.now;
|
||||
const later = DateTime.add(now, { seconds: 1 });
|
||||
|
||||
const staleDelegatedCompletion = {
|
||||
disposition: "open" as const,
|
||||
nextGeneration: 1,
|
||||
settledDeliveryCount: 0,
|
||||
delivery: null,
|
||||
};
|
||||
const newerCohort = {
|
||||
disposition: "open" as const,
|
||||
nextGeneration: 2,
|
||||
settledDeliveryCount: 1,
|
||||
delivery: {
|
||||
generation: 1,
|
||||
messageId: deliveryMessageId,
|
||||
taskIds: [taskId],
|
||||
},
|
||||
};
|
||||
const staleRun: OrchestrationV2Run = {
|
||||
id: runId,
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
providerThreadId,
|
||||
userMessageId: MessageId.make("message:checkpoint-capture-user"),
|
||||
rootNodeId,
|
||||
activeAttemptId: null,
|
||||
status: "waiting",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
// Snapshot taken before a concurrent cohort advanced during capture work.
|
||||
delegatedCompletion: staleDelegatedCompletion,
|
||||
};
|
||||
const rootNode = {
|
||||
id: rootNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
parentNodeId: null,
|
||||
rootNodeId,
|
||||
kind: "root_turn" as const,
|
||||
status: "waiting" as const,
|
||||
countsForRun: true,
|
||||
providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: scopeId,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
};
|
||||
const scope = {
|
||||
id: scopeId,
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
parentScopeId: null,
|
||||
providerThreadId,
|
||||
kind: "root_run" as const,
|
||||
ordinalWithinParent: 0,
|
||||
advancesAppRunCount: true,
|
||||
cwd: "/repo",
|
||||
createdAt: now,
|
||||
};
|
||||
const providerThread = {
|
||||
id: providerThreadId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
providerSessionId: null,
|
||||
appThreadId: threadId,
|
||||
ownerNodeId: rootNodeId,
|
||||
nativeThreadRef: null,
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle" as const,
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 1,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const readyBaseline = {
|
||||
id: CheckpointId.make("checkpoint:baseline-0"),
|
||||
threadId,
|
||||
scopeId,
|
||||
runId: null,
|
||||
nodeId: rootNodeId,
|
||||
parentCheckpointId: null,
|
||||
ordinalWithinScope: 0,
|
||||
appRunOrdinal: null,
|
||||
ref: CheckpointRef.make("checkpoint-ref:baseline-0"),
|
||||
status: "ready" as const,
|
||||
files: [],
|
||||
capturedAt: now,
|
||||
};
|
||||
const captured = {
|
||||
id: CheckpointId.make("checkpoint:captured-1"),
|
||||
threadId,
|
||||
scopeId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
parentCheckpointId: readyBaseline.id,
|
||||
ordinalWithinScope: 1,
|
||||
appRunOrdinal: 1,
|
||||
ref: CheckpointRef.make("checkpoint-ref:captured-1"),
|
||||
status: "ready" as const,
|
||||
files: [],
|
||||
capturedAt: now,
|
||||
};
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:thread"),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Checkpoint capture delegated completion",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:run-stale"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: staleRun,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:node"),
|
||||
type: "node.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: rootNode,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:provider-thread"),
|
||||
type: "provider-thread.updated",
|
||||
threadId,
|
||||
nodeId: rootNodeId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: providerThread,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:scope"),
|
||||
type: "checkpoint-scope.created",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
occurredAt: now,
|
||||
payload: scope,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:baseline"),
|
||||
type: "checkpoint.captured",
|
||||
threadId,
|
||||
nodeId: rootNodeId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: readyBaseline,
|
||||
});
|
||||
|
||||
const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
|
||||
const captureLayer = CheckpointCaptureService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
IdAllocator.layer,
|
||||
Layer.mock(CheckpointServiceV2)({
|
||||
materializeBaselineCheckpoint: () =>
|
||||
Effect.die("baseline materialization must be skipped when ordinal 0 is ready"),
|
||||
capture: () => Effect.succeed(captured),
|
||||
}),
|
||||
Layer.mock(EventSinkV2)({
|
||||
commitCommand: (input) =>
|
||||
Ref.set(committed, input.events).pipe(
|
||||
Effect.as({
|
||||
commandId: input.commandId,
|
||||
committed: true,
|
||||
sequence: 1,
|
||||
events: input.events,
|
||||
effects: [],
|
||||
} as never),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
|
||||
// Capture reads the waiting run while the projection still holds the stale cohort.
|
||||
yield* service.execute({ threadId, runId, scopeId });
|
||||
|
||||
const events = yield* Ref.get(committed);
|
||||
const runUpdated = events.find((event) => event.type === "run.updated");
|
||||
assert.isDefined(runUpdated);
|
||||
if (runUpdated?.type !== "run.updated") {
|
||||
return;
|
||||
}
|
||||
assert.equal(runUpdated.payload.status, "completed");
|
||||
assert.equal(runUpdated.payload.checkpointId, captured.id);
|
||||
assert.isUndefined(
|
||||
runUpdated.payload.delegatedCompletion,
|
||||
"checkpoint capture must omit delegatedCompletion so ProjectionStore can keep a newer cohort",
|
||||
);
|
||||
|
||||
// Race: a newer cohort lands on the projection after capture read the stale
|
||||
// waiting run and before the capture command's run.updated is applied.
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:checkpoint-capture:newer-cohort"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId,
|
||||
occurredAt: later,
|
||||
payload: {
|
||||
...staleRun,
|
||||
delegatedCompletion: newerCohort,
|
||||
},
|
||||
});
|
||||
|
||||
// Apply the real capture-emitted run.updated through ProjectionStore.
|
||||
yield* projectionStore.apply(runUpdated);
|
||||
|
||||
const projection = yield* projectionStore.getThreadProjection(threadId);
|
||||
const projectedRun = projection.runs[0];
|
||||
assert.isDefined(projectedRun);
|
||||
assert.equal(projectedRun?.status, "completed");
|
||||
assert.equal(projectedRun?.checkpointId, captured.id);
|
||||
assert.deepEqual(projectedRun?.delegatedCompletion, newerCohort);
|
||||
assert.equal(projectedRun?.delegatedCompletion?.delivery?.messageId, deliveryMessageId);
|
||||
assert.deepEqual(projectedRun?.delegatedCompletion?.delivery?.taskIds, [taskId]);
|
||||
}).pipe(Effect.provide(captureLayer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -122,6 +122,11 @@ export const layer: Layer.Layer<
|
||||
appRunOrdinal: run.ordinal,
|
||||
capturedAt,
|
||||
});
|
||||
// Match RunExecutionService: capture loaded the waiting run before
|
||||
// materializing baselines. Omit delegatedCompletion so a newer cohort
|
||||
// write during capture is not overwritten by this stale snapshot
|
||||
// (ProjectionStore preserves the field when absent from the payload).
|
||||
const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
|
||||
const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
|
||||
yield* eventSink.commitCommand({
|
||||
commandId,
|
||||
@@ -196,7 +201,7 @@ export const layer: Layer.Layer<
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: capturedAt,
|
||||
payload: {
|
||||
...run,
|
||||
...runWithoutDelegatedCompletion,
|
||||
status: "completed",
|
||||
completedAt: capturedAt,
|
||||
checkpointId: checkpoint.id,
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
NodeId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { OrchestratorV2 } from "./Orchestrator.ts";
|
||||
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
import { OrchestrationV2EventSinkLayerLive, OrchestrationV2LayerLive } from "./runtimeLayer.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-v2-delegated-completion-",
|
||||
});
|
||||
|
||||
const modelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
const VcsDriverRegistryTestLayer = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProcess.layer),
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const CheckpointStoreTestLayer = CheckpointStore.layer.pipe(
|
||||
Layer.provide(VcsDriverRegistryTestLayer),
|
||||
);
|
||||
|
||||
const driver = ProviderDriverKind.make("codex");
|
||||
const orchestrationAdapter = {
|
||||
instanceId: modelSelection.instanceId,
|
||||
driver,
|
||||
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
|
||||
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
|
||||
openSession: () => Effect.die("sessions are not used by delegated completion tests"),
|
||||
} as ProviderAdapterV2Shape;
|
||||
const providerInstance = {
|
||||
instanceId: modelSelection.instanceId,
|
||||
driverKind: driver,
|
||||
continuationIdentity: {
|
||||
driverKind: driver,
|
||||
continuationKey: "codex:test",
|
||||
},
|
||||
displayName: "Codex test",
|
||||
enabled: true,
|
||||
snapshot: {} as ProviderInstance["snapshot"],
|
||||
orchestrationAdapter,
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined),
|
||||
listInstances: Effect.succeed([providerInstance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.never,
|
||||
});
|
||||
|
||||
const TestLayer = Layer.mergeAll(
|
||||
OrchestrationLayerLive,
|
||||
OrchestrationV2LayerLive,
|
||||
OrchestrationV2EventSinkLayerLive,
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectEnrichmentService, {
|
||||
peek: () =>
|
||||
Effect.succeed({
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
repositoryIdentityResolved: false,
|
||||
}),
|
||||
request: () => Effect.void,
|
||||
getAvailable: () =>
|
||||
Effect.succeed({
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
repositoryIdentityResolved: false,
|
||||
}),
|
||||
invalidate: () => Effect.void,
|
||||
subscribeChanges: Effect.never,
|
||||
}),
|
||||
),
|
||||
Layer.provide(mcpSessionRegistryTestLayer),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(CheckpointStoreTestLayer),
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(ServerSettingsService.layerTest()),
|
||||
Layer.provide(TestProviderInstanceRegistry),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const seedParentWithTerminalTask = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly runId: RunId;
|
||||
readonly rootNodeId: NodeId;
|
||||
readonly taskId: NodeId;
|
||||
readonly deliveryState: "delivered" | "claimed" | "acknowledged" | "disposed";
|
||||
readonly completionWake?: "always" | "settled_only";
|
||||
readonly deliveryTaskIds?: ReadonlyArray<NodeId>;
|
||||
readonly now: DateTime.Utc;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const applicationEngine = yield* OrchestrationEngineService;
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const providerThreadId = ProviderThreadId.make(
|
||||
`provider-thread:${String(input.threadId).replace("thread:", "")}`,
|
||||
);
|
||||
|
||||
yield* applicationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(`command:seed-project:${input.threadId}`),
|
||||
projectId: input.projectId,
|
||||
title: "Delegated completion delivery",
|
||||
workspaceRoot: `/workspace/${input.projectId}`,
|
||||
defaultModelSelection: modelSelection,
|
||||
scripts: [],
|
||||
createdAt: DateTime.formatIso(input.now),
|
||||
});
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make(`command:seed-create:${input.threadId}`),
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Delegated completion delivery",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
commandId: CommandId.make(`command:seed-projection:${input.threadId}`),
|
||||
events: [
|
||||
{
|
||||
id: EventId.make(`event:seed-provider-thread:${input.threadId}`),
|
||||
type: "provider-thread.updated",
|
||||
threadId: input.threadId,
|
||||
driver,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: input.now,
|
||||
payload: {
|
||||
id: providerThreadId,
|
||||
driver,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
providerSessionId: null,
|
||||
appThreadId: input.threadId,
|
||||
ownerNodeId: input.rootNodeId,
|
||||
nativeThreadRef: {
|
||||
driver,
|
||||
nativeId: `native:${input.threadId}`,
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "active",
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 1,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: EventId.make(`event:seed-run:${input.threadId}`),
|
||||
type: "run.updated",
|
||||
threadId: input.threadId,
|
||||
runId: input.runId,
|
||||
nodeId: input.rootNodeId,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: input.now,
|
||||
payload: {
|
||||
id: input.runId,
|
||||
threadId: input.threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
modelSelection,
|
||||
providerThreadId,
|
||||
userMessageId: MessageId.make(`message:seed-user:${input.threadId}`),
|
||||
rootNodeId: input.rootNodeId,
|
||||
activeAttemptId: null,
|
||||
status: "running",
|
||||
requestedAt: input.now,
|
||||
startedAt: input.now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
delegatedCompletion: {
|
||||
disposition: "open",
|
||||
nextGeneration: 2,
|
||||
settledDeliveryCount: 1,
|
||||
delivery:
|
||||
input.deliveryTaskIds === undefined
|
||||
? null
|
||||
: {
|
||||
generation: 1,
|
||||
messageId: MessageId.make(`message:delegated-delivery:${input.threadId}`),
|
||||
taskIds: input.deliveryTaskIds,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: EventId.make(`event:seed-task:${input.threadId}`),
|
||||
type: "subagent.updated",
|
||||
threadId: input.threadId,
|
||||
runId: input.runId,
|
||||
nodeId: input.taskId,
|
||||
driver,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: input.now,
|
||||
payload: {
|
||||
id: input.taskId,
|
||||
threadId: input.threadId,
|
||||
runId: input.runId,
|
||||
parentNodeId: input.rootNodeId,
|
||||
origin: "app_owned",
|
||||
createdBy: "agent",
|
||||
driver,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
providerThreadId: null,
|
||||
childThreadId: null,
|
||||
nativeTaskRef: null,
|
||||
prompt: "Inspect the delivered ownership edge.",
|
||||
title: null,
|
||||
model: null,
|
||||
completionWake: input.completionWake ?? "settled_only",
|
||||
completionDelivery: {
|
||||
state: input.deliveryState,
|
||||
observedByRunId: input.deliveryState === "acknowledged" ? input.runId : null,
|
||||
},
|
||||
status: "completed",
|
||||
result: "child finished",
|
||||
startedAt: input.now,
|
||||
completedAt: input.now,
|
||||
updatedAt: input.now,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("delegated completion delivery repairs", (it) => {
|
||||
it.effect("builds completion text and metadata from the same live cohort", () =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:delegated-delivery-live-cohort");
|
||||
const projectId = ProjectId.make("project:delegated-delivery-live-cohort");
|
||||
const runId = RunId.make("run:delegated-delivery-live-cohort");
|
||||
const rootNodeId = NodeId.make("node:delegated-delivery-live-cohort-root");
|
||||
const firstTaskId = NodeId.make("node:delegated-delivery-live-cohort-first");
|
||||
const secondTaskId = NodeId.make("node:delegated-delivery-live-cohort-second");
|
||||
const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
|
||||
|
||||
yield* seedParentWithTerminalTask({
|
||||
threadId,
|
||||
projectId,
|
||||
runId,
|
||||
rootNodeId,
|
||||
taskId: firstTaskId,
|
||||
deliveryState: "claimed",
|
||||
completionWake: "always",
|
||||
deliveryTaskIds: [firstTaskId, secondTaskId],
|
||||
now,
|
||||
});
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:delegated-delivery-live-cohort"),
|
||||
threadId,
|
||||
messageId,
|
||||
text: `Delegated task ${firstTaskId} reached a terminal state.`,
|
||||
attachments: [],
|
||||
dispatchMode: { type: "queue_after_active" },
|
||||
createdBy: "agent",
|
||||
creationSource: "server",
|
||||
delegatedCompletion: {
|
||||
parentRunId: runId,
|
||||
generation: 1,
|
||||
taskIds: [firstTaskId],
|
||||
},
|
||||
});
|
||||
|
||||
const projection = yield* orchestrator.getThreadProjection(threadId);
|
||||
const message = projection.messages.find((candidate) => candidate.id === messageId);
|
||||
assert.deepEqual(message?.delegatedCompletion?.taskIds, [firstTaskId, secondTaskId]);
|
||||
assert.include(message?.text ?? "", String(firstTaskId));
|
||||
assert.include(message?.text ?? "", String(secondTaskId));
|
||||
assert.include(message?.text ?? "", "task_status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not re-offer when wake-policy upgrades after delivered ownership settled", () =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:delegated-delivery-a1");
|
||||
const projectId = ProjectId.make("project:delegated-delivery-a1");
|
||||
const runId = RunId.make("run:delegated-delivery-a1");
|
||||
const rootNodeId = NodeId.make("node:delegated-delivery-a1-root");
|
||||
const taskId = NodeId.make("node:delegated-delivery-a1-task");
|
||||
|
||||
yield* seedParentWithTerminalTask({
|
||||
threadId,
|
||||
projectId,
|
||||
runId,
|
||||
rootNodeId,
|
||||
taskId,
|
||||
deliveryState: "delivered",
|
||||
completionWake: "settled_only",
|
||||
now,
|
||||
});
|
||||
|
||||
const upgrade = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.wake-policy",
|
||||
commandId: CommandId.make("command:delegated-delivery-a1:wake-policy"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
completionWake: "always",
|
||||
});
|
||||
|
||||
const projection = yield* orchestrator.getThreadProjection(threadId);
|
||||
const task = projection.subagents.find((candidate) => candidate.id === taskId);
|
||||
const parentRun = projection.runs.find((candidate) => candidate.id === runId);
|
||||
|
||||
assert.equal(task?.completionWake, "always");
|
||||
assert.deepEqual(task?.completionDelivery, {
|
||||
state: "delivered",
|
||||
observedByRunId: null,
|
||||
});
|
||||
assert.deepEqual(parentRun?.delegatedCompletion, {
|
||||
disposition: "open",
|
||||
nextGeneration: 2,
|
||||
settledDeliveryCount: 1,
|
||||
delivery: null,
|
||||
});
|
||||
assert.isFalse(
|
||||
upgrade.storedEvents.some(
|
||||
(stored) =>
|
||||
stored.event.type === "subagent.updated" &&
|
||||
stored.event.payload.id === taskId &&
|
||||
stored.event.payload.completionDelivery?.state === "claimed",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
upgrade.storedEvents.some(
|
||||
(stored) =>
|
||||
stored.event.type === "run.updated" &&
|
||||
stored.event.payload.id === runId &&
|
||||
stored.event.payload.delegatedCompletion?.delivery !== null &&
|
||||
stored.event.payload.delegatedCompletion?.delivery !== undefined,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"treats repeated acknowledge and dispose with distinct command IDs as successful no-ops",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:delegated-delivery-a2");
|
||||
const projectId = ProjectId.make("project:delegated-delivery-a2");
|
||||
const runId = RunId.make("run:delegated-delivery-a2");
|
||||
const rootNodeId = NodeId.make("node:delegated-delivery-a2-root");
|
||||
const taskId = NodeId.make("node:delegated-delivery-a2-task");
|
||||
|
||||
yield* seedParentWithTerminalTask({
|
||||
threadId,
|
||||
projectId,
|
||||
runId,
|
||||
rootNodeId,
|
||||
taskId,
|
||||
deliveryState: "delivered",
|
||||
completionWake: "always",
|
||||
now,
|
||||
});
|
||||
|
||||
// Distinct command IDs mirror task_status vs t3_thread_read racing after
|
||||
// their shared read preflight saw delivered ownership.
|
||||
const firstAck = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.completion-delivery.acknowledge",
|
||||
commandId: CommandId.make("command:delegated-delivery-a2:ack-task-status"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
observedByRunId: runId,
|
||||
});
|
||||
const secondAck = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.completion-delivery.acknowledge",
|
||||
commandId: CommandId.make("command:delegated-delivery-a2:ack-thread-read"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
observedByRunId: runId,
|
||||
});
|
||||
|
||||
const firstAckTask = firstAck.storedEvents.find(
|
||||
(stored) =>
|
||||
stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
|
||||
);
|
||||
const secondAckTask = secondAck.storedEvents.find(
|
||||
(stored) =>
|
||||
stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
|
||||
);
|
||||
assert.isDefined(firstAckTask);
|
||||
assert.isDefined(secondAckTask);
|
||||
if (
|
||||
firstAckTask?.event.type !== "subagent.updated" ||
|
||||
secondAckTask?.event.type !== "subagent.updated"
|
||||
) {
|
||||
return yield* Effect.die(new Error("Acknowledge events missing."));
|
||||
}
|
||||
assert.equal(firstAckTask.event.payload.completionDelivery?.state, "acknowledged");
|
||||
assert.equal(secondAckTask.event.payload.completionDelivery?.state, "acknowledged");
|
||||
// Idempotent replay keeps the first observation's ownership and timestamp.
|
||||
assert.deepEqual(
|
||||
secondAckTask.event.payload.completionDelivery,
|
||||
firstAckTask.event.payload.completionDelivery,
|
||||
);
|
||||
assert.deepEqual(
|
||||
secondAckTask.event.payload.updatedAt,
|
||||
firstAckTask.event.payload.updatedAt,
|
||||
);
|
||||
assert.equal(secondAck.storedEvents.length, 1);
|
||||
|
||||
const afterAck = yield* orchestrator.getThreadProjection(threadId);
|
||||
assert.deepEqual(
|
||||
afterAck.subagents.find((candidate) => candidate.id === taskId)?.completionDelivery,
|
||||
{
|
||||
state: "acknowledged",
|
||||
observedByRunId: runId,
|
||||
},
|
||||
);
|
||||
|
||||
const firstDispose = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.completion-delivery.dispose",
|
||||
commandId: CommandId.make("command:delegated-delivery-a2:dispose-task-status"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
});
|
||||
const secondDispose = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.completion-delivery.dispose",
|
||||
commandId: CommandId.make("command:delegated-delivery-a2:dispose-thread-read"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
});
|
||||
|
||||
const firstDisposeTask = firstDispose.storedEvents.find(
|
||||
(stored) =>
|
||||
stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
|
||||
);
|
||||
const secondDisposeTask = secondDispose.storedEvents.find(
|
||||
(stored) =>
|
||||
stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
|
||||
);
|
||||
assert.isDefined(firstDisposeTask);
|
||||
assert.isDefined(secondDisposeTask);
|
||||
if (
|
||||
firstDisposeTask?.event.type !== "subagent.updated" ||
|
||||
secondDisposeTask?.event.type !== "subagent.updated"
|
||||
) {
|
||||
return yield* Effect.die(new Error("Dispose events missing."));
|
||||
}
|
||||
assert.equal(firstDisposeTask.event.payload.completionDelivery?.state, "disposed");
|
||||
assert.equal(secondDisposeTask.event.payload.completionDelivery?.state, "disposed");
|
||||
assert.deepEqual(
|
||||
secondDisposeTask.event.payload.completionDelivery,
|
||||
firstDisposeTask.event.payload.completionDelivery,
|
||||
);
|
||||
assert.equal(secondDispose.storedEvents.length, 1);
|
||||
|
||||
const afterDispose = yield* orchestrator.getThreadProjection(threadId);
|
||||
assert.deepEqual(
|
||||
afterDispose.subagents.find((candidate) => candidate.id === taskId)?.completionDelivery,
|
||||
{
|
||||
state: "disposed",
|
||||
observedByRunId: null,
|
||||
},
|
||||
);
|
||||
|
||||
const acknowledgeAfterDispose = yield* orchestrator.dispatch({
|
||||
type: "delegated_task.completion-delivery.acknowledge",
|
||||
commandId: CommandId.make("command:delegated-delivery-a2:ack-after-dispose"),
|
||||
parentThreadId: threadId,
|
||||
taskId,
|
||||
observedByRunId: runId,
|
||||
});
|
||||
const acknowledgedTask = acknowledgeAfterDispose.storedEvents.find(
|
||||
(stored) => stored.event.type === "subagent.updated",
|
||||
);
|
||||
if (acknowledgedTask?.event.type !== "subagent.updated") {
|
||||
return yield* Effect.die(new Error("Acknowledge-after-dispose event missing."));
|
||||
}
|
||||
assert.deepEqual(acknowledgedTask.event.payload.completionDelivery, {
|
||||
state: "disposed",
|
||||
observedByRunId: null,
|
||||
});
|
||||
assert.equal(acknowledgeAfterDispose.storedEvents.length, 1);
|
||||
|
||||
const afterStaleAcknowledge = yield* orchestrator.getThreadProjection(threadId);
|
||||
assert.deepEqual(
|
||||
afterStaleAcknowledge.subagents.find((candidate) => candidate.id === taskId)
|
||||
?.completionDelivery,
|
||||
{
|
||||
state: "disposed",
|
||||
observedByRunId: null,
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -153,6 +153,156 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves delegated completion ownership across stale run and task updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
const now = yield* DateTime.now;
|
||||
const later = DateTime.add(now, { seconds: 1 });
|
||||
const threadId = ThreadId.make("thread:projection-delegated-completion");
|
||||
const projectId = ProjectId.make("project:projection-delegated-completion");
|
||||
const runId = RunId.make("run:projection-delegated-completion");
|
||||
const rootNodeId = NodeId.make("node:projection-delegated-completion-root");
|
||||
const taskId = NodeId.make("node:projection-delegated-completion-task");
|
||||
const thread = {
|
||||
createdBy: "user" as const,
|
||||
creationSource: "web" as const,
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Delegated completion projection",
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
const run = {
|
||||
id: runId,
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId,
|
||||
modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make("message:projection-delegated-completion"),
|
||||
rootNodeId,
|
||||
activeAttemptId: null,
|
||||
status: "running" as const,
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
delegatedCompletion: {
|
||||
disposition: "stopped" as const,
|
||||
nextGeneration: 2,
|
||||
delivery: null,
|
||||
},
|
||||
};
|
||||
const task = {
|
||||
id: taskId,
|
||||
threadId,
|
||||
runId,
|
||||
parentNodeId: rootNodeId,
|
||||
origin: "app_owned" as const,
|
||||
createdBy: "agent" as const,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
providerThreadId: null,
|
||||
childThreadId: null,
|
||||
nativeTaskRef: null,
|
||||
prompt: "Inspect the stop barrier.",
|
||||
title: null,
|
||||
model: null,
|
||||
completionWake: "always" as const,
|
||||
completionDelivery: {
|
||||
state: "disposed" as const,
|
||||
observedByRunId: null,
|
||||
},
|
||||
status: "running" as const,
|
||||
result: null,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-delegated-completion:thread"),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: thread,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-delegated-completion:run"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: run,
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-delegated-completion:task"),
|
||||
type: "subagent.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: taskId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: task,
|
||||
});
|
||||
|
||||
const { delegatedCompletion: _delegatedCompletion, ...staleRun } = run;
|
||||
const { completionDelivery: _completionDelivery, ...staleTask } = task;
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-delegated-completion:stale-run"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId,
|
||||
occurredAt: later,
|
||||
payload: { ...staleRun, status: "interrupted", completedAt: later },
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-delegated-completion:stale-task"),
|
||||
type: "subagent.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: taskId,
|
||||
driver,
|
||||
providerInstanceId,
|
||||
occurredAt: later,
|
||||
payload: {
|
||||
...staleTask,
|
||||
status: "interrupted",
|
||||
completedAt: later,
|
||||
updatedAt: later,
|
||||
},
|
||||
});
|
||||
|
||||
const projection = yield* projectionStore.getThreadProjection(threadId);
|
||||
assert.deepEqual(projection.runs[0]?.delegatedCompletion, run.delegatedCompletion);
|
||||
assert.deepEqual(projection.subagents[0]?.completionDelivery, task.completionDelivery);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("only exposes interruptible runs through the shell activeRunId", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
OrchestrationV2ConversationMessage,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2ProjectedTurnItem,
|
||||
OrchestrationV2Run,
|
||||
OrchestrationV2Subagent,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestrationV2ShellThreadStatus,
|
||||
OrchestrationV2ThreadShell,
|
||||
@@ -137,6 +139,26 @@ function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>,
|
||||
return updated;
|
||||
}
|
||||
|
||||
function preserveDelegatedCompletion(
|
||||
current: OrchestrationV2Run | undefined,
|
||||
next: OrchestrationV2Run,
|
||||
): OrchestrationV2Run {
|
||||
if (next.delegatedCompletion !== undefined || current?.delegatedCompletion === undefined) {
|
||||
return next;
|
||||
}
|
||||
return { ...next, delegatedCompletion: current.delegatedCompletion };
|
||||
}
|
||||
|
||||
function preserveCompletionDelivery(
|
||||
current: OrchestrationV2Subagent | undefined,
|
||||
next: OrchestrationV2Subagent,
|
||||
): OrchestrationV2Subagent {
|
||||
if (next.completionDelivery !== undefined || current?.completionDelivery === undefined) {
|
||||
return next;
|
||||
}
|
||||
return { ...next, completionDelivery: current.completionDelivery };
|
||||
}
|
||||
|
||||
export function emptyProjection(
|
||||
event: Extract<OrchestrationV2DomainEvent, { readonly type: "thread.created" }>,
|
||||
): OrchestrationV2ThreadProjection {
|
||||
@@ -205,7 +227,13 @@ export function applyToProjection(
|
||||
case "run.updated":
|
||||
return withLocalVisibleTurnItems({
|
||||
...base,
|
||||
runs: upsertById(base.runs, event.payload),
|
||||
runs: upsertById(
|
||||
base.runs,
|
||||
preserveDelegatedCompletion(
|
||||
base.runs.find((run) => run.id === event.payload.id),
|
||||
event.payload,
|
||||
),
|
||||
),
|
||||
});
|
||||
case "run-attempt.created":
|
||||
case "run-attempt.updated":
|
||||
@@ -221,7 +249,13 @@ export function applyToProjection(
|
||||
case "subagent.updated":
|
||||
return {
|
||||
...base,
|
||||
subagents: upsertById(base.subagents, event.payload),
|
||||
subagents: upsertById(
|
||||
base.subagents,
|
||||
preserveCompletionDelivery(
|
||||
base.subagents.find((task) => task.id === event.payload.id),
|
||||
event.payload,
|
||||
),
|
||||
),
|
||||
};
|
||||
case "provider-session.attached":
|
||||
case "provider-session.updated":
|
||||
@@ -1149,7 +1183,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
status = excluded.status,
|
||||
requested_at = excluded.requested_at,
|
||||
completed_at = excluded.completed_at,
|
||||
payload_json = excluded.payload_json
|
||||
payload_json = CASE
|
||||
WHEN json_type(excluded.payload_json, '$.delegatedCompletion') IS NULL
|
||||
AND json_type(orchestration_v2_projection_runs.payload_json, '$.delegatedCompletion') IS NOT NULL
|
||||
THEN json_set(
|
||||
excluded.payload_json,
|
||||
'$.delegatedCompletion',
|
||||
json_extract(
|
||||
orchestration_v2_projection_runs.payload_json,
|
||||
'$.delegatedCompletion'
|
||||
)
|
||||
)
|
||||
ELSE excluded.payload_json
|
||||
END
|
||||
`;
|
||||
break;
|
||||
}
|
||||
@@ -1305,7 +1351,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
started_at = excluded.started_at,
|
||||
completed_at = excluded.completed_at,
|
||||
updated_at = excluded.updated_at,
|
||||
payload_json = excluded.payload_json
|
||||
payload_json = CASE
|
||||
WHEN json_type(excluded.payload_json, '$.completionDelivery') IS NULL
|
||||
AND json_type(orchestration_v2_projection_subagents.payload_json, '$.completionDelivery') IS NOT NULL
|
||||
THEN json_set(
|
||||
excluded.payload_json,
|
||||
'$.completionDelivery',
|
||||
json_extract(
|
||||
orchestration_v2_projection_subagents.payload_json,
|
||||
'$.completionDelivery'
|
||||
)
|
||||
)
|
||||
ELSE excluded.payload_json
|
||||
END
|
||||
`;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { ProviderDriverKind, ProviderThreadId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
MessageId,
|
||||
ProviderDriverKind,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -10,6 +16,16 @@ export interface ProviderContinuationRequest {
|
||||
readonly providerThreadId: ProviderThreadId;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly detail: string | null;
|
||||
/**
|
||||
* Durable ownership for an app-owned delegated-task completion delivery.
|
||||
* The continuation worker re-reads the cohort before dispatching so a later
|
||||
* task can join a queued wake and a stopped or acknowledged cohort is dropped.
|
||||
*/
|
||||
readonly delegatedCompletion?: {
|
||||
readonly parentRunId: RunId;
|
||||
readonly generation: number;
|
||||
readonly messageId: MessageId;
|
||||
};
|
||||
/**
|
||||
* How the continuation turn gets its content.
|
||||
*
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
MessageId,
|
||||
ProviderDriverKind,
|
||||
ProviderThreadId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -13,6 +15,7 @@ import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import {
|
||||
@@ -26,8 +29,10 @@ import { ThreadManagementService } from "./ThreadManagementService.ts";
|
||||
const threadId = ThreadId.make("thread-provider-continuation");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
|
||||
const driver = ProviderDriverKind.make("continuation-test");
|
||||
const parentRunId = RunId.make("run-provider-continuation-parent");
|
||||
const delegatedMessageId = MessageId.make("message-provider-continuation-delegated");
|
||||
const projection = {
|
||||
thread: { archivedAt: null },
|
||||
thread: { archivedAt: null, deletedAt: null },
|
||||
messages: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
|
||||
@@ -42,6 +47,25 @@ const request = (
|
||||
...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
|
||||
});
|
||||
|
||||
const delegatedProjection = (disposition: "open" | "stopped" | "disposed" = "open") =>
|
||||
({
|
||||
...projection,
|
||||
runs: [
|
||||
{
|
||||
id: parentRunId,
|
||||
delegatedCompletion: {
|
||||
disposition,
|
||||
nextGeneration: 2,
|
||||
delivery: {
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
taskIds: ["node-provider-continuation-first", "node-provider-continuation-second"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}) as unknown as OrchestrationV2ThreadProjection;
|
||||
|
||||
const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
|
||||
const generation = yield* Ref.make(0);
|
||||
const permit = yield* Semaphore.make(1);
|
||||
@@ -131,6 +155,421 @@ describe("ProviderContinuationService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("dispatches a current delegated completion as one server-owned queued message", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
const command = (yield* Queue.take(dispatched)) as {
|
||||
readonly createdBy: string;
|
||||
readonly creationSource: string;
|
||||
readonly delegatedCompletion: {
|
||||
readonly generation: number;
|
||||
readonly parentRunId: RunId;
|
||||
readonly taskIds: ReadonlyArray<string>;
|
||||
};
|
||||
readonly dispatchMode: { readonly type: string };
|
||||
readonly messageId: MessageId;
|
||||
readonly text: string;
|
||||
};
|
||||
assert.equal(command.createdBy, "agent");
|
||||
assert.equal(command.creationSource, "server");
|
||||
assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
|
||||
assert.equal(command.messageId, delegatedMessageId);
|
||||
assert.equal(command.delegatedCompletion.parentRunId, parentRunId);
|
||||
assert.equal(command.delegatedCompletion.generation, 1);
|
||||
assert.deepEqual(command.delegatedCompletion.taskIds, [
|
||||
"node-provider-continuation-first",
|
||||
"node-provider-continuation-second",
|
||||
]);
|
||||
assert.include(command.text, "task_status");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () => Effect.succeed(delegatedProjection()),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("retries a delegated completion after a transient dispatch failure", () => {
|
||||
return Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
const threads = Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: () => Effect.succeed(delegatedProjection()),
|
||||
dispatch: (command) =>
|
||||
Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
|
||||
Effect.flatMap((attempt) =>
|
||||
attempt === 0
|
||||
? Effect.fail(new Error("simulated transient dispatch failure") as never)
|
||||
: Queue.offer(dispatched, command).pipe(Effect.as({} as never)),
|
||||
),
|
||||
),
|
||||
});
|
||||
const worker = workerLive.pipe(
|
||||
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
|
||||
yield* TestClock.adjust("100 millis");
|
||||
const command = (yield* Queue.take(dispatched)) as {
|
||||
readonly messageId: MessageId;
|
||||
};
|
||||
assert.equal(command.messageId, delegatedMessageId);
|
||||
assert.equal(yield* Ref.get(attempts), 2);
|
||||
}).pipe(Effect.provide(Layer.merge(continuationRequestsLayer, worker)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("backs off repeated delegated completion dispatch failures", () => {
|
||||
return Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const disposition = yield* Ref.make<"open" | "disposed">("open");
|
||||
const threads = Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: () =>
|
||||
Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
|
||||
dispatch: () =>
|
||||
Ref.update(attempts, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
|
||||
),
|
||||
});
|
||||
const worker = workerLive.pipe(
|
||||
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
|
||||
yield* TestClock.adjust("100 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 2);
|
||||
yield* TestClock.adjust("199 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 2);
|
||||
yield* TestClock.adjust("1 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 3);
|
||||
|
||||
yield* Ref.set(disposition, "disposed");
|
||||
yield* TestClock.adjust("400 millis");
|
||||
}).pipe(Effect.provide(Layer.merge(continuationRequestsLayer, worker)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resets delegated completion retry backoff after archive or deletion", () => {
|
||||
return Effect.gen(function* () {
|
||||
for (const barrier of ["archivedAt", "deletedAt"] as const) {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const blockedProjectionReads = yield* Ref.make(0);
|
||||
const blockedRequestDropped = yield* Deferred.make<void>();
|
||||
const state = yield* Ref.make<"open" | "blocked" | "disposed">("open");
|
||||
const threads = Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: () =>
|
||||
Effect.gen(function* () {
|
||||
const currentState = yield* Ref.get(state);
|
||||
if (currentState === "blocked") {
|
||||
const reads = yield* Ref.updateAndGet(blockedProjectionReads, (count) => count + 1);
|
||||
if (reads === 2) {
|
||||
yield* Deferred.succeed(blockedRequestDropped, undefined);
|
||||
}
|
||||
}
|
||||
return {
|
||||
...delegatedProjection(currentState === "disposed" ? "disposed" : "open"),
|
||||
thread: {
|
||||
...projection.thread,
|
||||
[barrier]:
|
||||
currentState === "blocked"
|
||||
? DateTime.makeUnsafe("2026-08-05T00:00:00.000Z")
|
||||
: null,
|
||||
},
|
||||
};
|
||||
}),
|
||||
dispatch: () =>
|
||||
Ref.update(attempts, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.fail(new Error("simulated persistent failure") as never)),
|
||||
),
|
||||
});
|
||||
const worker = workerLive.pipe(
|
||||
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
|
||||
);
|
||||
const completionRequest = {
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text" as const,
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer(completionRequest);
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
|
||||
yield* Ref.set(state, "blocked");
|
||||
yield* TestClock.adjust("100 millis");
|
||||
yield* Deferred.await(blockedRequestDropped);
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
|
||||
yield* Ref.set(state, "open");
|
||||
yield* requests.offer(completionRequest);
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 2);
|
||||
yield* TestClock.adjust("99 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 2);
|
||||
yield* TestClock.adjust("1 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 3);
|
||||
|
||||
yield* Ref.set(state, "disposed");
|
||||
yield* TestClock.adjust("200 millis");
|
||||
}).pipe(Effect.provide(Layer.merge(continuationRequestsLayer, worker)), Effect.scoped);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("drops a delegated completion retry after its delivery closes", () => {
|
||||
return Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const disposition = yield* Ref.make<"open" | "disposed">("open");
|
||||
const threads = Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: () =>
|
||||
Ref.get(disposition).pipe(Effect.map((state) => delegatedProjection(state))),
|
||||
dispatch: () =>
|
||||
Ref.update(attempts, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.fail(new Error("simulated dispatch failure") as never)),
|
||||
),
|
||||
});
|
||||
const worker = workerLive.pipe(
|
||||
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
|
||||
yield* Ref.set(disposition, "disposed");
|
||||
yield* TestClock.adjust("100 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
}).pipe(Effect.provide(Layer.merge(continuationRequestsLayer, worker)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps a Grok delegated completion queued instead of restarting active work", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver: ProviderDriverKind.make("grok"),
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
const command = (yield* Queue.take(dispatched)) as {
|
||||
readonly dispatchMode: { readonly type: string };
|
||||
};
|
||||
assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () => Effect.succeed(delegatedProjection()),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"drops stopped and disposed delegated completions instead of reviving them after recovery",
|
||||
() => {
|
||||
return Effect.gen(function* () {
|
||||
for (const disposition of ["stopped", "disposed"] as const) {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () => Effect.succeed(delegatedProjection(disposition)),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("does not redispatch a persisted delegated completion message during recovery", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () =>
|
||||
Effect.succeed({
|
||||
...delegatedProjection(),
|
||||
messages: [{ id: delegatedMessageId }],
|
||||
} as unknown as OrchestrationV2ThreadProjection),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("drops archived and deleted delegated completions during recovery", () => {
|
||||
return Effect.gen(function* () {
|
||||
for (const barrier of ["archivedAt", "deletedAt"] as const) {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail: null,
|
||||
delivery: "message_text",
|
||||
delegatedCompletion: {
|
||||
parentRunId,
|
||||
generation: 1,
|
||||
messageId: delegatedMessageId,
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () =>
|
||||
Effect.succeed({
|
||||
...delegatedProjection(),
|
||||
thread: {
|
||||
...projection.thread,
|
||||
[barrier]: DateTime.makeUnsafe("2026-08-03T00:00:00.000Z"),
|
||||
},
|
||||
} as unknown as OrchestrationV2ThreadProjection),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("dispatches a current request exactly once", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CommandId } from "@t3tools/contracts";
|
||||
import { CommandId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import {
|
||||
@@ -11,6 +12,42 @@ import { ThreadManagementService } from "./ThreadManagementService.ts";
|
||||
|
||||
const CONTINUATION_MESSAGE_TEXT = "Background task completed.";
|
||||
|
||||
function delegatedCompletionText(taskIds: ReadonlyArray<string>): string {
|
||||
const taskList = taskIds.join(", ");
|
||||
return taskIds.length === 1
|
||||
? `Delegated task ${taskList} reached a terminal state. Use task_status with taskId ${taskList} to read the result.`
|
||||
: `Delegated tasks ${taskList} reached terminal states. Use task_status with each taskId to read the results.`;
|
||||
}
|
||||
|
||||
function currentDelegatedCompletionDelivery(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
completion: NonNullable<ProviderContinuationRequest["delegatedCompletion"]>,
|
||||
) {
|
||||
const sourceRun = projection.runs.find((candidate) => candidate.id === completion.parentRunId);
|
||||
const delivery = sourceRun?.delegatedCompletion?.delivery;
|
||||
const alreadyDispatched = projection.messages.some(
|
||||
(message) => message.id === completion.messageId,
|
||||
);
|
||||
if (
|
||||
sourceRun?.delegatedCompletion?.disposition !== "open" ||
|
||||
delivery === null ||
|
||||
delivery === undefined ||
|
||||
delivery.generation !== completion.generation ||
|
||||
delivery.messageId !== completion.messageId ||
|
||||
alreadyDispatched
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return delivery;
|
||||
}
|
||||
|
||||
function delegatedCompletionRetryKey(
|
||||
request: ProviderContinuationRequest,
|
||||
completion: NonNullable<ProviderContinuationRequest["delegatedCompletion"]>,
|
||||
): string {
|
||||
return `${request.threadId}:${completion.parentRunId}:${completion.generation}:${completion.messageId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains ProviderContinuationRequests and dispatches an internal
|
||||
* message.dispatch per request so the wake turn buffered by the adapter is
|
||||
@@ -23,15 +60,37 @@ export const workerLive = Layer.effectDiscard(
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
const threads = yield* ThreadManagementService;
|
||||
const retryAttempts = yield* Ref.make(new Map<string, number>());
|
||||
|
||||
const clearRetryAttempt = (key: string) =>
|
||||
Ref.update(retryAttempts, (current) => {
|
||||
if (!current.has(key)) return current;
|
||||
const updated = new Map(current);
|
||||
updated.delete(key);
|
||||
return updated;
|
||||
});
|
||||
|
||||
const nextRetryDelay = (key: string) =>
|
||||
Ref.modify(retryAttempts, (current) => {
|
||||
const attempt = current.get(key) ?? 0;
|
||||
const updated = new Map(current);
|
||||
updated.set(key, attempt + 1);
|
||||
return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const;
|
||||
});
|
||||
|
||||
const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")(
|
||||
function* (request: ProviderContinuationRequest) {
|
||||
const projection = yield* threads.getThreadProjection(request.threadId);
|
||||
if (projection.thread.archivedAt !== null) {
|
||||
if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
|
||||
yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
|
||||
threadId: request.threadId,
|
||||
providerThreadId: request.providerThreadId,
|
||||
});
|
||||
if (request.delegatedCompletion !== undefined) {
|
||||
yield* clearRetryAttempt(
|
||||
delegatedCompletionRetryKey(request, request.delegatedCompletion),
|
||||
);
|
||||
}
|
||||
// No continuation turn will start to clear the adapter's sticky offer.
|
||||
if (request.clearIfCurrent !== undefined) {
|
||||
yield* request.clearIfCurrent();
|
||||
@@ -42,6 +101,39 @@ export const workerLive = Layer.effectDiscard(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request.delegatedCompletion !== undefined) {
|
||||
const retryKey = delegatedCompletionRetryKey(request, request.delegatedCompletion);
|
||||
const delivery = currentDelegatedCompletionDelivery(
|
||||
projection,
|
||||
request.delegatedCompletion,
|
||||
);
|
||||
if (delivery === undefined) {
|
||||
yield* clearRetryAttempt(retryKey);
|
||||
return;
|
||||
}
|
||||
const commandId = yield* ids.allocate.command({
|
||||
fixtureName: "delegated-completion",
|
||||
commandName: "dispatch",
|
||||
});
|
||||
yield* threads.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId,
|
||||
threadId: request.threadId,
|
||||
messageId: delivery.messageId,
|
||||
text: delegatedCompletionText(delivery.taskIds),
|
||||
attachments: [],
|
||||
dispatchMode: { type: "queue_after_active" },
|
||||
createdBy: "agent",
|
||||
creationSource: "server",
|
||||
delegatedCompletion: {
|
||||
parentRunId: request.delegatedCompletion.parentRunId,
|
||||
generation: delivery.generation,
|
||||
taskIds: delivery.taskIds,
|
||||
},
|
||||
});
|
||||
yield* clearRetryAttempt(retryKey);
|
||||
return;
|
||||
}
|
||||
// The ordinal is display metadata only: allocate.message appends a
|
||||
// random UUID, so a stale projection read here cannot collide ids.
|
||||
const messageId = yield* ids.allocate.message({
|
||||
@@ -76,10 +168,35 @@ export const workerLive = Layer.effectDiscard(
|
||||
Effect.flatMap((request) =>
|
||||
dispatchContinuation(request).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
|
||||
threadId: request.threadId,
|
||||
providerThreadId: request.providerThreadId,
|
||||
cause,
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
|
||||
threadId: request.threadId,
|
||||
providerThreadId: request.providerThreadId,
|
||||
cause,
|
||||
});
|
||||
if (request.delegatedCompletion !== undefined) {
|
||||
const completion = request.delegatedCompletion;
|
||||
const retryKey = delegatedCompletionRetryKey(request, completion);
|
||||
const retryDelay = yield* nextRetryDelay(retryKey);
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep(`${retryDelay} millis`);
|
||||
const projection = yield* threads.getThreadProjection(request.threadId);
|
||||
if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
|
||||
yield* requests.offer(request);
|
||||
} else {
|
||||
yield* clearRetryAttempt(retryKey);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((retryCause) =>
|
||||
Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
|
||||
threadId: request.threadId,
|
||||
providerThreadId: request.providerThreadId,
|
||||
cause: retryCause,
|
||||
}).pipe(Effect.andThen(requests.offer(request))),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
|
||||
|
||||
describe("queued run delivery order", () => {
|
||||
it("keeps automatic completion delivery ahead of visible queued messages", () => {
|
||||
const projection = {
|
||||
messages: [
|
||||
{ id: "message:visible-first" },
|
||||
{
|
||||
id: "message:automatic",
|
||||
delegatedCompletion: {
|
||||
generation: 1,
|
||||
parentRunId: "run:parent",
|
||||
taskIds: ["task:child"],
|
||||
},
|
||||
},
|
||||
{ id: "message:visible-second" },
|
||||
],
|
||||
runs: [
|
||||
{
|
||||
id: "run:visible-first",
|
||||
ordinal: 2,
|
||||
queuePosition: 1,
|
||||
status: "queued",
|
||||
userMessageId: "message:visible-first",
|
||||
},
|
||||
{
|
||||
id: "run:automatic",
|
||||
ordinal: 4,
|
||||
queuePosition: 3,
|
||||
status: "queued",
|
||||
userMessageId: "message:automatic",
|
||||
},
|
||||
{
|
||||
id: "run:visible-second",
|
||||
ordinal: 3,
|
||||
queuePosition: 2,
|
||||
status: "queued",
|
||||
userMessageId: "message:visible-second",
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
|
||||
expect(queuedRunsInDeliveryOrder(projection).map((run) => run.id)).toEqual([
|
||||
"run:automatic",
|
||||
"run:visible-first",
|
||||
"run:visible-second",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
|
||||
export function isAutomaticCompletionRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
run: OrchestrationV2Run,
|
||||
): boolean {
|
||||
return projection.messages.some(
|
||||
(message) => message.id === run.userMessageId && message.delegatedCompletion !== undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function queuedRunsInDeliveryOrder(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): ReadonlyArray<OrchestrationV2Run> {
|
||||
const automaticCompletionMessageIds = new Set(
|
||||
projection.messages
|
||||
.filter((message) => message.delegatedCompletion !== undefined)
|
||||
.map((message) => message.id),
|
||||
);
|
||||
return projection.runs
|
||||
.filter((run) => run.status === "queued")
|
||||
.toSorted((left, right) => {
|
||||
const deliveryPriority =
|
||||
Number(automaticCompletionMessageIds.has(right.userMessageId)) -
|
||||
Number(automaticCompletionMessageIds.has(left.userMessageId));
|
||||
return (
|
||||
deliveryPriority ||
|
||||
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
|
||||
left.ordinal - right.ordinal
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -564,8 +564,13 @@ export const layer: Layer.Layer<
|
||||
: [];
|
||||
const persistedStatus =
|
||||
input.terminal.status === "completed" ? "waiting" : input.terminal.status;
|
||||
// Completion cohorts are advanced by Orchestrator while a provider
|
||||
// turn is in flight. Do not replay the run snapshot captured at start
|
||||
// over a newer acknowledgement, successor, or Stop barrier.
|
||||
const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } =
|
||||
input.run;
|
||||
const finalizedRun: OrchestrationV2Run = {
|
||||
...input.run,
|
||||
...runWithoutDelegatedCompletion,
|
||||
status: persistedStatus,
|
||||
completedAt: input.terminal.status === "completed" ? null : completedAt,
|
||||
};
|
||||
|
||||
@@ -80,6 +80,8 @@ export function existingThreadIdsForCommand(
|
||||
: [command.sourceThreadId, command.targetThreadId];
|
||||
case "delegated_task.request":
|
||||
case "delegated_task.wake-policy":
|
||||
case "delegated_task.completion-delivery.acknowledge":
|
||||
case "delegated_task.completion-delivery.dispose":
|
||||
return [command.parentThreadId];
|
||||
case "thread.created.record":
|
||||
return command.parentThreadId === command.targetThreadId
|
||||
|
||||
@@ -128,6 +128,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
|
||||
return [command.threadId];
|
||||
case "delegated_task.request":
|
||||
case "delegated_task.wake-policy":
|
||||
case "delegated_task.completion-delivery.acknowledge":
|
||||
case "delegated_task.completion-delivery.dispose":
|
||||
case "thread.created.record":
|
||||
return [command.parentThreadId];
|
||||
case "thread.fork":
|
||||
|
||||
@@ -1048,6 +1048,8 @@ const makeWsRpcLayer = (
|
||||
? command.targetThreadId
|
||||
: command.type === "delegated_task.request" ||
|
||||
command.type === "delegated_task.wake-policy" ||
|
||||
command.type === "delegated_task.completion-delivery.acknowledge" ||
|
||||
command.type === "delegated_task.completion-delivery.dispose" ||
|
||||
command.type === "thread.created.record"
|
||||
? command.parentThreadId
|
||||
: command.threadId,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
projection: null as unknown,
|
||||
workflow: null as unknown,
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime/environment", () => ({
|
||||
scopeThreadRef: () => ({}) as never,
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime/state/thread-workflows", () => ({
|
||||
deriveThreadQueueWorkflowState: () => state.workflow,
|
||||
}));
|
||||
|
||||
vi.mock("../../state/entities", () => ({
|
||||
useThreadProjection: () => state.projection,
|
||||
}));
|
||||
|
||||
vi.mock("../../state/threads", () => ({
|
||||
threadEnvironment: {
|
||||
cancelQueuedRun: Symbol("cancelQueuedRun"),
|
||||
editQueuedRun: Symbol("editQueuedRun"),
|
||||
promoteQueuedRun: Symbol("promoteQueuedRun"),
|
||||
reorderQueuedRun: Symbol("reorderQueuedRun"),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../state/use-atom-command", () => ({
|
||||
useAtomCommand: () => async () => undefined,
|
||||
}));
|
||||
|
||||
import { QueuedRunsControl } from "./QueuedRunsControl";
|
||||
|
||||
describe("QueuedRunsControl automatic completion delivery", () => {
|
||||
it("does not render a queue control when only hidden delivery remains", () => {
|
||||
state.projection = {
|
||||
projection: {
|
||||
messages: [
|
||||
{
|
||||
delegatedCompletion: {
|
||||
parentRunId: "run:parent",
|
||||
generation: 1,
|
||||
taskIds: ["task:child"],
|
||||
},
|
||||
id: "message:completion",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
state.workflow = {
|
||||
activeRun: { id: "run:active" },
|
||||
canPromoteToSteer: true,
|
||||
canReorder: true,
|
||||
queuedRuns: [],
|
||||
};
|
||||
|
||||
const html = renderToStaticMarkup(
|
||||
<QueuedRunsControl
|
||||
environmentId={"environment:test" as never}
|
||||
optimisticMessages={[]}
|
||||
threadId={"thread:test" as never}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -211,7 +211,9 @@ export function QueuedRunsControl(props: {
|
||||
className="size-6 text-muted-foreground"
|
||||
disabled={item.runId === null || busyRunId !== null}
|
||||
onClick={() => {
|
||||
if (item.runId !== null) setEditing({ runId: item.runId, draft: item.text });
|
||||
if (item.runId !== null) {
|
||||
setEditing({ runId: item.runId, draft: item.text });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PencilIcon className="size-3" />
|
||||
@@ -229,7 +231,9 @@ export function QueuedRunsControl(props: {
|
||||
item.serverIndex === 0
|
||||
}
|
||||
onClick={() => {
|
||||
if (item.runId === null || item.serverIndex === null) return;
|
||||
if (item.runId === null || item.serverIndex === null) {
|
||||
return;
|
||||
}
|
||||
void move(item.runId, queued[item.serverIndex - 1]?.run.id ?? null);
|
||||
}}
|
||||
>
|
||||
@@ -248,7 +252,9 @@ export function QueuedRunsControl(props: {
|
||||
item.serverIndex === queued.length - 1
|
||||
}
|
||||
onClick={() => {
|
||||
if (item.runId === null || item.serverIndex === null) return;
|
||||
if (item.runId === null || item.serverIndex === null) {
|
||||
return;
|
||||
}
|
||||
void move(item.runId, queued[item.serverIndex + 2]?.run.id ?? null);
|
||||
}}
|
||||
>
|
||||
@@ -267,7 +273,9 @@ export function QueuedRunsControl(props: {
|
||||
: "Send as a steer instead"
|
||||
}
|
||||
onClick={() => {
|
||||
if (item.runId !== null) void steer(item.runId);
|
||||
if (item.runId !== null) {
|
||||
void steer(item.runId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CornerUpRightIcon className="size-3" />
|
||||
|
||||
@@ -85,6 +85,47 @@ describe("thread workflows", () => {
|
||||
expect(state.canPromoteToSteer).toBe(true);
|
||||
});
|
||||
|
||||
it("hides automatic completion delivery from the visible queue", () => {
|
||||
const state = deriveThreadQueueWorkflowState({
|
||||
thread: { id: "thread", activeProviderThreadId: null },
|
||||
runs: [
|
||||
{
|
||||
id: "automatic",
|
||||
status: "queued",
|
||||
userMessageId: "message-automatic",
|
||||
ordinal: 2,
|
||||
queuePosition: 1,
|
||||
},
|
||||
{
|
||||
id: "visible",
|
||||
status: "queued",
|
||||
userMessageId: "message-visible",
|
||||
ordinal: 3,
|
||||
queuePosition: 2,
|
||||
},
|
||||
],
|
||||
messages: [
|
||||
{
|
||||
id: "message-automatic",
|
||||
text: "A delegated task reached a terminal state.",
|
||||
delegatedCompletion: {
|
||||
generation: 1,
|
||||
parentRunId: "run:parent",
|
||||
taskIds: ["task:child"],
|
||||
},
|
||||
},
|
||||
{ id: "message-visible", text: "Visible queued message" },
|
||||
],
|
||||
providerTurns: [],
|
||||
providerThreads: [],
|
||||
providerSessions: [],
|
||||
} as never);
|
||||
|
||||
expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
|
||||
["visible", "Visible queued message"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes only the promoted head from the visible queue", () => {
|
||||
const state = deriveThreadQueueWorkflowState({
|
||||
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
|
||||
|
||||
@@ -90,8 +90,15 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQu
|
||||
projection.providerTurns.some(
|
||||
(turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
|
||||
);
|
||||
const automaticCompletionMessageIds = new Set(
|
||||
projection.messages
|
||||
.filter((message) => message.delegatedCompletion !== undefined)
|
||||
.map((message) => message.id),
|
||||
);
|
||||
const queuedRuns = copySorted(
|
||||
projection.runs.filter((run) => run.status === "queued"),
|
||||
projection.runs.filter(
|
||||
(run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
|
||||
),
|
||||
(left, right) =>
|
||||
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
|
||||
left.ordinal - right.ordinal,
|
||||
|
||||
@@ -354,6 +354,42 @@ export const OrchestrationV2RunStatus = Schema.Literals([
|
||||
]);
|
||||
export type OrchestrationV2RunStatus = typeof OrchestrationV2RunStatus.Type;
|
||||
|
||||
export const OrchestrationV2DelegatedCompletionTaskDeliveryState = Schema.Literals([
|
||||
"pending",
|
||||
"claimed",
|
||||
"acknowledged",
|
||||
"delivered",
|
||||
"disposed",
|
||||
]);
|
||||
export type OrchestrationV2DelegatedCompletionTaskDeliveryState =
|
||||
typeof OrchestrationV2DelegatedCompletionTaskDeliveryState.Type;
|
||||
|
||||
export const OrchestrationV2DelegatedCompletionTaskDelivery = Schema.Struct({
|
||||
state: OrchestrationV2DelegatedCompletionTaskDeliveryState,
|
||||
observedByRunId: Schema.NullOr(RunId),
|
||||
});
|
||||
export type OrchestrationV2DelegatedCompletionTaskDelivery =
|
||||
typeof OrchestrationV2DelegatedCompletionTaskDelivery.Type;
|
||||
|
||||
export const OrchestrationV2DelegatedCompletionDelivery = Schema.Struct({
|
||||
generation: PositiveInt,
|
||||
messageId: MessageId,
|
||||
taskIds: Schema.Array(NodeId),
|
||||
});
|
||||
export type OrchestrationV2DelegatedCompletionDelivery =
|
||||
typeof OrchestrationV2DelegatedCompletionDelivery.Type;
|
||||
|
||||
export const OrchestrationV2DelegatedCompletionCohort = Schema.Struct({
|
||||
disposition: Schema.Literals(["open", "stopped", "disposed"]),
|
||||
nextGeneration: PositiveInt,
|
||||
// Optional for compatibility with cohorts persisted before bounded
|
||||
// follow-up delivery was introduced. Missing means no delivery has settled.
|
||||
settledDeliveryCount: Schema.optional(NonNegativeInt),
|
||||
delivery: Schema.NullOr(OrchestrationV2DelegatedCompletionDelivery),
|
||||
});
|
||||
export type OrchestrationV2DelegatedCompletionCohort =
|
||||
typeof OrchestrationV2DelegatedCompletionCohort.Type;
|
||||
|
||||
export const OrchestrationV2Run = Schema.Struct({
|
||||
id: RunId,
|
||||
threadId: ThreadId,
|
||||
@@ -377,6 +413,7 @@ export const OrchestrationV2Run = Schema.Struct({
|
||||
planId: PlanId,
|
||||
}),
|
||||
),
|
||||
delegatedCompletion: Schema.optional(OrchestrationV2DelegatedCompletionCohort),
|
||||
});
|
||||
export type OrchestrationV2Run = typeof OrchestrationV2Run.Type;
|
||||
|
||||
@@ -464,6 +501,7 @@ export const OrchestrationV2Subagent = Schema.Struct({
|
||||
// live run (wait-mode delegations, whose result returns through the
|
||||
// blocking tool call). Absent on legacy records; treated as settled_only.
|
||||
completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
|
||||
completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery),
|
||||
status: Schema.Literals([
|
||||
"pending",
|
||||
"running",
|
||||
@@ -621,6 +659,13 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({
|
||||
streaming: Schema.Boolean,
|
||||
createdAt: Schema.DateTimeUtc,
|
||||
updatedAt: Schema.DateTimeUtc,
|
||||
delegatedCompletion: Schema.optional(
|
||||
Schema.Struct({
|
||||
parentRunId: RunId,
|
||||
generation: PositiveInt,
|
||||
taskIds: Schema.Array(NodeId),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type OrchestrationV2ConversationMessage = typeof OrchestrationV2ConversationMessage.Type;
|
||||
|
||||
@@ -1983,6 +2028,13 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
titleSeed: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
sourcePlanRef: Schema.optional(Schema.Struct({ threadId: ThreadId, planId: PlanId })),
|
||||
delegatedCompletion: Schema.optional(
|
||||
Schema.Struct({
|
||||
parentRunId: RunId,
|
||||
generation: PositiveInt,
|
||||
taskIds: Schema.Array(NodeId),
|
||||
}),
|
||||
),
|
||||
dispatchMode: Schema.Union([
|
||||
Schema.Struct({ type: Schema.Literal("defer_start") }),
|
||||
Schema.Struct({ type: Schema.Literal("steer_active"), targetRunId: RunId }),
|
||||
@@ -2103,6 +2155,19 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
taskId: NodeId,
|
||||
completionWake: Schema.Literals(["always", "settled_only"]),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("delegated_task.completion-delivery.acknowledge"),
|
||||
commandId: CommandId,
|
||||
parentThreadId: ThreadId,
|
||||
taskId: NodeId,
|
||||
observedByRunId: Schema.NullOr(RunId),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("delegated_task.completion-delivery.dispose"),
|
||||
commandId: CommandId,
|
||||
parentThreadId: ThreadId,
|
||||
taskId: NodeId,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("thread.created.record"),
|
||||
commandId: CommandId,
|
||||
|
||||
Reference in new issue
Block a user