Skip to content

Commit 2900026

Browse files
scotthuangscotthuangPatrick-Erichsen
authored
fix: stop selected channel sessions from WebChat (#111108)
* fix: stop selected channel sessions from WebChat * fix: clear channel working state after stop * fix: cancel queued turns before session abort * fix: replay pending stops after reconnect * fix: align stop lifecycle test fixtures * fix(ui): bind pending aborts to gateway client * test(ui): keep chat pane specs within line limit * chore(ios): refresh native i18n inventory * chore: retrigger PR checks * fix(system-agent): avoid blocking TUI catalog discovery * fix: preserve session abort ownership * test: align abort coverage with current main * test: assert scoped session abort broadcast * fix(agent-runs): expose SDK runtime abort state * fix(ui): clear queued main-session stops by scope * fix(ui): replay only exact run aborts * fix(gateway): protect session abort cleanup * fix(ui): narrow session abort intent * test(ui): avoid unbound request assertions --------- Co-authored-by: scotthuang <[email protected]> Co-authored-by: Patrick Erichsen <[email protected]>
1 parent 4aa9c9f commit 2900026

31 files changed

Lines changed: 1900 additions & 218 deletions

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7374,21 +7374,25 @@ public struct SessionsAbortParams: Codable, Sendable {
73747374
public let key: String?
73757375
public let runid: String?
73767376
public let agentid: String?
7377+
public let clearqueued: Bool?
73777378

73787379
public init(
73797380
key: String? = nil,
73807381
runid: String? = nil,
7381-
agentid: String? = nil)
7382+
agentid: String? = nil,
7383+
clearqueued: Bool? = nil)
73827384
{
73837385
self.key = key
73847386
self.runid = runid
73857387
self.agentid = agentid
7388+
self.clearqueued = clearqueued
73867389
}
73877390

73887391
private enum CodingKeys: String, CodingKey {
73897392
case key
73907393
case runid = "runId"
73917394
case agentid = "agentId"
7395+
case clearqueued = "clearQueued"
73927396
}
73937397
}
73947398

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ methods. Treat this as feature discovery, not a full enumeration of
577577
- `sessions.groups.list`, `sessions.groups.put`, `sessions.groups.rename`, and `sessions.groups.delete` manage the gateway-owned custom session group catalog (names + display order). Membership stays on each session's `category` field; rename and delete update member sessions server-side.
578578
- `sessions.send` sends a message into an existing session.
579579
- `sessions.steer` is the interrupt-and-steer variant for an active session.
580-
- `sessions.abort` aborts active work for a session. Pass `key` plus optional `runId`, or `runId` alone for active runs the gateway can resolve to a session.
580+
- `sessions.abort` aborts active work for a session. Pass `key` plus optional `runId`, or `runId` alone for active runs the gateway can resolve to a session. Supplying `runId` keeps cancellation scoped to that run. Set `clearQueued: true` on a key-only non-global request to also discard followup and lane queues owned by that session. Existing callers that omit `clearQueued` preserve those queues. The literal `global` key keeps the existing agent-qualified `chat.abort` ownership rules and does not perform non-global followup or lane cleanup.
581581
- `sessions.patch` updates session metadata/overrides and reports the resolved canonical model plus effective `agentRuntime`. Spawn lineage (`spawnedBy`, `spawnedWorkspaceDir`, `spawnedCwd`, `spawnDepth`, `subagentRole`, `subagentControlScope`) is no longer publicly patchable; those facts are written once by trusted creation paths, and requests that still send them are rejected.
582582
- `sessions.reset`, `sessions.delete`, and `sessions.compact` perform session maintenance.
583583
- `sessions.get` returns the full stored session row.

‎docs/web/control-ui.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -460,11 +460,11 @@ The macOS app keeps its native link-browser sidebar for links clicked in the das
460460

461461
</Accordion>
462462
<Accordion title="Stop and abort">
463-
- Click **Stop** (calls `chat.abort`).
463+
- Click **Stop**. Runs with an exact local run ID call `chat.abort`; when selected-session state reports active work but the Control UI has no local run ID, it calls `sessions.abort` instead. For non-global sessions, that selected-session path also discards queued follow-ups so they cannot restart work after the stop.
464464
- While a run is active, normal follow-ups use the Gateway's effective `messages.queue` mode. `steer` injects into the running turn; other modes keep the browser's durable queued delivery. Steering rejection also falls back to that queue. Click **Steer** on a queued message to inject it manually.
465465
- **Settings → Appearance → Chat → Follow-ups while the agent is working** can override that server default for the current browser. The page marks an override explicitly and offers **Reset to server default**. `Steer into the active run` sends follow-ups immediately, while `Queue until the run ends` holds them until the run finishes.
466466
- Type `/stop` (or standalone abort phrases like `stop`, `stop action`, `stop run`, `stop openclaw`, `please stop`) to abort out-of-band.
467-
- `chat.abort` supports `{ sessionKey }` (no `runId`) to abort all active runs for that session.
467+
- `chat.abort` supports `{ sessionKey }` (no `runId`) to abort all active runs for that session. The Control UI uses `sessions.abort` when it has no local run ID.
468468

