Skip to content

Commit d585181

Browse files
fix: harden active steering ownership
1 parent f3724f0 commit d585181

9 files changed

Lines changed: 258 additions & 57 deletions

‎extensions/copilot/src/attempt-active-run.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ type CopilotQueueMessageOptions = Parameters<typeof queueAgentHarnessMessage>[2]
1717
export function registerCopilotActiveRun(params: {
1818
abortActiveSession: () => void;
1919
bridge: ReturnType<typeof attachEventBridge> | undefined;
20+
canAcceptSteering: () => boolean;
2021
input: AttemptParamsLike;
2122
isAborted: () => boolean;
2223
isSettled: () => boolean;
@@ -49,6 +50,9 @@ export function registerCopilotActiveRun(params: {
4950
) {
5051
return;
5152
}
53+
if (!params.canAcceptSteering()) {
54+
throw new Error("Copilot steering is unavailable before initial user validation");
55+
}
5256
const messageId = await params.session.send({ prompt: text });
5357
if (options?.waitForTranscriptCommit === true) {
5458
await waitForPersistenceReceipt(
@@ -57,7 +61,7 @@ export function registerCopilotActiveRun(params: {
5761
);
5862
}
5963
},
60-
isStreaming: () => !params.isSettled() && !params.isAborted(),
64+
isStreaming: () => params.canAcceptSteering() && !params.isSettled() && !params.isAborted(),
6165
isAborted: params.isAborted,
6266
isCompacting: () => params.bridge?.isCompacting() ?? false,
6367
// session.send resolves with the injected user-message id; the journal

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export async function runCopilotExecution(context: {
108108
let session: SessionLike | undefined;
109109
let bridge: ReturnType<typeof attachEventBridge> | undefined;
110110
let transcriptJournal: AttemptTranscriptJournal | undefined;
111+
let initialSdkUserValidated = false;
111112
const nativeSubagentTaskMirror = createCopilotNativeSubagentTaskMirror({
112113
agentId: sessionAgentId,
113114
now,
@@ -407,6 +408,9 @@ export async function runCopilotExecution(context: {
407408
abortSession: () => session?.abort() ?? Promise.resolve(),
408409
attempt: input,
409410
messages,
411+
onInitialSdkUserValidated: () => {
412+
initialSdkUserValidated = true;
413+
},
410414
sdkSessionId,
411415
});
412416
bridge = attachEventBridge(session, {
@@ -457,6 +461,7 @@ export async function runCopilotExecution(context: {
457461
activeRunHandleRef = registerCopilotActiveRun({
458462
abortActiveSession,
459463
bridge,
464+
canAcceptSteering: () => initialSdkUserValidated,
460465
input,
461466
isAborted: () => aborted,
462467
isSettled: () => settled,

‎extensions/copilot/src/attempt-transcript-journal.test.ts‎

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -215,48 +215,6 @@ describe("Copilot attempt transcript journal", () => {
215215
]);
216216
});
217217

218-
it("resolves a steering receipt only after pending tool results and the user turn persist", async () => {
219-
const { journal, session } = await createFixture();
220-
await journal.persistInitialUser();
221-
session.emit(event("user.message", "initial-user", { content: "inspect both files" }));
222-
session.emit(
223-
event("assistant.message", "assistant-tools", {
224-
content: "checking",
225-
messageId: "assistant-tools",
226-
toolRequests: [{ arguments: {}, name: "read", toolCallId: "call-1" }],
227-
}),
228-
);
229-
session.emit(
230-
event("user.message", "steered-user", {
231-
content: "change course",
232-
delivery: "steering",
233-
}),
234-
);
235-
236-
let receiptSettled = false;
237-
const receipt = journal.waitForSdkUserPersisted("steered-user").then(() => {
238-
receiptSettled = true;
239-
});
240-
await Promise.resolve();
241-
expect(receiptSettled).toBe(false);
242-
243-
session.emit(
244-
event("tool.execution_complete", "tool-result", {
245-
result: { content: "done" },
246-
success: true,
247-
toolCallId: "call-1",
248-
}),
249-
);
250-
await receipt;
251-
252-
expect(journal.snapshot().messagesSnapshot.map((message) => message.role)).toEqual([
253-
"user",
254-
"assistant",
255-
"toolResult",
256-
"user",
257-
]);
258-
});
259-
260218
it("replaces the originally staged user when async resolution changes it", async () => {
261219
const { journal, recorder } = await createFixture();
262220
recorder.resolveMessage.mockResolvedValue({

‎extensions/copilot/src/attempt-transcript-journal.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ export function createAttemptTranscriptJournal(params: {
7070
abortSession: () => Promise<void>;
7171
attempt: AttemptParamsLike;
7272
messages: AgentMessage[];
73+
onInitialSdkUserValidated?: () => void;
7374
sdkSessionId: string;
7475
}) {
7576
const hiddenTurn = params.attempt.trigger === "memory";
@@ -425,6 +426,7 @@ export function createAttemptTranscriptJournal(params: {
425426
replayInvalid = true;
426427
} else {
427428
initialSdkUserValidated = true;
429+
params.onInitialSdkUserValidated?.();
428430
}
429431
persistenceReceipt.resolve();
430432
return;
@@ -439,6 +441,8 @@ export function createAttemptTranscriptJournal(params: {
439441
const outcome = await append(write);
440442
if (!outcome) {
441443
replayInvalid = true;
444+
persistenceReceipt.reject(new Error("Copilot steering user write was suppressed"));
445+
return;
442446
}
443447
await publish(accept(outcome));
444448
persistenceReceipt.resolve();
@@ -527,6 +531,12 @@ export function createAttemptTranscriptJournal(params: {
527531
const outcome = await append(write);
528532
if (!outcome) {
529533
replayInvalid = true;
534+
if (write.eventId) {
535+
sdkUserPersistenceReceipt(write.eventId).reject(
536+
new Error("Copilot steering user write was suppressed"),
537+
);
538+
}
539+
continue;
530540
}
531541
const didAppend = accept(outcome);
532542
appended ||= didAppend;

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,6 +1932,7 @@ describe("runCopilotAttempt", () => {
19321932
const sdk = makeFakeSdk({
19331933
onCreateSession: (session, cfg) => {
19341934
session.sendAndWait.mockImplementationOnce(async () => {
1935+
session.emit("user.message", { __eventId: "initial-user", content: "hello" });
19351936
const handler = cfg.onUserInputRequest;
19361937
if (typeof handler !== "function") {
19371938
throw new Error("expected onUserInputRequest handler");
@@ -2022,6 +2023,178 @@ describe("runCopilotAttempt", () => {
20222023
await expect(attempt).resolves.toMatchObject({ terminal: { kind: "ok" } });
20232024
});
20242025

2026+
it("holds a steering receipt until pending tool results and the user turn persist", async () => {
2027+
const initialTurn = createDeferred<SessionEventShape | undefined>();
2028+
const sdk = makeFakeSdk({
2029+
onCreateSession: (session) => {
2030+
session.sendAndWait.mockImplementationOnce(async () => {
2031+
session.emit("user.message", { __eventId: "initial-user", content: "hello" });
2032+
session.emit("assistant.message", {
2033+
__eventId: "assistant-tools",
2034+
content: "checking",
2035+
messageId: "assistant-tools",
2036+
toolRequests: [{ arguments: {}, name: "read", toolCallId: "call-1" }],
2037+
});
2038+
return initialTurn.promise;
2039+
});
2040+
session.send.mockImplementationOnce(async (options) => {
2041+
session.emit("user.message", {
2042+
__eventId: "steered-user",
2043+
content: (options as { prompt?: string }).prompt,
2044+
delivery: "steering",
2045+
});
2046+
return "steered-user";
2047+
});
2048+
},
2049+
});
2050+
const attempt = runCopilotAttempt(makeParams(), { pool: makeFakePool(sdk) });
2051+
2052+
await vi.waitFor(() => expect(requireSession(sdk).sendAndWait).toHaveBeenCalledTimes(1));
2053+
const handle = expectDefined(
2054+
gatewayQuestionMock.setActiveEmbeddedRun.mock.calls.at(-1)?.[1] as
2055+
| {
2056+
queueMessage: (
2057+
text: string,
2058+
options?: { waitForTranscriptCommit?: boolean },
2059+
) => Promise<void>;
2060+
}
2061+
| undefined,
2062+
"active Copilot steering handle",
2063+
);
2064+
let receiptSettled = false;
2065+
const receipt = handle
2066+
.queueMessage("change course", { waitForTranscriptCommit: true })
2067+
.then(() => {
2068+
receiptSettled = true;
2069+
});
2070+
await Promise.resolve();
2071+
expect(receiptSettled).toBe(false);
2072+
2073+
requireSession(sdk).emit("tool.execution_complete", {
2074+
__eventId: "tool-result",
2075+
result: { content: "done" },
2076+
success: true,
2077+
toolCallId: "call-1",
2078+
});
2079+
await receipt;
2080+
2081+
initialTurn.resolve(makeAssistantMessageEvent("done"));
2082+
await expect(attempt).resolves.toMatchObject({ terminal: { kind: "ok" } });
2083+
});
2084+
2085+
it("rejects a waited steering receipt without leaking an unhandled rejection", async () => {
2086+
initializeGlobalHookRunner(
2087+
createMockPluginRegistry([
2088+
{
2089+
hookName: "before_message_write",
2090+
handler: (input: unknown) => {
2091+
const message = (input as { message: AgentMessage }).message;
2092+
return message.role === "user" &&
2093+
typeof message.content === "string" &&
2094+
message.content.includes("suppressed steer")
2095+
? { block: true }
2096+
: undefined;
2097+
},
2098+
},
2099+
]),
2100+
);
2101+
const initialTurn = createDeferred<SessionEventShape | undefined>();
2102+
const sdk = makeFakeSdk({
2103+
onCreateSession: (session) => {
2104+
session.sendAndWait.mockImplementationOnce(async () => {
2105+
session.emit("user.message", { __eventId: "initial-user", content: "hello" });
2106+
return initialTurn.promise;
2107+
});
2108+
session.send.mockImplementation(async (options) => {
2109+
const prompt = (options as { prompt?: string }).prompt ?? "";
2110+
const eventId = prompt.includes("fire and forget")
2111+
? "suppressed-steer-unobserved"
2112+
: "suppressed-steer-waited";
2113+
session.emit("user.message", {
2114+
__eventId: eventId,
2115+
content: prompt,
2116+
delivery: "steering",
2117+
});
2118+
return eventId;
2119+
});
2120+
},
2121+
});
2122+
const attempt = runCopilotAttempt(makeParams(), { pool: makeFakePool(sdk) });
2123+
2124+
await vi.waitFor(() => expect(requireSession(sdk).sendAndWait).toHaveBeenCalledTimes(1));
2125+
const handle = expectDefined(
2126+
gatewayQuestionMock.setActiveEmbeddedRun.mock.calls.at(-1)?.[1] as
2127+
| {
2128+
queueMessage: (
2129+
text: string,
2130+
options?: { waitForTranscriptCommit?: boolean },
2131+
) => Promise<void>;
2132+
}
2133+
| undefined,
2134+
"active Copilot steering handle",
2135+
);
2136+
const unhandledRejections: unknown[] = [];
2137+
const onUnhandledRejection = (reason: unknown) => {
2138+
unhandledRejections.push(reason);
2139+
};
2140+
process.on("unhandledRejection", onUnhandledRejection);
2141+
try {
2142+
await expect(
2143+
handle.queueMessage("fire and forget suppressed steer"),
2144+
).resolves.toBeUndefined();
2145+
await waitForEventLoopTurn();
2146+
expect(unhandledRejections).toEqual([]);
2147+
2148+
await expect(
2149+
handle.queueMessage("waited suppressed steer", { waitForTranscriptCommit: true }),
2150+
).rejects.toThrow("steering user write was suppressed");
2151+
2152+
initialTurn.resolve(makeAssistantMessageEvent("done"));
2153+
await expect(attempt).resolves.toMatchObject({ terminal: { kind: "ok" } });
2154+
await waitForEventLoopTurn();
2155+
expect(unhandledRejections).toEqual([]);
2156+
} finally {
2157+
process.off("unhandledRejection", onUnhandledRejection);
2158+
}
2159+
});
2160+
2161+
it("rejects active steering before the initial SDK user event is validated", async () => {
2162+
gatewayQuestionMock.setActiveEmbeddedRun.mockClear();
2163+
const initialTurn = createDeferred<SessionEventShape | undefined>();
2164+
const sdk = makeFakeSdk({
2165+
onCreateSession: (session) => {
2166+
session.sendAndWait.mockImplementationOnce(() => initialTurn.promise);
2167+
},
2168+
});
2169+
const attempt = runCopilotAttempt(makeParams(), { pool: makeFakePool(sdk) });
2170+
2171+
await vi.waitFor(() => {
2172+
expect(requireSession(sdk).sendAndWait).toHaveBeenCalledTimes(1);
2173+
});
2174+
const handle = expectDefined(
2175+
gatewayQuestionMock.setActiveEmbeddedRun.mock.calls.at(-1)?.[1] as
2176+
| {
2177+
queueMessage: (text: string) => Promise<void>;
2178+
}
2179+
| undefined,
2180+
"registered Copilot run handle",
2181+
);
2182+
await expect(handle.queueMessage("too early")).rejects.toThrow(
2183+
"unavailable before initial user validation",
2184+
);
2185+
expect(requireSession(sdk).send).not.toHaveBeenCalled();
2186+
2187+
requireSession(sdk).emit("user.message", {
2188+
__eventId: "initial-user",
2189+
content: "hello",
2190+
});
2191+
await expect(handle.queueMessage("now steer")).resolves.toBeUndefined();
2192+
expect(requireSession(sdk).send).toHaveBeenCalledWith({ prompt: "now steer" });
2193+
2194+
initialTurn.resolve(makeAssistantMessageEvent("done"));
2195+
await expect(attempt).resolves.toMatchObject({ terminal: { kind: "ok" } });
2196+
});
2197+
20252198
it("enableSessionTelemetry is omitted from createSession when undefined (SDK default)", async () => {
20262199
const sdk = makeFakeSdk();
20272200
const pool = makeFakePool(sdk);

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,9 @@ describe("runReplyAgent active steering", () => {
702702
});
703703

704704
it.each([
705+
"no_active_run",
706+
"not_streaming",
707+
"stale_run",
705708
"compacting",
706709
"image_input_unsupported",
707710
"source_reply_delivery_mode_mismatch",
@@ -727,6 +730,7 @@ describe("runReplyAgent active steering", () => {
727730
isActive: true,
728731
isStreaming: true,
729732
shouldSteer: true,
733+
shouldFollowup: true,
730734
resolvedQueueMode: "steer",
731735
});
732736

‎src/gateway/server-methods/chat-send-admission.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import { randomUUID } from "node:crypto";
22
import { isFutureDateTimestampMs } from "@openclaw/normalization-core/number-coercion";
33
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
44
import { createAgentRunRestartAbortError } from "../../agents/run-termination.js";
5-
import { isReplyRunAbortableForSignal } from "../../auto-reply/reply/reply-run-registry.js";
5+
import {
6+
isReplyRunAbortableForSignal,
7+
replyRunRegistry,
8+
} from "../../auto-reply/reply/reply-run-registry.js";
69
import { resolveSessionWorkStartError } from "../../config/sessions.js";
710
import { SESSION_ROUTING_CHANGED_ERROR_REASON } from "../../config/sessions/main-session.js";
811
import {
@@ -66,6 +69,7 @@ export async function admitChatSend(params: {
6669
agentId,
6770
resolvedSessionModel,
6871
resolvedSessionAuthProvider,
72+
activeRunScopeKey,
6973
timeoutMs,
7074
now,
7175
restartSafeRequest,
@@ -193,7 +197,12 @@ export async function admitChatSend(params: {
193197
if (entry && !latestEntry) {
194198
throw new Error(`Session "${sessionKey}" was deleted while starting work. Retry.`);
195199
}
196-
if (commitOutcome && expectedLeafEntryId !== undefined) {
200+
// An active owner can advance this branch while a steer is being composed.
201+
// The lifecycle admission keeps branch identity fixed after this check; if
202+
// the owner clears, acceptance-aware dispatch preserves this turn as follow-up.
203+
const hasActiveSteeringOwner =
204+
p.queueMode === "steer" && replyRunRegistry.isStreaming(activeRunScopeKey);
205+
if (commitOutcome && expectedLeafEntryId !== undefined && !hasActiveSteeringOwner) {
197206
// Runtime session identity resolves through the canonical SQLite accessor;
198207
// legacy/reset-archive files are read-only history fallbacks, never send targets.
199208
const currentLeafEntryId = latestEntry?.sessionId

‎src/gateway/server-methods/chat-send-session.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,8 @@ function loadChatSendSessionContext(params: {
7474
const expectedSessionRoutingContract = normalizeOptionalChatText(
7575
p.expectedSessionRoutingContract,
7676
);
77-
// An active run advances its own transcript leaf while steering remains valid.
78-
// Treat explicit steers as run-owned input so normal branch fencing cannot reject them.
7977
const expectedLeafEntryId =
80-
p.queueMode === "steer"
81-
? undefined
82-
: p.expectedLeafEntryId === null
83-
? null
84-
: normalizeOptionalChatText(p.expectedLeafEntryId);
78+
p.expectedLeafEntryId === null ? null : normalizeOptionalChatText(p.expectedLeafEntryId);
8579
const sessionRoutingChanged = (candidateConfig: OpenClawConfig) =>
8680
expectedSessionRoutingContract !== undefined &&
8781
expectedSessionRoutingContract.toLowerCase() !== resolveSessionRoutingContract(candidateConfig);

0 commit comments

Comments
 (0)