Skip to content

Commit dd7f7ad

Browse files
authored
feat(sessions): show preambles as live subtitles (#112958)
* feat(sessions): show preambles as live subtitles * fix(sessions): harden preamble observer ordering * fix(sessions): suppress duplicate preamble restore * fix(sessions): preserve preamble observer lifecycle * fix(ci): satisfy session subtitle checks * fix(sessions): preserve terminal and preamble dedupe * fix(sessions): finalize contextless terminal runs * test(sessions): cover dormant contextless terminals * fix(sessions): preserve queued preambles across dormancy
1 parent b0525e1 commit dd7f7ad

20 files changed

Lines changed: 1614 additions & 319 deletions

‎apps/.i18n/native-source.json‎

Lines changed: 91 additions & 91 deletions
Large diffs are not rendered by default.

‎apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1603,6 +1603,14 @@ class NodeRuntime private constructor(
16031603
} catch (err: Throwable) {
16041604
Log.d("OpenClawRuntime", "sessions.subscribe failed: ${err.message ?: err::class.java.simpleName}")
16051605
}
1606+
try {
1607+
operatorSession.request("sessions.observer.visibility", """{"visible":true}""")
1608+
} catch (err: Throwable) {
1609+
Log.d(
1610+
"OpenClawRuntime",
1611+
"sessions.observer.visibility failed: ${err.message ?: err::class.java.simpleName}",
1612+
)
1613+
}
16061614
}
16071615

16081616
private val nodeSession =