469469
</Accordion>
470470
<Accordion title="Abort partial retention">
@@ -484,7 +484,8 @@ realtime/session actions pause until the connection returns; **Retry now** in th
484484
immediate attempt. Chat remains editable: ordinary text and attachment sends are kept in the
485485
current tab's gateway/session-scoped browser storage, shown as waiting for reconnect, and sent
486486
automatically when the Gateway returns. Live controls and slash commands remain unavailable while
487-
offline.
487+
offline, except that **Stop** can queue an exact local run ID for replay. A session-only stop
488+
is not replayed because newer work may start in that session before the connection returns.
488489

489490
When this browser already holds credentials (a configured token/password or an approved device
490491
token), first opens and reloads show a small animated OpenClaw mark while the connection is

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ export async function activateCodexAttemptTurn(
184184
await activeSteeringQueue.queue(text, optionsLocal);
185185
},
186186
isStreaming: () => !state.completed && !runAbortController.signal.aborted,
187+
isAborted: () => runAbortController.signal.aborted,
187188
isStopped: () => state.completed || state.timedOut || runAbortController.signal.aborted,
188189
isAbortable: () =>
189190
!terminalState.terminalOutcomeFrozen || terminalState.sharedAbortAllowedAfterTerminalOutcome,

‎extensions/codex/src/app-server/run-attempt.steering.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,40 @@ async function waitAndQueueActiveRunMessage(
107107
}
108108

