Skip to content
24 changes: 24 additions & 0 deletions apps/server/src/orchestration-v2/CommandPolicy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,30 @@ it("steers a Grok follow-up into its running turn without restarting it", () =>
assert.isTrue(grok.turns.supportsActiveSteering);
});

// regression: #32606 a slash command steered into a running turn replaced the task
it.each([
["/compact", { type: "queue_after_active" }],
["/context", { type: "queue_after_active" }],
[" /context all\n", { type: "queue_after_active" }],
["/plugin:review-pr 12", { type: "queue_after_active" }],
["/home/me/x.ts fails", { type: "steer_active", targetRunId: activeRunId }],
["/ context", { type: "steer_active", targetRunId: activeRunId }],
["$skill /context", { type: "steer_active", targetRunId: activeRunId }],
] as const)("steers %j only when it is not a slash command", (text, expected) => {
const projection = dispatchProjection(baseCapabilities);
for (const deliveryIntent of ["auto", "steer"] as const) {
assert.deepEqual(
CommandPolicy.resolveMessageDispatch(projection, {
dispatchMode: { type: "start_immediately" },
deliveryIntent,
text,
attachments: [],
}),
expected,
);
}
});

it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => {
const projection = dispatchProjection(baseCapabilities);
const maintenance = {
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/orchestration-v2/CommandPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { isSlashCommand } from "@t3tools/shared/composerTrigger";
import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
Expand Down Expand Up @@ -101,6 +102,25 @@ export function goalCommandStopsActiveRun(
}
}

export function resolveMessageDispatch(
projection: OrchestrationV2ThreadProjection,
message: Pick<
Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
"dispatchMode" | "deliveryIntent" | "text" | "attachments"
>,
): MessageDispatchMode {
const mode = resolveMessageDispatchIntent(
projection,
message.dispatchMode,
message.deliveryIntent,
);
// A provider runs a steered command in place of the turn's task, so commands wait.
return mode.type === "steer_active" && isSlashCommand(message)
? { type: "queue_after_active" }
: mode;
}

/** How a message joins active work when it is free to steer. */
export function resolveMessageDispatchIntent(
projection: OrchestrationV2ThreadProjection,
requestedMode: MessageDispatchMode,
Expand Down
66 changes: 51 additions & 15 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts";
import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
import { outputRequestProblem } from "./runOutput.ts";
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
import { isSlashCommand } from "@t3tools/shared/composerTrigger";
import {
backgroundWorkHoldsCompletion,
derivePendingBackgroundWork,
Expand Down Expand Up @@ -126,6 +127,7 @@ import {
isNativeMaintenanceCommand,
providerSwitchWaitsForTurn,
providerTurnCapabilities,
resolveMessageDispatch,
resolveMessageDispatchIntent,
} from "./CommandPolicy.ts";
import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts";
Expand Down Expand Up @@ -6308,6 +6310,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
}
yield* ensureSteeringMessage(input.command, input);
// An explicit restart already gives up the turn, so only steering holds commands back.
if (!input.forceRestart && isSlashCommand(input)) {
return yield* new OrchestratorDispatchError({
commandId: input.command.commandId,
commandType: input.command.type,
cause:
"Commands must run as a separate turn. Queue it or wait for the active turn to finish.",
});
}
const targetMessage = input.projection.messages.find(
(message) => message.id === targetRun.userMessageId,
);
Expand Down Expand Up @@ -7416,11 +7427,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
projection = applyToProjection(projection, event);
}
let modelSelection = command.modelSelection ?? projection.thread.modelSelection;
let dispatchMode = resolveMessageDispatchIntent(
projection,
command.dispatchMode,
command.deliveryIntent,
);
// Native goal commands must not steer an existing turn.
const parsedGoalCommand = parseGoalCommand(command);
const goalCommand =
parsedGoalCommand === null ||
(yield* goalDriverFor(command, modelSelection.instanceId)) === undefined
? null
: parsedGoalCommand;
// A goal command keeps the run it was sent at; the goal handling below queues it.
let dispatchMode =
goalCommand === null
? resolveMessageDispatch(projection, command)
: resolveMessageDispatchIntent(projection, command.dispatchMode, command.deliveryIntent);
if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
const targetRunId = dispatchMode.targetRunId;
const target = projection.runs.find((run) => run.id === targetRunId);
Expand Down Expand Up @@ -7515,13 +7533,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
) {
dispatchMode = { type: "queue_after_active" };
}
// Native goal commands must not steer an existing turn.
const parsedGoalCommand = parseGoalCommand(command);
const goalCommand =
parsedGoalCommand === null ||
(yield* goalDriverFor(command, modelSelection.instanceId)) === undefined
? null
: parsedGoalCommand;
let queuedRunStop:
| { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true }
| undefined;
Expand Down Expand Up @@ -7672,6 +7683,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const commandNotice = noticeKind === "command" && command.creationSource === "server";
if (
!freshContext &&
// Steering refuses a command, so a notice that reads like one stays queued.
!isSlashCommand(command) &&
(delegatedCompletion !== undefined
? delegatedCompletion.taskIds.every(
(id) =>
Expand Down Expand Up @@ -11856,8 +11869,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: "A message that asks for a result can't steer the current turn.",
});
}
if (goalCommand !== null) {
yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId);
// A steered command replaces the turn's task, so promoting one only moves it first.
if (goalCommand !== null || isSlashCommand(queuedMessage)) {
if (goalCommand !== null) {
yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId);
}
const goal = projection.providerThreads.find(
(candidate) => candidate.id === target?.providerThreadId,
)?.goal;
Expand All @@ -11871,6 +11887,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
payload: { ...queuedRun, queuePosition: 1 },
});
const stops =
goalCommand !== null &&
target !== undefined &&
isLiveRun(target) &&
goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) &&
Expand Down Expand Up @@ -12298,6 +12315,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
});
}
// A command cannot steer, so an edit into one keeps it queued where it is.
if (
queuedRun.steerWhenReadyRunId !== undefined &&
isSlashCommand({
text: command.text,
attachments: command.attachments ?? queuedMessage.attachments,
})
) {
const { steerWhenReadyRunId: _, ...queued } = queuedRun;
yield* emitEvent({
type: "run.updated",
threadId: command.threadId,
runId: queuedRun.id,
...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: queued,
});
}
// Thread deletion only cleans files the thread still references.
const keptAttachmentIds = new Set(
(command.attachments ?? queuedMessage.attachments).map((attachment) => attachment.id),
Expand Down Expand Up @@ -14182,7 +14218,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
);

/** Puts a queued goal command first and, given a target, stops the run in its way. */
/** Puts a queued command first and, given a target, stops the run in its way. */
const stopRunForQueuedCommand = Effect.fn("Orchestrator.stopRunForQueuedCommand")(
function* (input: {
readonly command: Extract<
Expand Down
Loading
Loading