Skip to content

Commit 65922f9

Browse files
authored
fix(gateway): share generated session titles with worktree names and start title work at dispatch (#124787)
Worktree sessions now derive their worktree/branch name from the same concise generated title the sidebar shows (bounded 8s wait, raw-prompt slug then crustacean fallback), persisted once as displayName so the chat-send pass never duplicates the model call. Dashboard title scheduling moves from the dispatch chain's finally (after the whole first turn) back to dispatch start, so long or interrupted first turns no longer leave sessions silently untitled (regression from #122471). slugifyWorktreeTitle truncates at word boundaries; dead generatedDisplayName plumbing removed.
1 parent da85382 commit 65922f9

7 files changed

Lines changed: 265 additions & 90 deletions

File tree

‎src/agents/worktrees/name.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ describe("slugifyWorktreeTitle", () => {
1010
expect(slugifyWorktreeTitle(title)).toBe(expected);
1111
});
1212

13-
it("truncates at the worktree contract limit without a trailing dash", () => {
13+
it("truncates at the last complete word within the worktree contract limit", () => {
14+
expect(slugifyWorktreeTitle(`${"a".repeat(50)} complete unfinished`)).toBe(
15+
`${"a".repeat(50)}-complete`,
16+
);
1417
expect(slugifyWorktreeTitle(`${"a".repeat(63)} two`)).toBe("a".repeat(63));
1518
});
1619

‎src/agents/worktrees/name.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,13 @@ export function slugifyWorktreeTitle(title: string): string | undefined {
99
.toLowerCase()
1010
.replace(/&/g, " and ")
1111
.replace(/[^a-z0-9]+/g, "-")
12-
.replace(/^-+|-+$/g, "")
13-
.slice(0, WORKTREE_NAME_MAX_LENGTH)
14-
.replace(/-+$/g, "");
15-
return slug || undefined;
12+
.replace(/^-+|-+$/g, "");
13+
if (slug.length <= WORKTREE_NAME_MAX_LENGTH) {
14+
return slug || undefined;
15+
}
16+
const truncated = slug.slice(0, WORKTREE_NAME_MAX_LENGTH);
17+
const wordBoundary = truncated.lastIndexOf("-");
18+
return wordBoundary > 0 ? truncated.slice(0, wordBoundary) : truncated;
1619
}
1720

1821
/** Maps names that can converge after a `-1000` suffix into one allocation lane. */

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

Lines changed: 67 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { stripInboundMetadata } from "../auto-reply/reply/strip-inbound-meta.js"
99
import { updateSessionEntry } from "../config/sessions/session-accessor.js";
1010
import type { SessionEntry } from "../config/sessions/types.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
12+
import { withTimeout } from "../infra/fs-safe.js";
1213
import { parseAgentSessionKey } from "../sessions/session-key-utils.js";
1314
import { getOrCreatePromise } from "../shared/lazy-promise.js";
1415
import { stripInlineDirectiveTagsForDisplay } from "../utils/directive-tags.js";
@@ -29,6 +30,8 @@ type DashboardSessionTitleModelEntry = Pick<
2930

3031
const DASHBOARD_SESSION_TITLE_MAX_CHARS = 60;
3132
const DASHBOARD_SESSION_TITLE_SOURCE_MAX_CHARS = 1_000;
33+
const WORKTREE_SESSION_TITLE_TIMEOUT_MS = 8_000;
34+
const WORKTREE_SESSION_TITLE_ATTEMPT_TIMEOUT_MS = 4_000;
3235
const DASHBOARD_SESSION_TITLE_PROMPT =
3336
"Generate a concise session title (3-6 words, max 60 characters) from the user's first message. Use the same language as the message, in sentence case: capitalize only the first word and words that language always capitalizes. No emoji. Return only the title.";
3437

@@ -160,6 +163,7 @@ async function generateDashboardSessionTitle(params: {
160163
entry?: DashboardSessionTitleModelEntry;
161164
userMessage: string;
162165
attachments?: readonly ChatAttachment[];
166+
timeoutMs?: number;
163167
}): Promise<string | null> {
164168
const sourceText = buildDashboardSessionTitleSource({
165169
message: params.userMessage,
@@ -200,10 +204,65 @@ async function generateDashboardSessionTitle(params: {
200204
...(preferredProfile ? { preferredProfile } : {}),
201205
normalizeLabel: normalizeDashboardSessionTitle,
202206
maxLength: DASHBOARD_SESSION_TITLE_MAX_CHARS,
207+
...(params.timeoutMs ? { timeoutMs: params.timeoutMs } : {}),
203208
});
204209
return generated ? normalizeDashboardSessionTitle(generated) : null;
205210
}
206211

212+
export function prepareWorktreeSessionTitle(params: {
213+
cfg: OpenClawConfig;
214+
agentId: string;
215+
userMessage: string;
216+
attachments?: readonly ChatAttachment[];
217+
onError: (error: unknown) => void;
218+
}) {
219+
const source = buildDashboardSessionTitleSource({
220+
message: params.userMessage,
221+
attachments: params.attachments,
222+
});
223+
if (!source) {
224+
return undefined;
225+
}
226+
const generated = withTimeout(
227+
generateDashboardSessionTitle({
228+
...params,
229+
timeoutMs: WORKTREE_SESSION_TITLE_ATTEMPT_TIMEOUT_MS,
230+
}),
231+
WORKTREE_SESSION_TITLE_TIMEOUT_MS,
232+
"worktree title generation",
233+
).catch((error: unknown) => {
234+
params.onError(error);
235+
return null;
236+
});
237+
return {
238+
source,
239+
generated,
240+
persist: async (
241+
agentId: string,
242+
entry: SessionEntry,
243+
sessionKey: string,
244+
storePath: string,
245+
) => {
246+
try {
247+
const attempt = await maybeGenerateSessionTitle({
248+
cfg: params.cfg,
249+
agentId,
250+
entry,
251+
sessionId: entry.sessionId,
252+
sessionKey,
253+
storePath,
254+
userMessage: source,
255+
titleGeneration: generated,
256+
});
257+
return attempt.kind === "persisted";
258+
} catch (error) {
259+
params.onError(error);
260+
return false;
261+
}
262+
},
263+
};
264+
}
265+
207266
export async function maybeGenerateDashboardSessionTitle(params: {
208267
cfg: OpenClawConfig;
209268
agentId: string;
@@ -238,6 +297,7 @@ export async function maybeGenerateSessionTitle(params: {
238297
storePath: string;
239298
currentUserMessage?: string;
240299
userMessage: string;
300+
titleGeneration?: Promise<string | null>;
241301
}): Promise<SessionTitleAttempt> {
242302
if (hasExplicitSessionName(params.entry) || params.entry?.sessionId !== params.sessionId) {
243303
return { kind: "skipped" };
@@ -278,12 +338,13 @@ export async function maybeGenerateSessionTitle(params: {
278338
sessionTitleRequests,
279339
requestKey,
280340
async () => {
281-
const displayName = await generateDashboardSessionTitle({
282-
cfg: params.cfg,
283-
agentId: params.agentId,
284-
entry: params.entry,
285-
userMessage: sourceText,
286-
});
341+
const displayName = await (params.titleGeneration ??
342+
generateDashboardSessionTitle({
343+
cfg: params.cfg,
344+
agentId: params.agentId,
345+
entry: params.entry,
346+
userMessage: sourceText,
347+
}));
287348
if (!displayName) {
288349
return false;
289350
}

‎src/gateway/server-methods/chat-send-agent-dispatch.ts‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -516,17 +516,18 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
516516
// in chat-send-admission.ts: unreferenced staged media is discarded.
517517
void discardPreparedChatSendAttachments(attachments.offloadedRefs);
518518
}
519-
// Cosmetic title work starts only after the accepted turn finishes. Starting it
520-
// before dispatch can make a cold utility runtime starve the user's real turn.
521-
scheduleChatDashboardSessionTitle({
522-
admittedSessionId,
523-
agentId,
524-
cfg,
525-
context,
526-
request,
527-
sessionKey,
528-
sessionLoadOptions: session.sessionLoadOptions,
529-
storePath: session.storePath,
530-
});
531519
});
520+
// Title work starts at turn admission, concurrently with the launched run. It must never run
521+
// serially before dispatch (a cold utility runtime can starve the turn) or wait for completion
522+
// (long or interrupted first turns would silently remain untitled, and restart loses the chain).
523+
scheduleChatDashboardSessionTitle({
524+
admittedSessionId,
525+
agentId,
526+
cfg,
527+
context,
528+
request,
529+
sessionKey,
530+
sessionLoadOptions: session.sessionLoadOptions,
531+
storePath: session.storePath,
532+
});
532533
}

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

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
} from "../../projects/project-registry.js";
2828
import { normalizeAgentId, parseAgentSessionKey } from "../../routing/session-key.js";
2929
import { resolveUserPath } from "../../utils.js";
30-
import { buildDashboardSessionTitleSource } from "../dashboard-session-title.js";
30+
import { prepareWorktreeSessionTitle } from "../dashboard-session-title.js";
3131
import { ADMIN_SCOPE, authorizeOperatorScopesForRequiredScope } from "../method-scopes.js";
3232
import { buildDashboardSessionKey, createGatewaySession } from "../session-create-service.js";
3333
import { ensureSessionGroupRegistered } from "../session-groups.js";
@@ -234,6 +234,22 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
234234
);
235235
return;
236236
}
237+
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
242+
? 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)}`),
251+
})
252+
: undefined;
237253
let projectRoot: string | undefined;
238254
if (requestedProjectId) {
239255
const project = resolveProjectRegistry(cfg, requestedProjectId);
@@ -423,17 +439,14 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
423439
}
424440
sessionWorktree = existing;
425441
} else {
442+
const generatedTitle = await worktreeTitle?.generated;
426443
sessionWorktree = await managedWorktrees.create({
427444
repoRoot: workspace,
428445
ownerKind: "session",
429446
ownerId: lifecycleTarget.key,
430447
name: requestedWorktreeName,
431448
suggestedName: slugifyWorktreeTitle(
432-
normalizeOptionalString(p.label) ??
433-
buildDashboardSessionTitleSource({
434-
message: initialMessage ?? "",
435-
attachments: initialAttachments,
436-
}),
449+
explicitSessionLabel ?? generatedTitle ?? worktreeTitle?.source ?? "",
437450
),
438451
baseRef: requestedWorktreeBaseRef,
439452
// Checkout hooks and .openclaw/worktree-setup.sh run repo code; keep them
@@ -577,6 +590,9 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
577590
if (!authority.hasActive()) {
578591
return;
579592
}
593+
if (await worktreeTitle?.persist(agentId, entry, key, storePath)) {
594+
emitSessionsChanged(context, { sessionKey: key, agentId, reason: "chat.title" });
595+
}
580596
await captureCreatedSessionDiffBaseline({ key, agentId, cfg, entry, storePath });
581597
if (hasInitialTurn) {
582598
if (!authority.hasActive()) {

0 commit comments

Comments
 (0)