Skip to content

Commit 4874083

Browse files
committed
fix(sessions): preserve naming and startup progress
1 parent cbb8926 commit 4874083

26 files changed

Lines changed: 1074 additions & 449 deletions

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ The **+** in the sidebar's **Sessions** toolbar opens a full-page draft at `/new
295295

296296
The folder defaults to the agent workspace. Write-scoped connections can browse, restore recent Gateway folders, and start sessions anywhere inside a configured agent workspace; another absolute Gateway path requires `operator.admin` but can run directly without being a Git checkout. Local placement keeps the optional **Worktree** control with a base-branch picker backed by `worktrees.branches` (no fetch) and an optional worktree name (the branch becomes `openclaw/<name>`). Choosing either a device or cloud profile forces a managed worktree from the selected Gateway source. **Start in terminal** is available only for local placement.
297297

298-
For local worktree sessions, sending the first message opens the admitted session before naming, checkout, and setup finish. The chat shows the submitted message and preparation stages. Setup failures remain visible in that session; send a retry there after correcting the problem. Stopping during setup cancels preparation without starting the agent.
298+
For local worktree sessions, sending the first message opens the admitted session before naming, checkout, and setup finish. The chat shows the submitted message and preparation stages. A generated title is saved as soon as naming completes, independently of checkout and setup. Setup failures remain visible in that session; send a retry there after correcting the problem. The retry reuses the saved title. If naming itself fails, another attempt uses the original first prompt, including text attachments. Stopping during setup cancels preparation without starting the agent. Steering an active run keeps its progress visible, and delayed history cannot replace a newer startup stage or restore startup labels after activity begins.
299299

300300
For a remote target, the Control UI creates the managed-worktree session with an empty initial message and no `execNode`, dispatches it by exact `deviceId`, `autoDevice: true`, or `profileId` (plus an optional cloud machine class), waits for active placement, and then sends the first message and attachments with the same idempotency key used by recovery. Explicit and automatic device dispatch require `operator.write`; cloud profile dispatch requires `operator.admin`. The composer footer chooses the new session's model and reasoning level.
301301

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

Lines changed: 77 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
11
// Dashboard title tests cover eligibility, routing, normalization, and guarded persistence.
2-
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33

44
const generateConversationLabelWithFallback = vi.hoisted(() => vi.fn());
55
const resolveUtilityModelRefForAgent = vi.hoisted(() => vi.fn());
66
const readSessionTitleFieldsFromTranscript = vi.hoisted(() => vi.fn());
77
const updateSessionEntry = vi.hoisted(() => vi.fn());
8+
const loadSessionEntry = vi.hoisted(() => vi.fn());
89

910
vi.mock("../agents/utility-model.js", () => ({ resolveUtilityModelRefForAgent }));
1011
vi.mock("../auto-reply/reply/conversation-label-generator.js", () => ({
1112
generateConversationLabelWithFallback,
1213
}));
13-
vi.mock("../config/sessions/session-accessor.js", () => ({ updateSessionEntry }));
14+
vi.mock("../config/sessions/session-accessor.js", () => ({
15+
patchSessionEntryCore: updateSessionEntry,
16+
loadSessionEntry,
17+
}));
1418
vi.mock("./session-transcript-title-reader.js", () => ({ readSessionTitleFieldsFromTranscript }));
1519

1620
import type { SessionEntry } from "../config/sessions/types.js";
1721
import type { OpenClawConfig } from "../config/types.openclaw.js";
22+
import { createDeferredCore } from "../shared/deferred.js";
1823
import type { ChatAttachment } from "./chat-attachments.js";
1924
import {
2025
buildDashboardSessionTitleSource,
26+
generateWorktreeSessionTitle,
2127
maybeGenerateDashboardSessionTitle,
2228
} from "./dashboard-session-title.js";
2329

@@ -30,6 +36,7 @@ const baseEntry: SessionEntry = {
3036
};
3137

