Skip to content

Commit 3f732ae

Browse files
authored
fix: session_status 'current' resolves to live run session instead of stale sandbox key (#76708) (#76995)
Summary: - The PR threads a live `runSessionKey` through embedded tool construction, updates `session_status({sessionKey:"current"})` resolution, and adds unit, Telegram QA, workflow, and changelog coverage for #76708. - Reproducibility: yes. Source inspection shows current main gives `session_status` only the sandbox/requester ... plus PR follow-up describe a focused Telegram Docker scenario that fails pre-fix and passes with this head. Automerge notes: - PR branch already contained follow-up commit before automerge: fix: preserve session visibility semantics for runSessionKey (#76708) - PR branch already contained follow-up commit before automerge: fix: cover Telegram current session status Validation: - ClawSweeper review passed for head c3c964e. - Required merge gates passed before the squash merge. Prepared head SHA: c3c964e Review: #76995 (comment) Co-authored-by: Alex Knight <[email protected]> Co-authored-by: Alex Knight <[email protected]>
1 parent 02b9dbd commit 3f732ae

12 files changed

Lines changed: 210 additions & 8 deletions

File tree

‎.github/workflows/openclaw-release-checks.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,7 @@ jobs:
462462
published_upgrade_survivor_baselines: all-since-2026.4.23
463463
published_upgrade_survivor_scenarios: reported-issues
464464
telegram_mode: mock-openai
465-
telegram_scenarios: telegram-help-command,telegram-commands-command,telegram-tools-compact-command,telegram-whoami-command,telegram-context-command,telegram-mention-gating
465+
telegram_scenarios: telegram-help-command,telegram-commands-command,telegram-tools-compact-command,telegram-whoami-command,telegram-context-command,telegram-current-session-status-tool,telegram-mention-gating
466466
secrets:
467467
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
468468
OPENAI_BASE_URL: ${{ secrets.OPENAI_BASE_URL }}

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ Docs: https://docs.openclaw.ai
135135
- Channels/streaming: expose `streaming.progress.label`, `labels`, `maxLines`, and `toolProgress` in bundled channel config metadata so progress draft settings appear in config, docs, and control surfaces. Thanks @vincentkoc.
136136
- Channels/streaming: normalize whitespace and case for `streaming.progress.label: "auto"` so progress draft labels keep using the built-in label pool instead of rendering a literal `auto` title. Thanks @vincentkoc.
137137
- Plugins/Codex: preserve Codex-native OAuth routing for `/codex bind` app-server turns so bound sessions keep the selected Codex auth profile instead of falling back to public OpenAI credentials. (#76714) Thanks @keshavbotagent.
138+
- Telegram: keep status checks pointed at the active chat so asking for the current session no longer reports an old direct-message conversation. (#76708) Thanks @amknight.
138139
- Gateway/install: prefer supported system Node over nvm/fnm/volta/asdf/mise when regenerating managed gateway services, so `gateway install --force` no longer recreates service definitions that doctor immediately flags as version-manager-backed. Fixes #76339. Thanks @brokemac79.
139140
- Cron/status: render explicit `delivery.mode: "none"` jobs as no-delivery previews and label cron session history distinctly instead of showing fallback delivery or direct-session rows. Fixes #76945.
140141
- Gateway/usage: serve `usage.cost` and `sessions.usage` from a durable transcript aggregate cache with lock-safe background refreshes and localized stale-cache status, so large usage views avoid repeated full scans. (#76650) Thanks @Marvinthebored.

‎extensions/qa-lab/src/live-transports/telegram/telegram-live.runtime.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ describe("telegram live qa runtime", () => {
331331
"telegram-tools-compact-command",
332332
"telegram-whoami-command",
333333
"telegram-context-command",
334+
"telegram-current-session-status-tool",
334335
"telegram-mentioned-message-reply",
335336
"telegram-mention-gating",
336337
]);
@@ -340,9 +341,15 @@ describe("telegram live qa runtime", () => {
340341
"telegram-tools-compact-command",
341342
"telegram-whoami-command",
342343
"telegram-context-command",
344+
"telegram-current-session-status-tool",
343345
"telegram-mentioned-message-reply",
344346
"telegram-mention-gating",
345347
]);
348+
expect(
349+
scenarios
350+
.find((scenario) => scenario.id === "telegram-current-session-status-tool")
351+
?.buildRun("sut_bot").expectedTextIncludes,
352+
).toEqual(["QA-TELEGRAM-CURRENT-SESSION-OK", ":telegram:group:"]);
346353
expect(
347354
scenarios
348355
.find((scenario) => scenario.id === "telegram-mentioned-message-reply")

‎extensions/qa-lab/src/live-transports/telegram/telegram-live.runtime.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ type TelegramQaScenarioId =
4747
| "telegram-tools-compact-command"
4848
| "telegram-whoami-command"
4949
| "telegram-context-command"
50+
| "telegram-current-session-status-tool"
5051
| "telegram-mentioned-message-reply"
5152
| "telegram-mention-gating";
5253

@@ -208,6 +209,7 @@ type TelegramMessage = {
208209

209210
type TelegramUpdate = {
210211
update_id: number;
212+
edited_message?: TelegramMessage;
211213
message?: TelegramMessage;
212214
};
213215

@@ -270,6 +272,17 @@ const TELEGRAM_QA_SCENARIOS: TelegramQaScenarioDefinition[] = [
270272
expectedTextIncludes: ["/context list", "Inline shortcut"],
271273
}),
272274
},
275+
{
276+
id: "telegram-current-session-status-tool",
277+
title: "Telegram current session_status tool call",
278+
defaultEnabled: false,
279+
timeoutMs: 60_000,
280+
buildRun: (sutUsername) => ({
281+
expectReply: true,
282+
input: `@${sutUsername} Telegram current session_status QA check. Call session_status with sessionKey set to current, then reply with the exact QA marker and resolved session key.`,
283+
expectedTextIncludes: ["QA-TELEGRAM-CURRENT-SESSION-OK", ":telegram:group:"],
284+
}),
285+
},
273286
{
274287
id: "telegram-mentioned-message-reply",
275288
title: "Telegram mentioned message gets a reply",
@@ -471,7 +484,7 @@ function detectMediaKinds(message: TelegramMessage) {
471484
}
472485

473486
function normalizeTelegramObservedMessage(update: TelegramUpdate): TelegramObservedMessage | null {
474-
const message = update.message;
487+
const message = update.message ?? update.edited_message;
475488
if (!message?.from?.id) {
476489
return null;
477490
}
@@ -608,7 +621,7 @@ async function flushTelegramUpdates(token: string) {
608621
{
609622
offset,
610623
timeout: 0,
611-
allowed_updates: ["message"],
624+
allowed_updates: ["message", "edited_message"],
612625
},
613626
15_000,
614627
);
@@ -653,10 +666,12 @@ async function waitForObservedMessage(params: {
653666
observedMessages: TelegramObservedMessage[];
654667
observationScenarioId: string;
655668
observationScenarioTitle: string;
669+
expectedTextIncludes?: string[];
656670
}) {
657671
const startedAt = Date.now();
658672
let offset = params.initialOffset;
659673
let lastPollingError: unknown;
674+
let lastExpectedMismatch: Error | undefined;
660675
while (Date.now() - startedAt < params.timeoutMs) {
661676
const remainingMs = Math.max(
662677
1_000,
@@ -671,7 +686,7 @@ async function waitForObservedMessage(params: {
671686
{
672687
offset,
673688
timeout: timeoutSeconds,
674-
allowed_updates: ["message"],
689+
allowed_updates: ["message", "edited_message"],
675690
},
676691
timeoutSeconds * 1000 + 5_000,
677692
);
@@ -703,10 +718,23 @@ async function waitForObservedMessage(params: {
703718
};
704719
params.observedMessages.push(observedMessage);
705720
if (matchedScenario) {
721+
try {
722+
assertTelegramScenarioReply({
723+
expectedTextIncludes: params.expectedTextIncludes,
724+
message: observedMessage,
725+
});
726+
} catch (error) {
727+
lastExpectedMismatch =
728+
error instanceof Error ? error : new Error(formatErrorMessage(error));
729+
continue;
730+
}
706731
return { message: observedMessage, nextOffset: offset, observedAtMs: batchObservedAtMs };
707732
}
708733
}
709734
}
735+
if (lastExpectedMismatch) {
736+
throw lastExpectedMismatch;
737+
}
710738
const timeoutMessage = `timed out after ${params.timeoutMs}ms waiting for Telegram message`;
711739
if (lastPollingError) {
712740
throw new Error(
@@ -1332,6 +1360,9 @@ export async function runTelegramQaLive(params: {
13321360
observedMessages,
13331361
observationScenarioId: scenario.id,
13341362
observationScenarioTitle: scenario.title,
1363+
expectedTextIncludes: scenarioRun.expectReply
1364+
? scenarioRun.expectedTextIncludes
1365+
: undefined,
13351366
predicate: (message) =>
13361367
matchesTelegramScenarioReply({
13371368
allowAnySutReply: scenarioRun.allowAnySutReply,

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ const QA_TOOL_PROGRESS_PROMPT_RE = /tool progress qa check/i;
152152
const QA_GROUP_VISIBLE_REPLY_TOOL_PROMPT_RE = /qa group visible reply tool check/i;
153153
const QA_GROUP_MESSAGE_UNAVAILABLE_FALLBACK_PROMPT_RE =
154154
/qa group message unavailable fallback check/i;
155+
const QA_TELEGRAM_CURRENT_SESSION_STATUS_PROMPT_RE = /telegram current session_status qa check/i;
155156
const QA_SUBAGENT_DIRECT_FALLBACK_PROMPT_RE = /subagent direct fallback qa check/i;
156157
const QA_SUBAGENT_DIRECT_FALLBACK_WORKER_RE = /subagent direct fallback worker/i;
157158
const QA_SUBAGENT_DIRECT_FALLBACK_MARKER = "QA-SUBAGENT-DIRECT-FALLBACK-OK";
@@ -673,6 +674,28 @@ function hasToolErrorOutput(toolJson: Record<string, unknown> | null, toolOutput
673674
return /\b(?:error|failed|failure|not found|no such file|enoent)\b/i.test(toolOutput);
674675
}
675676

677+
function extractSessionStatusSessionKey(
678+
toolJson: Record<string, unknown> | null,
679+
toolOutput: string,
680+
) {
681+
const details = toolJson?.details;
682+
if (details && typeof details === "object") {
683+
const sessionKey = (details as { sessionKey?: unknown }).sessionKey;
684+
if (typeof sessionKey === "string" && sessionKey.trim()) {
685+
return sessionKey.trim();
686+
}
687+
}
688+
const topLevelSessionKey = toolJson?.sessionKey;
689+
if (typeof topLevelSessionKey === "string" && topLevelSessionKey.trim()) {
690+
return topLevelSessionKey.trim();
691+
}
692+
const statusLineSessionKey = /(?:^|\n)[^\n]*Session:\s*([^\s•\n]+)/u.exec(toolOutput)?.[1];
693+
if (statusLineSessionKey?.trim()) {
694+
return statusLineSessionKey.trim();
695+
}
696+
return /"sessionKey"\s*:\s*"([^"]+)"/.exec(toolOutput)?.[1]?.trim() ?? "";
697+
}
698+
676699
function isHeartbeatPrompt(text: string) {
677700
const trimmed = text.trim();
678701
if (!trimmed || /remember this fact/i.test(trimmed)) {
@@ -1349,6 +1372,17 @@ async function buildResponsesPayload(
13491372
exactMarkerDirective ?? exactReplyDirective ?? "QA-GROUP-FALLBACK-OK",
13501373
);
13511374
}
1375+
if (QA_TELEGRAM_CURRENT_SESSION_STATUS_PROMPT_RE.test(allInputText)) {
1376+
if (!toolOutput && hasDeclaredTool(body, "session_status")) {
1377+
return buildToolCallEventsWithArgs("session_status", { sessionKey: "current" });
1378+
}
1379+
const sessionKey = extractSessionStatusSessionKey(toolJson, toolOutput);
1380+
return buildAssistantEvents(
1381+
sessionKey.includes(":telegram:group:")
1382+
? `QA-TELEGRAM-CURRENT-SESSION-OK ${sessionKey}`
1383+
: `QA-TELEGRAM-CURRENT-SESSION-BAD ${sessionKey || "missing-session-key"}`,
1384+
);
1385+
}
13521386
if (/\bmarker\b/i.test(allInputText) && exactReplyDirective) {
13531387
return buildAssistantEvents(exactReplyDirective);
13541388
}

‎src/agents/openclaw-tools.session-status.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,61 @@ describe("session_status tool", () => {
492492
expect(details.sessionKey).toBe("main");
493493
});
494494

495+
it("resolves sessionKey=current to runSessionKey under default tree visibility (#76708)", async () => {
496+
resetSessionStore({
497+
"agent:main:telegram:default:direct:1234": {
498+
sessionId: "s-tg-direct",
499+
updatedAt: 5,
500+
status: "done",
501+
},
502+
"agent:main:main": {
503+
sessionId: "s-main",
504+
updatedAt: 10,
505+
status: "running",
506+
},
507+
});
508+
509+
// Default visibility is "tree". The tool is constructed with the Telegram
510+
// sandbox key as agentSessionKey but the live run session key as runSessionKey.
511+
// semantic-current must be treated as self for visibility purposes.
512+
const tool = createSessionStatusTool({
513+
agentSessionKey: "agent:main:telegram:default:direct:1234",
514+
runSessionKey: "agent:main:main",
515+
config: mockConfig as never,
516+
});
517+
518+
const result = await tool.execute("call-current-run-session", { sessionKey: "current" });
519+
const details = result.details as { ok?: boolean; sessionKey?: string };
520+
expect(details.ok).toBe(true);
521+
expect(details.sessionKey).toBe("agent:main:main");
522+
});
523+
524+
it("rejects explicit cross-session key under tree visibility even when it equals runSessionKey (#76708)", async () => {
525+
resetSessionStore({
526+
"agent:main:telegram:default:direct:1234": {
527+
sessionId: "s-tg-direct",
528+
updatedAt: 5,
529+
status: "done",
530+
},
531+
"agent:main:main": {
532+
sessionId: "s-main",
533+
updatedAt: 10,
534+
status: "running",
535+
},
536+
});
537+
538+
// Same setup but with an explicit key — should NOT bypass visibility.
539+
const tool = createSessionStatusTool({
540+
agentSessionKey: "agent:main:telegram:default:direct:1234",
541+
runSessionKey: "agent:main:main",
542+
config: mockConfig as never,
543+
});
544+
545+
await expect(
546+
tool.execute("call-explicit-key", { sessionKey: "agent:main:main" }),
547+
).rejects.toThrow(/visibility is restricted/);
548+
});
549+
495550
it("treats the TUI client label as the current requester session", async () => {
496551
resetSessionStore({
497552
"agent:main:main": {
@@ -590,6 +645,29 @@ describe("session_status tool", () => {
590645
expect(details.statusText).toContain("🧠 Model:");
591646
});
592647

648+
it("resolves sandboxed sessionKey=current to the requester when no run session override exists", async () => {
649+
resetSessionStore({});
650+
651+
const tool = getSessionStatusTool("agent:main:telegram:group:-5096326138", {
652+
sandboxed: true,
653+
});
654+
655+
const result = await tool.execute("call-current-sandboxed-channel", {
656+
sessionKey: "current",
657+
});
658+
const details = result.details as { ok?: boolean; sessionKey?: string; statusText?: string };
659+
expect(details.ok).toBe(true);
660+
expect(details.sessionKey).toBe("agent:main:telegram:group:-5096326138");
661+
expect(details.statusText).toContain("OpenClaw");
662+
expect(details.statusText).toContain("🧠 Model:");
663+
expect(callGatewayMock).not.toHaveBeenCalledWith(
664+
expect.objectContaining({
665+
method: "sessions.resolve",
666+
params: expect.objectContaining({ key: "current" }),
667+
}),
668+
);
669+
});
670+
593671
it("resolves the default session_status lookup for a channel-plugin requester via implicit fallback", async () => {
594672
resetSessionStore({});
595673

‎src/agents/openclaw-tools.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,12 @@ export function createOpenClawTools(
260260
sandboxBrowserBridgeUrl?: string;
261261
allowHostBrowserControl?: boolean;
262262
agentSessionKey?: string;
263+
/**
264+
* The actual live run session key. When the tool is constructed with a sandbox/policy
265+
* session key, this allows `session_status({sessionKey:"current"})` to resolve to
266+
* the live run session instead of the stale sandbox key.
267+
*/
268+
runSessionKey?: string;
263269
agentChannel?: GatewayMessageChannel;
264270
agentAccountId?: string;
265271
/** Delivery target for topic/thread routing. */
@@ -588,6 +594,7 @@ export function createOpenClawTools(
588594
}),
589595
createSessionStatusTool({
590596
agentSessionKey: options?.agentSessionKey,
597+
runSessionKey: options?.runSessionKey,
591598
config: resolvedConfig,
592599
sandboxed: options?.sandboxed,
593600
}),

‎src/agents/pi-embedded-runner/compact.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,10 @@ async function compactEmbeddedPiSessionDirectOnce(
664664
messageProvider: resolvedMessageProvider,
665665
agentAccountId: params.agentAccountId,
666666
sessionKey: sandboxSessionKey,
667+
runSessionKey:
668+
params.sessionKey && params.sessionKey !== sandboxSessionKey
669+
? params.sessionKey
670+
: undefined,
667671
sessionId: params.sessionId,
668672
runId: params.runId,
669673
groupId: params.groupId,

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -885,6 +885,13 @@ export async function runEmbeddedAttempt(
885885
ownerOnlyToolAllowlist: params.ownerOnlyToolAllowlist,
886886
allowGatewaySubagentBinding: params.allowGatewaySubagentBinding,
887887
sessionKey: sandboxSessionKey,
888+
// When sandboxSessionKey differs from the real run session key (e.g. Telegram
889+
// direct peer key vs agent:main:main), pass the live key so session_status
890+
// "current" resolves to the active run session, not the stale sandbox key.
891+
runSessionKey:
892+
params.sessionKey && params.sessionKey !== sandboxSessionKey
893+
? params.sessionKey
894+
: undefined,
888895
sessionId: params.sessionId,
889896
runId: params.runId,
890897
agentDir,

‎src/agents/pi-tools.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,12 @@ export function createOpenClawCodingTools(options?: {
274274
messageThreadId?: string | number;
275275
sandbox?: SandboxContext | null;
276276
sessionKey?: string;
277+
/**
278+
* The actual live run session key. When the tool set is constructed with a
279+
* sandbox/policy session key, this allows `session_status({sessionKey:"current"})`
280+
* to resolve to the live run session instead of the stale sandbox key.
281+
*/
282+
runSessionKey?: string;
277283
/** Ephemeral session UUID — regenerated on /new and /reset. */
278284
sessionId?: string;
279285
/** Stable run identifier for this agent invocation. */
@@ -698,6 +704,7 @@ export function createOpenClawCodingTools(options?: {
698704
sandboxBrowserBridgeUrl: sandbox?.browser?.bridgeUrl,
699705
allowHostBrowserControl: sandbox ? sandbox.browserAllowHostControl : true,
700706
agentSessionKey: options?.sessionKey,
707+
runSessionKey: options?.runSessionKey,
701708
agentChannel: resolveGatewayMessageChannel(options?.messageProvider),
702709
agentAccountId: options?.agentAccountId,
703710
agentTo: options?.messageTo,

0 commit comments

Comments
 (0)