Skip to content

Commit 1b8d837

Browse files
steipeteSebTardif
andauthored
fix(tui): preserve queued prompt lifecycle (#100123)
Allow busy TUI sessions to forward prompts into the configured queue while keeping queued-turn admission, cancellation, restart, and transcript ownership consistent across the TUI, Gateway, and followup queue. Co-authored-by: Sebastien Tardif <[email protected]>
1 parent 3dff585 commit 1b8d837

56 files changed

Lines changed: 3517 additions & 374 deletions

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: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7778,21 +7778,25 @@ public struct ChatAbortParams: Codable, Sendable {
77787778
public let sessionkey: String
77797779
public let agentid: String?
77807780
public let runid: String?
7781+
public let preservesideruns: Bool?
77817782

77827783
public init(
77837784
sessionkey: String,
77847785
agentid: String? = nil,
7785-
runid: String?)
7786+
runid: String?,
7787+
preservesideruns: Bool? = nil)
77867788
{
77877789
self.sessionkey = sessionkey
77887790
self.agentid = agentid
77897791
self.runid = runid
7792+
self.preservesideruns = preservesideruns
77907793
}
77917794

77927795
private enum CodingKeys: String, CodingKey {
77937796
case sessionkey = "sessionKey"
77947797
case agentid = "agentId"
77957798
case runid = "runId"
7799+
case preservesideruns = "preserveSideRuns"
77967800
}
77977801
}
77987802

‎docs/concepts/queue.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,28 @@ keys.
118118
- Applies to auto-reply agent runs across all inbound channels that use the gateway reply pipeline (WhatsApp web, Telegram, Slack, Discord, Signal, iMessage, webchat, etc.).
119119
- Default lane (`main`) is process-wide for inbound + main heartbeats; set `agents.defaults.maxConcurrent` to allow multiple sessions in parallel.
120120
- Additional lanes may exist (e.g. `cron`, `cron-nested`, `nested`, `subagent`) so background jobs can run in parallel without blocking inbound replies. Isolated cron agent turns hold a `cron` slot while their inner agent execution uses `cron-nested`; both use `cron.maxConcurrentRuns`. Shared non-cron `nested` flows keep their own lane behavior. These detached runs are tracked as [background tasks](/automation/tasks).
121+
122+
## Queued-turn cancellation
123+
124+
When Gateway admits a prompt into the followup/collect queue (for example a TUI
125+
or webchat `chat.send` while another turn is active), it keeps a **Gateway-owned
126+
cancel identity** for that client `runId` until the queued content runs or is
127+
dropped. The identity follows content folded into an overflow summary.
128+
129+
- `chat.abort` with a specific `runId` cancels that turn while it is still queued,
130+
if the requester is authorized (same ownership rules as active runs).
131+
- `chat.abort` for a session without `runId` cancels **authorized queued turns
132+
first**, then aborts authorized active runs. That order prevents queue drain
133+
from promoting work into a half-stopped session.
134+
- Clearing the entire session queue without per-requester checks is not the stop
135+
path for multi-owner sessions.
136+
- Queued waits are not projected as active agent runs for `sessions.list` and do
137+
not own active-run timeout semantics; only the active phase does.
138+
139+
Clients (including the TUI) forward mid-run prompts and let Gateway apply the
140+
queue mode. Esc/`/stop` uses a session-scoped abort so lost local handles cannot
141+
leave a still-queued prompt running.
142+
121143
- Per-session lanes guarantee that only one agent run touches a given session at a time.
122144
- No external dependencies or background worker threads; pure TypeScript + promises.
123145

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2757,6 +2757,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
27572757
- H2: Precedence
27582758
- H2: Per-session overrides
27592759
- H2: Scope and guarantees
2760+
- H2: Queued-turn cancellation
27602761
- H2: Troubleshooting
27612762
- H2: Related
27622763

‎packages/gateway-protocol/src/index.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ describe("lazy protocol validators", () => {
118118
sessionKey: "global",
119119
agentId: "work",
120120
runId: "run-global-work",
121+
preserveSideRuns: true,
121122
}),
122123
).toBe(true);
123124
expect(

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ export const ChatAbortParamsSchema = Type.Object(
107107
sessionKey: NonEmptyString,
108108
agentId: Type.Optional(NonEmptyString),
109109
runId: Type.Optional(NonEmptyString),
110+
preserveSideRuns: Type.Optional(Type.Boolean()),
110111
},
111112
{ additionalProperties: false },
112113
);

