Skip to content

Commit 8d9a7ab

Browse files
100yenadminobviyus
authored andcommitted
fix(reply): steer active non-streaming runs
1 parent bfc4e1d commit 8d9a7ab

8 files changed

Lines changed: 167 additions & 8 deletions

File tree

‎src/agents/embedded-agent-runner/run-state.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export type EmbeddedAgentQueueHandle = {
2020
kind?: "embedded";
2121
queueMessage: (text: string, options?: EmbeddedAgentQueueMessageOptions) => Promise<void>;
2222
isStreaming: () => boolean;
23+
isStopped?: () => boolean;
2324
isCompacting: () => boolean;
2425
supportsTranscriptCommitWait?: boolean;
2526
cancel?: (reason?: "user_abort" | "restart" | "superseded") => void;

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3759,6 +3759,7 @@ export async function runEmbeddedAttempt(
37593759
params.onAttemptAbort?.();
37603760
abortRun(false, reason === "restart" ? createAgentRunRestartAbortError() : undefined);
37613761
};
3762+
let acceptingSteerMessages = true;
37623763
const queueHandle: EmbeddedAgentQueueHandle & {
37633764
kind: "embedded";
37643765
cancel: (reason?: "user_abort" | "restart" | "superseded") => void;
@@ -3771,6 +3772,7 @@ export async function runEmbeddedAttempt(
37713772
await steerActiveSessionWithOptionalDeliveryWait(activeSession, text, options);
37723773
},
37733774
isStreaming: () => activeSession.isStreaming,
3775+
isStopped: () => !acceptingSteerMessages || aborted || runAbortController.signal.aborted,
37743776
isCompacting: () => subscription.isCompacting(),
37753777
supportsTranscriptCommitWait: true,
37763778
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
@@ -4918,6 +4920,7 @@ export async function runEmbeddedAttempt(
49184920
promptErrorSource = "prompt";
49194921
}
49204922
} finally {
4923+
acceptingSteerMessages = false;
49214924
log.debug(
49224925
`embedded run prompt end: runId=${params.runId} sessionId=${params.sessionId} durationMs=${Date.now() - promptStartedAt}`,
49234926
);

‎src/agents/embedded-agent-runner/runs.test.ts‎

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,21 @@ function createRunHandle(
4747
abort?: () => void;
4848
isCompacting?: boolean;
4949
isStreaming?: boolean;
50+
isStopped?: () => boolean;
51+
queueMessage?: (
52+
text: string,
53+
options?: Parameters<RunHandle["queueMessage"]>[1],
54+
) => Promise<void>;
5055
supportsTranscriptCommitWait?: boolean;
5156
} = {},
5257
): RunHandle {
5358
// Minimal handle fixture with overrideable lifecycle probes for registry
5459
// behavior; individual tests supply queue/abort behavior when needed.
5560
const abort = overrides.abort ?? (() => {});
5661
return {
57-
queueMessage: async () => {},
62+
queueMessage: overrides.queueMessage ?? (async () => {}),
5863
isStreaming: () => overrides.isStreaming ?? true,
64+
...(overrides.isStopped ? { isStopped: overrides.isStopped } : {}),
5965
isCompacting: () => overrides.isCompacting ?? false,
6066
supportsTranscriptCommitWait: overrides.supportsTranscriptCommitWait,
6167
abort,
@@ -231,6 +237,68 @@ describe("embedded-agent runner run registry", () => {
231237
expect(queueMessage).toHaveBeenCalledWith("continue", { steeringMode: "all" });
232238
});
233239

240+
it("queues into active non-streaming handles that expose live stopped state", () => {
241+
const queueMessage = vi.fn(async () => {});
242+
setActiveEmbeddedRun(
243+
"session-active-non-streaming",
244+
createRunHandle({
245+
isStreaming: false,
246+
isStopped: () => false,
247+
queueMessage,
248+
}),
249+
);
250+
251+
expect(
252+
queueEmbeddedAgentMessageWithOutcome("session-active-non-streaming", "continue").queued,
253+
).toBe(true);
254+
expect(queueMessage).toHaveBeenCalledWith("continue", { steeringMode: "all" });
255+
});
256+
257+
it("does not queue into stopped handles", () => {
258+
const queueMessage = vi.fn(async () => {});
259+
setActiveEmbeddedRun(
260+
"session-stopped",
261+
createRunHandle({
262+
isStreaming: true,
263+
isStopped: () => true,
264+
queueMessage,
265+
}),
266+
);
267+
268+
const outcome = queueEmbeddedAgentMessageWithOutcome("session-stopped", "continue");
269+
270+
expect(outcome).toEqual({
271+
queued: false,
272+
sessionId: "session-stopped",
273+
reason: "not_streaming",
274+
gatewayHealth: "live",
275+
});
276+
expect(queueMessage).not.toHaveBeenCalled();
277+
});
278+
279+
it("fails closed when stopped state checks throw", () => {
280+
const queueMessage = vi.fn(async () => {});
281+
setActiveEmbeddedRun(
282+
"session-bad-state",
283+
createRunHandle({
284+
isStopped: () => {
285+
throw new Error("bad stopped state");
286+
},
287+
queueMessage,
288+
}),
289+
);
290+
291+
const outcome = queueEmbeddedAgentMessageWithOutcome("session-bad-state", "continue");
292+
293+
expect(outcome).toEqual({
294+
queued: false,
295+
sessionId: "session-bad-state",
296+
reason: "not_streaming",
297+
gatewayHealth: "live",
298+
});
299+
expect(queueMessage).not.toHaveBeenCalled();
300+
});
301+
234302
it("returns a structured no-active-run queue failure", () => {
235303
const outcome = queueEmbeddedAgentMessageWithOutcome("session-missing", "continue");
236304

@@ -588,5 +656,4 @@ describe("embedded-agent runner run registry", () => {
588656
clearActiveEmbeddedRun("session-snapshot", handle);
589657
expect(getActiveEmbeddedRunSnapshot("session-snapshot")).toBeUndefined();
590658
});
591-
592659
});

‎src/agents/embedded-agent-runner/runs.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,20 @@ function formatQueueError(err: unknown): string {
333333
return err instanceof Error ? err.message : String(err);
334334
}
335335

336+
function isEmbeddedQueueHandleMessageInjectable(
337+
sessionId: string,
338+
handle: EmbeddedAgentQueueHandle,
339+
): boolean {
340+
try {
341+
return handle.isStopped === undefined ? handle.isStreaming() : !handle.isStopped();
342+
} catch (err) {
343+
diag.warn(
344+
`queue message failed: sessionId=${sessionId} reason=injectable_check_failed err=${String(err)}`,
345+
);
346+
return false;
347+
}
348+
}
349+
336350
export async function queueEmbeddedAgentMessageWithOutcomeAsync(
337351
sessionId: string,
338352
text: string,
@@ -395,7 +409,7 @@ function prepareEmbeddedAgentQueueMessage(
395409
diag.debug(`queue message failed: sessionId=${sessionId} reason=no_active_run`);
396410
return { kind: "complete", outcome: createQueueFailureOutcome(sessionId, "no_active_run") };
397411
}
398-
if (!handle.isStreaming()) {
412+
if (!isEmbeddedQueueHandleMessageInjectable(sessionId, handle)) {
399413
diag.debug(`queue message failed: sessionId=${sessionId} reason=not_streaming`);
400414
return { kind: "complete", outcome: createQueueFailureOutcome(sessionId, "not_streaming") };
401415
}

‎src/auto-reply/reply/agent-runner.media-paths.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ describe("runReplyAgent media path normalization", () => {
407407
expect(createReplyMediaContextRuntimeMock).not.toHaveBeenCalled();
408408
});
409409

410-
it("steers active prompts in steer queue mode", async () => {
410+
it("steers active non-streaming prompts in steer queue mode", async () => {
411411
queueEmbeddedAgentMessageWithOutcomeAsyncMock.mockImplementation(async (sessionId: string) => ({
412412
queued: true,
413413
sessionId,
@@ -420,7 +420,8 @@ describe("runReplyAgent media path normalization", () => {
420420
resolvedQueue: { mode: "steer" } as QueueSettings,
421421
shouldSteer: true,
422422
shouldFollowup: true,
423-
isStreaming: true,
423+
isActive: true,
424+
isStreaming: false,
424425
}),
425426
);
426427

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,7 +1189,6 @@ export async function runReplyAgent(params: {
11891189
shouldFollowup,
11901190
isActive,
11911191
isRunActive,
1192-
isStreaming,
11931192
opts,
11941193
typing,
11951194
sessionEntry,
@@ -1275,7 +1274,7 @@ export async function runReplyAgent(params: {
12751274
}
12761275
};
12771276

1278-
if (effectiveShouldSteer && isStreaming) {
1277+
if (effectiveShouldSteer && isActive) {
12791278
const steerSessionId =
12801279
(sessionKey ? replyRunRegistry.resolveSessionId(sessionKey) : undefined) ??
12811280
followupRun.run.sessionId;

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,71 @@ describe("reply run registry", () => {
475475
expect(queueMessage).toHaveBeenCalledWith("hello");
476476
});
477477

478+
it("queues messages through active non-streaming backends with live stopped state", () => {
479+
const queueMessage = vi.fn(async () => {});
480+
const operation = createReplyOperation({
481+
sessionKey: "agent:main:main",
482+
sessionId: "session-running",
483+
resetTriggered: false,
484+
});
485+
486+
operation.attachBackend({
487+
kind: "embedded",
488+
cancel: vi.fn(),
489+
isStreaming: () => false,
490+
isStopped: () => false,
491+
queueMessage,
492+
});
493+
operation.setPhase("running");
494+
495+
expect(queueReplyRunMessage("session-running", "hello")).toBe(true);
496+
expect(queueMessage).toHaveBeenCalledWith("hello");
497+
});
498+
499+
it("does not queue messages through stopped backends", () => {
500+
const queueMessage = vi.fn(async () => {});
501+
const operation = createReplyOperation({
502+
sessionKey: "agent:main:main",
503+
sessionId: "session-running",
504+
resetTriggered: false,
505+
});
506+
507+
operation.attachBackend({
508+
kind: "embedded",
509+
cancel: vi.fn(),
510+
isStreaming: () => true,
511+
isStopped: () => true,
512+
queueMessage,
513+
});
514+
operation.setPhase("running");
515+
516+
expect(queueReplyRunMessage("session-running", "hello")).toBe(false);
517+
expect(queueMessage).not.toHaveBeenCalled();
518+
});
519+
520+
it("fails closed when backend stopped state checks throw", () => {
521+
const queueMessage = vi.fn(async () => {});
522+
const operation = createReplyOperation({
523+
sessionKey: "agent:main:main",
524+
sessionId: "session-running",
525+
resetTriggered: false,
526+
});
527+
528+
operation.attachBackend({
529+
kind: "embedded",
530+
cancel: vi.fn(),
531+
isStreaming: () => true,
532+
isStopped: () => {
533+
throw new Error("bad stopped state");
534+
},
535+
queueMessage,
536+
});
537+
operation.setPhase("running");
538+
539+
expect(queueReplyRunMessage("session-running", "hello")).toBe(false);
540+
expect(queueMessage).not.toHaveBeenCalled();
541+
});
542+
478543
it("aborts compacting runs through the registry compatibility helper", () => {
479544
const compactingOperation = createReplyOperation({
480545
sessionKey: "agent:main:main",

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export type ReplyBackendHandle = {
1919
readonly kind: ReplyBackendKind;
2020
cancel(reason?: ReplyBackendCancelReason): void;
2121
isStreaming(): boolean;
22+
isStopped?: () => boolean;
2223
queueMessage?: (text: string) => Promise<void>;
2324
/**
2425
* Compatibility-only hook so legacy "abort compacting runs" paths can still
@@ -235,6 +236,14 @@ function getAttachedBackend(operation: ReplyOperation): ReplyBackendHandle | und
235236
return attachedBackendByOperation.get(operation);
236237
}
237238

239+
function isReplyBackendMessageInjectable(backend: ReplyBackendHandle): boolean {
240+
try {
241+
return backend.isStopped === undefined ? backend.isStreaming() : !backend.isStopped();
242+
} catch {
243+
return false;
244+
}
245+
}
246+
238247
/** Run work after an operation no longer owns its session lane. */
239248
export function runAfterReplyOperationClear(
240249
operation: ReplyOperation,
@@ -726,7 +735,7 @@ export function queueReplyRunMessage(sessionId: string, text: string): boolean {
726735
if (!operation || operation.phase !== "running" || !backend?.queueMessage) {
727736
return false;
728737
}
729-
if (!backend.isStreaming()) {
738+
if (!isReplyBackendMessageInjectable(backend)) {
730739
return false;
731740
}
732741
void backend.queueMessage(text);

0 commit comments

Comments
 (0)