Skip to content

Commit 7057b6c

Browse files
author
nux
committed
test: add unit tests for steer mode message injection (op-6we)
Add tests covering: - queueEmbeddedPiMessage: no active run, active but not streaming (original bug case), active but compacting, active and streaming - Steer guard in runReplyAgent: shouldSteer+isActive injects message, shouldSteer+!isActive skips injection, !shouldSteer skips injection These tests verify the fix that changed the steer guard from isStreaming to isActive (issue #48003 / PR #52351).
1 parent 6340e6e commit 7057b6c

2 files changed

Lines changed: 284 additions & 0 deletions

File tree

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
abortEmbeddedPiRun,
66
clearActiveEmbeddedRun,
77
getActiveEmbeddedRunSnapshot,
8+
queueEmbeddedPiMessage,
89
setActiveEmbeddedRun,
910
updateActiveEmbeddedRunSnapshot,
1011
waitForActiveEmbeddedRuns,
@@ -141,3 +142,59 @@ describe("pi-embedded runner run registry", () => {
141142
expect(getActiveEmbeddedRunSnapshot("session-snapshot")).toBeUndefined();
142143
});
143144
});
145+
146+
describe("queueEmbeddedPiMessage", () => {
147+
afterEach(() => {
148+
__testing.resetActiveEmbeddedRuns();
149+
});
150+
151+
function createQueueableHandle(
152+
overrides: { isCompacting?: boolean; isStreaming?: boolean } = {},
153+
): RunHandle & { queueMessageSpy: ReturnType<typeof vi.fn> } {
154+
const queueMessageSpy = vi.fn<(text: string) => Promise<void>>().mockResolvedValue(undefined);
155+
return {
156+
queueMessage: queueMessageSpy,
157+
isStreaming: () => overrides.isStreaming ?? true,
158+
isCompacting: () => overrides.isCompacting ?? false,
159+
abort: () => {},
160+
queueMessageSpy,
161+
};
162+
}
163+
164+
it("returns false when no active run exists for the session", () => {
165+
const result = queueEmbeddedPiMessage("no-such-session", "hello");
166+
expect(result).toBe(false);
167+
});
168+
169+
it("queues message when session is active but NOT streaming (original bug case)", () => {
170+
// Simulates the between-turns state that was previously blocked by the
171+
// removed isStreaming guard.
172+
const handle = createQueueableHandle({ isStreaming: false });
173+
setActiveEmbeddedRun("session-not-streaming", handle);
174+
175+
const result = queueEmbeddedPiMessage("session-not-streaming", "steer message");
176+
177+
expect(result).toBe(true);
178+
expect(handle.queueMessageSpy).toHaveBeenCalledWith("steer message");
179+
});
180+
181+
it("returns false when session is active but compacting", () => {
182+
const handle = createQueueableHandle({ isCompacting: true });
183+
setActiveEmbeddedRun("session-compacting", handle);
184+
185+
const result = queueEmbeddedPiMessage("session-compacting", "steer message");
186+
187+
expect(result).toBe(false);
188+
expect(handle.queueMessageSpy).not.toHaveBeenCalled();
189+
});
190+
191+
it("queues message when session is active and streaming (not compacting)", () => {
192+
const handle = createQueueableHandle();
193+
setActiveEmbeddedRun("session-streaming", handle);
194+
195+
const result = queueEmbeddedPiMessage("session-streaming", "steer message");
196+
197+
expect(result).toBe(true);
198+
expect(handle.queueMessageSpy).toHaveBeenCalledWith("steer message");
199+
});
200+
});
Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
/**
2+
* Tests for the steer guard in runReplyAgent — verifies that steer mode
3+
* message injection uses `isActive` (not `isStreaming`) to decide whether
4+
* to inject a steer message into an already-running agent session.
5+
*
6+
* Covers the fix for issue #48003 / PR #52351.
7+
*/
8+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9+
import type { TemplateContext } from "../templating.js";
10+
import type { FollowupRun, QueueSettings } from "./queue.js";
11+
import { createMockTypingController } from "./test-helpers.js";
12+
13+
const runEmbeddedPiAgentMock = vi.fn();
14+
const runCliAgentMock = vi.fn();
15+
const runWithModelFallbackMock = vi.fn();
16+
const queueEmbeddedPiMessageMock = vi.fn();
17+
18+
vi.mock("@mariozechner/pi-ai/oauth", () => ({
19+
getOAuthApiKey: vi.fn(),
20+
getOAuthProviders: vi.fn().mockReturnValue([]),
21+
refreshOAuthApiKey: vi.fn(),
22+
}));
23+
24+
vi.mock("../../agents/model-fallback.js", () => ({
25+
runWithModelFallback: (params: {
26+
provider: string;
27+
model: string;
28+
run: (provider: string, model: string) => Promise<unknown>;
29+
}) => runWithModelFallbackMock(params),
30+
}));
31+
32+
vi.mock("../../agents/pi-embedded.js", async () => {
33+
const actual = await vi.importActual<typeof import("../../agents/pi-embedded.js")>(
34+
"../../agents/pi-embedded.js",
35+
);
36+
return {
37+
...actual,
38+
queueEmbeddedPiMessage: (...args: unknown[]) => queueEmbeddedPiMessageMock(...args),
39+
runEmbeddedPiAgent: (params: unknown) => runEmbeddedPiAgentMock(params),
40+
};
41+
});
42+
43+
vi.mock("../../agents/cli-runner.js", async () => {
44+
const actual = await vi.importActual<typeof import("../../agents/cli-runner.js")>(
45+
"../../agents/cli-runner.js",
46+
);
47+
return {
48+
...actual,
49+
runCliAgent: (params: unknown) => runCliAgentMock(params),
50+
};
51+
});
52+
53+
vi.mock("../../runtime.js", async () => {
54+
const actual = await vi.importActual<typeof import("../../runtime.js")>("../../runtime.js");
55+
return {
56+
...actual,
57+
defaultRuntime: {
58+
...actual.defaultRuntime,
59+
log: vi.fn(),
60+
error: vi.fn(),
61+
exit: vi.fn(),
62+
},
63+
};
64+
});
65+
66+
vi.mock("./queue.js", async () => {
67+
const actual = await vi.importActual<typeof import("./queue.js")>("./queue.js");
68+
return {
69+
...actual,
70+
enqueueFollowupRun: vi.fn(),
71+
scheduleFollowupDrain: vi.fn(),
72+
};
73+
});
74+
75+
const loadCronStoreMock = vi.fn();
76+
vi.mock("../../cron/store.js", async () => {
77+
const actual = await vi.importActual<typeof import("../../cron/store.js")>("../../cron/store.js");
78+
return {
79+
...actual,
80+
loadCronStore: (...args: unknown[]) => loadCronStoreMock(...args),
81+
};
82+
});
83+
84+
import { runReplyAgent } from "./agent-runner.js";
85+
86+
type RunWithModelFallbackParams = {
87+
provider: string;
88+
model: string;
89+
run: (provider: string, model: string) => Promise<unknown>;
90+
};
91+
92+
beforeEach(() => {
93+
runEmbeddedPiAgentMock.mockClear();
94+
runCliAgentMock.mockClear();
95+
runWithModelFallbackMock.mockClear();
96+
queueEmbeddedPiMessageMock.mockClear();
97+
loadCronStoreMock.mockClear();
98+
loadCronStoreMock.mockResolvedValue({ version: 1, jobs: [] });
99+
100+
runWithModelFallbackMock.mockImplementation(
101+
async ({ provider, model, run }: RunWithModelFallbackParams) => ({
102+
result: await run(provider, model),
103+
provider,
104+
model,
105+
}),
106+
);
107+
});
108+
109+
afterEach(() => {
110+
vi.useRealTimers();
111+
});
112+
113+
describe("runReplyAgent steer mode message injection", () => {
114+
function createSteerRun(params: {
115+
shouldSteer: boolean;
116+
isActive: boolean;
117+
isStreaming?: boolean;
118+
shouldFollowup?: boolean;
119+
queueEmbeddedResult?: boolean;
120+
}) {
121+
const typing = createMockTypingController();
122+
const sessionCtx = {
123+
Provider: "webchat",
124+
OriginatingTo: "session:steer",
125+
AccountId: "primary",
126+
MessageSid: "msg-steer",
127+
} as unknown as TemplateContext;
128+
const resolvedQueue = { mode: "steer" } as unknown as QueueSettings;
129+
const followupRun = {
130+
prompt: "steer this",
131+
summaryLine: "steer this",
132+
enqueuedAt: Date.now(),
133+
run: {
134+
sessionId: "session-steer",
135+
sessionKey: "main",
136+
messageProvider: "webchat",
137+
sessionFile: "/tmp/session.jsonl",
138+
workspaceDir: "/tmp",
139+
config: {},
140+
skillsSnapshot: {},
141+
provider: "anthropic",
142+
model: "claude",
143+
thinkLevel: "low",
144+
verboseLevel: "off",
145+
elevatedLevel: "off",
146+
bashElevated: { enabled: false, allowed: false, defaultLevel: "off" },
147+
timeoutMs: 1_000,
148+
blockReplyBreak: "message_end",
149+
},
150+
} as unknown as FollowupRun;
151+
152+
queueEmbeddedPiMessageMock.mockReturnValue(params.queueEmbeddedResult ?? false);
153+
154+
return {
155+
promise: runReplyAgent({
156+
commandBody: "steer this",
157+
followupRun,
158+
queueKey: "main",
159+
resolvedQueue,
160+
shouldSteer: params.shouldSteer,
161+
shouldFollowup: params.shouldFollowup ?? false,
162+
isActive: params.isActive,
163+
isStreaming: params.isStreaming ?? false,
164+
typing,
165+
sessionCtx,
166+
defaultModel: "anthropic/claude",
167+
resolvedVerboseLevel: "off",
168+
isNewSession: false,
169+
blockStreamingEnabled: false,
170+
resolvedBlockStreamingBreak: "message_end",
171+
shouldInjectGroupIntro: false,
172+
typingMode: "instant",
173+
}),
174+
typing,
175+
};
176+
}
177+
178+
it("injects steer message when shouldSteer=true AND isActive=true", async () => {
179+
const { promise, typing } = createSteerRun({
180+
shouldSteer: true,
181+
isActive: true,
182+
queueEmbeddedResult: true,
183+
});
184+
185+
const result = await promise;
186+
187+
expect(queueEmbeddedPiMessageMock).toHaveBeenCalledWith("session-steer", "steer this");
188+
// When steered successfully and shouldFollowup=false, returns undefined (early exit).
189+
expect(result).toBeUndefined();
190+
expect(typing.cleanup).toHaveBeenCalled();
191+
});
192+
193+
it("does NOT inject steer message when shouldSteer=true AND isActive=false", async () => {
194+
// When isActive is false, the steer guard is skipped entirely and the
195+
// agent proceeds to a full run.
196+
runEmbeddedPiAgentMock.mockResolvedValueOnce({
197+
payloads: [{ text: "ok" }],
198+
meta: {},
199+
});
200+
201+
const { promise } = createSteerRun({
202+
shouldSteer: true,
203+
isActive: false,
204+
});
205+
206+
const result = await promise;
207+
208+
expect(queueEmbeddedPiMessageMock).not.toHaveBeenCalled();
209+
expect(result).toBeDefined();
210+
});
211+
212+
it("does NOT inject steer message when shouldSteer=false", async () => {
213+
runEmbeddedPiAgentMock.mockResolvedValueOnce({
214+
payloads: [{ text: "ok" }],
215+
meta: {},
216+
});
217+
218+
const { promise } = createSteerRun({
219+
shouldSteer: false,
220+
isActive: true,
221+
});
222+
223+
await promise;
224+
225+
expect(queueEmbeddedPiMessageMock).not.toHaveBeenCalled();
226+
});
227+
});

0 commit comments

Comments
 (0)