Skip to content

Commit b2709ce

Browse files
authored
fix(gateway): honor selected model for worktree titles (#124902)
* fix(gateway): honor selected model for worktree titles Carry the create request’s explicit or catalog-backed provider, model, runtime, and auth profile into create-time title routing without blocking on model-catalog loading. Related: #124787 * fix(gateway): validate worktree title route Reuse the canonical model-policy resolver before prestarting title generation. Denied or invalid selections now skip title completion while persisted creation remains the sole live-catalog availability validator. * fix(gateway): normalize denied title selection Preserve the null suppression sentinel at the preparation boundary while forwarding only the title generator’s optional entry shape. * fix(gateway): inherit worktree title route * fix(gateway): preserve normalized session categories Keep post-commit category registration aligned with the normalized category persisted by session creation after the helper extraction.
1 parent ea3a5bf commit b2709ce

6 files changed

Lines changed: 334 additions & 93 deletions

File tree

‎src/gateway/dashboard-session-title.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,10 +212,14 @@ async function generateDashboardSessionTitle(params: {
212212
export function prepareWorktreeSessionTitle(params: {
213213
cfg: OpenClawConfig;
214214
agentId: string;
215+
entry?: DashboardSessionTitleModelEntry | null;
215216
userMessage: string;
216217
attachments?: readonly ChatAttachment[];
217218
onError: (error: unknown) => void;
218219
}) {
220+
if (params.entry === null) {
221+
return undefined;
222+
}
219223
const source = buildDashboardSessionTitleSource({
220224
message: params.userMessage,
221225
attachments: params.attachments,
@@ -226,6 +230,7 @@ export function prepareWorktreeSessionTitle(params: {
226230
const generated = withTimeout(
227231
generateDashboardSessionTitle({
228232
...params,
233+
entry: params.entry ?? undefined,
229234
timeoutMs: WORKTREE_SESSION_TITLE_ATTEMPT_TIMEOUT_MS,
230235
}),
231236
WORKTREE_SESSION_TITLE_TIMEOUT_MS,
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { formatErrorMessage } from "../../infra/errors.js";
2+
import { ensureSessionGroupRegistered } from "../session-groups.js";
3+
import { emitSessionsChanged } from "./session-change-event.js";
4+
import { sessionLog } from "./sessions-shared.js";
5+
6+
export function registerCreatedSessionCategory(
7+
category: string | undefined,
8+
context: Parameters<typeof emitSessionsChanged>[0],
9+
): void {
10+
if (!category) {
11+
return;
12+
}
13+
try {
14+
if (ensureSessionGroupRegistered(category)) {
15+
// Catalog bookkeeping follows the authoritative session commit and has
16+
// its own invalidation. Its failure must not make a durable create ambiguous.
17+
emitSessionsChanged(context, { reason: "groups" });
18+
}
19+
} catch (error) {
20+
sessionLog.warn(`failed to register created session category: ${formatErrorMessage(error)}`);
21+
}
22+
}

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

Lines changed: 45 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,11 @@ import { normalizeAgentId, parseAgentSessionKey } from "../../routing/session-ke
2929
import { resolveUserPath } from "../../utils.js";
3030
import { prepareWorktreeSessionTitle } from "../dashboard-session-title.js";
3131
import { ADMIN_SCOPE, authorizeOperatorScopesForRequiredScope } from "../method-scopes.js";
32-
import { buildDashboardSessionKey, createGatewaySession } from "../session-create-service.js";
33-
import { ensureSessionGroupRegistered } from "../session-groups.js";
34-
import type { PrepareGatewaySessionLifecycle } from "../session-lifecycle-preparation.js";
32+
import {
33+
buildDashboardSessionKey,
34+
createGatewaySession,
35+
resolveSessionCreateModelSelection as resolveCreateTitleEntry,
36+
} from "../session-create-service.js";
3537
import { resolveRequestedSessionAgentId as resolveRequestedGlobalAgentId } from "../session-request-agent.js";
3638
import { resolveSessionStoreAgentId } from "../session-store-key.js";
3739
import { readSessionMessageCountAsync } from "../session-transcript-readers.js";
@@ -43,6 +45,7 @@ import { createAgentRuntimeAuthorityGuard } from "./agent-runtime-authority.js";
4345
import { chatHandlers } from "./chat.js";
4446
import { resolveRegisteredCatalogCreateTarget } from "./session-catalog.js";
4547
import { emitSessionsChanged } from "./session-change-event.js";
48+
import { registerCreatedSessionCategory } from "./session-create-category.js";
4649
import { captureCreatedSessionDiffBaseline } from "./session-create-diff-baseline.js";
4750
import {
4851
resolveSessionCreateInitialTurn,
@@ -54,24 +57,6 @@ import type { GatewayRequestHandlers } from "./types.js";
5457
import { assertValidParams } from "./validation.js";
5558
import { resolveWorkspacePathContainment } from "./workspace-path-containment.js";
5659

57-
function registerCreatedSessionCategory(
58-
category: string | undefined,
59-
context: Parameters<typeof emitSessionsChanged>[0],
60-
): void {
61-
if (!category) {
62-
return;
63-
}
64-
try {
65-
if (ensureSessionGroupRegistered(category)) {
66-
// Catalog bookkeeping follows the authoritative session commit and has
67-
// its own invalidation. Its failure must not make a durable create ambiguous.
68-
emitSessionsChanged(context, { reason: "groups" });
69-
}
70-
} catch (error) {
71-
sessionLog.warn(`failed to register created session category: ${formatErrorMessage(error)}`);
72-
}
73-
}
74-
7560
export const sessionCreateHandlers: GatewayRequestHandlers = {
7661
"sessions.create": async ({
7762
req,
@@ -86,6 +71,8 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
8671
return;
8772
}
8873
const p = params;
74+
const parentSessionKey = normalizeOptionalString(p.parentSessionKey);
75+
const requestedModel = normalizeOptionalString(p.model);
8976
const cfg = context.getRuntimeConfig();
9077
const authority = createAgentRuntimeAuthorityGuard(client, context, respond);
9178
const commitGuard =
@@ -96,19 +83,15 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
9683
}
9784
: undefined;
9885
const catalogId = normalizeOptionalString(p.catalogId);
99-
if (catalogId && p.model) {
100-
respond(
101-
false,
102-
undefined,
103-
errorShape(ErrorCodes.INVALID_REQUEST, "sessions.create catalogId cannot include model"),
104-
);
105-
return;
106-
}
107-
if (catalogId && p.key) {
86+
const catalogConflict = p.model ? "model" : p.key ? "key" : undefined;
87+
if (catalogId && catalogConflict) {
10888
respond(
10989
false,
11090
undefined,
111-
errorShape(ErrorCodes.INVALID_REQUEST, "sessions.create catalogId cannot include key"),
91+
errorShape(
92+
ErrorCodes.INVALID_REQUEST,
93+
`sessions.create catalogId cannot include ${catalogConflict}`,
94+
),
11295
);
11396
return;
11497
}
@@ -235,19 +218,27 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
235218
return;
236219
}
237220
const explicitSessionLabel = normalizeOptionalString(p.label);
238-
// Start before repository resolution, but cap the whole shared request: either
239-
// naming gets a title within eight seconds or creation falls back to the raw source.
240-
const worktreeTitle =
241-
p.worktree === true && !requestedWorktreeName && !explicitSessionLabel
221+
const titleAgentId = normalizeAgentId(explicitlyRequestedAgent.agentId);
222+
const shouldPrepareWorktreeTitle =
223+
p.worktree === true && !requestedWorktreeName && !explicitSessionLabel;
224+
const deferWorktreeTitle =
225+
shouldPrepareWorktreeTitle && Boolean(parentSessionKey) && !catalogTarget && !requestedModel;
226+
const worktreeTitleParams = shouldPrepareWorktreeTitle
227+
? {
228+
cfg,
229+
agentId: titleAgentId,
230+
userMessage: initialMessage ?? "",
231+
attachments: initialAttachments,
232+
onError: (error: unknown) =>
233+
sessionLog.warn(`worktree title failed: ${formatErrorMessage(error)}`),
234+
}
235+
: undefined;
236+
// Known routes start before repository resolution; inherited routes wait for parent validation.
237+
let worktreeTitle =
238+
worktreeTitleParams && !deferWorktreeTitle
242239
? prepareWorktreeSessionTitle({
243-
cfg,
244-
agentId: normalizeAgentId(
245-
catalogAgentId ?? explicitlyRequestedAgent.agentId ?? explicitlyRequestedAgentId,
246-
),
247-
userMessage: initialMessage ?? "",
248-
attachments: initialAttachments,
249-
onError: (error) =>
250-
sessionLog.warn(`worktree title failed: ${formatErrorMessage(error)}`),
240+
...worktreeTitleParams,
241+
entry: resolveCreateTitleEntry(cfg, titleAgentId, catalogTarget?.target ?? p.model),
251242
})
252243
: undefined;
253244
let projectRoot: string | undefined;
@@ -290,7 +281,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
290281
let sessionWorktree: Awaited<ReturnType<typeof managedWorktrees.create>> | undefined;
291282
const sessionExecCwd = requestedExecNode ? requestedCwd : undefined;
292283
let sessionCwd = requestedExecNode ? undefined : (projectRoot ?? requestedCwd);
293-
let prepareLifecycle: PrepareGatewaySessionLifecycle | undefined;
284+
let prepareLifecycle: Parameters<typeof createGatewaySession>[0]["prepareLifecycle"];
294285
if (sessionCwd && !requestedExecNode && (requestedProjectId || p.worktree !== true)) {
295286
const targetAgentId = normalizeAgentId(
296287
sessionAgentId ??
@@ -335,7 +326,6 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
335326
);
336327
let targetKey = explicitKey;
337328
let preservesUnspecifiedKey = false;
338-
const parentSessionKey = normalizeOptionalString(p.parentSessionKey);
339329
if (
340330
!targetKey &&
341331
parentSessionKey &&
@@ -397,6 +387,12 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
397387
const scopes = Array.isArray(client?.connect.scopes) ? client.connect.scopes : [];
398388
prepareLifecycle = async (lifecycleTarget) => {
399389
try {
390+
if (deferWorktreeTitle && worktreeTitleParams) {
391+
worktreeTitle = prepareWorktreeSessionTitle({
392+
...worktreeTitleParams,
393+
entry: lifecycleTarget.titleModelSelection,
394+
});
395+
}
400396
const boundId = normalizeOptionalString(lifecycleTarget.entry?.worktree?.id);
401397
let existing = boundId ? managedWorktrees.findLiveById(boundId) : undefined;
402398
if (
@@ -515,7 +511,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
515511
if (
516512
sessionCreation.inheritedToolPolicy &&
517513
spawnActorSessionKey &&
518-
normalizeOptionalString(p.parentSessionKey) !== spawnActorSessionKey
514+
parentSessionKey !== spawnActorSessionKey
519515
) {
520516
respond(
521517
false,
@@ -536,21 +532,20 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
536532
if (!authority.ensureActive()) {
537533
return;
538534
}
539-
const category = normalizeOptionalString(p.category);
540535
const created = await createGatewaySession({
541536
cfg,
542537
key: sessionKey,
543538
agentId: sessionAgentId,
544539
label: p.label,
545540
category: p.category,
546-
...(catalogTarget ? { catalogTarget: catalogTarget.target } : { model: p.model }),
541+
...(catalogTarget ? { catalogTarget: catalogTarget.target } : { model: requestedModel }),
547542
thinkingLevel: p.thinkingLevel,
548543
projectId: requestedProjectId,
549544
incognito: p.incognito,
550545
...(client?.connect ? { requestingOperatorScopes: clientScopes } : {}),
551546
visibility: p.visibility,
552547
allowExistingModelSelection,
553-
parentSessionKey: p.parentSessionKey,
548+
parentSessionKey,
554549
spawnDepth: p.spawnDepth,
555550
spawnToolPolicy:
556551
sessionCreation.via === "spawn" && sessionCreation.inheritedToolPolicy
@@ -640,7 +635,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
640635
respond(false, undefined, created.error);
641636
return;
642637
}
643-
registerCreatedSessionCategory(category, context);
638+
registerCreatedSessionCategory(normalizeOptionalString(p.category), context);
644639
if (created.resetExisting) {
645640
await captureCreatedSessionDiffBaseline({
646641
key: created.key,

0 commit comments

Comments
 (0)