Skip to content

Commit 0b85f9c

Browse files
authored
feat: resolve short session references in the gateway (#120512)
* feat(gateway): resolve short session references * refactor(ui): delegate short session resolution to gateway * fix: complete short session resolver integration * fix(gateway): filter deleted-agent short sessions * fix(ui): support older gateway short links * docs(web): qualify short-link candidate limits for older gateways * refactor(protocol): split session resolve schema * fix(gateway): filter session resolver visibility
1 parent 1609ae9 commit 0b85f9c

22 files changed

Lines changed: 933 additions & 296 deletions

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4690,6 +4690,8 @@ public struct SessionsResolveParams: Codable, Sendable {
46904690
public let key: String?
46914691
public let sessionid: String?
46924692
public let label: String?
4693+
public let shortid: String?
4694+
public let slughint: String?
46934695
public let agentid: String?
46944696
public let spawnedby: String?
46954697
public let includeglobal: Bool?
@@ -4700,6 +4702,8 @@ public struct SessionsResolveParams: Codable, Sendable {
47004702
key: String? = nil,
47014703
sessionid: String? = nil,
47024704
label: String? = nil,
4705+
shortid: String? = nil,
4706+
slughint: String? = nil,
47034707
agentid: String? = nil,
47044708
spawnedby: String? = nil,
47054709
includeglobal: Bool? = nil,
@@ -4709,6 +4713,8 @@ public struct SessionsResolveParams: Codable, Sendable {
47094713
self.key = key
47104714
self.sessionid = sessionid
47114715
self.label = label
4716+
self.shortid = shortid
4717+
self.slughint = slughint
47124718
self.agentid = agentid
47134719
self.spawnedby = spawnedby
47144720
self.includeglobal = includeglobal
@@ -4720,6 +4726,8 @@ public struct SessionsResolveParams: Codable, Sendable {
47204726
case key
47214727
case sessionid = "sessionId"
47224728
case label
4729+
case shortid = "shortId"
4730+
case slughint = "slugHint"
47234731
case agentid = "agentId"
47244732
case spawnedby = "spawnedBy"
47254733
case includeglobal = "includeGlobal"

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ methods. Treat this as feature discovery, not a full enumeration of
619619
- `sessions.messages.subscribe` and `sessions.messages.unsubscribe` toggle transcript/message event subscriptions for one session. Pass `includeApprovals: true` to also receive sanitized `session.approval` lifecycle events for approvals whose persisted audience includes that exact session and whose reviewer binding authorizes the subscribing client. The subscribe response then includes a bounded pending `approvalReplay`; it is authoritative when `truncated` is false. The opt-in is per subscribe call, not sticky: re-subscribing to the same session without `includeApprovals: true` removes an existing approval subscription. In addition to normal session-read authority, this opt-in requires `operator.admin`, or `operator.approvals` on a paired device.
620620
- `sessions.preview` returns bounded transcript previews for specific session keys.
621621
- `sessions.describe` returns one gateway session row for an exact session key.
622-
- `sessions.resolve` resolves or canonicalizes a session target.
622+
- `sessions.resolve` resolves or canonicalizes a session target by key, raw session ID, label, or Control UI short ID. Ambiguous short IDs return a bounded candidate list as a successful RPC result.
623623
- `sessions.create` creates a new session entry. Optional `model` and `thinkingLevel` values persist the initial model and reasoning overrides atomically. `worktree: true` provisions a managed worktree; optional `worktreeBaseRef`/`worktreeName` select the base ref and branch name, and `execNode` (`operator.admin`) binds session exec to a node host. Without `worktreeName`, OpenClaw derives a readable name from the session label or generated first-message title, then falls back to a crustacean-themed name; names already occupied by another owner, local branch, or unmanaged path receive a numeric suffix. The created worktree is echoed in the result and persisted on the session row (`worktree: { id, branch, repoRoot }`). When the entry is created but its nested initial `chat.send` is rejected, the successful result includes `runStarted: false` and `runError`; clients can preserve the prompt and retry against the returned session key. A caller that passes `parentSessionKey` with `emitCommandHooks: true` should also declare the lifecycle disposition of a distinct child: `succeedsParent: true` ends the parent with `session_end`, while `false` keeps the parent active and emits only the child's `session_start`. Omitting `succeedsParent` preserves the legacy parent-rollover behavior for existing clients. The disposition requires both parent linkage and command hooks; a fork cannot succeed its parent. Main-session reset-in-place behavior is unchanged because no distinct child is created. New rows are stamped with write-once creation provenance (`createdVia`, `createdActor`, `createdAt`) from the trusted creation seam; adopting an existing key never restamps it. For human profile actors, `createdActor.label` is resolved from the current user profile when the row is projected and is never stored on the session entry, so profile renames do not drift. Session rows also carry `parentSessionKey` (navigation parent, persisted), `controlOwnerSessionKey` (runtime controller when live), `forkSource` (exact source key + transcript generation for forks), and `previousSessionId` (prior transcript generation under the same key).
624624
- `sessions.dispatch` (`operator.admin`) moves an existing local OpenClaw session with a session-owned managed worktree to a configured cloud-worker profile. Pass `{ key, profileId, agentId? }`. The method is absent when no worker profile is configured, closes local turn admission before draining active work, and returns only after placement reaches `active` worker ownership. Dispatch is one-way; worker-to-local pull-back is not part of this RPC.
625625
- `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.

‎docs/web/urls.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,12 @@ slug matching.
103103
If one short id matches more than one session and the slug does not settle it,
104104
the UI does not guess. It shows a small disambiguation view with the matching
105105
display names, agents, and longer id prefixes. Use a longer prefix to make the
106-
URL unique. Resolution examines at
107-
most five pages of search results; if more remain, the view says that the search
108-
was incomplete instead of guessing.
106+
URL unique. Current Gateways return at most ten recent candidates; when that
107+
bound is reached, the view treats the result as incomplete instead of guessing.
108+
Against an older Gateway that predates short-id resolve support, the UI falls
109+
back to the prior bounded list search, scanning at most five pages of results.
110+
It likewise reports an incomplete search instead of guessing when that fallback
111+
cannot prove uniqueness.
109112

110113
Canonical links do not use `?session=` or `?face=`. Released links such as
111114
`/chat?session=<sessionKey>` are accepted only at the application boundary as a

‎packages/gateway-protocol/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ Several identifier names coexist because they identify different things:
128128

129129
Follow each method schema rather than converting fields based on their spelling.
130130
`sessions.resolve` is the explicit bridge when a caller has a key, raw session ID,
131-
label, or parent/agent scope.
131+
label, Control UI short ID, or parent/agent scope.
132132

133133
### Intentionally open fields
134134

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import type { Static } from "typebox";
2+
import { Type } from "typebox";
3+
import { closedObject } from "./closed-object.js";
4+
import { NonEmptyString, SessionLabelString } from "./primitives.js";
5+
6+
/** Resolves a session by key, raw session id, label, short URL id, or parent/agent scope. */
7+
export const SessionsResolveParamsSchema = closedObject({
8+
key: Type.Optional(NonEmptyString),
9+
sessionId: Type.Optional(NonEmptyString),
10+
label: Type.Optional(SessionLabelString),
11+
/** Bare 8-32 character hexadecimal prefix of a session key's trailing UUID. */
12+
shortId: Type.Optional(NonEmptyString),
13+
/** Optional display-name slug used only to narrow ambiguous shortId matches. */
14+
slugHint: Type.Optional(NonEmptyString),
15+
agentId: Type.Optional(NonEmptyString),
16+
spawnedBy: Type.Optional(NonEmptyString),
17+
includeGlobal: Type.Optional(Type.Boolean()),
18+
includeUnknown: Type.Optional(Type.Boolean()),
19+
/** Return a successful `{ ok: false }` response when the selector does not match a session. */
20+
allowMissing: Type.Optional(Type.Boolean()),
21+
});
22+
23+
export type SessionsResolveParams = Static<typeof SessionsResolveParamsSchema>;

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

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { SessionsCreateParamsSchema } from "./sessions-create.js";
1111
import { SessionToolOverridesSchema } from "./sessions-row.js";
1212

1313
export { SessionsCreateParamsSchema };
14+
export { SessionsResolveParamsSchema, type SessionsResolveParams } from "./sessions-resolve.js";
1415
export {
1516
SESSIONS_ARCHIVE_MANY_MAX_TARGETS,
1617
SessionsArchiveManyParamsSchema,
@@ -427,19 +428,6 @@ export const SessionsDescribeParamsSchema = closedObject({
427428
includeLastMessage: Type.Optional(Type.Boolean()),
428429
});
429430

430-
/** Resolves a session by key, raw session id, label, or parent/agent scope. */
431-
export const SessionsResolveParamsSchema = closedObject({
432-
key: Type.Optional(NonEmptyString),
433-
sessionId: Type.Optional(NonEmptyString),
434-
label: Type.Optional(SessionLabelString),
435-
agentId: Type.Optional(NonEmptyString),
436-
spawnedBy: Type.Optional(NonEmptyString),
437-
includeGlobal: Type.Optional(Type.Boolean()),
438-
includeUnknown: Type.Optional(Type.Boolean()),
439-
/** Return a successful `{ ok: false }` response when the selector does not match a session. */
440-
allowMissing: Type.Optional(Type.Boolean()),
441-
});
442-
443431
export const SessionWorktreeInfoSchema = closedObject({
444432
id: NonEmptyString,
445433
path: NonEmptyString,
@@ -834,7 +822,6 @@ export type SessionsListParams = Static<typeof SessionsListParamsSchema>;
834822
export type SessionsCleanupParams = Static<typeof SessionsCleanupParamsSchema>;
835823
export type SessionsPreviewParams = Static<typeof SessionsPreviewParamsSchema>;
836824
export type SessionsDescribeParams = Static<typeof SessionsDescribeParamsSchema>;
837-
export type SessionsResolveParams = Static<typeof SessionsResolveParamsSchema>;
838825
export type SessionsSearchParams = Static<typeof SessionsSearchParamsSchema>;
839826
export type SessionsSearchHit = Static<typeof SessionsSearchHitSchema>;
840827
export type SessionsSearchResult = Static<typeof SessionsSearchResultSchema>;

‎packages/session-url-contract/src/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ type BuildControlUiSessionPathParams = {
1111
shortIdLength?: number;
1212
};
1313

14-
const SESSION_UUID_SUFFIX_RE = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/iu;
14+
export const SESSION_UUID_SUFFIX_RE =
15+
/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/iu;
16+
export const SHORT_SESSION_ID_RE = /^[0-9a-f]{8,32}$/iu;
1517
const SHORT_SESSION_REF_RE = /^(?:.*-)?([0-9a-f]{8,32})$/iu;
1618
const VALID_AGENT_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/iu;
1719
const INVALID_AGENT_ID_CHARS_RE = /[^a-z0-9_-]+/giu;

‎src/agents/tools/embedded-gateway-stub.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,28 @@ describe("embedded gateway stub", () => {
113113
expect(result).toEqual({ ok: true, key: "agent:main:main" });
114114
expect(runtime.resolveSessionKeyFromResolveParams).toHaveBeenCalledWith({
115115
cfg: { agents: { list: [{ id: "main", default: true }] } },
116+
client: null,
116117
p: { sessionId: "sess-main", includeGlobal: true },
117118
});
118119
});
119120

121+
it("preserves short-id ambiguity as a successful embedded response", async () => {
122+
const candidates = [
123+
{ key: "agent:main:thread:12345678-0aaa-4000-8000-000000000001", displayName: "One" },
124+
{ key: "agent:main:thread:12345678-0bbb-4000-8000-000000000002", displayName: "Two" },
125+
];
126+
runtime.resolveSessionKeyFromResolveParams.mockResolvedValueOnce({
127+
ok: true,
128+
ambiguous: true,
129+
candidates,
130+
});
131+
132+
const callGateway = createEmbeddedCallGateway();
133+
await expect(
134+
callGateway({ method: "sessions.resolve", params: { shortId: "12345678" } }),
135+
).resolves.toEqual({ ok: false, candidates });
136+
});
137+
120138
it("throws resolver errors for unresolved sessions", async () => {
121139
runtime.resolveSessionKeyFromResolveParams.mockResolvedValueOnce({
122140
ok: false,

‎src/agents/tools/embedded-gateway-stub.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ interface EmbeddedGatewayRuntime {
8888
};
8989
resolveSessionKeyFromResolveParams: (opts: {
9090
cfg: OpenClawConfig;
91+
client: null;
9192
p: SessionsResolveParams;
9293
}) => Promise<SessionsResolveResult>;
9394
loadSessionEntry: (
@@ -215,6 +216,7 @@ async function handleSessionsResolve(params: Record<string, unknown>) {
215216
const cfg = rt.getRuntimeConfig();
216217
const resolved = await rt.resolveSessionKeyFromResolveParams({
217218
cfg,
219+
client: null,
218220
p: params as SessionsResolveParams,
219221
});
220222
if (!resolved.ok) {
@@ -223,6 +225,9 @@ async function handleSessionsResolve(params: Record<string, unknown>) {
223225
if ("missing" in resolved) {
224226
return { ok: false };
225227
}
228+
if ("ambiguous" in resolved) {
229+
return { ok: false, candidates: resolved.candidates };
230+
}
226231
return { ok: true, key: resolved.key };
227232
}
228233

‎src/gateway/server-methods/sessions-read.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -646,14 +646,14 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
646646
undefined,
647647
);
648648
},
649-
"sessions.resolve": async ({ params, respond, context }) => {
649+
"sessions.resolve": async ({ params, respond, context, client }) => {
650650
if (!assertValidParams(params, validateSessionsResolveParams, "sessions.resolve", respond)) {
651651
return;
652652
}
653653
const p = params;
654654
const cfg = context.getRuntimeConfig();
655655

656-
const resolved = await resolveSessionKeyFromResolveParams({ cfg, p });
656+
const resolved = await resolveSessionKeyFromResolveParams({ cfg, client, p });
657657
if (!resolved.ok) {
658658
respond(false, undefined, resolved.error);
659659
return;
@@ -662,6 +662,10 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
662662
respond(true, { ok: false }, undefined);
663663
return;
664664
}
665+
if ("ambiguous" in resolved) {
666+
respond(true, { ok: false, candidates: resolved.candidates }, undefined);
667+
return;
668+
}
665669
respond(true, { ok: true, key: resolved.key }, undefined);
666670
},
667671
"sessions.get": async ({ params, respond, context }) => {

0 commit comments

Comments
 (0)