3238
function titleParams(entry: SessionEntry | undefined = baseEntry) {
39+
loadSessionEntry.mockReturnValue(entry);
3340
return {
3441
cfg,
3542
agentId: "main",
@@ -44,7 +51,9 @@ function titleParams(entry: SessionEntry | undefined = baseEntry) {
4451
function mockSessionUpdate(current: SessionEntry): void {
4552
updateSessionEntry.mockImplementation(async (_scope, update) => {
4653
const patch = await update({ ...current });
47-
return patch ? { ...current, ...patch } : current;
54+
const result = patch ? { ...current, ...patch } : current;
55+
loadSessionEntry.mockReturnValue(result);
56+
return result;
4857
});
4958
}
5059

@@ -53,6 +62,7 @@ describe("maybeGenerateDashboardSessionTitle", () => {
5362
generateConversationLabelWithFallback.mockReset();
5463
resolveUtilityModelRefForAgent.mockReset();
5564
updateSessionEntry.mockReset();
65+
loadSessionEntry.mockReset().mockReturnValue(baseEntry);
5666
readSessionTitleFieldsFromTranscript.mockReset();
5767
readSessionTitleFieldsFromTranscript.mockReturnValue({
5868
firstUserMessage: null,
@@ -63,6 +73,8 @@ describe("maybeGenerateDashboardSessionTitle", () => {
6373
mockSessionUpdate(baseEntry);
6474
});
6575

76+
afterEach(() => vi.useRealTimers());
77+
6678
it("generates and persists a dashboard display name", async () => {
6779
await expect(maybeGenerateDashboardSessionTitle(titleParams())).resolves.toBe(true);
6880

@@ -241,9 +253,11 @@ describe("maybeGenerateDashboardSessionTitle", () => {
241253
["channel name", { entry: { ...baseEntry, groupChannel: "releases" } }],
242254
["space name", { entry: { ...baseEntry, space: "Engineering" } }],
243255
])("skips %s", async (_name, override) => {
244-
await expect(
245-
maybeGenerateDashboardSessionTitle({ ...titleParams(), ...override }),
246-
).resolves.toBe(false);
256+
const params = { ...titleParams(), ...override };
257+
loadSessionEntry.mockReturnValue(params.entry);
258+
await expect(maybeGenerateDashboardSessionTitle({ ...params, entry: baseEntry })).resolves.toBe(
259+
false,
260+
);
247261

248262
expect(generateConversationLabelWithFallback).not.toHaveBeenCalled();
249263
expect(updateSessionEntry).not.toHaveBeenCalled();
@@ -317,6 +331,63 @@ describe("maybeGenerateDashboardSessionTitle", () => {
317331
expect(generateConversationLabelWithFallback).toHaveBeenCalledOnce();
318332
});
319333

334+
it("bounds a worktree join without cancelling the canonical background naming request", async () => {
335+
vi.useFakeTimers();
336+
const naming = createDeferredCore<string>();
337+
generateConversationLabelWithFallback.mockReturnValue(naming.promise);
338+
const params = titleParams();
339+
const background = maybeGenerateDashboardSessionTitle(params);
340+
const onError = vi.fn();
341+
const onPersisted = vi.fn();
342+
const worktree = generateWorktreeSessionTitle({
343+
...params,
344+
sessionKey: "dashboard:chat-1",
345+
onError,
346+
onPersisted,
347+
});
348+
await vi.advanceTimersByTimeAsync(8_000);
349+
await expect(worktree).resolves.toBeUndefined();
350+
expect(onError).toHaveBeenCalledOnce();
351+
naming.resolve("Release Planning");
352+
await expect(background).resolves.toBe(true);
353+
expect(generateConversationLabelWithFallback).toHaveBeenCalledOnce();
354+
expect(onPersisted).not.toHaveBeenCalled();
355+
expect(loadSessionEntry()).toMatchObject({ displayName: "Release Planning" });
356+
});
357+
358+
it("revalidates worktree authority inside the final title commit", async () => {
359+
const writePrepared = createDeferredCore();
360+
const releaseWrite = createDeferredCore();
361+
let active = true;
362+
const commitGuard = () => {
363+
if (!active) {
364+
throw new Error("run closed");
365+
}
366+
};
367+
updateSessionEntry.mockImplementation(async (_scope, update, options) => {
368+
const patch = await update({ ...baseEntry });
369+
writePrepared.resolve();
370+
await releaseWrite.promise;
371+
options.assertCommitAllowed?.();
372+
loadSessionEntry.mockReturnValue({ ...baseEntry, ...patch });
373+
return loadSessionEntry();
374+
});
375+
const onPersisted = vi.fn();
376+
const worktree = generateWorktreeSessionTitle({
377+
...titleParams(),
378+
commitGuard,
379+
onError: vi.fn(),
380+
onPersisted,
381+
});
382+
const rejected = expect(worktree).rejects.toThrow("run closed");
383+
await writePrepared.promise;
384+
active = false;
385+
releaseWrite.resolve();
386+
await rejected;
387+
expect(loadSessionEntry()).not.toHaveProperty("displayName");
388+
expect(onPersisted).not.toHaveBeenCalled();
389+
});
390+
320391
it("deduplicates concurrent title requests for one session generation", async () => {
321392
let resolveLabel!: (value: string) => void;
322393
generateConversationLabelWithFallback.mockReturnValue(

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

Lines changed: 77 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ import { resolveSessionRuntimeOverrideForProvider } from "../agents/session-runt
66
import { resolveUtilityModelRefForAgent } from "../agents/utility-model.js";
77
import { generateConversationLabelWithFallback } from "../auto-reply/reply/conversation-label-generator.js";
88
import { stripInboundMetadata } from "../auto-reply/reply/strip-inbound-meta.js";
9-
import { updateSessionEntry } from "../config/sessions/session-accessor.js";
9+
import { loadSessionEntry, patchSessionEntryCore } from "../config/sessions/session-accessor.js";
1010
import type { SessionEntry } from "../config/sessions/types.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
1212
import { withTimeout } from "../infra/fs-safe.js";
1313
import { parseAgentSessionKey } from "../sessions/session-key-utils.js";
1414
import { getOrCreatePromise } from "../shared/lazy-promise.js";
1515
import { isValidAttachmentBase64, type ChatAttachment } from "./chat-attachments.js";
16+
import { resolveStoredSessionKeyForAgentStore } from "./session-store-key.js";
1617
import { readSessionTitleFieldsFromTranscript } from "./session-transcript-title-reader.js";
1718

1819
type DashboardSessionTitleModelEntry = Pick<
@@ -97,14 +98,14 @@ type SessionTitleAttempt =
9798
| { kind: "skipped" }
9899
| { kind: "in-flight"; settled: Promise<boolean> };
99100

101+
export function resolveExplicitSessionName(entry: SessionEntry | undefined): string | undefined {
102+
return [entry?.label, entry?.displayName, entry?.subject, entry?.groupChannel, entry?.space]
103+
.map((value) => value?.trim())
104+
.find(Boolean);
105+
}
106+
100107
export function hasExplicitSessionName(entry: SessionEntry | undefined): boolean {
101-
return Boolean(
102-
entry?.label?.trim() ||
103-
entry?.displayName?.trim() ||
104-
entry?.subject?.trim() ||
105-
entry?.groupChannel?.trim() ||
106-
entry?.space?.trim(),
107-
);
108+
return Boolean(resolveExplicitSessionName(entry));
108109
}
109110

110111
function isDashboardSessionKey(sessionKey: string): boolean {
@@ -208,63 +209,35 @@ async function generateDashboardSessionTitle(params: {
208209
return generated ? normalizeDashboardSessionTitle(generated) : null;
209210
}
210211

211-
export function prepareWorktreeSessionTitle(params: {
212-
cfg: OpenClawConfig;
213-
agentId: string;
214-
entry?: DashboardSessionTitleModelEntry | null;
215-
userMessage: string;
216-
attachments?: readonly ChatAttachment[];
217-
onError: (error: unknown) => void;
218-
}) {
219-
if (params.entry === null) {
220-
return undefined;
221-
}
222-
const source = buildDashboardSessionTitleSource({
223-
message: params.userMessage,
224-
attachments: params.attachments,
212+
/** Worktree callers bound their own wait without cancelling another naming owner's request. */
213+
export async function generateWorktreeSessionTitle(
214+
params: Parameters<typeof maybeGenerateSessionTitle>[0] & {
215+
onError: (error: unknown) => void;
216+
onPersisted: () => void;
217+
},
218+
): Promise<string | undefined> {
219+
const request = maybeGenerateSessionTitle({ ...params, worktree: true }).then(async (attempt) => {
220+
if (attempt.kind === "in-flight") {
221+
await attempt.settled;
222+
} else if (attempt.kind === "persisted") {
223+
params.onPersisted();
224+
}
225225
});
226-
if (!source) {
227-
return undefined;
228-
}
229-
const generated = withTimeout(
230-
generateDashboardSessionTitle({
231-
...params,
232-
entry: params.entry ?? undefined,
233-
timeoutMs: WORKTREE_SESSION_TITLE_ATTEMPT_TIMEOUT_MS,
234-
}),
235-
WORKTREE_SESSION_TITLE_TIMEOUT_MS,
236-
"worktree title generation",
237-
).catch((error: unknown) => {
226+
try {
227+
await withTimeout(request, WORKTREE_SESSION_TITLE_TIMEOUT_MS, "worktree title generation");
228+
} catch (error) {
238229
params.onError(error);
239-
return null;
230+
}
231+
params.commitGuard?.();
232+
const current = loadSessionEntry({
233+
agentId: params.agentId,
234+
sessionKey: resolveStoredSessionKeyForAgentStore(params),
235+
storePath: params.storePath,
240236
});
241-
return {
242-
source,
243-
generated,
244-
persist: async (
245-
agentId: string,
246-
entry: SessionEntry,
247-
sessionKey: string,
248-
storePath: string,
249-
) => {
250-
try {
251-
const attempt = await maybeGenerateSessionTitle({
252-
cfg: params.cfg,
253-
agentId,
254-
entry,
255-
sessionId: entry.sessionId,
256-
sessionKey,
257-
storePath,
258-
userMessage: source,
259-
titleGeneration: generated,
260-
});
261-
return attempt.kind === "persisted";
262-
} catch (error) {
263-
params.onError(error);
264-
return false;
265-
}
266-
},
267-
};
237+
if (current?.sessionId !== params.sessionId) {
238+
throw new Error("Session changed while naming its worktree; retry from the current session.");
239+
}
240+
return resolveExplicitSessionName(current);
268241
}
269242

270243
export async function maybeGenerateDashboardSessionTitle(params: {
@@ -301,13 +274,17 @@ export async function maybeGenerateSessionTitle(params: {
301274
storePath: string;
302275
currentUserMessage?: string;
303276
userMessage: string;
304-
titleGeneration?: Promise<string | null>;
277+
worktree?: boolean;
278+
commitGuard?: () => void;
305279
}): Promise<SessionTitleAttempt> {
306-
if (hasExplicitSessionName(params.entry) || params.entry?.sessionId !== params.sessionId) {
280+
const sessionKey = resolveStoredSessionKeyForAgentStore(params);
281+
const scope = { agentId: params.agentId, sessionKey, storePath: params.storePath };
282+
const entry = loadSessionEntry(scope);
283+
if (hasExplicitSessionName(entry) || entry?.sessionId !== params.sessionId) {
307284
return { kind: "skipped" };
308285
}
309286

310-
const requestKey = `${params.storePath}\0${params.sessionKey}\0${params.sessionId}`;
287+
const requestKey = `${params.storePath}\0${sessionKey}\0${params.sessionId}`;
311288
const existing = sessionTitleRequests.get(requestKey);
312289
if (existing) {
313290
return { kind: "in-flight", settled: existing };
@@ -317,56 +294,61 @@ export async function maybeGenerateSessionTitle(params: {
317294
// title the session from its original user message when the transcript owns it.
318295
const transcriptSource = readSessionTitleFieldsFromTranscript({
319296
agentId: params.agentId,
320-
sessionEntry: params.entry,
297+
sessionEntry: entry,
321298
sessionId: params.sessionId,
322-
sessionKey: params.sessionKey,
299+
sessionKey,
323300
storePath: params.storePath,
324301
}).firstUserMessage;
325302
const transcriptText = transcriptSource ? stripInboundMetadata(transcriptSource).trim() : "";
326303
const currentText = params.currentUserMessage?.trim() ?? "";
327304
// A first-turn transcript may win the persistence race before title work starts.
328305
// When it is the current turn, retain the supplied attachment-enriched source.
329306
const sourceText =
330-
!transcriptText || (currentText && currentText === transcriptText)
307+
entry.pendingWorktree?.titleSource?.trim() ??
308+
(!transcriptText || (currentText && currentText === transcriptText)
331309
? params.userMessage.trim()
332-
: transcriptText;
310+
: transcriptText);
333311
if (!sourceText) {
334312
return { kind: "skipped" };
335313
}
336314

337315
const request = getOrCreatePromise(
338316
sessionTitleRequests,
339317
requestKey,
340-
async () => {
341-
const displayName = await (params.titleGeneration ??
342-
generateDashboardSessionTitle({
318+
() =>
319+
Promise.resolve().then(async () => {
320+
params.commitGuard?.();
321+
const generation = generateDashboardSessionTitle({
343322
cfg: params.cfg,
344323
agentId: params.agentId,
345-
entry: params.entry,
324+
entry: params.entry ?? entry,
346325
userMessage: sourceText,
347-
}));
348-
if (!displayName) {
349-
return false;
350-
}
326+
...(params.worktree ? { timeoutMs: WORKTREE_SESSION_TITLE_ATTEMPT_TIMEOUT_MS } : {}),
327+
});
328+
const displayName = await (params.worktree
329+
? withTimeout(generation, WORKTREE_SESSION_TITLE_TIMEOUT_MS, "worktree title generation")
330+
: generation);
331+
if (!displayName) {
332+
return false;
333+
}
351334

352-
let persisted = false;
353-
await updateSessionEntry(
354-
{
355-
agentId: params.agentId,
356-
sessionKey: params.sessionKey,
357-
storePath: params.storePath,
358-
},
359-
(current) => {
360-
if (current.sessionId !== params.sessionId || hasExplicitSessionName(current)) {
361-
return null;
362-
}
363-
persisted = true;
364-
return { displayName };
365-
},
366-
{ requireWriteSuccess: true },
367-
);
368-
return persisted;
369-
},
335+
let persisted = false;
336+
await patchSessionEntryCore(
337+
scope,
338+
(current) => {
339+
if (current.sessionId !== params.sessionId || hasExplicitSessionName(current)) {
340+
return null;
341+
}
342+
persisted = true;
343+
return { displayName };
344+
},
345+
{
346+
requireWriteSuccess: true,
347+
...(params.commitGuard ? { assertCommitAllowed: params.commitGuard } : {}),
348+
},
349+
);
350+
return persisted;
351+
}),
370352
{ evictOnSettled: true },
371353
);
372354
return (await request) ? { kind: "persisted" } : { kind: "skipped" };

0 commit comments

Comments
 (0)