Skip to content

Commit 47ce757

Browse files
committed
fix(auto-reply): adopt the target run slot when command turns continue into agent turns
Native command turns keep #104144 source-keyed admission, but a turn that continues into a full agent turn (/steer fallback, /goal, /learn, unhandled body) now moves its reservation and lifecycle lease to the target session before running. Concurrent target inbounds see the owner and queue/steer instead of double-admitting and splitting the session into two conversation families; steering also targets the registered run owner instead of a stale source-keyed reservation. Fixes #104844
1 parent 3c7edce commit 47ce757

10 files changed

Lines changed: 368 additions & 31 deletions

‎src/auto-reply/reply/agent-runner-direct-runtime-config.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ function createReplyOperation(): ReplyOperation {
126126
markWaitingForDeferredMaintenance: vi.fn(),
127127
markDeferredMaintenanceWaitEnded: vi.fn(),
128128
updateSessionId: vi.fn(),
129+
updateSessionKey: vi.fn(),
129130
hasOwnedSessionId: vi.fn(() => false),
130131
attachBackend: vi.fn(),
131132
detachBackend: vi.fn(),

‎src/auto-reply/reply/agent-runner-execution.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ function createMockReplyOperation(): {
523523
markWaitingForDeferredMaintenance: vi.fn(),
524524
markDeferredMaintenanceWaitEnded: vi.fn(),
525525
updateSessionId: updateSessionIdMock,
526+
updateSessionKey: vi.fn(),
526527
attachBackend: vi.fn(),
527528
detachBackend: vi.fn(),
528529
freezeAbort: freezeAbortMock,

‎src/auto-reply/reply/agent-runner-memory.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ function createReplyOperation(): TestReplyOperation {
5959
hasOwnedSessionId: vi.fn((sessionId: string) => sessionId === "session"),
6060
setPhase: vi.fn<ReplyOperation["setPhase"]>(),
6161
updateSessionId: vi.fn<ReplyOperation["updateSessionId"]>(),
62+
updateSessionKey: vi.fn<ReplyOperation["updateSessionKey"]>(),
6263
attachBackend: vi.fn(),
6364
detachBackend: vi.fn(),
6465
freezeAbort: vi.fn(),

‎src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ import {
3030
type ReplyOperationRunState,
3131
type ReplyOptionsWithOperationRunState,
3232
} from "./reply-operation-run-state.js";
33-
import { createReplyOperation, testing as replyRunTesting } from "./reply-run-registry.js";
33+
import {
34+
createReplyOperation,
35+
testing as replyRunTesting,
36+
type ReplyOperation,
37+
} from "./reply-run-registry.js";
3438
import { consumeReplyUsageState } from "./reply-usage-state.js";
3539
import { createMockTypingController } from "./test-helpers.js";
3640

@@ -214,6 +218,7 @@ function createMinimalRun(params?: {
214218
shouldSteer?: boolean;
215219
shouldFollowup?: boolean;
216220
resolvedQueueMode?: string;
221+
replyOperation?: ReplyOperation;
217222
currentInboundEventKind?: FollowupRun["currentInboundEventKind"];
218223
sessionCtx?: Partial<TemplateContext>;
219224
runOverrides?: Partial<FollowupRun["run"]>;
@@ -289,6 +294,7 @@ function createMinimalRun(params?: {
289294
resolvedBlockStreamingBreak: "message_end",
290295
shouldInjectGroupIntro: false,
291296
typingMode: params?.typingMode ?? "instant",
297+
replyOperation: params?.replyOperation,
292298
});
293299
},
294300
};
@@ -324,6 +330,42 @@ describe("runReplyAgent active steering", () => {
324330
);
325331
});
326332

333+
it("steers against the session's registered run owner, not a source-keyed reservation", async () => {
334+
// A native command continuation whose target-slot adoption was skipped
335+
// (#104844) still carries its slash-source reservation; steering must
336+
// target the operation that owns this session's run slot.
337+
state.queueEmbeddedAgentMessageMock.mockReturnValueOnce(true);
338+
const targetOwner = createReplyOperation({
339+
sessionKey: "main",
340+
sessionId: "target-active-session",
341+
resetTriggered: false,
342+
});
343+
targetOwner.setPhase("running");
344+
const sourceReservation = createReplyOperation({
345+
sessionKey: "agent:main:telegram:slash:steer-user",
346+
sessionId: "source-reservation-session",
347+
resetTriggered: false,
348+
});
349+
const { run } = createMinimalRun({
350+
isActive: true,
351+
isStreaming: true,
352+
shouldSteer: true,
353+
resolvedQueueMode: "steer",
354+
replyOperation: sourceReservation,
355+
});
356+
357+
await expect(run()).resolves.toBeUndefined();
358+
359+
expect(state.queueEmbeddedAgentMessageMock).toHaveBeenCalledWith(
360+
"target-active-session",
361+
"hello",
362+
expect.objectContaining({ steeringMode: "all" }),
363+
);
364+
365+
targetOwner.complete();
366+
sourceReservation.complete();
367+
});
368+
327369
it("waits for transcript commit and keeps a rejected adoption finalizer irrevocably adopted", async () => {
328370
const finalizerError = new Error("dedupe finalizer failed");
329371
const events: string[] = [];

‎src/auto-reply/reply/agent-runner.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1268,8 +1268,15 @@ export async function runReplyAgent(params: {
12681268

12691269
let shouldQueueAfterSteerRejection = false;
12701270
if (effectiveShouldSteer && isActive) {
1271+
// Steer against the operation that owns THIS session's run slot. A native
1272+
// command continuation whose slot adoption was skipped (#104844) still
1273+
// carries a source-keyed reservation; steering by its stale sessionId
1274+
// would miss the live target run.
1275+
const registeredReplyOperation = sessionKey ? replyRunRegistry.get(sessionKey) : undefined;
12711276
const activeReplyOperation =
1272-
providedReplyOperation ?? (sessionKey ? replyRunRegistry.get(sessionKey) : undefined);
1277+
providedReplyOperation?.key === sessionKey
1278+
? providedReplyOperation
1279+
: (registeredReplyOperation ?? providedReplyOperation);
12731280
const steerSessionId = activeReplyOperation?.sessionId ?? followupRun.run.sessionId;
12741281
const steerOutcome = await queueEmbeddedAgentMessageWithOutcomeAsync(
12751282
steerSessionId,

‎src/auto-reply/reply/get-reply-run.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ import {
112112
type ReplyOperation,
113113
} from "./reply-run-registry.js";
114114
import { resolveReplyToMode } from "./reply-threading.js";
115+
import { admitReplyTurn } from "./reply-turn-admission.js";
115116
import { resolveRoutedDeliveryThreadId } from "./routed-delivery-thread.js";
116117
import { resolveRuntimePolicySessionKey } from "./runtime-policy-session-key.js";
117118
import type { ReplySessionEntryHandle } from "./session-entry-handle.js";
@@ -1076,7 +1077,23 @@ export async function runPreparedReply(
10761077
}
10771078
}
10781079
const providedReplyOperation = opts?.replyOperation;
1080+
// Native command turns reserve their operation under the slash SOURCE key so
1081+
// commands never contend with the target's active run (#104144). When such a
1082+
// turn continues into a full agent turn (/steer fallback, /goal, /learn,
1083+
// unhandled body), it mutates the TARGET session: it must adopt the target's
1084+
// run slot before running or concurrent target inbounds double-admit and
1085+
// split the session (#104844).
1086+
const commandTurnContinuationTargetKey =
1087+
providedReplyOperation !== undefined &&
1088+
providedReplyOperation.result === null &&
1089+
providedReplyOperation.phase === "queued" &&
1090+
sessionKey !== undefined &&
1091+
providedReplyOperation.key !== sessionKey &&
1092+
resolveCommandTurnTargetSessionKey(ctx) !== undefined
1093+
? sessionKey
1094+
: undefined;
10791095
if (
1096+
commandTurnContinuationTargetKey === undefined &&
10801097
providedReplyOperation !== undefined &&
10811098
providedReplyOperation.result === null &&
10821099
providedReplyOperation.phase === "queued" &&
@@ -1085,7 +1102,9 @@ export async function runPreparedReply(
10851102
) {
10861103
// Dispatch reserves a queued operation before session init. If stale init
10871104
// rotates the session, move the reservation so later steer/abort paths
1088-
// target the session that will actually run.
1105+
// target the session that will actually run. Command-turn continuations
1106+
// rebind after slot adoption below: rebinding first would collide with a
1107+
// still-active target operation that owns the same session ID.
10891108
providedReplyOperation.updateSessionId(sessionId);
10901109
}
10911110
const isOwnPreDispatchOperationSession = (candidateSessionId: string | undefined): boolean =>
@@ -1295,6 +1314,35 @@ export async function runPreparedReply(
12951314
isReplyRunStreamingForSessionId(replyOperationActiveSessionId)),
12961315
};
12971316
};
1317+
if (commandTurnContinuationTargetKey && providedReplyOperation) {
1318+
const adoption = await admitReplyTurn({
1319+
sessionKey: commandTurnContinuationTargetKey,
1320+
sessionId: providedReplyOperation.sessionId,
1321+
expectedSessionId: preparedSessionState.sessionEntry?.sessionId,
1322+
storePath,
1323+
kind: "visible",
1324+
resetTriggered: effectiveResetTriggered,
1325+
routeThreadId: currentRouteThreadId,
1326+
upstreamAbortSignal: opts?.abortSignal,
1327+
// Never wait on the target's active turn: a blocked continuation would
1328+
// re-create the #104142 command-lane wedge. When the slot is owned, the
1329+
// queue policy below sees the target-keyed owner and steers/queues this
1330+
// turn instead of running it concurrently.
1331+
waitForActive: false,
1332+
adoptOperation: providedReplyOperation,
1333+
});
1334+
if (adoption.status === "skipped" && adoption.reason === "aborted") {
1335+
typing.cleanup();
1336+
return undefined;
1337+
}
1338+
if (
1339+
adoption.status === "owned" &&
1340+
sessionId !== undefined &&
1341+
sessionId !== providedReplyOperation.sessionId
1342+
) {
1343+
providedReplyOperation.updateSessionId(sessionId);
1344+
}
1345+
}
12981346
const { activeSessionId, isActive, isStreaming } = resolveQueueBusyState();
12991347
const activeRunAcceptsCurrentThread = resolveActiveRunAcceptsCurrentThread({ isActive });
13001348
const isHeartbeatRun = opts?.isHeartbeat === true;

‎src/auto-reply/reply/reply-run-registry.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
queueReplyRunMessage,
2222
REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
2323
REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS,
24+
ReplyRunAlreadyActiveError,
2425
replyRunRegistry,
2526
runAfterReplyOperationClear,
2627
resolveActiveReplyRunSessionId,
@@ -1060,4 +1061,66 @@ describe("reply run registry", () => {
10601061
expect(compactingOperation.result).toEqual({ kind: "aborted", code: "aborted_for_restart" });
10611062
expect(runningOperation.result).toBeNull();
10621063
});
1064+
1065+
it("moves a queued reservation to the target slot and frees the source", async () => {
1066+
const sourceSessionKey = "agent:main:telegram:slash:rekey-user";
1067+
const targetSessionKey = "agent:main:telegram:group:rekey-target";
1068+
const operation = createReplyOperation({
1069+
sessionKey: sourceSessionKey,
1070+
sessionId: "rekey-session",
1071+
resetTriggered: false,
1072+
});
1073+
const sourceIdle = replyRunRegistry.waitForIdle(sourceSessionKey, 1_000);
1074+
1075+
operation.updateSessionKey(targetSessionKey);
1076+
1077+
expect(operation.key).toBe(targetSessionKey);
1078+
expect(replyRunRegistry.get(sourceSessionKey)).toBeUndefined();
1079+
expect(replyRunRegistry.get(targetSessionKey)).toBe(operation);
1080+
expect(resolveActiveReplyRunSessionId(targetSessionKey)).toBe("rekey-session");
1081+
await expect(sourceIdle).resolves.toBe(true);
1082+
1083+
const targetWait = waitForReplyRunEndBySessionId("rekey-session", 1_000);
1084+
operation.complete();
1085+
await expect(targetWait).resolves.toBe(true);
1086+
expect(replyRunRegistry.get(targetSessionKey)).toBeUndefined();
1087+
});
1088+
1089+
it("refuses to rekey onto an owned target slot and keeps the source slot", () => {
1090+
const targetSessionKey = "agent:main:telegram:group:rekey-owned";
1091+
const sourceSessionKey = "agent:main:telegram:slash:rekey-blocked";
1092+
const blocker = createReplyOperation({
1093+
sessionKey: targetSessionKey,
1094+
sessionId: "owned-session",
1095+
resetTriggered: false,
1096+
});
1097+
const operation = createReplyOperation({
1098+
sessionKey: sourceSessionKey,
1099+
sessionId: "blocked-session",
1100+
resetTriggered: false,
1101+
});
1102+
1103+
expect(() => operation.updateSessionKey(targetSessionKey)).toThrow(ReplyRunAlreadyActiveError);
1104+
expect(operation.key).toBe(sourceSessionKey);
1105+
expect(replyRunRegistry.get(sourceSessionKey)).toBe(operation);
1106+
expect(replyRunRegistry.get(targetSessionKey)).toBe(blocker);
1107+
1108+
blocker.complete();
1109+
operation.complete();
1110+
});
1111+
1112+
it("refuses to rekey after the run leaves the queued phase", () => {
1113+
const operation = createReplyOperation({
1114+
sessionKey: "agent:main:telegram:slash:rekey-late",
1115+
sessionId: "late-session",
1116+
resetTriggered: false,
1117+
});
1118+
operation.setPhase("running");
1119+
1120+
expect(() => operation.updateSessionKey("agent:main:telegram:group:rekey-late")).toThrow(
1121+
/Cannot rekey reply operation/,
1122+
);
1123+
1124+
operation.complete();
1125+
});
10631126
});

0 commit comments

Comments
 (0)