Skip to content

Commit 9f09001

Browse files
committed
fix(reply): preserve active session state
1 parent f17fd73 commit 9f09001

8 files changed

Lines changed: 104 additions & 35 deletions

‎src/auto-reply/reply.triggers.group-intro-prompts.cases.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export function registerGroupIntroPromptCases(): void {
1515
setup?: (cfg: ReturnType<typeof makeCfg>) => void;
1616
};
1717
const groupParticipationNote =
18-
"Be a good group participant: mostly lurk and follow the conversation; reply only when directly addressed or you can add clear value. Emoji reactions are welcome when available. Write like a human. Avoid Markdown tables. Don't type literal \\n sequences; use real line breaks sparingly.";
18+
"Be a good group participant: mostly lurk and follow the conversation; reply only when directly addressed or you can add clear value. Emoji reactions are welcome when available. Write like a human. Avoid Markdown tables. Minimize empty lines and use normal chat conventions, not document-style spacing. Don't type literal \\n sequences; use real line breaks sparingly.";
1919
const cases: GroupIntroCase[] = [
2020
{
2121
name: "discord",
@@ -44,8 +44,8 @@ export function registerGroupIntroPromptCases(): void {
4444
Provider: "whatsapp",
4545
},
4646
expected: [
47-
`You are in the WhatsApp group chat "Ops". Your replies are automatically sent to this group chat. Do not use the message tool to send to this same group — just reply normally.`,
48-
`Activation: trigger-only (you are invoked only when explicitly mentioned; recent context may be included). WhatsApp IDs: SenderId is the participant JID (group participant id). ${groupParticipationNote} Address the specific sender noted in the message context.`,
47+
`You are in the WhatsApp group chat "Ops". Your replies are automatically sent to this group chat. Do not use the message tool to send to this same group - just reply normally.`,
48+
`Activation: trigger-only (you are invoked only when explicitly mentioned; recent context may be included). ${groupParticipationNote} Address the specific sender noted in the message context.`,
4949
],
5050
},
5151
{

‎src/auto-reply/reply.triggers.trigger-handling.targets-active-session-native-stop.e2e.test.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,15 +145,13 @@ function mockSuccessfulCompaction() {
145145

146146
function makeUnauthorizedWhatsAppCfg(home: string) {
147147
const baseCfg = makeCfg(home);
148-
return {
149-
...baseCfg,
150-
channels: {
151-
...baseCfg.channels,
152-
whatsapp: {
153-
allowFrom: ["+1000"],
154-
},
148+
baseCfg.channels = {
149+
...baseCfg.channels,
150+
whatsapp: {
151+
allowFrom: ["+1000"],
155152
},
156153
};
154+
return baseCfg;
157155
}
158156

159157
async function expectResetBlockedForNonOwner(params: { home: string }): Promise<void> {

‎src/auto-reply/reply.triggers.trigger-handling.test-harness.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ const installPiEmbeddedMock = () =>
6565

6666
installPiEmbeddedMock();
6767

68+
vi.doMock("../agents/pi-embedded-runner/runs.js", () => ({
69+
abortEmbeddedPiRun: (...args: unknown[]) => piEmbeddedMocks.abortEmbeddedPiRun(...args),
70+
}));
71+
6872
const providerUsageMocks = vi.hoisted(() => ({
6973
loadProviderUsageSummary: vi.fn().mockResolvedValue({
7074
updatedAt: 0,

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -319,13 +319,14 @@ export const handleUsageCommand: CommandHandler = async (params, allowTextComman
319319
const current = resolveResponseUsageMode(currentRaw);
320320
const next = requested ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
321321

322-
if (params.sessionEntry && params.sessionStore && params.sessionKey) {
322+
if (targetSessionEntry && params.sessionStore && params.sessionKey) {
323323
if (next === "off") {
324-
delete params.sessionEntry.responseUsage;
324+
delete targetSessionEntry.responseUsage;
325325
} else {
326-
params.sessionEntry.responseUsage = next;
326+
targetSessionEntry.responseUsage = next;
327327
}
328-
await persistSessionEntry(params);
328+
params.sessionStore[params.sessionKey] = targetSessionEntry;
329+
await persistSessionEntry({ ...params, sessionEntry: targetSessionEntry });
329330
}
330331

331332
return {

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

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import crypto from "node:crypto";
2-
import path from "node:path";
32
import { normalizeChatType } from "../../channels/chat-type.js";
43
import { normalizeAnyChannelId } from "../../channels/registry.js";
54
import { applyMergePatch } from "../../config/merge-patch.js";
6-
import type { SessionEntry } from "../../config/sessions/types.js";
5+
import { resolveSessionTranscriptPath, resolveStorePath } from "../../config/sessions/paths.js";
6+
import { resolveSessionKey } from "../../config/sessions/session-key.js";
7+
import { loadSessionStore } from "../../config/sessions/store.js";
8+
import type { SessionEntry, SessionScope } from "../../config/sessions/types.js";
79
import type { OpenClawConfig } from "../../config/types.openclaw.js";
810
import {
911
normalizeOptionalLowercaseString,
@@ -29,21 +31,18 @@ function isSlowReplyTestAllowed(env: NodeJS.ProcessEnv = process.env): boolean {
2931
);
3032
}
3133

32-
function resolveFastSessionKey(ctx: MsgContext): string {
34+
function resolveFastSessionKey(params: {
35+
ctx: MsgContext;
36+
sessionScope: SessionScope;
37+
mainKey?: string;
38+
}): string {
39+
const { ctx } = params;
3340
const nativeCommandTarget =
3441
ctx.CommandSource === "native" ? normalizeOptionalString(ctx.CommandTargetSessionKey) : "";
3542
if (nativeCommandTarget) {
3643
return nativeCommandTarget;
3744
}
38-
const existing = normalizeOptionalString(ctx.SessionKey);
39-
if (existing) {
40-
return existing;
41-
}
42-
const provider =
43-
normalizeOptionalString(ctx.Provider) ?? normalizeOptionalString(ctx.Surface) ?? "main";
44-
const destination =
45-
normalizeOptionalString(ctx.To) ?? normalizeOptionalString(ctx.From) ?? "default";
46-
return `agent:main:${provider}:${destination}`;
45+
return resolveSessionKey(params.sessionScope, ctx, params.mainKey);
4746
}
4847

4948
function markReplyConfigRuntimeMode(
@@ -200,10 +199,18 @@ export function initFastReplySessionState(params: {
200199
commandAuthorized: boolean;
201200
workspaceDir: string;
202201
}): SessionInitResult {
203-
const { ctx, cfg, agentId, commandAuthorized, workspaceDir } = params;
202+
const { ctx, cfg, agentId, commandAuthorized } = params;
204203
const sessionScope = cfg.session?.scope ?? "per-sender";
205-
const sessionKey = resolveFastSessionKey(ctx);
206-
const sessionId = crypto.randomUUID();
204+
const sessionKey = resolveFastSessionKey({
205+
ctx,
206+
sessionScope,
207+
mainKey: cfg.session?.mainKey,
208+
});
209+
const storePath = resolveStorePath(cfg.session?.store, { agentId });
210+
const sessionStore: Record<string, SessionEntry> = loadSessionStore(storePath, {
211+
skipCache: true,
212+
});
213+
const existingEntry = sessionStore[sessionKey];
207214
const commandSource = ctx.BodyForCommands ?? ctx.CommandBody ?? ctx.RawBody ?? ctx.Body ?? "";
208215
const triggerBodyNormalized = stripStructuralPrefixes(commandSource).trim();
209216
const normalizedChatType = normalizeChatType(ctx.ChatType);
@@ -213,15 +220,40 @@ export function initFastReplySessionState(params: {
213220
: triggerBodyNormalized;
214221
const resetMatch = strippedForReset.match(/^\/(new|reset)(?:\s|$)/i);
215222
const resetTriggered = Boolean(resetMatch);
223+
const previousSessionEntry = resetTriggered && existingEntry ? { ...existingEntry } : undefined;
224+
const sessionId =
225+
!resetTriggered && existingEntry ? existingEntry.sessionId : crypto.randomUUID();
216226
const bodyStripped = resetTriggered
217227
? strippedForReset.slice(resetMatch?.[0].length ?? 0).trimStart()
218228
: (ctx.BodyForAgent ?? ctx.Body ?? "");
219229
const now = Date.now();
220-
const sessionFile = path.join(workspaceDir, ".openclaw", "sessions", `${sessionId}.jsonl`);
230+
const sessionFile =
231+
!resetTriggered && existingEntry?.sessionFile
232+
? existingEntry.sessionFile
233+
: resolveSessionTranscriptPath(sessionId, agentId);
221234
const sessionEntry: SessionEntry = {
235+
...(!resetTriggered ? existingEntry : undefined),
222236
sessionId,
223237
sessionFile,
224238
updatedAt: now,
239+
thinkingLevel: resetTriggered ? existingEntry?.thinkingLevel : existingEntry?.thinkingLevel,
240+
verboseLevel: resetTriggered ? existingEntry?.verboseLevel : existingEntry?.verboseLevel,
241+
reasoningLevel: resetTriggered ? existingEntry?.reasoningLevel : existingEntry?.reasoningLevel,
242+
ttsAuto: resetTriggered ? existingEntry?.ttsAuto : existingEntry?.ttsAuto,
243+
responseUsage: !resetTriggered ? existingEntry?.responseUsage : undefined,
244+
modelOverride: resetTriggered ? existingEntry?.modelOverride : existingEntry?.modelOverride,
245+
providerOverride: resetTriggered
246+
? existingEntry?.providerOverride
247+
: existingEntry?.providerOverride,
248+
authProfileOverride: resetTriggered
249+
? existingEntry?.authProfileOverride
250+
: existingEntry?.authProfileOverride,
251+
authProfileOverrideSource: resetTriggered
252+
? existingEntry?.authProfileOverrideSource
253+
: existingEntry?.authProfileOverrideSource,
254+
authProfileOverrideCompactionCount: resetTriggered
255+
? existingEntry?.authProfileOverrideCompactionCount
256+
: existingEntry?.authProfileOverrideCompactionCount,
225257
...(normalizedChatType ? { chatType: normalizedChatType } : {}),
226258
...(normalizeOptionalString(ctx.Provider)
227259
? { channel: normalizeOptionalString(ctx.Provider) }
@@ -233,7 +265,7 @@ export function initFastReplySessionState(params: {
233265
? { groupChannel: normalizeOptionalString(ctx.GroupChannel) }
234266
: {}),
235267
};
236-
const sessionStore: Record<string, SessionEntry> = { [sessionKey]: sessionEntry };
268+
sessionStore[sessionKey] = sessionEntry;
237269
const sessionCtx: TemplateContext = {
238270
...ctx,
239271
SessionKey: sessionKey,
@@ -244,19 +276,19 @@ export function initFastReplySessionState(params: {
244276
return {
245277
sessionCtx,
246278
sessionEntry,
247-
previousSessionEntry: undefined,
248279
sessionStore,
249280
sessionKey,
250281
sessionId,
251-
isNewSession: resetTriggered || !ctx.SessionKey,
282+
isNewSession: resetTriggered || !existingEntry,
252283
resetTriggered,
253284
systemSent: false,
254285
abortedLastRun: false,
255-
storePath: normalizeOptionalString(cfg.session?.store) ?? "",
286+
storePath,
256287
sessionScope,
257288
groupResolution: undefined,
258289
isGroup,
259290
bodyStripped,
260291
triggerBodyNormalized,
292+
previousSessionEntry,
261293
};
262294
}

‎src/auto-reply/reply/get-reply-run.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ function loadSessionStoreRuntime() {
118118
return sessionStoreRuntimePromise;
119119
}
120120

121+
function stripPromptThinkingDirectives(body: string): string {
122+
return body
123+
.split("\n")
124+
.map((line) =>
125+
line
126+
.replace(/(^|\s)\/(?:thinking|think|t)(?=$|\s|:)(?:\s*:\s*|\s+)?[A-Za-z-]*/gi, "$1")
127+
.replace(/[ \t]{2,}/g, " ")
128+
.trimEnd(),
129+
)
130+
.join("\n");
131+
}
132+
121133
type RunPreparedReplyParams = {
122134
ctx: MsgContext;
123135
sessionCtx: TemplateContext;
@@ -314,7 +326,9 @@ export async function runPreparedReply(
314326
cfg,
315327
})
316328
: null;
317-
const baseBodyFinal = isBareSessionReset ? buildBareSessionResetPrompt(cfg) : baseBody;
329+
const baseBodyFinal = isBareSessionReset
330+
? buildBareSessionResetPrompt(cfg)
331+
: stripPromptThinkingDirectives(baseBody);
318332
const envelopeOptions = resolveEnvelopeFormatOptions(cfg);
319333
const inboundUserContext = buildInboundUserContextPrefix(
320334
isNewSession

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { finalizeInboundContext } from "./inbound-context.js";
3636
import { emitPreAgentMessageHooks } from "./message-preprocess-hooks.js";
3737
import { createFastTestModelSelectionState } from "./model-selection.js";
3838
import { initSessionState } from "./session.js";
39+
import { resolveStoredModelOverride } from "./stored-model-override.js";
3940
import { createTypingController } from "./typing.js";
4041

4142
type ResetCommandAction = "new" | "reset";
@@ -320,6 +321,17 @@ export async function getReplyFromConfig(
320321
normalizeOptionalString(sessionEntry.modelOverride) ||
321322
normalizeOptionalString(sessionEntry.providerOverride),
322323
);
324+
const storedModelOverride = resolveStoredModelOverride({
325+
sessionEntry,
326+
sessionStore,
327+
sessionKey,
328+
parentSessionKey: sessionEntry.parentSessionKey ?? sessionCtx.ParentSessionKey,
329+
defaultProvider,
330+
});
331+
if (storedModelOverride?.model && !hasResolvedHeartbeatModelOverride) {
332+
provider = storedModelOverride.provider ?? defaultProvider;
333+
model = storedModelOverride.model;
334+
}
323335
if (!hasResolvedHeartbeatModelOverride && !hasSessionModelOverride && channelModelOverride) {
324336
const resolved = resolveModelRefFromString({
325337
raw: channelModelOverride.model,

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,14 @@ function resolveProviderLabel(rawProvider: string | undefined): string {
9090
if (isInternalMessageChannel(providerKey)) {
9191
return "WebChat";
9292
}
93+
const labels: Record<string, string> = {
94+
imessage: "iMessage",
95+
whatsapp: "WhatsApp",
96+
};
97+
const label = labels[providerKey];
98+
if (label) {
99+
return label;
100+
}
93101
return `${providerKey.at(0)?.toUpperCase() ?? ""}${providerKey.slice(1)}`;
94102
}
95103

0 commit comments

Comments
 (0)