Files
t3code/apps/server/src/orchestration-v2/ThreadStop.test.ts
T
2026-10-11 10:28:14 -07:00

708 lines
27 KiB
TypeScript

import { assert, it } from "@effect/vitest";
import {
CommandId,
EventId,
MessageId,
NodeId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderTurnId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ServerSettings from "../serverSettings.ts";
import { CLAUDE_PROVIDER } from "./Adapters/ClaudeAdapterV2.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
import { OrchestrationEffectRequestV2 } from "./EffectOutbox.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "gpt-5.1-codex" };
const adapter = {
instanceId,
driver: ProviderDriverKind.make("codex"),
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
openSession: () => Effect.die("Runs here never reach a provider"),
} as ProviderAdapter.ProviderAdapterV2["Service"];
const layerDatabase = SqlitePersistence.layerMemory;
// No effect worker: runs stay unstarted, so Stop ends them without a provider.
const layerTest = ThreadManagementService.layer.pipe(
Layer.provideMerge(
Layer.mergeAll(
layerDatabase,
ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
ProviderReplayHarness.layerWithRegistry(
{ name: "thread-stop" },
ProviderAdapterRegistry.layerFromAdapters([adapter]),
{ databaseLayer: layerDatabase, runEffectWorker: false },
),
),
),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
);
const encodeEffectRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
const pullRequest = (number: number) => ({
host: "github.com",
repository: "pingdotgg/t3code",
number,
});
const createWatchingThread = (threadId: ThreadId, number: number) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make(`create:${threadId}`),
threadId,
projectId: ProjectId.make("project:thread-stop"),
title: threadId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdBy: "user",
creationSource: "web",
});
yield* watch(threadId, number);
});
const watch = (threadId: ThreadId, number: number) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
yield* orchestrator.dispatch({
type: "thread.pull-request.watch",
commandId: CommandId.make(`watch:${threadId}:${number}`),
threadId,
...pullRequest(number),
watching: true,
link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
});
});
const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make(`send:${threadId}:${text}`),
threadId,
messageId: MessageId.make(`message:${threadId}:${text}`),
text,
attachments: [],
dispatchMode: { type },
createdBy: "user",
creationSource: "web",
});
});
/** Delegates `task` from the parent's latest run and returns the child thread. */
const delegate = (parentThreadId: ThreadId, task: string) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
yield* orchestrator.dispatch({
type: "delegated_task.request",
commandId: CommandId.make(`delegate:${task}`),
parentThreadId,
parentRunId: parentRun.id,
parentNodeId: parentRun.rootNodeId!,
task,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
completionWake: "always",
createdBy: "agent",
creationSource: "mcp",
});
const projection = yield* orchestrator.getThreadProjection(parentThreadId);
return projection.subagents.find((candidate) => candidate.prompt === task)!.childThreadId!;
});
const threadState = (threadId: ThreadId) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projection = yield* orchestrator.getThreadProjection(threadId);
return {
runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`),
watched: (projection.thread.pullRequests ?? [])
.filter((link) => link.watch !== undefined)
.map((link) => link.number),
};
});
it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threads = yield* ThreadManagementService.ThreadManagementService;
const sql = yield* SqlClient.SqlClient;
const parentThreadId = ThreadId.make("thread:stop-parent");
yield* createWatchingThread(parentThreadId, 1);
yield* send(parentThreadId, "first", "start_immediately");
const childThreadId = yield* delegate(parentThreadId, "child task");
// The parent owns its pull requests; a delegated task cannot watch one.
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
yield* send(childThreadId, "child follow-up", "queue_after_active");
// The run that delegated the child ends before the run the user stops, so
// only a Stop that covers earlier runs keeps the stopped child from waking it.
const now = yield* DateTime.now;
const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
yield* projections.apply({
id: EventId.make("event:stop-parent:first-run-completed"),
type: "run.updated",
threadId: parentThreadId,
runId: firstRun.id,
occurredAt: now,
payload: { ...firstRun, status: "completed", completedAt: now },
});
yield* send(parentThreadId, "second", "start_immediately");
const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
const stopCommandId = CommandId.make("stop-parent");
yield* orchestrator.dispatch({
type: "run.interrupt",
commandId: stopCommandId,
threadId: parentThreadId,
runId: secondRun.id,
holdQueue: true,
});
assert.deepEqual(yield* threadState(parentThreadId), {
runs: ["completed", "interrupted"],
watched: [],
});
const parent = yield* orchestrator.getThreadProjection(parentThreadId);
assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
const effects = yield* sql<{ readonly effect_type: string }>`
SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
`;
assert.include(
effects.map((row) => row.effect_type),
"delegated-tasks.stop",
);
// What the delegated-tasks.stop effect runs once the Stop commits.
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
assert.deepEqual(yield* threadState(childThreadId), {
runs: ["interrupted", "queued:held"],
watched: [],
});
assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
// A retried effect stops nothing twice.
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
}).pipe(Effect.provide(layerTest)),
);
it.effect(
"thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
() =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const threadId = ThreadId.make("thread:stop-idle");
yield* createWatchingThread(threadId, 3);
yield* orchestrator.dispatch({
type: "thread.stop",
commandId: CommandId.make("stop-idle"),
threadId,
});
assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
const again = yield* orchestrator.dispatch({
type: "thread.stop",
commandId: CommandId.make("stop-idle-again"),
threadId,
});
assert.lengthOf(again.storedEvents, 0);
}).pipe(Effect.provide(layerTest)),
);
it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threadId = ThreadId.make("thread:stop-barrier");
yield* createWatchingThread(threadId, 4);
yield* send(threadId, "work", "start_immediately");
const now = yield* DateTime.now;
const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
yield* projections.apply({
id: EventId.make("event:stop-barrier:running"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "running" },
});
// A queued message the user cancelled does not count as the latest run.
yield* send(threadId, "queued", "queue_after_active");
const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
yield* orchestrator.dispatch({
type: "queued-run.cancel",
commandId: CommandId.make("cancel-queued"),
threadId,
runId: queued.id,
});
// Stop reached the run, but its provider has not stopped it yet.
yield* projections.apply({
id: EventId.make("event:stop-barrier:interrupt-request"),
type: "turn-item.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: {
id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
threadId,
runId: run.id,
nodeId: run.rootNodeId!,
providerThreadId: run.providerThreadId!,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1_000,
status: "completed",
title: "Interrupt requested",
startedAt: now,
completedAt: now,
updatedAt: now,
type: "run_interrupt_request",
message: "Stop",
},
});
assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
// A slow watch_pull_request call can land after the stopped run ended.
yield* projections.apply({
id: EventId.make("event:stop-barrier:interrupted"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "interrupted", completedAt: now },
});
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
assert.deepEqual(yield* threadState(threadId), {
runs: ["interrupted", "cancelled"],
watched: [4],
});
// The user can still stop and restart a watch by hand.
for (const watching of [false, true]) {
yield* orchestrator.dispatch({
type: "thread.pull-request.watch",
commandId: CommandId.make(`manual-watch:${watching}`),
threadId,
...pullRequest(4),
watching,
});
}
assert.deepEqual((yield* threadState(threadId)).watched, [4]);
}).pipe(Effect.provide(layerTest)),
);
it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread:stop-restart");
yield* createWatchingThread(threadId, 8);
yield* send(threadId, "work", "start_immediately");
const now = yield* DateTime.now;
const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
// A server restart cut the run before its provider started; its continuation is pending.
yield* projections.apply({
id: EventId.make("event:stop-restart:cancelled"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
});
const at = DateTime.formatIso(now);
yield* sql`
INSERT INTO orchestration_v2_effect_outbox (
effect_id, command_id, thread_id, effect_type, payload_json, status,
attempt_count, available_at, created_at, updated_at
) VALUES (
${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
'provider-runtime.continue',
${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
'pending', 0, ${at}, ${at}, ${at}
)
`;
yield* orchestrator.dispatch({
type: "thread.stop",
commandId: CommandId.make("stop-restart"),
threadId,
});
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make("restart-continuation"),
threadId,
messageId: MessageId.make("message:restart-continuation"),
text: "Continue.",
attachments: [],
dispatchMode: { type: "start_immediately" },
createdBy: "agent",
creationSource: "server",
restartContinuationOfRunId: run.id,
});
assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
}).pipe(Effect.provide(layerTest)),
);
it.effect.each(["thread.stop", "run.interrupt"] as const)(
"a successful %s blocks a newer restart continuation when completion timestamps tie",
(stopType) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread:stop-resumed-queue");
yield* createWatchingThread(threadId, 12);
yield* send(threadId, "first", "start_immediately");
yield* send(threadId, "queued", "queue_after_active");
const now = yield* DateTime.now;
const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
assert.isDefined(first);
assert.isDefined(queued);
for (const run of [first!, queued!]) {
yield* projections.apply({
id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload:
run.id === first!.id
? { ...run, status: "completed", completedAt: now }
: { ...run, queueHeld: true },
});
}
// A later turn runs ahead of the held queue, then recovery cancels it.
yield* send(threadId, "restart source", "start_immediately");
const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
yield* projections.apply({
id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
type: "run.updated",
threadId,
runId: source.id,
occurredAt: now,
payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
});
const at = DateTime.formatIso(now);
yield* sql`
INSERT INTO orchestration_v2_effect_outbox (
effect_id, command_id, thread_id, effect_type, payload_json, status,
attempt_count, available_at, created_at, updated_at
) VALUES (
${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
'provider-runtime.continue',
${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
'pending', 0, ${at}, ${at}, ${at}
)
`;
yield* orchestrator.dispatch({
type: "queue.resume",
commandId: CommandId.make("resume-older-queue"),
threadId,
});
assert.equal(
(yield* orchestrator.getThreadProjection(threadId)).runs.find(
(run) => run.id === queued!.id,
)?.status,
"starting",
);
yield* orchestrator.dispatch(
stopType === "thread.stop"
? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
: {
type: "run.interrupt",
commandId: CommandId.make("stop-resumed-queue"),
threadId,
runId: queued!.id,
holdQueue: true,
},
);
const stopped = yield* orchestrator.getThreadProjection(threadId);
const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
assert.equal(interrupted.status, "interrupted");
assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make("restart-after-stop"),
threadId,
messageId: MessageId.make("message:restart-after-stop"),
text: "Continue.",
attachments: [],
dispatchMode: { type: "start_immediately" },
createdBy: "agent",
creationSource: "server",
restartContinuationOfRunId: source.id,
});
assert.deepEqual(yield* threadState(threadId), {
runs: ["completed", "interrupted", "cancelled"],
watched: [],
});
}).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
);
it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threads = yield* ThreadManagementService.ThreadManagementService;
const parentThreadId = ThreadId.make("thread:stop-partial");
yield* createWatchingThread(parentThreadId, 6);
yield* send(parentThreadId, "work", "start_immediately");
const childThreadId = yield* delegate(parentThreadId, "stoppable task");
const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
// A task whose thread is gone, listed before the one that can stop.
yield* projections.apply({
id: EventId.make("event:stop-partial:missing-task"),
type: "subagent.updated",
threadId: parentThreadId,
runId: task.runId!,
nodeId: NodeId.make("node:stop-partial:missing"),
providerInstanceId: instanceId,
occurredAt: yield* DateTime.now,
payload: {
...task,
id: NodeId.make("node:stop-partial:missing"),
childThreadId: ThreadId.make("thread:stop-partial:missing"),
startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
},
});
const walked = yield* Effect.exit(
threads.stopDelegatedTasks({
threadId: parentThreadId,
commandId: CommandId.make("stop-partial"),
}),
);
assert.isTrue(Exit.isFailure(walked));
assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
}).pipe(Effect.provide(layerTest)),
);
it.effect("thread.stop on a finished thread refuses a late agent watch", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threadId = ThreadId.make("thread:stop-finished");
yield* createWatchingThread(threadId, 9);
yield* send(threadId, "work", "start_immediately");
const now = yield* DateTime.now;
const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
yield* projections.apply({
id: EventId.make("event:stop-finished:completed"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "completed", startedAt: now, completedAt: now },
});
yield* orchestrator.dispatch({
type: "thread.stop",
commandId: CommandId.make("stop-finished"),
threadId,
});
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 10))));
assert.deepEqual(yield* threadState(threadId), { runs: ["completed"], watched: [] });
}).pipe(Effect.provide(layerTest)),
);
it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threadId = ThreadId.make("thread:stop-lost-session");
yield* createWatchingThread(threadId, 11);
yield* send(threadId, "work", "start_immediately");
const now = yield* DateTime.now;
const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
// The turn is running, but its provider session is gone, so the interrupt fails.
yield* projections.apply({
id: EventId.make("event:stop-lost-session:running"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "running", startedAt: now },
});
yield* projections.apply({
id: EventId.make("event:stop-lost-session:turn"),
type: "provider-turn.updated",
threadId,
occurredAt: now,
payload: {
id: ProviderTurnId.make("provider-turn:stop-lost-session"),
providerThreadId: run.providerThreadId!,
nodeId: run.rootNodeId!,
runAttemptId: run.activeAttemptId!,
nativeTurnRef: null,
ordinal: 1,
status: "running",
startedAt: now,
completedAt: null,
},
});
yield* orchestrator.dispatch({
type: "thread.stop",
commandId: CommandId.make("stop-lost-session"),
threadId,
});
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
}).pipe(Effect.provide(layerTest)),
);
it.effect(
"a native child stop persists only its targeted effect and leaves its owner's queue and watch alone",
() =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread:native-child-stop");
yield* createWatchingThread(threadId, 20);
yield* send(threadId, "owner", "start_immediately");
yield* delegate(threadId, "native-child-fixture");
const before = yield* orchestrator.getThreadProjection(threadId);
const run = before.runs[0]!;
const now = yield* DateTime.now;
const subagent = {
...before.subagents[0]!,
origin: "provider_native" as const,
driver: CLAUDE_PROVIDER,
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
nativeTaskRef: {
driver: CLAUDE_PROVIDER,
nativeId: "claude-task",
strength: "strong" as const,
},
status: "running" as const,
startedAt: now,
};
yield* projections.apply({
id: EventId.make("event:native-child-stop:agent"),
type: "subagent.updated",
threadId,
runId: run.id,
nodeId: subagent.id,
occurredAt: now,
payload: subagent,
});
const providerThread = before.providerThreads.find(
(thread) => thread.id === run.providerThreadId,
)!;
yield* projections.apply({
id: EventId.make("event:native-child-stop:provider-thread"),
type: "provider-thread.updated",
threadId,
occurredAt: now,
payload: {
...providerThread,
driver: CLAUDE_PROVIDER,
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
providerSessionId: ProviderSessionId.make("session:native-child-stop"),
},
});
const providerTurnId = ProviderTurnId.make("turn:native-child-stop");
yield* projections.apply({
id: EventId.make("event:native-child-stop:provider-turn"),
type: "provider-turn.updated",
threadId,
occurredAt: now,
payload: {
id: providerTurnId,
providerThreadId: providerThread.id,
nodeId: run.rootNodeId!,
runAttemptId: run.activeAttemptId!,
nativeTurnRef: null,
ordinal: 1,
status: "completed",
startedAt: now,
completedAt: now,
},
});
// The owner has finished but its child and queued prompt remain.
yield* projections.apply({
id: EventId.make("event:native-child-stop:owner-completed"),
type: "run.updated",
threadId,
runId: run.id,
occurredAt: now,
payload: { ...run, status: "completed", startedAt: now, completedAt: now },
});
yield* send(threadId, "queued", "queue_after_active");
const stateBefore = yield* threadState(threadId);
const commandId = CommandId.make("stop-native-child");
yield* orchestrator.dispatch({
type: "subagent.stop",
commandId,
threadId,
runId: run.id,
subagentId: subagent.id,
});
assert.deepEqual(yield* threadState(threadId), stateBefore);
const effects = yield* sql<{ payload_json: string }>`
SELECT payload_json FROM orchestration_v2_effect_outbox WHERE command_id = ${commandId}
`;
assert.equal(effects.length, 1);
assert.deepEqual(JSON.parse(effects[0]!.payload_json), {
type: "provider-turn.interrupt",
providerSessionId: "session:native-child-stop",
providerThreadId: providerThread.id,
providerTurnId,
subagent: { id: subagent.id, nativeTaskId: "claude-task" },
});
assert.equal(
(yield* orchestrator.getThreadProjection(threadId)).subagents[0]?.status,
"running",
);
const unrelated = yield* Effect.exit(
orchestrator.dispatch({
type: "subagent.stop",
commandId: CommandId.make("stop-unknown-child"),
threadId,
runId: run.id,
subagentId: NodeId.make("unknown-child"),
}),
);
assert.isTrue(Exit.isFailure(unrelated));
}).pipe(Effect.provide(layerTest)),
);