109109
describe("runCodexAppServerAttempt steering", () => {
110+
it("marks the active run aborted before asynchronous cleanup releases its handle", async () => {
111+
const { requests, waitForMethod } = createStartedThreadHarness();
112+
const params = createSteeringParams();
113+
activeRunRegistrationMocks.setActiveEmbeddedRun.mockClear();
114+
activeRunRegistrationMocks.clearActiveEmbeddedRun.mockClear();
115+
116+
const run = runCodexAppServerAttempt(params);
117+
await waitForMethod("turn/start");
118+
119+
let handle: { abort: () => void; isAborted?: () => boolean } | undefined;
120+
await vi.waitFor(() => {
121+
handle = activeRunRegistrationMocks.setActiveEmbeddedRun.mock.calls.findLast(
122+
(call) => call[0] === params.sessionId,
123+
)?.[1] as typeof handle;
124+
expect(handle).toBeDefined();
125+
}, fastWait);
126+
expect(handle?.isAborted?.()).toBe(false);
127+
128+
handle?.abort();
129+
expect(handle?.isAborted?.()).toBe(true);
130+
expect(activeRunRegistrationMocks.clearActiveEmbeddedRun).not.toHaveBeenCalled();
131+
await expect(run).resolves.toMatchObject({ aborted: true });
132+
expect(activeRunRegistrationMocks.clearActiveEmbeddedRun).toHaveBeenCalledWith(
133+
params.sessionId,
134+
handle,
135+
params.sessionKey,
136+
params.sessionFile,
137+
);
138+
expect(requests).toContainEqual({
139+
method: "turn/interrupt",
140+
params: { threadId: "thread-1", turnId: "turn-1" },
141+
});
142+
});
143+
110144
it("accepts Gateway transcript-backed steering for the active Codex turn", async () => {
111145
const { requests, waitForMethod, completeTurn, notify } = createStartedThreadHarness();
112146
const params = createSteeringParams();

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const gatewayQuestionMock = vi.hoisted(() => ({
4343
waiters: new Map<string, (value: unknown) => void>(),
4444
cancelError: undefined as Error | undefined,
4545
warn: vi.fn(),
46+
setActiveEmbeddedRun: vi.fn(),
4647
}));
4748

4849
vi.mock("openclaw/plugin-sdk/agent-harness-runtime", async (importOriginal) => {
@@ -81,6 +82,12 @@ vi.mock("openclaw/plugin-sdk/agent-harness-runtime", async (importOriginal) => {
8182
}
8283
return await actual.callGatewayTool(...args);
8384
},
85+
setActiveEmbeddedRun: (
86+
...args: Parameters<typeof actual.setActiveEmbeddedRun>
87+
): ReturnType<typeof actual.setActiveEmbeddedRun> => {
88+
gatewayQuestionMock.setActiveEmbeddedRun(...args);
89+
return actual.setActiveEmbeddedRun(...args);
90+
},
8491
};
8592
});
8693

@@ -1361,14 +1368,12 @@ describe("runCopilotAttempt", () => {
13611368
});
13621369

13631370
it("active-run abort path marks the attempt as externally aborted", async () => {
1371+
gatewayQuestionMock.setActiveEmbeddedRun.mockClear();
13641372
const sendDeferred = createDeferred<SessionEventShape | undefined>();
13651373
const sessionCreated = createDeferred<FakeSession>();
13661374
const sdk = makeFakeSdk({
13671375
onCreateSession: (session) => {
13681376
session.sendAndWait.mockReturnValue(sendDeferred.promise);
1369-
session.abort.mockImplementationOnce(async () => {
1370-
sendDeferred.resolve(undefined);
1371-
});
13721377
sessionCreated.resolve(session);
13731378
},
13741379
});
@@ -1381,12 +1386,21 @@ describe("runCopilotAttempt", () => {
13811386
});
13821387
const session = await sessionCreated.promise;
13831388
await vi.waitFor(() => expect(session.sendAndWait).toHaveBeenCalledTimes(1));
1389+
const activeRunHandle = expectDefined(
1390+
gatewayQuestionMock.setActiveEmbeddedRun.mock.calls.findLast(
1391+
([sessionId]) => sessionId === "session-1",
1392+
)?.[1] as { isAborted?: () => boolean } | undefined,
1393+
"active Copilot run handle",
1394+
);
1395+
expect(activeRunHandle.isAborted?.()).toBe(false);
13841396

13851397
gatewayQuestionMock.cancelError = new Error("gateway unavailable");
13861398
expect(abortAgentHarnessRun("session-1")).toBe(true);
1399+
expect(activeRunHandle.isAborted?.()).toBe(true);
1400+
expect(session.abort).toHaveBeenCalledTimes(1);
1401+
sendDeferred.resolve(undefined);
13871402
const result = await runPromise;
13881403

1389-
expect(session.abort).toHaveBeenCalledTimes(1);
13901404
expect(result.terminal).toMatchObject({ kind: "aborted", source: "external" });
13911405
await vi.waitFor(() =>
13921406
expect(gatewayQuestionMock.warn).toHaveBeenCalledWith(

‎extensions/copilot/src/attempt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,7 @@ export async function runCopilotAttempt(
10701070
throw new Error("Copilot runtime is not waiting for user input.");
10711071
},
10721072
isStreaming: () => !settled && !aborted,
1073+
isAborted: () => aborted,
10731074
isCompacting: () => bridge?.isCompacting() ?? false,
10741075
sourceReplyDeliveryMode: input.sourceReplyDeliveryMode,
10751076
cancel: () => {

‎packages/gateway-protocol/src/schema/sessions.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,8 @@ export const SessionsAbortParamsSchema = closedObject({
432432
key: Type.Optional(NonEmptyString),
433433
runId: Type.Optional(NonEmptyString),
434434
agentId: Type.Optional(NonEmptyString),
435+
/** Also discard followup and lane queues for a key-only non-global session abort. */
436+
clearQueued: Type.Optional(Type.Boolean()),
435437
});
436438

437439
/** Mutable per-session preferences and routing metadata. */

‎packages/sdk/src/index.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1414,6 +1414,23 @@ describe("OpenClaw SDK", () => {
14141414
]);
14151415
});
14161416

1417+
it("keeps key-only Session.abort compatible by omitting clearQueued", async () => {
1418+
const transport = new FakeTransport({
1419+
"sessions.create": { key: "session-main", label: "Main" },
1420+
"sessions.abort": { ok: true, abortedRunId: null, status: "no-active-run" },
1421+
});
1422+
const oc = new OpenClaw({ transport });
1423+
1424+
const session = await oc.sessions.create({ key: "session-main" });
1425+
await session.abort();
1426+
1427+
expect(transport.calls.at(-1)).toEqual({
1428+
method: "sessions.abort",
1429+
options: undefined,
1430+
params: { key: "session-main" },
1431+
});
1432+
});
1433+
14171434
it("normalizes Gateway agent stream events into SDK events", () => {
14181435
const ts = 1_777_000_000_000;
14191436

‎src/agents/embedded-agent-runner/compact.queued.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ export async function compactEmbeddedAgentSession(
262262
kind: "embedded",
263263
queueMessage: async () => {},
264264
isStreaming: () => true,
265+
isAborted: () => abortSignal.aborted,
265266
isCompacting: () => true,
266267
abort: (reason) => controller.abort(reason ?? "user_abort"),
267268
cancel: (reason) => controller.abort(reason ?? "user_abort"),

0 commit comments

Comments
 (0)