Skip to content

Commit 48ea089

Browse files
authored
fix(ui): make active-run steering reliable (#120083)
* fix(ui): make active-run steering reliable * chore: leave release notes to release prep * fix(ui): align steer result typing with main * fix(gateway): reject stale steering owners
1 parent c636060 commit 48ea089

11 files changed

Lines changed: 238 additions & 42 deletions

File tree

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

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -107,20 +107,32 @@ describe("reply run registry", () => {
107107
expect(isReplyRunAbortableForCompaction("session-compact")).toBe(true);
108108
});
109109

110-
it("matches streaming owners only to their immutable originating leaf", () => {
110+
it("matches injectable owners only to their immutable originating leaf", () => {
111111
const operation = createTestReplyOperation({ originatingLeafEntryId: "leaf-a" });
112+
let stopped = false;
113+
const queueMessage = vi.fn(async () => {});
112114
operation.setPhase("running");
113115
operation.attachBackend({
114116
kind: "embedded",
115117
cancel: () => {},
116-
isStreaming: () => true,
117-
queueMessage: async () => {},
118+
isStreaming: () => false,
119+
isStopped: () => stopped,
120+
queueMessage,
118121
});
119122

120-
expect(replyRunRegistry.isStreamingFromOriginatingLeaf("agent:main:main", "leaf-a")).toBe(true);
121-
expect(replyRunRegistry.isStreamingFromOriginatingLeaf("agent:main:main", "leaf-b")).toBe(
122-
false,
123-
);
123+
expect(
124+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-a"),
125+
).toBe(true);
126+
expect(
127+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-b"),
128+
).toBe(false);
129+
expect(queueReplyRunMessage(operation.sessionId, "steer during tool work")).toBe(true);
130+
expect(queueMessage).toHaveBeenCalledWith("steer during tool work");
131+
stopped = true;
132+
expect(
133+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-a"),
134+
).toBe(false);
135+
expect(queueReplyRunMessage(operation.sessionId, "late steer")).toBe(false);
124136
});
125137

126138
it("records reply-operation progress without claiming embedded-run activity", () => {
@@ -1204,28 +1216,40 @@ describe("reply run registry", () => {
12041216
expect(queueMessage).toHaveBeenCalledWith("hello");
12051217
});
12061218

1207-
it("refuses stale reply-run steering until real activity resumes", () => {
1219+
it("refuses stale injectable owners for admission and delivery until activity resumes", () => {
12081220
vi.useFakeTimers();
12091221
try {
12101222
const queueMessage = vi.fn(async () => {});
12111223
const operation = createTestReplyOperation({
12121224
sessionId: "session-running",
1225+
originatingLeafEntryId: "leaf-a",
12131226
});
12141227
operation.attachBackend({
12151228
kind: "embedded",
12161229
cancel: vi.fn(),
1217-
isStreaming: () => true,
1230+
isStreaming: () => false,
1231+
isStopped: () => false,
12181232
queueMessage,
12191233
});
12201234
operation.setPhase("running");
12211235

1236+
expect(
1237+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-a"),
1238+
).toBe(true);
1239+
12221240
vi.advanceTimersByTime(RUN_STALE_TAKEOVER_MS + 1);
12231241

1242+
expect(
1243+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-a"),
1244+
).toBe(false);
12241245
expect(queueReplyRunMessage("session-running", "stale")).toBe(false);
12251246
expect(queueMessage).not.toHaveBeenCalled();
12261247

12271248
operation.recordActivity();
12281249

1250+
expect(
1251+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf("agent:main:main", "leaf-a"),
1252+
).toBe(true);
12291253
expect(queueReplyRunMessage("session-running", "fresh")).toBe(true);
12301254
expect(queueMessage).toHaveBeenCalledWith("fresh");
12311255
} finally {

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

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ type ReplyRunRegistry = {
240240
get(sessionKey: string): ReplyOperation | undefined;
241241
isActive(sessionKey: string): boolean;
242242
isStreaming(sessionKey: string): boolean;
243-
isStreamingFromOriginatingLeaf(
243+
isMessageInjectableFromOriginatingLeaf(
244244
sessionKey: string,
245245
originatingLeafEntryId: string | null,
246246
): boolean;
@@ -429,6 +429,15 @@ function isReplyBackendMessageInjectable(backend: ReplyBackendHandle): boolean {
429429
}
430430
}
431431

432+
function isReplyOperationMessageInjectable(
433+
operation: ReplyOperation,
434+
backend: ReplyBackendHandle,
435+
): boolean {
436+
// Admission and delivery must share freshness or a stale owner can waive the
437+
// transcript-leaf fence and then reject the same steer during injection.
438+
return !isReplyRunEvidenceStale(operation) && isReplyBackendMessageInjectable(backend);
439+
}
440+
432441
/** Run work after an operation no longer owns its session lane. */
433442
export function runAfterReplyOperationClear(
434443
operation: ReplyOperation,
@@ -1176,7 +1185,7 @@ export const replyRunRegistry: ReplyRunRegistry = {
11761185
}
11771186
return getAttachedBackend(operation)?.isStreaming() ?? false;
11781187
},
1179-
isStreamingFromOriginatingLeaf(sessionKey, originatingLeafEntryId) {
1188+
isMessageInjectableFromOriginatingLeaf(sessionKey, originatingLeafEntryId) {
11801189
const operation = this.get(sessionKey);
11811190
if (
11821191
!operation ||
@@ -1185,7 +1194,8 @@ export const replyRunRegistry: ReplyRunRegistry = {
11851194
) {
11861195
return false;
11871196
}
1188-
return getAttachedBackend(operation)?.isStreaming() ?? false;
1197+
const backend = getAttachedBackend(operation);
1198+
return backend ? isReplyOperationMessageInjectable(operation, backend) : false;
11891199
},
11901200
abort(sessionKey) {
11911201
const operation = this.get(sessionKey);
@@ -1294,12 +1304,7 @@ export function queueReplyRunMessage(
12941304
if (!operation || operation.phase !== "running" || !backend?.queueMessage) {
12951305
return false;
12961306
}
1297-
// Steering into an evidence-dead run swallows the human message that would
1298-
// otherwise trigger stale takeover through normal reply admission.
1299-
if (isReplyRunEvidenceStale(operation)) {
1300-
return false;
1301-
}
1302-
if (!isReplyBackendMessageInjectable(backend)) {
1307+
if (!isReplyOperationMessageInjectable(operation, backend)) {
13031308
return false;
13041309
}
13051310
if (resolveReplyBackendQueueMessageMismatch(backend, options)) {

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,10 @@ export async function admitChatSend(params: {
203203
const hasActiveSteeringOwner =
204204
p.queueMode === "steer" &&
205205
expectedLeafEntryId !== undefined &&
206-
replyRunRegistry.isStreamingFromOriginatingLeaf(activeRunScopeKey, expectedLeafEntryId);
206+
replyRunRegistry.isMessageInjectableFromOriginatingLeaf(
207+
activeRunScopeKey,
208+
expectedLeafEntryId,
209+
);
207210
if (commitOutcome && expectedLeafEntryId !== undefined && !hasActiveSteeringOwner) {
208211
// Runtime session identity resolves through the canonical SQLite accessor;
209212
// legacy/reset-archive files are read-only history fallbacks, never send targets.

‎src/gateway/server-methods/chat.directive-tags.test.ts‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { waitForSessionTranscriptIndexReconcile } from "../../config/sessions/se
3333
import { resolveMirroredTranscriptText } from "../../config/sessions/transcript-mirror.js";
3434
import { withOwnedSessionTranscriptWrites } from "../../config/sessions/transcript-write-context.js";
3535
import { getAgentRunContext } from "../../infra/agent-run-registry.js";
36+
import { RUN_STALE_TAKEOVER_MS } from "../../logging/diagnostic-run-activity.js";
3637
import { runExclusiveSessionLifecycleMutation } from "../../sessions/session-lifecycle-admission.js";
3738
import {
3839
disposeOpenClawAgentDatabaseByPath,
@@ -1358,7 +1359,7 @@ describe("chat directive tag stripping for non-streaming final payloads", () =>
13581359
expect(context.addChatRun).not.toHaveBeenCalled();
13591360
});
13601361

1361-
it("allows an explicit steer after its active owner advances the transcript leaf", async () => {
1362+
it("allows an explicit steer during injectable non-streaming tool work", async () => {
13621363
await createGatewayUserTurnSqliteFixture("openclaw-chat-send-steer-moving-leaf-");
13631364
await appendTranscriptMessage(transcriptScope(), {
13641365
eventId: "current-leaf",
@@ -1377,7 +1378,8 @@ describe("chat directive tag stripping for non-streaming final payloads", () =>
13771378
operation.attachBackend({
13781379
kind: "embedded",
13791380
cancel: () => {},
1380-
isStreaming: () => true,
1381+
isStreaming: () => false,
1382+
isStopped: () => false,
13811383
queueMessage: async () => {},
13821384
});
13831385

@@ -1403,6 +1405,54 @@ describe("chat directive tag stripping for non-streaming final payloads", () =>
14031405
expect(mockState.lastDispatchOriginatingLeafEntryId).toBe("leaf-before-active-run-output");
14041406
});
14051407

1408+
it("rejects a moved-leaf steer when the non-streaming owner evidence is stale", async () => {
1409+
await createGatewayUserTurnSqliteFixture("openclaw-chat-send-steer-stale-owner-");
1410+
await appendTranscriptMessage(transcriptScope(), {
1411+
eventId: "current-leaf",
1412+
message: { role: "assistant", content: "stale tool work" },
1413+
now: 1,
1414+
parentId: null,
1415+
});
1416+
const { context, respond, send } = createChatRequestFixture();
1417+
vi.useFakeTimers({ toFake: ["Date"] });
1418+
const operation = replyRunRegistry.begin({
1419+
sessionKey: "main",
1420+
sessionId: mockState.sessionId,
1421+
resetTriggered: false,
1422+
originatingLeafEntryId: "leaf-before-stale-run-output",
1423+
});
1424+
operation.setPhase("running");
1425+
operation.attachBackend({
1426+
kind: "embedded",
1427+
cancel: () => {},
1428+
isStreaming: () => false,
1429+
isStopped: () => false,
1430+
queueMessage: async () => {},
1431+
});
1432+
1433+
try {
1434+
vi.advanceTimersByTime(RUN_STALE_TAKEOVER_MS + 1);
1435+
await send({
1436+
idempotencyKey: "idem-steer-stale-owner",
1437+
requestParams: {
1438+
expectedLeafEntryId: "leaf-before-stale-run-output",
1439+
queueMode: "steer",
1440+
},
1441+
waitFor: "none",
1442+
});
1443+
} finally {
1444+
operation.complete();
1445+
vi.useRealTimers();
1446+
}
1447+
1448+
expect(lastRespondCall(respond)).toEqual([
1449+
false,
1450+
undefined,
1451+
expect.objectContaining({ details: { reason: "active-leaf-changed" } }),
1452+
]);
1453+
expect(context.addChatRun).not.toHaveBeenCalled();
1454+
});
1455+
14061456
it("rejects a stale explicit steer when a different leaf owns the active run", async () => {
14071457
await createGatewayUserTurnSqliteFixture("openclaw-chat-send-steer-different-owner-");
14081458
await appendTranscriptMessage(transcriptScope(), {

‎ui/src/e2e/chat-flow.history-recovery.e2e.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ suite.define(() => {
578578
await gateway.closeLatest(1006, "lost ack");
579579

580580
const queue = page.locator(".chat-queue");
581-
await queue.getByText("Needs review").waitFor({ timeout: 10_000 });
581+
await queue.getByText("Delivery uncertain").waitFor({ timeout: 10_000 });
582582
expect(await gateway.getRequests("chat.send")).toHaveLength(1);
583583
await queue.locator(".chat-queue__retry").click();
584584

‎ui/src/i18n/locales/en.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4286,6 +4286,8 @@ export const en: TranslationMap = {
42864286
chat: {
42874287
sendErrors: {
42884288
activeLeafChanged: "The thread switched branches — review and resend.",
4289+
steerRunNoLongerActive:
4290+
"This steer still targets the previous run, but that run is no longer active.",
42894291
},
42904292
waitingForApproval: "Waiting for approval…",
42914293
startupStatus: {
@@ -4712,7 +4714,7 @@ export const en: TranslationMap = {
47124714
waitingForRun: "Waiting for current run",
47134715
runningCommand: "Running command",
47144716
waitingForReconnect: "Waiting for reconnect",
4715-
needsReview: "Needs review",
4717+
needsReview: "Delivery uncertain",
47164718
},
47174719
imageCount: "Image ({count})",
47184720
},

‎ui/src/pages/chat/chat-send-actions.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { GatewayRequestError } from "../../api/gateway.ts";
12
import { t } from "../../i18n/index.ts";
23
import type { ChatAttachment, ChatQueueItem } from "../../lib/chat/chat-types.ts";
34
import { generateUUID } from "../../lib/uuid.ts";
@@ -27,13 +28,27 @@ import {
2728
} from "./chat-send-request.ts";
2829
import { listStoredChatOutboxes, storedChatOutboxScopeKey } from "./composer-persistence.ts";
2930
import { formatConnectError } from "./connect-error.ts";
31+
import { hasAbortableSessionRun } from "./run-lifecycle.ts";
3032
import {
3133
OFFLINE_QUEUE_STORAGE_ERROR,
3234
steerQueuedChatMessage as steerQueuedChatMessageLifecycle,
3335
type SteerSendDependencies,
3436
} from "./steer-lifecycle.ts";
3537
import { isInflightSteer } from "./steered-chip.ts";
3638

39+
function applyChatSendError(state: ChatState, err: unknown, canApplyError: () => boolean): string {
40+
const error = isActiveLeafChangedError(err)
41+
? t("chat.sendErrors.activeLeafChanged")
42+
: formatConnectError(err);
43+
if (canApplyError()) {
44+
setChatError(state, error);
45+
if (isActiveLeafChangedError(err)) {
46+
void Promise.all([loadChatHistory(state), loadChatBranches(state)]);
47+
}
48+
}
49+
return error;
50+
}
51+
3752
export async function sendChatMessageWithGeneratedRunId(
3853
state: ChatState,
3954
message: string,
@@ -60,18 +75,8 @@ export async function sendChatMessageWithGeneratedRunId(
6075
...(options.queueMode ? { queueMode: options.queueMode } : {}),
6176
});
6277
} catch (err) {
63-
if (canApplyError()) {
64-
setChatError(
65-
state,
66-
isActiveLeafChangedError(err)
67-
? t("chat.sendErrors.activeLeafChanged")
68-
: formatConnectError(err),
69-
);
70-
if (isActiveLeafChangedError(err)) {
71-
void Promise.all([loadChatHistory(state), loadChatBranches(state)]);
72-
}
73-
}
74-
return null;
78+
const error = applyChatSendError(state, err, canApplyError);
79+
return err instanceof GatewayRequestError ? { kind: "rejected" as const, error } : null;
7580
}
7681
}
7782

@@ -130,6 +135,25 @@ export async function retryQueuedChatMessage(host: ChatHost, id: string) {
130135
) {
131136
return;
132137
}
138+
if (item.kind === "steered") {
139+
if (!host.connected || !host.client || !hasAbortableSessionRun(host)) {
140+
setChatError(host, t("chat.sendErrors.steerRunNoLongerActive"));
141+
return;
142+
}
143+
const retry = updateQueuedMessage(host, id, (entry) => ({
144+
...entry,
145+
sendAttempts: 0,
146+
sendError: undefined,
147+
sendRequestStartedAtMs: undefined,
148+
sendState: "waiting-idle",
149+
}));
150+
if (!retry) {
151+
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
152+
return;
153+
}
154+
await steerQueuedChatMessageLifecycle(host, id, steerSendDependencies);
155+
return;
156+
}
133157
let outbox = findStoredOutbox(host, item.id);
134158
if (!outbox) {
135159
const wasVolatile = isVolatileQueuedMessage(host, item.id);

‎ui/src/pages/chat/chat-send-submit.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,12 +167,17 @@ async function sendDetachedCommandMessage(
167167
runId: opts.runId,
168168
},
169169
);
170-
const ok = ack?.status === "ok" || ack?.status === "started" || ack?.status === "in_flight";
170+
const sendAck = ack && !("kind" in ack) ? ack : null;
171+
const ok =
172+
sendAck?.status === "ok" || sendAck?.status === "started" || sendAck?.status === "in_flight";
171173
if (!ok && !restoreFailedCommandComposer(host, opts.recovery)) {
172174
releaseChatAttachmentPayloads(excludeComposerAttachments(host, opts.attachments));
173175
}
174-
if (isTerminalFailureChatSendAck(ack) && submittedCommandScopeIsVisible(host, opts.recovery)) {
175-
setChatError(host, formatTerminalChatSendAckError(ack, "detached"));
176+
if (
177+
isTerminalFailureChatSendAck(sendAck) &&
178+
submittedCommandScopeIsVisible(host, opts.recovery)
179+
) {
180+
setChatError(host, formatTerminalChatSendAckError(sendAck, "detached"));
176181
}
177182
if (ok) {
178183
const submittedScopeIsVisible = submittedCommandScopeIsVisible(host, opts.recovery);

0 commit comments

Comments
 (0)