Skip to content

Commit 663c85b

Browse files
committed
fix(ui): associate steering work by target run
1 parent 4312a36 commit 663c85b

6 files changed

Lines changed: 177 additions & 22 deletions

File tree

‎ui/src/pages/chat/chat-state.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { resolveChatAvatarUrl, selectedChatSessionRow } from "./chat-state-route
2626
import { buildChatItems } from "./chat-thread-build.ts";
2727
import { getChatSessionProjection } from "./history-merge.ts";
2828
import { scheduleControlUiAfterPaint } from "./performance.ts";
29+
import { applySessionMessagePayload } from "./session-message-apply.ts";
2930

3031
beforeEach(() => {
3132
vi.spyOn(assistantIdentity, "loadLocalAssistantIdentity").mockReturnValue({
@@ -135,6 +136,45 @@ describe("canonical session message recovery", () => {
135136
});
136137
});
137138

139+
it("retires live commentary when its durable row arrives during an active run", () => {
140+
const runId = "active-run";
141+
const text = "Checking the workspace.";
142+
const { state } = createSessionEventState({
143+
connected: false,
144+
chatMessages: [],
145+
chatRunId: runId,
146+
chatStream: null,
147+
chatStreamSegments: [{ text, ts: 1, runId, itemId: "commentary-1" }],
148+
chatToolMessages: [],
149+
});
150+
151+
applySessionMessagePayload(
152+
state,
153+
{
154+
sessionKey: state.sessionKey,
155+
runId,
156+
messageId: "commentary-message-1",
157+
messageSeq: 1,
158+
message: {
159+
role: "assistant",
160+
runId,
161+
content: [{ type: "text", text }],
162+
timestamp: 1,
163+
openclawStreamFallback: {
164+
replacementText: text,
165+
source: "segment",
166+
itemId: "commentary-1",
167+
},
168+
},
169+
},
170+
true,
171+
{ kind: "history-delta" },
172+
);
173+
174+
expect(state.chatStreamSegments).toEqual([]);
175+
expect(renderedTranscript(state)).toEqual([{ role: "assistant", text }]);
176+
});
177+
138178
it("keeps cumulative assistant output split across an authoritative steer", () => {
139179
const activeRunId = "active-run";
140180
const steerRunId = "steer-request";

‎ui/src/pages/chat/chat-thread-grouping.ts‎

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
chatItemStartsUserTurn,
1616
safeNormalizeMessage,
1717
} from "./chat-turn-boundary.ts";
18-
import { persistedSteerTargetRunId } from "./stream-causal-boundary.ts";
18+
import { indexTurnContinuations } from "./stream-causal-boundary.ts";
1919

2020
export function isKeyedAssistantStreamFallbackMessage(message: unknown): boolean {
2121
const record = asRecord(message);
@@ -554,18 +554,17 @@ function isFinalReplyGroup(item: TurnRenderItem): boolean {
554554
return item.kind === "group" && !item.isStreaming && assistantGroupCanOwnActiveRunStatus(item);
555555
}
556556

557-
function turnStartsWithSteer(turn: TurnRenderItem[]): boolean {
557+
function turnUserMessages(turn: TurnRenderItem[]): unknown[] {
558558
const boundary = turn[0];
559559
if (!boundary || boundary.kind === "stream-run") {
560-
return false;
560+
return [];
561561
}
562562
if (boundary.kind === "group") {
563-
return (
564-
boundary.role.toLowerCase() === "user" &&
565-
boundary.messages.some(({ message }) => persistedSteerTargetRunId(message) !== null)
566-
);
563+
return boundary.role.toLowerCase() === "user"
564+
? boundary.messages.map(({ message }) => message)
565+
: [];
567566
}
568-
return boundary.kind === "message" && persistedSteerTargetRunId(boundary.message) !== null;
567+
return boundary.kind === "message" && chatItemStartsUserTurn(boundary) ? [boundary.message] : [];
569568
}
570569

571570
/**
@@ -605,11 +604,12 @@ export function collapseCompletedTurnWork(
605604
turns.push(currentTurn);
606605
}
607606

608-
const continuesIntoSteer = turns.map((_, turnIndex) =>
609-
turnStartsWithSteer(turns[turnIndex + 1] ?? []),
607+
const { continuationTurnIndexes, precedingContinuationTurnIndexes } = indexTurnContinuations(
608+
turns,
609+
turnUserMessages,
610610
);
611611
const finalReplyIndexes = turns.map((turn, turnIndex) => {
612-
if (continuesIntoSteer[turnIndex]) {
612+
if (continuationTurnIndexes.has(turnIndex)) {
613613
return -1;
614614
}
615615
for (let index = turn.length - 1; index >= 0; index -= 1) {
@@ -624,14 +624,22 @@ export function collapseCompletedTurnWork(
624624
index >= 0 ? (turns[turnIndex]?.[index] as MessageGroup) : undefined,
625625
);
626626
for (let turnIndex = turns.length - 2; turnIndex >= 0; turnIndex -= 1) {
627-
if (!terminalReplies[turnIndex] && continuesIntoSteer[turnIndex]) {
628-
terminalReplies[turnIndex] = terminalReplies[turnIndex + 1];
627+
const continuationTurnIndex = continuationTurnIndexes.get(turnIndex);
628+
if (!terminalReplies[turnIndex] && continuationTurnIndex !== undefined) {
629+
terminalReplies[turnIndex] = terminalReplies[continuationTurnIndex];
629630
}
630631
}
631-
let activeRunStartIndex = turns.length - 1;
632+
const liveTurnIndexes = new Set<number>();
632633
if (opts.runWorking) {
633-
while (activeRunStartIndex > 0 && turnStartsWithSteer(turns[activeRunStartIndex] ?? [])) {
634-
activeRunStartIndex -= 1;
634+
let liveTurnIndex = turns.length - 1;
635+
liveTurnIndexes.add(liveTurnIndex);
636+
for (;;) {
637+
const precedingTurnIndex = precedingContinuationTurnIndexes.get(liveTurnIndex);
638+
if (precedingTurnIndex === undefined) {
639+
break;
640+
}
641+
liveTurnIndex = precedingTurnIndex;
642+
liveTurnIndexes.add(liveTurnIndex);
635643
}
636644
}
637645

@@ -641,7 +649,7 @@ export function collapseCompletedTurnWork(
641649
// While the run works, the trailing turn also stays expanded so activity
642650
// is watchable until the terminal rebuild collapses it.
643651
const isLive =
644-
(opts.runWorking && turnIndex >= activeRunStartIndex) ||
652+
liveTurnIndexes.has(turnIndex) ||
645653
turn.some(
646654
(item) => item.kind === "stream-run" || (item.kind === "group" && item.isStreaming),
647655
);
@@ -683,12 +691,14 @@ export function collapseCompletedTurnWork(
683691
const startTimestamp = boundaryTimestamp == null ? firstGroup.timestamp : boundaryTimestamp;
684692
const endTimestamp = terminalReply.timestamp;
685693
const durationMs = endTimestamp > startTimestamp ? endTimestamp - startTimestamp : null;
686-
const nextBoundary = turns[turnIndex + 1]?.[0];
694+
const continuationBoundary = turns[continuationTurnIndexes.get(turnIndex) ?? -1]?.[0];
687695
result.push(...turn.slice(0, segmentStart));
688696
result.push({
689697
kind: "work-group",
690698
// The final reply survives older-history prepends; the first work row does not.
691-
key: `work:${finalReplyIndex >= 0 || !nextBoundary ? terminalReply.key : nextBoundary.key}`,
699+
key: `work:${
700+
finalReplyIndex >= 0 || !continuationBoundary ? terminalReply.key : continuationBoundary.key
701+
}`,
692702
groups,
693703
durationMs,
694704
});

‎ui/src/pages/chat/chat-thread.test.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -840,11 +840,20 @@ describe("collapseCompletedTurnWork", () => {
840840

841841
it("collapses completed pre-steer work before the steering message", () => {
842842
const messages = [
843-
userMessage("do it", 1_000),
843+
userMessage("do it", 1_000, {
844+
__openclaw: { idempotencyKey: "active-run:user", senderId: "operator" },
845+
}),
844846
assistantMessage("Checking…", 2_000),
845847
toolResult("call-1", 3_000),
848+
userMessage("queued follow-up", 3_500, {
849+
__openclaw: { idempotencyKey: "queued-run:user", senderId: "peer" },
850+
}),
846851
userMessage("continue", 4_000, {
847-
__openclaw: { steerTargetRunId: "active-run" },
852+
__openclaw: {
853+
idempotencyKey: "steer-run:user",
854+
senderId: "operator",
855+
steerTargetRunId: "active-run",
856+
},
848857
}),
849858
assistantMessage("All done.", 5_000),
850859
];
@@ -856,7 +865,13 @@ describe("collapseCompletedTurnWork", () => {
856865
).toBe(false);
857866

858867
const completed = collapsedItems({ messages });
859-
expect(completed.map((item) => item.kind)).toEqual(["group", "work-group", "group", "group"]);
868+
expect(completed.map((item) => item.kind)).toEqual([
869+
"group",
870+
"work-group",
871+
"group",
872+
"group",
873+
"group",
874+
]);
860875
expect(requireWorkGroup(completed[1]).durationMs).toBe(4_000);
861876
});
862877

‎ui/src/pages/chat/session-message-apply.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
reduceChatSessionProjection,
1414
} from "./history-merge.ts";
1515
import { persistedSteerTargetRunId, rolloverChatStream } from "./stream-causal-boundary.ts";
16+
import { prunePersistedAssistantStreamSegments } from "./stream-segment-pruning.ts";
1617

1718
type SessionMessageApplySource =
1819
| { kind: "history-delta" }
@@ -129,6 +130,9 @@ export function applySessionMessagePayload(
129130
},
130131
{ scope, runActive },
131132
);
133+
if (incoming.role === "assistant" && projection.messages.includes(message)) {
134+
prunePersistedAssistantStreamSegments(state, message, incoming.runId);
135+
}
132136
const steerTargetRunId = persistedSteerTargetRunId(message);
133137
const currentRunId = state.chatRunId;
134138
if (

‎ui/src/pages/chat/stream-causal-boundary.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,68 @@ export function persistedSteerTargetRunId(message: unknown): string | null {
3737
return normalizeOptionalString(metadata?.steerTargetRunId) ?? null;
3838
}
3939

40+
function turnRunId(messages: unknown[]): string | null {
41+
for (const message of messages) {
42+
const identity = userTurnSendIdentity(message);
43+
if (identity?.startsWith("send:")) {
44+
return identity.slice("send:".length);
45+
}
46+
}
47+
return null;
48+
}
49+
50+
function turnSteerTargetRunId(messages: unknown[]): string | null {
51+
for (const message of messages) {
52+
const targetRunId = persistedSteerTargetRunId(message);
53+
if (targetRunId) {
54+
return targetRunId;
55+
}
56+
}
57+
return null;
58+
}
59+
60+
export function indexTurnContinuations<T>(
61+
turns: T[][],
62+
userMessagesForTurn: (turn: T[]) => unknown[],
63+
): {
64+
continuationTurnIndexes: Map<number, number>;
65+
precedingContinuationTurnIndexes: Map<number, number>;
66+
} {
67+
const runTurnIndexes = new Map<string, number>();
68+
const steerTurnIndexesByTarget = new Map<string, number[]>();
69+
for (const [turnIndex, turn] of turns.entries()) {
70+
const userMessages = userMessagesForTurn(turn);
71+
const runId = turnRunId(userMessages);
72+
if (runId && !runTurnIndexes.has(runId)) {
73+
runTurnIndexes.set(runId, turnIndex);
74+
}
75+
const targetRunId = turnSteerTargetRunId(userMessages);
76+
if (targetRunId) {
77+
const steerTurns = steerTurnIndexesByTarget.get(targetRunId) ?? [];
78+
steerTurns.push(turnIndex);
79+
steerTurnIndexesByTarget.set(targetRunId, steerTurns);
80+
}
81+
}
82+
83+
const continuationTurnIndexes = new Map<number, number>();
84+
const precedingContinuationTurnIndexes = new Map<number, number>();
85+
for (const [targetRunId, steerTurnIndexes] of steerTurnIndexesByTarget) {
86+
let previousTurnIndex = runTurnIndexes.get(targetRunId);
87+
if (previousTurnIndex === undefined) {
88+
continue;
89+
}
90+
for (const steerTurnIndex of steerTurnIndexes) {
91+
if (steerTurnIndex <= previousTurnIndex) {
92+
continue;
93+
}
94+
continuationTurnIndexes.set(previousTurnIndex, steerTurnIndex);
95+
precedingContinuationTurnIndexes.set(steerTurnIndex, previousTurnIndex);
96+
previousTurnIndex = steerTurnIndex;
97+
}
98+
}
99+
return { continuationTurnIndexes, precedingContinuationTurnIndexes };
100+
}
101+
40102
export function latestPersistedSteerBoundary(
41103
messages: unknown[],
42104
activeRunId: string,

‎ui/src/pages/chat/stream-segment-pruning.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
12
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
23
import {
34
advanceAccumulatedStreamText,
@@ -67,6 +68,29 @@ export function discardStreamSegmentIndexes(
6768
);
6869
}
6970

71+
/** A durable commentary row immediately replaces its keyed live projection.
72+
* Waiting for terminal cleanup renders both copies throughout the active run. */
73+
export function prunePersistedAssistantStreamSegments(
74+
state: StreamCausalBoundaryState,
75+
message: unknown,
76+
runId?: string | null,
77+
): void {
78+
const fallback = asNullableRecord(asNullableRecord(message)?.openclawStreamFallback);
79+
const itemId = normalizeOptionalString(fallback?.itemId);
80+
if (!itemId || !state.chatStreamSegments) {
81+
return;
82+
}
83+
const ownerRunId = normalizeOptionalString(runId);
84+
const replacedIndexes = state.chatStreamSegments.flatMap((segment, index) => {
85+
if (normalizeOptionalString(segment.itemId) !== itemId) {
86+
return [];
87+
}
88+
const segmentRunId = normalizeOptionalString(segment.runId);
89+
return ownerRunId && segmentRunId && ownerRunId !== segmentRunId ? [] : [index];
90+
});
91+
discardStreamSegmentIndexes(state, replacedIndexes);
92+
}
93+
7094
export function pruneHistoryReplacedStreamSegments(
7195
messages: unknown[],
7296
state: StreamSegmentPruningState,

0 commit comments

Comments
 (0)