‎apps/ios/Sources/RootSidebarModel.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ final class RootSidebarModel {
155155
method: "sessions.subscribe",
156156
paramsJSON: nil,
157157
timeoutSeconds: 12)
158+
_ = try? await appModel.operatorSession.request(
159+
method: "sessions.observer.visibility",
160+
paramsJSON: #"{"visible":true}"#,
161+
timeoutSeconds: 12)
158162
},
159163
onEvent: { [weak self] frame in
160164
await self?.handleSessionEvent(frame, appModel: appModel) ?? false

‎docs/gateway/protocol.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,9 @@ methods. Treat this as feature discovery, not a full enumeration of
653653
- `session.approval`: sanitized pending and terminal approval truth for an
654654
explicitly opted-in exact-session subscriber. Child approvals use the
655655
persisted ancestor audience; events never mutate transcripts or wake agents.
656+
- `session.observer`: safe live session headline and status digest. A model-authored
657+
preamble can update the headline immediately; utility-model assessments replace
658+
it later when available. Web, iOS, and Android use the same run-scoped digest.
656659
- `sessions.changed`: session index or metadata changed.
657660
- `presence`: system presence snapshot updates.
658661
- `tick`: periodic keepalive/liveness event.

‎docs/web/control-ui.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ The Control UI is a small **Vite + Lit** single-page app served by the Gateway:
1414

1515
It speaks **directly to the Gateway WebSocket** on the same port.
1616

17-
While you watch a running session, the Gateway can use that agent's utility model to produce a compact status digest. Chat shows it as a one-line status pill that expands into a card with the assessment, plan progress, pull requests, and elapsed time. The card can expand once when a run becomes stuck or needs input; the `/btw` side chat takes priority over the expanded card.
17+
While you watch a running session, the Gateway shows the model's latest safe preamble immediately as the session headline. When a utility model is available, it can replace that headline with a richer compact status digest after enough activity accumulates. Chat shows the result as a one-line status pill that expands into a card with the assessment, plan progress, pull requests, and elapsed time. The card can expand once when a run becomes stuck or needs input; the `/btw` side chat takes priority over the expanded card.
1818

1919
The expanded card also accepts short questions about the run. Answers use only the observer's current digest and sanitized bounded notes, stay in the browser for that session, and never enter or interrupt the main agent run. If the observations do not contain the answer, the observer says that it cannot know.
2020

21-
After the first digest arrives, it owns that run's sidebar subtitle instead of heuristic live activity. A final done or failed digest remains visible while the session is unread, then the row returns to its normal work subtitle.
21+
The headline owns that run's sidebar subtitle instead of heuristic live activity. It is shared with the official iOS and Android session lists. A final done or failed digest remains visible while the session is unread, then the row returns to its normal work subtitle.
2222

23-
Session observation is enabled by default. In **Settings > Appearance > Sidebar**, you can turn it off gateway-wide, inspect the resolved small model and its provenance, or choose automatic routing, disable utility tasks, or select an explicit `agents.defaults.utilityModel`. The equivalent config controls are `gateway.controlUi.sessionObserver: false` and `agents.defaults.utilityModel: ""`.
23+
Session observation is enabled by default. Safe preamble headlines do not require a utility model; the utility model only owns richer assessments and terminal summaries. In **Settings > Appearance > Sidebar**, you can turn observation off gateway-wide, inspect the resolved small model and its provenance, or choose automatic routing, disable utility tasks, or select an explicit `agents.defaults.utilityModel`. The equivalent config controls are `gateway.controlUi.sessionObserver: false` and `agents.defaults.utilityModel: ""`.
2424

2525
## Quick open (local)
2626

‎src/agents/session-preamble.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
2+
import { sanitizeProgressStatusText } from "../channels/progress-draft-status-text.js";
3+
import { stripMarkdown } from "../shared/text/strip-markdown.js";
4+
5+
export function normalizeSessionPreambleText(value: unknown, maxChars: number): string {
6+
if (typeof value !== "string") {
7+
return "";
8+
}
9+
const sanitized = sanitizeProgressStatusText(value);
10+
if (!sanitized) {
11+
return "";
12+
}
13+
const normalized = stripMarkdown(sanitized, { linkStyle: "label" }).replace(/\s+/gu, " ").trim();
14+
return truncateUtf16Safe(normalized, maxChars);
15+
}

‎src/gateway/server-runtime-subscriptions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ export function startGatewayEventSubscriptions(params: {
7676
const sessionObserver = createSessionObserver({
7777
getConfig: getRuntimeConfig,
7878
subscribers: params.sessionMessageSubscribers,
79+
sessionEventSubscribers: params.sessionEventSubscribers,
7980
broadcastToConnIds: params.broadcastToConnIds,
8081
});
8182
const unsubscribePrivateAuditEvents = auditEnabled
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type {
2+
SessionEventSubscriberRegistry,
3+
SessionMessageSubscriberRegistry,
4+
} from "./server-chat-state.js";
5+
6+
export function createSessionObserverAudience(params: {
7+
subscribers: SessionMessageSubscriberRegistry;
8+
sessionEventSubscribers?: SessionEventSubscriberRegistry;
9+
isVisible: (connId: string) => boolean;
10+
}) {
11+
return {
12+
has(sessionKey: string): boolean {
13+
for (const connId of params.subscribers.get(sessionKey)) {
14+
if (params.isVisible(connId)) {
15+
return true;
16+
}
17+
}
18+
for (const connId of params.sessionEventSubscribers?.getAll() ?? []) {
19+
if (params.isVisible(connId)) {
20+
return true;
21+
}
22+
}
23+
return false;
24+
},
25+
26+
recipients(sessionKey: string): ReadonlySet<string> {
27+
const recipients = new Set(params.subscribers.get(sessionKey));
28+
for (const connId of params.sessionEventSubscribers?.getAll() ?? []) {
29+
if (params.isVisible(connId)) {
30+
recipients.add(connId);
31+
}
32+
}
33+
return recipients;
34+
},
35+
};
36+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import {
2+
buildSessionObserverPrompt,
3+
normalizeSessionObserverModelOutput,
4+
SESSION_OBSERVER_MODEL_MAX_TOKENS,
5+
SESSION_OBSERVER_SYSTEM_PROMPT,
6+
} from "./session-observer-model.js";
7+
import type { SessionObserverDeps, SessionObserverState } from "./session-observer-model.js";
8+
9+
const MODEL_TIMEOUT_MS = 10_000;
10+
11+
type PrepareModel = NonNullable<SessionObserverDeps["prepareModel"]>;
12+
type CompleteModel = NonNullable<SessionObserverDeps["completeModel"]>;
13+
14+
export function createSessionObserverCompletion(params: {
15+
getConfig: SessionObserverDeps["getConfig"];
16+
prepareModel: PrepareModel;
17+
completeModel: CompleteModel;
18+
now: () => number;
19+
setTimeoutFn: typeof setTimeout;
20+
clearTimeoutFn: typeof clearTimeout;
21+
isCurrent: (state: SessionObserverState) => boolean;
22+
}) {
23+
const ensurePrepared = async (state: SessionObserverState) => {
24+
const modelRef = state.utilityModelRef;
25+
if (!modelRef) {
26+
throw new Error("session observer utility model is unavailable");
27+
}
28+
state.preparedPromise ??= params.prepareModel({
29+
cfg: params.getConfig(),
30+
agentId: state.agentId,
31+
modelRef,
32+
useUtilityModel: true,
33+
allowMissingApiKeyModes: ["aws-sdk"],
34+
});
35+
return await state.preparedPromise;
36+
};
37+
38+
return async (state: SessionObserverState, notes: readonly string[]) => {
39+
const controller = new AbortController();
40+
state.activeController = controller;
41+
const timeout = params.setTimeoutFn(() => controller.abort(), MODEL_TIMEOUT_MS);
42+
const aborted = new Promise<never>((_resolve, reject) => {
43+
controller.signal.addEventListener(
44+
"abort",
45+
() => reject(new Error("session observer model call timed out or was cancelled")),
46+
{ once: true },
47+
);
48+
});
49+
try {
50+
const execute = async () => {
51+
const prepared = await ensurePrepared(state);
52+
if (!params.isCurrent(state) || controller.signal.aborted) {
53+
throw new Error("session observer state is no longer active");
54+
}
55+
if ("error" in prepared) {
56+
throw new Error(prepared.error);
57+
}
58+
for (let attempt = 0; attempt < 2; attempt += 1) {
59+
if (!params.isCurrent(state) || controller.signal.aborted) {
60+
throw new Error("session observer state is no longer active");
61+
}
62+
const result = await params.completeModel({
63+
model: prepared.model,
64+
auth: prepared.auth,
65+
cfg: params.getConfig(),
66+
context: {
67+
systemPrompt: SESSION_OBSERVER_SYSTEM_PROMPT,
68+
messages: [
69+
{
70+
role: "user",
71+
content: buildSessionObserverPrompt(state, notes),
72+
timestamp: params.now(),
73+
},
74+
],
75+
},
76+
options: {
77+
maxTokens: Math.min(
78+
SESSION_OBSERVER_MODEL_MAX_TOKENS,
79+
Math.floor(prepared.model.maxTokens),
80+
),
81+
temperature: 0.2,
82+
signal: controller.signal,
83+
},
84+
});
85+
if (result.stopReason === "error") {
86+
throw new Error(result.errorMessage?.trim() || "session observer completion failed");
87+
}
88+
const text = result.content
89+
.filter((block): block is { type: "text"; text: string } => block.type === "text")
90+
.map((block) => block.text)
91+
.join("")
92+
.trim();
93+
const parsed = normalizeSessionObserverModelOutput(text);
94+
if (parsed) {
95+
return parsed;
96+
}
97+
}
98+
throw new Error("session observer returned invalid JSON twice");
99+
};
100+
return await Promise.race([execute(), aborted]);
101+
} finally {
102+
params.clearTimeoutFn(timeout);
103+
if (state.activeController === controller) {
104+
state.activeController = undefined;
105+
}
106+
}
107+
};
108+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { createSessionActivityNoteState } from "../agents/session-activity-notes.js";
3+
import { createSessionObserverModelSlots } from "./session-observer-model-slots.js";
4+
import type { SessionObserverState } from "./session-observer-model.js";
5+
6+
function modelState(index: number, terminalHealth?: "done" | "failed"): SessionObserverState {
7+
return {
8+
...createSessionActivityNoteState(),
9+
sessionKey: `agent:main:session-${index}`,
10+
runId: `run-${index}`,
11+
agentId: "main",
12+
utilityModelRef: "openai/gpt-test",
13+
startedAt: index,
14+
lastActivityAt: index,
15+
lastRunAt: index,
16+
revision: 0,
17+
digestCount: 0,
18+
consecutiveFailures: 0,
19+
lastDigestNoteSequence: 0,
20+
inFlight: terminalHealth !== undefined,
21+
finalPending: terminalHealth !== undefined,
22+
...(terminalHealth ? { terminalHealth } : {}),
23+
};
24+
}
25+
26+
describe("session observer model slots", () => {
27+
it("demotes the oldest nonterminal model state", () => {
28+
const states = new Map<string, SessionObserverState>();
29+
const terminal = modelState(0, "done");
30+
states.set(terminal.sessionKey, terminal);
31+
for (let index = 1; index < 6; index += 1) {
32+
const state = modelState(index);
33+
states.set(state.sessionKey, state);
34+
}
35+
const demote = vi.fn();
36+
const slots = createSessionObserverModelSlots({
37+
states,
38+
maxSessions: 6,
39+
resolve: () => "openai/gpt-test",
40+
demote,
41+
});
42+
43+
expect(slots.claim("main")).toBe("openai/gpt-test");
44+
expect(demote).toHaveBeenCalledWith(states.get("agent:main:session-1"));
45+
expect(demote).not.toHaveBeenCalledWith(terminal);
46+
});
47+
48+
it("does not evict terminal finalizations when every slot is protected", () => {
49+
const states = new Map<string, SessionObserverState>();
50+
for (let index = 0; index < 6; index += 1) {
51+
const state = modelState(index, "done");
52+
states.set(state.sessionKey, state);
53+
}
54+
const demote = vi.fn();
55+
const slots = createSessionObserverModelSlots({
56+
states,
57+
maxSessions: 6,
58+
resolve: () => "openai/gpt-test",
59+
demote,
60+
});
61+
62+
expect(slots.claim("main")).toBeUndefined();
63+
expect(demote).not.toHaveBeenCalled();
64+
});
65+
});

0 commit comments

Comments
 (0)