Skip to content

Commit 6c9954c

Browse files
authored
fix: preserve cloud turns when follow-up input arrives (#132887)
* fix: preserve cloud turns when follow-up input arrives * test: align session admission fixtures and checks * fix: refresh accepted input during active cloud turns * test: use complete page state for pending input events * fix(ui): keep live tool echoes with their canonical invocation * docs: clarify durable pending input coverage * fix(ui): read canonical run identity for tool activity * test: publish process readiness after signal setup
1 parent 64f4a18 commit 6c9954c

74 files changed

Lines changed: 3196 additions & 442 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20773,6 +20773,7 @@ public struct ChatHistoryParams: Codable, Sendable {
2077320773
public let cursor: String?
2077420774
public let limit: Int?
2077520775
public let offset: Int?
20776+
public let pendingbefore: Int?
2077620777
public let messageid: String?
2077720778
public let sessionid: String?
2077820779
public let maxchars: Int?
@@ -20783,6 +20784,7 @@ public struct ChatHistoryParams: Codable, Sendable {
2078320784
cursor: String? = nil,
2078420785
limit: Int? = nil,
2078520786
offset: Int? = nil,
20787+
pendingbefore: Int? = nil,
2078620788
messageid: String? = nil,
2078720789
sessionid: String? = nil,
2078820790
maxchars: Int? = nil)
@@ -20792,6 +20794,7 @@ public struct ChatHistoryParams: Codable, Sendable {
2079220794
self.cursor = cursor
2079320795
self.limit = limit
2079420796
self.offset = offset
20797+
self.pendingbefore = pendingbefore
2079520798
self.messageid = messageid
2079620799
self.sessionid = sessionid
2079720800
self.maxchars = maxchars
@@ -20803,6 +20806,7 @@ public struct ChatHistoryParams: Codable, Sendable {
2080320806
case cursor
2080420807
case limit
2080520808
case offset
20809+
case pendingbefore = "pendingBefore"
2080620810
case messageid = "messageId"
2080720811
case sessionid = "sessionId"
2080820812
case maxchars = "maxChars"
@@ -20817,6 +20821,7 @@ public struct ChatHistoryDeltaResult: Codable, Sendable {
2081720821
public let agentslist: AnyCodable?
2081820822
public let inflightrun: AnyCodable?
2081920823
public let metadata: AnyCodable?
20824+
public let pendinginputs: [String: AnyCodable]?
2082020825

2082120826
public init(
2082220827
kind: String,
@@ -20825,7 +20830,8 @@ public struct ChatHistoryDeltaResult: Codable, Sendable {
2082520830
sessioninfo: AnyCodable,
2082620831
agentslist: AnyCodable? = nil,
2082720832
inflightrun: AnyCodable? = nil,
20828-
metadata: AnyCodable? = nil)
20833+
metadata: AnyCodable? = nil,
20834+
pendinginputs: [String: AnyCodable]? = nil)
2082920835
{
2083020836
self.kind = kind
2083120837
self.messages = messages
@@ -20834,6 +20840,7 @@ public struct ChatHistoryDeltaResult: Codable, Sendable {
2083420840
self.agentslist = agentslist
2083520841
self.inflightrun = inflightrun
2083620842
self.metadata = metadata
20843+
self.pendinginputs = pendinginputs
2083720844
}
2083820845

2083920846
private enum CodingKeys: String, CodingKey {
@@ -20844,6 +20851,7 @@ public struct ChatHistoryDeltaResult: Codable, Sendable {
2084420851
case agentslist = "agentsList"
2084520852
case inflightrun = "inFlightRun"
2084620853
case metadata
20854+
case pendinginputs = "pendingInputs"
2084720855
}
2084820856
}
2084920857

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3672,7 +3672,7 @@ src/sessions/session-upstream-links.ts 2
36723672
src/sessions/session-upstream-monitor.ts 2
36733673
src/sessions/user-turn-transcript-runtime-context.ts 2
36743674
src/sessions/user-turn-transcript.media-normalize.ts 2
3675-
src/sessions/user-turn-transcript.ts 11
3675+
src/sessions/user-turn-transcript.ts 5
36763676
src/shared/account-enabled.ts 1
36773677
src/shared/assistant-error-format.ts 3
36783678
src/shared/bounded-serial-queue.ts 1

‎docs/concepts/session-tool.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@ Gateway sharing operations are outside this run-audit boundary.
5151

5252
`sessions_history` fetches the conversation transcript for a specific session. By default, tool results are excluded; pass `includeTools: true` to see them. Use `limit` for the newest bounded tail. Pass `offset: 0` when you need pagination metadata, then pass returned `nextOffset` values to page backward through older OpenClaw transcript windows without reading raw transcript files. Explicit offset pages do not merge external CLI fallback imports; use the default newest-tail view (no `offset`) when you need that merged display history.
5353

54+
Durably admitted inputs from `sessions_send` or the Gateway `agent` method
55+
appear separately in `pendingInputs`, not in transcript `messages`. Each row
56+
records `queued`, `cancelled`, or `interrupted`.
57+
Cancelled and interrupted inputs are retained for inspection and never run
58+
automatically. Use `pendingBefore` with the page's `nextBefore` to read older
59+
inputs; `limit` bounds both pages. Pending previews share a 4 KB budget within
60+
the overall 80 KB response budget, so use a smaller `limit` for richer previews.
61+
5462
The returned view is intentionally bounded and redacted:
5563

5664
- credential/token-like text is redacted even when general-purpose log redaction is disabled

‎docs/web/control-ui.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,19 @@ On the first identified connection, the Control UI uploads existing browser-loca
124124

125125
When a remote project session starts before its repository finishes cloning, chat shows workspace preparation progress. If preparation fails, opening or reloading chat restores the session's failure summary. Correct the reported problem, then send a new message in the same session to retry preparation.
126126

127+
Inputs accepted through `sessions_send` or the Gateway `agent` method while a
128+
cloud turn is running remain visible with a waiting notice until their own turn
129+
starts. They are stored separately from the active model transcript. If
130+
cancellation or a Gateway restart interrupts that wait,
131+
the input stays readable with its recorded disposition and is never resent
132+
automatically. Copy it into the composer to start a new attempt. **Earlier
133+
accepted inputs** pages through retained inputs; **Latest accepted inputs**
134+
returns to the newest page. Long accepted input uses the normal full-message
135+
reader without becoming a transcript reply, fork, or rewind target.
136+
137+
Ordinary browser follow-ups still use the existing chat queue, including collect
138+
mode; they do not yet have this durable pending-input custody.
139+
127140
## Personal identity
128141

129142
Authenticated people have a durable Gateway profile with a display name, avatar, linked emails, and optional verified GitHub identity. Open **Settings → Profile → Identity** to update the editable fields. The profile follows the authenticated person across browsers; clearing browser site data does not delete it.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
/** Largest history page accepted by the Gateway wire contract. */
22
export const CHAT_HISTORY_MAX_ENTRIES = 1000;
3+
/** Display-only custody records; never transcript branch entry IDs. */
4+
export const CHAT_PENDING_INPUT_MESSAGE_PREFIX = "pending:";

‎packages/gateway-protocol/src/schema/logs-chat.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,29 @@ export const ChatHistoryParamsSchema = closedObject({
2929
cursor: Type.Optional(Type.String()),
3030
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: CHAT_HISTORY_MAX_ENTRIES })),
3131
offset: Type.Optional(Type.Integer({ minimum: 0 })),
32+
pendingBefore: Type.Optional(Type.Integer({ minimum: 1 })),
3233
messageId: Type.Optional(NonEmptyString),
3334
sessionId: Type.Optional(NonEmptyString),
3435
maxChars: Type.Optional(Type.Integer({ minimum: 1, maximum: 500_000 })),
3536
});
3637

38+
/** Accepted input awaiting a turn, separate from canonical model history. */
39+
export const ChatPendingInputsPageSchema = closedObject({
40+
items: Type.Array(
41+
closedObject({
42+
id: NonEmptyString,
43+
runId: Type.Optional(Type.String({ minLength: 1, maxLength: 256 })),
44+
message: Type.Unknown(),
45+
acceptedAt: Type.Number(),
46+
state: Type.String({ enum: ["queued", "cancelled", "interrupted"] }),
47+
}),
48+
{ maxItems: 20 },
49+
),
50+
total: Type.Integer({ minimum: 0 }),
51+
nextBefore: Type.Optional(Type.Integer({ minimum: 1 })),
52+
});
53+
export type ChatPendingInputsPage = Static<typeof ChatPendingInputsPageSchema>;
54+
3755
/**
3856
* Bounded forward catch-up response. Clients replay `messages` as `session.message`
3957
* payloads. There is no continuation loop: more than 200 raw events or the byte
@@ -47,6 +65,7 @@ export const ChatHistoryDeltaResultSchema = closedObject({
4765
agentsList: Type.Optional(Type.Unknown()),
4866
inFlightRun: Type.Optional(Type.Unknown()),
4967
metadata: Type.Optional(Type.Unknown()),
68+
pendingInputs: Type.Optional(ChatPendingInputsPageSchema),
5069
});
5170

5271
/** Normal cursor discontinuity; clients recover with a fresh tail request. */

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 78 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -2592,51 +2592,56 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
25922592
expect(sessionStore["agent:main:main"]?.restartRecoveryDeliveryRunId).toBe("session-1");
25932593
});
25942594

2595-
it("persists only the CLI assistant reply after the runner persists the current user turn", async () => {
2596-
type AttemptCall = {
2597-
onUserMessagePersisted?: () => void;
2598-
userTurnTranscriptRecorder: UserTurnTranscriptRecorder;
2599-
};
2600-
setupSingleAttemptFallback();
2601-
setupStoredSession();
2602-
const result = makeSuccessResult("openai", "gpt-5.4") as ReturnType<
2603-
typeof makeSuccessResult
2604-
> & {
2605-
meta: Record<string, unknown> & { executionTrace: Record<string, unknown> };
2606-
};
2607-
result.meta.executionTrace = {
2608-
runner: "cli",
2609-
fallbackUsed: false,
2610-
winnerProvider: "openai",
2611-
winnerModel: "gpt-5.4",
2612-
};
2613-
state.runAgentAttemptMock.mockImplementation(async (attemptParams: AttemptCall) => {
2614-
attemptParams.userTurnTranscriptRecorder.markRuntimePersisted();
2615-
attemptParams.onUserMessagePersisted?.();
2616-
return result;
2617-
});
2618-
state.persistCliTurnTranscriptMock.mockResolvedValue({
2619-
kind: "persisted",
2620-
sessionEntry: state.sessionEntryMock,
2621-
});
2622-
const userTurnTranscriptRecorder = createUserTurnTranscriptRecorder({
2623-
input: { text: "hello", idempotencyKey: "canonical-user:user" },
2624-
target: () => undefined,
2625-
});
2595+
it.each([true, false])(
2596+
"does not duplicate a recorder-owned CLI input after completion (persisted=%s)",
2597+
async (persisted) => {
2598+
type AttemptCall = {
2599+
onUserMessagePersisted?: () => void;
2600+
userTurnTranscriptRecorder: UserTurnTranscriptRecorder;
2601+
};
2602+
setupSingleAttemptFallback();
2603+
setupStoredSession();
2604+
const result = makeSuccessResult("openai", "gpt-5.4") as ReturnType<
2605+
typeof makeSuccessResult
2606+
> & {
2607+
meta: Record<string, unknown> & { executionTrace: Record<string, unknown> };
2608+
};
2609+
result.meta.executionTrace = {
2610+
runner: "cli",
2611+
fallbackUsed: false,
2612+
winnerProvider: "openai",
2613+
winnerModel: "gpt-5.4",
2614+
};
2615+
state.runAgentAttemptMock.mockImplementation(async (attemptParams: AttemptCall) => {
2616+
if (persisted) {
2617+
attemptParams.userTurnTranscriptRecorder.markRuntimePersisted();
2618+
attemptParams.onUserMessagePersisted?.();
2619+
}
2620+
return result;
2621+
});
2622+
state.persistCliTurnTranscriptMock.mockResolvedValue({
2623+
kind: "persisted",
2624+
sessionEntry: state.sessionEntryMock,
2625+
});
2626+
const userTurnTranscriptRecorder = createUserTurnTranscriptRecorder({
2627+
input: { text: "hello", idempotencyKey: "canonical-user:user" },
2628+
target: () => undefined,
2629+
});
26262630

2627-
await agentCommand({
2628-
message: "hello",
2629-
to: "+1234567890",
2630-
userTurnTranscriptRecorder,
2631-
});
2631+
await agentCommand({
2632+
message: "hello",
2633+
to: "+1234567890",
2634+
userTurnTranscriptRecorder,
2635+
});
26322636

2633-
expect(mockCallArg(state.runAgentAttemptMock)).toMatchObject({
2634-
userTurnTranscriptRecorder,
2635-
});
2636-
expect(mockCallArg(state.persistCliTurnTranscriptMock)).toMatchObject({
2637-
skipUserTurn: true,
2638-
});
2639-
});
2637+
expect(mockCallArg(state.runAgentAttemptMock)).toMatchObject({
2638+
userTurnTranscriptRecorder,
2639+
});
2640+
expect(mockCallArg(state.persistCliTurnTranscriptMock)).toMatchObject({
2641+
skipUserTurn: true,
2642+
});
2643+
},
2644+
);
26402645

26412646
it("does not treat backend CLI session id as OpenClaw session identity", async () => {
26422647
setupSingleAttemptFallback();
@@ -5184,12 +5189,12 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
51845189
const onExecutionStarted = vi.fn();
51855190
state.acpRunTurnMock.mockImplementationOnce(async (params: unknown) => {
51865191
const callbacks = params as {
5187-
onBeforePrompt?: () => void;
5192+
onBeforePrompt?: () => Promise<void> | void;
51885193
onLifecycle?: (event: { type: string; at: number }) => void;
51895194
onEvent?: (event: unknown) => void;
51905195
};
51915196
expect(onExecutionStarted).not.toHaveBeenCalled();
5192-
callbacks.onBeforePrompt?.();
5197+
await callbacks.onBeforePrompt?.();
51935198
expect(onExecutionStarted).toHaveBeenCalledOnce();
51945199
callbacks.onLifecycle?.({ type: "prompt_submitted", at: Date.now() });
51955200
callbacks.onEvent?.({ type: "done", stopReason: "end_turn" });
@@ -5204,6 +5209,34 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
52045209
expect(onExecutionStarted).toHaveBeenCalledTimes(1);
52055210
});
52065211

5212+
it("rejects an ACP prompt before execution when its accepted input cannot enter the transcript", async () => {
5213+
setupAcpSession();
5214+
const recorder = createUserTurnTranscriptRecorder({
5215+
input: { text: "accepted ACP input", idempotencyKey: "acp-input:user" },
5216+
target: () => undefined,
5217+
});
5218+
const onExecutionStarted = vi.fn();
5219+
const submitPrompt = vi.fn();
5220+
state.acpRunTurnMock.mockImplementationOnce(async (params: unknown) => {
5221+
const callbacks = params as { onBeforePrompt?: () => Promise<void> | void };
5222+
await callbacks.onBeforePrompt?.();
5223+
submitPrompt();
5224+
});
5225+
5226+
await expect(
5227+
agentCommand({
5228+
message: "accepted ACP input",
5229+
sessionKey: "agent:main:main",
5230+
userTurnTranscriptRecorder: recorder,
5231+
onExecutionStarted,
5232+
}),
5233+
).rejects.toThrow("ACP input could not enter the session transcript");
5234+
5235+
expect(onExecutionStarted).not.toHaveBeenCalled();
5236+
expect(submitPrompt).not.toHaveBeenCalled();
5237+
expect(state.persistAcpTurnTranscriptMock).not.toHaveBeenCalled();
5238+
});
5239+
52075240
it("keeps session provenance for internal ACP turns", async () => {
52085241
setupAcpSession();
52095242

‎src/agents/agent-tool-definition-adapter.after-tool-call.fires-once.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@ async function loadFreshAfterToolCallModulesForTest() {
9393
vi.doMock("../plugins/hook-runner-global.js", () => ({
9494
getGlobalHookRunner: () => hookMocks.runner,
9595
}));
96-
vi.doMock("../infra/agent-events.js", () => ({
96+
vi.doMock("../infra/agent-events.js", async (importOriginal) => ({
97+
...(await importOriginal<typeof import("../infra/agent-events.js")>()),
9798
emitAgentCommandOutputEvent: vi.fn(),
9899
emitAgentEvent: vi.fn(),
99100
emitAgentItemEvent: vi.fn(),

‎src/agents/command/acp-execution.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,13 @@ export async function runAcpAgentCommand(params: {
162162
requestId: params.runId,
163163
signal: params.opts.abortSignal,
164164
onElicitation,
165-
onBeforePrompt: params.opts.onExecutionStarted,
165+
onBeforePrompt: async () => {
166+
const recorder = params.opts.userTurnTranscriptRecorder;
167+
if (recorder && !recorder.hasPersisted() && !(await recorder.persistApproved())) {
168+
throw new Error("ACP input could not enter the session transcript");
169+
}
170+
params.opts.onExecutionStarted?.();
171+
},
166172
onLifecycle: (event) => {
167173
if (event.type === "prompt_submitted") {
168174
attemptExecutionRuntime.emitAcpPromptSubmitted({
@@ -255,7 +261,10 @@ export async function runAcpAgentCommand(params: {
255261
const transcriptResult = await attemptExecutionRuntime.persistAcpTurnTranscript({
256262
body: params.body,
257263
transcriptBody: params.transcriptBody,
258-
...(params.opts.suppressPromptPersistence !== true && params.opts.transcriptMedia?.length
264+
userTurnTranscriptRecorder: params.opts.userTurnTranscriptRecorder,
265+
...(!params.opts.userTurnTranscriptRecorder &&
266+
params.opts.suppressPromptPersistence !== true &&
267+
params.opts.transcriptMedia?.length
259268
? {
260269
userInput: {
261270
text: params.transcriptBody,

‎src/agents/command/post-run.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,9 @@ export async function finalizeEmbeddedAgentCommand(params: {
214214
skipAssistantTurn: assistantTranscriptOwned,
215215
skipUserTurn:
216216
suppressUserTurnPersistence ||
217+
// A supplied recorder owns input admission; the terminal mirror must
218+
// not synthesize an unkeyed copy when that input never reached execution.
219+
params.opts.userTurnTranscriptRecorder !== undefined ||
217220
userTurnTranscriptRecorder.hasPersisted() ||
218221
userTurnTranscriptRecorder.isBlocked(),
219222
});

0 commit comments

Comments
 (0)