Skip to content

Commit bc76bb8

Browse files
authored
feat(agents): agent-controlled session status, attention, and TTL in the sessions tool (#111583)
* feat(agents): agent-controlled session status, attention, and TTL in the sessions tool * feat(protocol): sessions.patch agent status fields and curated attention icon ids * chore(protocol): regenerate bindings for agent-status patch fields, unexport internal cap * chore(sessions): unexport internal agent-status TTL default
1 parent 25d6f13 commit bc76bb8

34 files changed

Lines changed: 581 additions & 26 deletions

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6184,6 +6184,9 @@ public struct SessionsPatchParams: Codable, Sendable {
61846184
public let label: AnyCodable?
61856185
public let category: AnyCodable?
61866186
public let icon: AnyCodable?
6187+
public let statusnote: AnyCodable?
6188+
public let attention: AnyCodable?
6189+
public let ttlminutes: Int?
61876190
public let archived: Bool?
61886191
public let pinned: Bool?
61896192
public let unread: Bool?
@@ -6216,6 +6219,9 @@ public struct SessionsPatchParams: Codable, Sendable {
62166219
label: AnyCodable? = nil,
62176220
category: AnyCodable? = nil,
62186221
icon: AnyCodable? = nil,
6222+
statusnote: AnyCodable? = nil,
6223+
attention: AnyCodable? = nil,
6224+
ttlminutes: Int? = nil,
62196225
archived: Bool? = nil,
62206226
pinned: Bool? = nil,
62216227
unread: Bool? = nil,
@@ -6247,6 +6253,9 @@ public struct SessionsPatchParams: Codable, Sendable {
62476253
self.label = label
62486254
self.category = category
62496255
self.icon = icon
6256+
self.statusnote = statusnote
6257+
self.attention = attention
6258+
self.ttlminutes = ttlminutes
62506259
self.archived = archived
62516260
self.pinned = pinned
62526261
self.unread = unread
@@ -6280,6 +6289,9 @@ public struct SessionsPatchParams: Codable, Sendable {
62806289
case label
62816290
case category
62826291
case icon
6292+
case statusnote = "statusNote"
6293+
case attention
6294+
case ttlminutes = "ttlMinutes"
62836295
case archived
62846296
case pinned
62856297
case unread

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ and [Linux](/platforms/linux) desktop apps, the
192192

193193
## Sidebar navigation
194194

195-
The sidebar organizes everything around the agent. The identity row at the top is the active agent; below it, the **Pages** section starts with **Home** — the agent's rolling main session, badged with its unread or running state — followed by the pinned destinations (**Usage**, **Automations**, and **Plugins** by default). The customize control on the Pages header opens a menu with every other destination, including plugin-provided tabs, plus **Edit pinned items**; right-clicking the navigation area opens the pin editor directly. The session list below splits into zones: **Threads** for the agent's chat sessions (the main session stays behind Home; sessions it spawned appear here as top-level threads, and named threads show without a type prefix), **Groups** for group and room conversations, and **Coding** for sessions bound to a managed worktree or exec node (rows show a `repo ⎇ branch` line plus the node host), ACP-backed harness sessions, and the Codex/Claude CLI catalogs. Coding starts collapsed on first run and remembers your choice; its collapsed header keeps the true count and shows a running indicator while contained sessions work. Custom groups (the session `category`) and **Pinned** rows sit above Threads, and assigning a session to a custom group always wins over the automatic zone classification. The Threads header holds the sort control (Created or Last updated, plus a Group by toggle) and the **+** that opens the New session page. Opening a session moves the selection highlight without reordering rows. Parent sessions with recent child runs show a disclosure and child count; expand it to inspect nested child sessions, live or terminal status, and runtime without leaving the sidebar. Selecting a child opens its chat and automatically reveals its ancestor path. Child rows stay outside root grouping, pinning, dragging, multi-select, and pagination; collapsed zones do not consume the visible page budget. Sessions with new activity since they were last read show an unread dot, and opening one marks it read. Cloud-worker lifecycle states use a globe badge; local and reclaimed sessions omit a placement badge because local execution is the default. Each root session row has a context menu (kebab button or right-click) with Pin/Unpin, Mark as unread/read, Rename, Fork, Move to group (including New group and Remove from group), Archive, and Delete; touch layouts keep the direct pin and menu controls visible. Cmd/Ctrl-click toggles root rows into a multi-select and Shift-click extends it across the visible order; opening the menu on a selected row then offers batch actions (Mark N as unread/read, Move N to group, Archive N, Delete N) that apply to every selected session, with a single confirmation for batch delete. Drag a root session onto **Pinned** to pin it, or onto a custom group to move it. Custom group headers can be collapsed, expanded, or dragged to reorder them; group names and their order live in the gateway (`sessions.groups.*`), so they follow you across browsers, while collapsed state stays in the browser profile. Group headers also have a menu (kebab button or right-click) with Rename group, New group, and Delete group; renaming or deleting a group updates every member session server-side, including archived ones, and deleting a group keeps its sessions and moves them back to Threads.
195+
The sidebar organizes everything around the agent. The identity row at the top is the active agent; below it, the **Pages** section starts with **Home** — the agent's rolling main session, badged with its unread or running state — followed by the pinned destinations (**Usage**, **Automations**, and **Plugins** by default). The customize control on the Pages header opens a menu with every other destination, including plugin-provided tabs, plus **Edit pinned items**; right-clicking the navigation area opens the pin editor directly. The session list below splits into zones: **Threads** for the agent's chat sessions (the main session stays behind Home; sessions it spawned appear here as top-level threads, and named threads show without a type prefix), **Groups** for group and room conversations, and **Coding** for sessions bound to a managed worktree or exec node (rows show a `repo ⎇ branch` line plus the node host), ACP-backed harness sessions, and the Codex/Claude CLI catalogs. Coding starts collapsed on first run and remembers your choice; its collapsed header keeps the true count and shows a running indicator while contained sessions work. Custom groups (the session `category`) and **Pinned** rows sit above Threads, and assigning a session to a custom group always wins over the automatic zone classification. The Threads header holds the sort control (Created or Last updated, plus a Group by toggle) and the **+** that opens the New session page. Opening a session moves the selection highlight without reordering rows. Parent sessions with recent child runs show a disclosure and child count; expand it to inspect nested child sessions, live or terminal status, and runtime without leaving the sidebar. Selecting a child opens its chat and automatically reveals its ancestor path. Child rows stay outside root grouping, pinning, dragging, multi-select, and pagination; collapsed zones do not consume the visible page budget. Sessions with new activity since they were last read show an unread dot, and opening one marks it read. An agent can also publish a short expiring status line and optionally request attention with a curated amber icon; that declaration clears when you open the session, send the next message, clear it explicitly, or its TTL expires. Cloud-worker lifecycle states use a globe badge; local and reclaimed sessions omit a placement badge because local execution is the default. Each root session row has a context menu (kebab button or right-click) with Pin/Unpin, Mark as unread/read, Rename, Fork, Move to group (including New group and Remove from group), Archive, and Delete; touch layouts keep the direct pin and menu controls visible. Cmd/Ctrl-click toggles root rows into a multi-select and Shift-click extends it across the visible order; opening the menu on a selected row then offers batch actions (Mark N as unread/read, Move N to group, Archive N, Delete N) that apply to every selected session, with a single confirmation for batch delete. Drag a root session onto **Pinned** to pin it, or onto a custom group to move it. Custom group headers can be collapsed, expanded, or dragged to reorder them; group names and their order live in the gateway (`sessions.groups.*`), so they follow you across browsers, while collapsed state stays in the browser profile. Group headers also have a menu (kebab button or right-click) with Rename group, New group, and Delete group; renaming or deleting a group updates every member session server-side, including archived ones, and deleting a group keeps its sessions and moves them back to Threads.
196196

197197
## New session page
198198

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Gateway Protocol schema module defines protocol validation shapes.
22
import type { Static } from "typebox";
33
import { Type } from "typebox";
4+
import { SESSION_AGENT_ATTENTION_ICON_IDS } from "../session-icon.js";
45
import { closedObject } from "./closed-object.js";
56
import { ErrorShapeSchema } from "./frames.js";
67
import { PluginJsonValueSchema } from "./plugins.js";
@@ -369,6 +370,15 @@ export const SessionsPatchParamsSchema = closedObject({
369370
description: "Sidebar icon: one emoji, name:<id>, or svg:<svg ...>...</svg>.",
370371
}),
371372
),
373+
statusNote: Type.Optional(
374+
Type.Union([Type.String({ maxLength: 120 }), Type.Null()], {
375+
description: "Short expiring sidebar status note; null clears it and any declared attention.",
376+
}),
377+
),
378+
attention: Type.Optional(
379+
Type.Union([Type.String({ enum: [...SESSION_AGENT_ATTENTION_ICON_IDS] }), Type.Null()]),
380+
),
381+
ttlMinutes: Type.Optional(Type.Integer({ minimum: 1, maximum: 120 })),
372382
archived: Type.Optional(Type.Boolean()),
373383
pinned: Type.Optional(Type.Boolean()),
374384
unread: Type.Optional(

‎packages/gateway-protocol/src/session-icon.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,23 @@ export type SessionIcon =
33
| { kind: "emoji"; emoji: string }
44
| { kind: "svg"; svg: string };
55

6+
export const SESSION_AGENT_ATTENTION_ICON_IDS = [
7+
"hand",
8+
"key",
9+
"alert",
10+
"flag",
11+
"lock",
12+
"hourglass",
13+
] as const;
14+
15+
export type SessionAgentAttentionIconId = (typeof SESSION_AGENT_ATTENTION_ICON_IDS)[number];
16+
17+
export type SessionAgentStatus = {
18+
note: string;
19+
expiresAt: number;
20+
attention?: SessionAgentAttentionIconId;
21+
};
22+
623
export type SessionIconNormalizationResult =
724
| { ok: true; value: string }
825
| { ok: false; reason: string };

‎src/agents/command/session-preparation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ export async function prepareEmbeddedSessionState(params: {
130130
updatedAt: now,
131131
sessionStartedAt: entry.sessionStartedAt ?? now,
132132
lastInteractionAt: now,
133+
agentStatus: undefined,
133134
};
134135
applyVerboseOverride(next, params.verboseOverride);
135136
sessionEntry = await persistSessionEntry({

‎src/agents/tools/sessions-tool.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,27 @@ describe("sessions tool", () => {
2323
expect(GATEWAY_OWNER_ONLY_CORE_TOOLS).toContain("sessions");
2424
});
2525

26+
it("advertises the full model-visible sidebar presence contract", () => {
27+
const tool = createSessionsTool({ agentSessionKey: "agent:main:main", callGateway: vi.fn() });
28+
expect(tool.parameters).toMatchObject({
29+
type: "object",
30+
properties: {
31+
action: {
32+
type: "string",
33+
enum: ["patch", "group_list", "group_set", "group_rename", "group_delete"],
34+
},
35+
label: { type: "string", description: expect.stringContaining("Empty string clears") },
36+
statusNote: { type: "string", maxLength: 120 },
37+
attention: {
38+
type: "string",
39+
enum: ["clear", "hand", "key", "alert", "flag", "lock", "hourglass"],
40+
},
41+
ttlMinutes: { type: "integer", minimum: 1, maximum: 120 },
42+
archived: { type: "boolean", description: expect.stringContaining("without deleting") },
43+
},
44+
});
45+
});
46+
2647
it("patches its session, then reverts a failed agent-selected model", async () => {
2748
await withTempDir({ prefix: "openclaw-sessions-tool-" }, async (dir) => {
2849
const storePath = path.join(dir, "sessions.json");
@@ -386,6 +407,40 @@ describe("sessions tool", () => {
386407
]);
387408
});
388409

410+
it("patches and clears title, status, attention, and archive state", async () => {
411+
const callGateway = vi.fn(async () => ({ ok: true }));
412+
const tool = createSessionsTool({
413+
agentSessionKey: "agent:main:main",
414+
config: {},
415+
callGateway: callGateway as never,
416+
});
417+
418+
await tool.execute("declare", {
419+
action: "patch",
420+
label: "Waiting on staging",
421+
statusNote: "Blocked: need the staging password",
422+
attention: "key",
423+
ttlMinutes: 45,
424+
archived: true,
425+
});
426+
await tool.execute("clear", { action: "patch", label: "", attention: "clear" });
427+
428+
expect(callGateway.mock.calls).toEqual([
429+
[
430+
"sessions.patch",
431+
{
432+
key: "agent:main:main",
433+
label: "Waiting on staging",
434+
statusNote: "Blocked: need the staging password",
435+
attention: "key",
436+
ttlMinutes: 45,
437+
archived: true,
438+
},
439+
],
440+
["sessions.patch", { key: "agent:main:main", label: null, attention: null }],
441+
]);
442+
});
443+
389444
it("rejects an empty patch", async () => {
390445
const callGateway = vi.fn();
391446
const tool = createSessionsTool({

‎src/agents/tools/sessions-tool.ts‎

Lines changed: 55 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
/** Session self-service tool. */
22
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
33
import { Type } from "typebox";
4+
import { SESSION_AGENT_ATTENTION_ICON_IDS } from "../../../packages/gateway-protocol/src/session-icon.js";
45
import { getRuntimeConfig } from "../../config/config.js";
56
import type { OpenClawConfig } from "../../config/types.openclaw.js";
67
import { withAgentSessionModelPatchOrigin } from "../../gateway/session-model-patch-origin.js";
78
import { resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
9+
import { stringEnum } from "../schema/typebox.js";
810
import type { AnyAgentTool } from "./common.js";
911
import { jsonResult, readStringParam, ToolAuthorizationError, ToolInputError } from "./common.js";
1012
import {
@@ -26,22 +28,41 @@ const GROUP_NAMES_MAX_ITEMS = 200;
2628

2729
const SessionsToolSchema = Type.Object(
2830
{
29-
action: Type.Union(
30-
ACTIONS.map((action) => Type.Literal(action)),
31-
{
32-
description: "Action",
33-
},
34-
),
31+
action: stringEnum(ACTIONS, { description: "Action" }),
3532
sessionKey: Type.Optional(Type.String({ description: "Target session. Default: current" })),
36-
label: Type.Optional(Type.String({ description: "Session label" })),
33+
label: Type.Optional(
34+
Type.String({ description: "Sidebar title override. Empty string clears it." }),
35+
),
3736
icon: Type.Optional(
3837
Type.String({
3938
description:
4039
"Sidebar icon: an emoji, name:<curated-id>, or svg:<svg …> you draw yourself (tiny, sanitized). Empty string removes it.",
4140
}),
4241
),
42+
statusNote: Type.Optional(
43+
Type.String({
44+
maxLength: 120,
45+
description:
46+
"Short sidebar status line. Empty string clears it and declared attention. Clears automatically when the user reads or replies, or when its TTL expires.",
47+
}),
48+
),
49+
attention: Type.Optional(
50+
stringEnum(["clear", ...SESSION_AGENT_ATTENTION_ICON_IDS] as const, {
51+
description:
52+
"Request user attention with a curated icon; requires an active statusNote. 'clear' clears both attention and statusNote.",
53+
}),
54+
),
55+
ttlMinutes: Type.Optional(
56+
Type.Integer({
57+
minimum: 1,
58+
maximum: 120,
59+
description: "Status/attention lifetime in minutes. Default 30; maximum 120.",
60+
}),
61+
),
4362
pinned: Type.Optional(Type.Boolean({ description: "Pin session" })),
44-
archived: Type.Optional(Type.Boolean({ description: "Archive session" })),
63+
archived: Type.Optional(
64+
Type.Boolean({ description: "True archives without deleting; false restores the session." }),
65+
),
4566
model: Type.Optional(Type.String({ description: "Model override" })),
4667
thinkingLevel: Type.Optional(Type.String({ description: "Thinking override" })),
4768
names: Type.Optional(Type.Array(Type.String(), { description: "Ordered group names" })),
@@ -70,6 +91,17 @@ function readBoolean(params: Record<string, unknown>, key: string): boolean | un
7091
return value;
7192
}
7293

94+
function readInteger(params: Record<string, unknown>, key: string): number | undefined {
95+
const value = params[key];
96+
if (value === undefined) {
97+
return undefined;
98+
}
99+
if (!Number.isInteger(value)) {
100+
throw new ToolInputError(`${key} must be an integer`);
101+
}
102+
return value as number;
103+
}
104+
73105
function readClearableString(params: Record<string, unknown>, key: string): string | null {
74106
const value = params[key];
75107
if (value === null) {
@@ -183,10 +215,22 @@ export function createSessionsTool(opts: SessionsToolOptions = {}): AnyAgentTool
183215
);
184216
const patch = {
185217
key,
186-
...(params.label !== undefined
187-
? { label: readStringParam(params, "label", { required: true }) }
188-
: {}),
218+
...(params.label !== undefined ? { label: readClearableString(params, "label") } : {}),
189219
...(params.icon !== undefined ? { icon: readClearableString(params, "icon") } : {}),
220+
...(params.statusNote !== undefined
221+
? { statusNote: readClearableString(params, "statusNote") }
222+
: {}),
223+
...(params.attention !== undefined
224+
? {
225+
attention:
226+
readStringParam(params, "attention", { required: true }) === "clear"
227+
? null
228+
: readStringParam(params, "attention", { required: true }),
229+
}
230+
: {}),
231+
...(params.ttlMinutes !== undefined
232+
? { ttlMinutes: readInteger(params, "ttlMinutes") }
233+
: {}),
190234
...(params.pinned !== undefined ? { pinned: readBoolean(params, "pinned") } : {}),
191235
...(params.archived !== undefined ? { archived: readBoolean(params, "archived") } : {}),
192236
...(params.model !== undefined

‎src/auto-reply/reply/get-reply-fast-path.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ export function initFastReplySessionState(params: {
216216
updatedAt: now,
217217
sessionStartedAt: resetTriggered ? now : (existingEntry?.sessionStartedAt ?? now),
218218
lastInteractionAt: now,
219+
agentStatus: undefined,
219220
thinkingLevel: resetTriggered ? existingEntry?.thinkingLevel : existingEntry?.thinkingLevel,
220221
verboseLevel: resetTriggered ? existingEntry?.verboseLevel : existingEntry?.verboseLevel,
221222
reasoningLevel: resetTriggered ? existingEntry?.reasoningLevel : existingEntry?.reasoningLevel,

‎src/auto-reply/reply/session.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,7 @@ async function initSessionStateAttemptLocked(
898898
? now
899899
: (baseEntry?.sessionStartedAt ?? lifecycleTimestamps.sessionStartedAt),
900900
lastInteractionAt: isSystemEvent ? baseEntry?.lastInteractionAt : now,
901+
agentStatus: isSystemEvent ? baseEntry?.agentStatus : undefined,
901902
systemSent,
902903
abortedLastRun: recoveredTerminalEntry ? undefined : abortedLastRun,
903904
// Persist previously stored thinking/verbose levels when present.

‎src/config/sessions/types.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
SessionAcpMeta,
77
} from "@openclaw/acp-core/types";
88
import { normalizeOptionalString, type FastMode } from "@openclaw/normalization-core/string-coerce";
9+
import type { SessionAgentStatus } from "../../../packages/gateway-protocol/src/session-icon.js";
910
import type { ChatType } from "../../channels/chat-type.js";
1011
import type { ChannelId } from "../../channels/plugins/channel-id.types.js";
1112
import type { ChannelRouteRef } from "../../plugin-sdk/channel-route.js";
@@ -265,6 +266,8 @@ export type SessionEntry = SessionRestartRecoveryState &
265266
icon?: string;
266267
/** Timestamp (ms) when an operator client last marked the session read. */
267268
lastReadAt?: number;
269+
/** Agent-declared sidebar presence; projection drops it after expiresAt. */
270+
agentStatus?: SessionAgentStatus;
268271
/** Timestamp (ms) when an operator explicitly marked the session unread; cleared on read. */
269272
markedUnreadAt?: number;
270273
/** Timestamp (ms) of the latest completed agent run; metadata patches do not update it. */

0 commit comments

Comments
 (0)