‎scripts/protocol-gen-swift.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ const DEFAULTED_OPTIONAL_INIT_PARAM_ENTRIES: readonly [string, readonly string[]
6464
["SessionsUsageParams", ["agentId", "agentScope"]],
6565
["ChatHistoryParams", ["agentId", "offset"]],
6666
["ChatSendParams", ["agentId"]],
67-
["ChatAbortParams", ["agentId"]],
67+
["ChatAbortParams", ["agentId", "preserveSideRuns"]],
6868
["ChatInjectParams", ["agentId"]],
6969
["ChatDeltaEvent", ["agentId"]],
7070
["ChatFinalEvent", ["agentId"]],
@@ -73,7 +73,7 @@ const DEFAULTED_OPTIONAL_INIT_PARAM_ENTRIES: readonly [string, readonly string[]
7373
["ArtifactsListParams", ["agentId"]],
7474
["ArtifactsGetParams", ["agentId"]],
7575
["ArtifactsDownloadParams", ["agentId"]],
76-
["ChatAbortParams", ["agentId"]],
76+
["ChatAbortParams", ["agentId", "preserveSideRuns"]],
7777
["ChatAbortedEvent", ["agentId"]],
7878
["ChatDeltaEvent", ["agentId"]],
7979
["ChatErrorEvent", ["agentId"]],

‎src/auto-reply/get-reply-options.types.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,14 @@ export type QueuedReplyDeliveryCorrelation = {
4343

4444
/** Lifecycle hooks for queued follow-up replies. */
4545
export type QueuedReplyLifecycle = {
46-
onEnqueued?: () => void;
46+
/** Stable cancellation owner used to keep collect-mode batches authorization-safe. */
47+
ownerKey?: string;
48+
/** Return false when the external owner rejects this queue identity. */
49+
onEnqueued?: () => boolean | void;
50+
/** Retires this source's cancellation ownership while retaining its live identity. */
51+
onCancellationRetired?: () => void;
52+
/** Called after the queued turn owns the reply lane, before model/tool execution. */
53+
onAdmitted?: () => void;
4754
onComplete?: () => void;
4855
};
4956

‎src/auto-reply/reply/dispatch-from-config.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,48 @@ describe("dispatchReplyFromConfig", () => {
21982198
}
21992199
});
22002200

2201+
it("lets Gateway-owned turns reach queue resolution while a reply operation is active", async () => {
2202+
setNoAbort();
2203+
const sessionKey = "agent:main:main";
2204+
const activeOperation = createReplyOperation({
2205+
sessionKey,
2206+
sessionId: "active-session",
2207+
resetTriggered: false,
2208+
});
2209+
activeOperation.setPhase("running");
2210+
const dispatcher = createDispatcher();
2211+
const replyResolver = vi.fn(async () => undefined);
2212+
2213+
try {
2214+
const result = await dispatchReplyFromConfig({
2215+
ctx: buildTestCtx({
2216+
Provider: "webchat",
2217+
Surface: "webchat",
2218+
SessionKey: sessionKey,
2219+
BodyForAgent: "queue this turn",
2220+
}),
2221+
cfg: emptyConfig,
2222+
dispatcher,
2223+
replyOptions: {
2224+
queuedFollowupLifecycle: {
2225+
onEnqueued: vi.fn(),
2226+
onComplete: vi.fn(),
2227+
},
2228+
},
2229+
replyResolver,
2230+
});
2231+
2232+
expect(result).toMatchObject({
2233+
queuedFinal: false,
2234+
counts: { tool: 0, block: 0, final: 0 },
2235+
});
2236+
expect(replyResolver).toHaveBeenCalledTimes(1);
2237+
expect(replyRunRegistry.get(sessionKey)).toBe(activeOperation);
2238+
} finally {
2239+
activeOperation.complete();
2240+
}
2241+
});
2242+
22012243
it("clears stale active reply operations for terminal sessions and retries admission", async () => {
22022244
setNoAbort();
22032245
const sessionKey = "agent:main:telegram:group:-1003774691294";

‎src/auto-reply/reply/dispatch-from-config.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,11 @@ import {
6262
toPluginMessageContext,
6363
toPluginMessageReceivedEvent,
6464
} from "../../hooks/message-hook-mappers.js";
65+
import { isAbortError } from "../../infra/abort-signal.js";
6566
import { isDiagnosticsEnabled } from "../../infra/diagnostic-events.js";
6667
import { measureDiagnosticsTimelineSpan } from "../../infra/diagnostics-timeline.js";
6768
import { formatErrorMessage } from "../../infra/errors.js";
6869
import { getSessionBindingService } from "../../infra/outbound/session-binding-service.js";
69-
import { isAbortError } from "../../infra/abort-signal.js";
7070
import type { StuckSessionRecoveryOutcome } from "../../logging/diagnostic-session-recovery.js";
7171
import {
7272
logMessageDispatchCompleted,
@@ -1452,6 +1452,16 @@ export async function dispatchReplyFromConfig(
14521452
crypto.randomUUID();
14531453
const replyTurnKind = resolveReplyTurnKind(params.replyOptions);
14541454
const allowActivePreDispatch = phase === "pre_dispatch" && replyTurnKind === "visible";
1455+
const allowGatewayQueueResolution =
1456+
phase === "dispatch" &&
1457+
replyTurnKind === "visible" &&
1458+
params.replyOptions?.queuedFollowupLifecycle !== undefined &&
1459+
replyRunRegistry.get(dispatchOperationSessionKey) !== undefined;
1460+
if (allowGatewayQueueResolution) {
1461+
// Gateway turns need to reach getReplyFromConfig while the owner is active;
1462+
// that layer applies the session's steer/followup/collect/drop policy.
1463+
return { status: "ready" };
1464+
}
14551465
const allowSlackRoutedThreadBypass =
14561466
phase === "dispatch" &&
14571467
shouldLetSlackRoutedThreadBypassBusyReplyOperation({

‎src/auto-reply/reply/followup-runner.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,32 @@ function createQueuedRun(
618618
}
619619

620620
describe("createFollowupRunner reply-lane admission", () => {
621+
it("notifies queued owners after admission and before model execution", async () => {
622+
const events: string[] = [];
623+
runEmbeddedAgentMock.mockImplementationOnce(async () => {
624+
events.push("run");
625+
return { payloads: [], meta: {} };
626+
});
627+
const runner = createFollowupRunner({
628+
typing: createMockTypingController(),
629+
typingMode: "instant",
630+
sessionKey: "main",
631+
defaultModel: "anthropic/claude",
632+
});
633+
634+
await runner(
635+
createQueuedRun({
636+
queuedLifecycle: {
637+
onAdmitted: () => events.push("admitted"),
638+
onComplete: () => events.push("complete"),
639+
},
640+
run: { provider: "anthropic", model: "claude" },
641+
}),
642+
);
643+
644+
expect(events).toEqual(["admitted", "run", "complete"]);
645+
});
646+
621647
it("passes prepared media user turns to embedded runtime dispatch", async () => {
622648
const preparedUserTurnMessage = {
623649
role: "user",
@@ -888,6 +914,7 @@ describe("createFollowupRunner reply-lane admission", () => {
888914

889915
it("preserves non-compaction preflight failures for queued followup runs", async () => {
890916
runPreflightCompactionIfNeededMock.mockRejectedValueOnce(new Error("session load failed"));
917+
const onComplete = vi.fn();
891918
const runner = createFollowupRunner({
892919
typing: createMockTypingController(),
893920
typingMode: "instant",
@@ -906,12 +933,14 @@ describe("createFollowupRunner reply-lane admission", () => {
906933
model: "claude",
907934
sessionKey: "main",
908935
},
936+
queuedLifecycle: { onComplete },
909937
}),
910938
),
911939
).rejects.toThrow("session load failed");
912940

913941
expect(runEmbeddedAgentMock).not.toHaveBeenCalled();
914942
expect(routeReplyMock).not.toHaveBeenCalled();
943+
expect(onComplete).not.toHaveBeenCalled();
915944
});
916945
});
917946

0 commit comments

Comments
 (0)