Skip to content

Commit 25083b5

Browse files
feat(ui): start named sessions with /new --name
1 parent 2993b39 commit 25083b5

10 files changed

Lines changed: 285 additions & 46 deletions

File tree

‎docs/tools/slash-commands.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ plugins.
171171
<Accordion title="Sessions and runs">
172172
| Command | Description |
173173
| --- | --- |
174-
| `/new [model]` | Archive the current session and start a fresh one; in Control UI, optional text names a newly created dashboard session instead |
174+
| `/new [model]` | Archive the current session and start a fresh one; Control UI also supports `/new --name <title>` for a labeled dashboard session |
175175
| `/reset [soft [message]]` | Reset the current session in place. `soft` keeps the transcript, drops reused CLI backend session ids, and reruns startup |
176176
| `/name <title>` | Name or rename the current session. Omit the title to see the current name and a suggestion |
177177
| `/compact [instructions]` | Compact the session context. See [Compaction](/concepts/compaction) |
@@ -183,12 +183,14 @@ plugins.
183183

184184
<Note>
185185
Control UI intercepts typed `/new` to create and switch to a fresh
186-
dashboard session. When `/new <name>` creates a new dashboard session,
187-
`<name>` becomes its session name; use `/model` to change models and
188-
`/name <title>` to rename the current session. When `session.dmScope:
189-
"main"` is configured and the current parent is the agent's main session,
190-
typed `/new` resets the main session in place instead. Typed `/reset`
191-
still runs the Gateway's in-place reset.
186+
dashboard session. Use `/new --name <title>` to name the new session;
187+
quotes around a multi-word title are optional. Bare `/new` and other
188+
`/new <text>` forms keep the existing anonymous dashboard-session
189+
behavior. Use `/model` to change models and `/name <title>` to rename the
190+
current session. When `session.dmScope: "main"` is configured and the
191+
current parent is the agent's main session, typed `/new` resets the main
192+
session in place instead. Typed `/reset` still runs the Gateway's in-place
193+
reset.
192194
</Note>
193195

194196
</Accordion>
@@ -499,7 +501,7 @@ See [BTW side questions](/tools/btw) for the full behavior.
499501
</Accordion>
500502
<Accordion title="Argument notes">
501503
- Commands accept an optional `:` between the command and args (`/think: high`, `/send: on`).
502-
- Outside Control UI, `/new <model>` accepts a model alias, `provider/model`, or a provider name (fuzzy match); if no match, the text is treated as the message body. In Control UI, when `/new <name>` creates a new dashboard session, `<name>` becomes its session name; use `/model` to switch models.
504+
- Outside Control UI, `/new <model>` accepts a model alias, `provider/model`, or a provider name (fuzzy match); if no match, the text is treated as the message body. In Control UI, `/new --name <title>` labels the new dashboard session; other `/new <text>` forms keep the existing anonymous-create behavior. Use `/model` to switch models.
503505
- `/allowlist add|remove` requires `commands.config: true` and honors channel `configWrites`.
504506

505507
</Accordion>

‎ui/src/lib/sessions/index.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ export type SessionRunTerminal = {
8282
endedAt: number;
8383
};
8484

85+
export type SessionCreateOptions = {
86+
/** Runs after the Gateway returns the key and before the canonical list refresh publishes. */
87+
onCreated?: (key: string) => void;
88+
};
89+
8590
export type SessionPatch = {
8691
label?: string | null;
8792
category?: string | null;
@@ -174,8 +179,11 @@ export type SessionCapability = {
174179
reconcileChanged: (payload: unknown, options?: SessionReconcileOptions) => SessionChangedResult;
175180
reconcileRunTerminal: (terminal: SessionRunTerminal) => boolean;
176181
refresh: (options?: SessionRefreshOptions) => Promise<void>;
177-
createResult: (params?: SessionCreateParams) => Promise<SessionCreateOutcome | null>;
178-
create: (params?: SessionCreateParams) => Promise<string | null>;
182+
createResult: (
183+
params?: SessionCreateParams,
184+
options?: SessionCreateOptions,
185+
) => Promise<SessionCreateOutcome | null>;
186+
create: (params?: SessionCreateParams, options?: SessionCreateOptions) => Promise<string | null>;
179187
patch: (
180188
key: string,
181189
patch: SessionPatch,
@@ -792,7 +800,10 @@ export function createSessionCapability(gateway: SessionGateway): SessionCapabil
792800
return request;
793801
};
794802

795-
const createResult = async (params: SessionCreateParams = {}) => {
803+
const createResult = async (
804+
params: SessionCreateParams = {},
805+
options: SessionCreateOptions = {},
806+
) => {
796807
const scope = captureConnection();
797808
if (!scope || state.loading) {
798809
return null;
@@ -806,6 +817,7 @@ export function createSessionCapability(gateway: SessionGateway): SessionCapabil
806817
if (!isCurrentConnection(scope)) {
807818
return null;
808819
}
820+
options.onCreated?.(result.key);
809821
await refresh({ agentId: params.agentId, force: true });
810822
if (!isCurrentConnection(scope)) {
811823
return null;
@@ -824,8 +836,8 @@ export function createSessionCapability(gateway: SessionGateway): SessionCapabil
824836
}
825837
};
826838

827-
const create = async (params: SessionCreateParams = {}) =>
828-
(await createResult(params))?.key ?? null;
839+
const create = async (params: SessionCreateParams = {}, options: SessionCreateOptions = {}) =>
840+
(await createResult(params, options))?.key ?? null;
829841

830842
const LEGACY_GROUPS_STORAGE_KEY = "openclaw:sessions:custom-groups";
831843
let groupsLoadedEpoch = -1;

‎ui/src/pages/chat/chat-commands.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export type ChatCommandHost = Parameters<typeof handleAbortChat>[0] &
5757
chatModelCatalog: ModelCatalogEntry[];
5858
sessionsResult?: SessionsListResult | null;
5959
sessionsResultAgentId?: string | null;
60-
createChatSession?: (params?: { label?: string }) => Promise<void>;
60+
createChatSession?: (params?: { label?: string }) => Promise<boolean | void>;
6161
exportCurrentChat?: () => Promise<void> | void;
6262
refreshCurrentSessionTools?: () => Promise<void>;
6363
refreshCurrentChat?: () => Promise<void>;
@@ -196,6 +196,30 @@ export function shouldQueueLocalSlashCommand(name: string): boolean {
196196
return !["stop", "export-session", "steer", "redirect", "new"].includes(name);
197197
}
198198

199+
type NewSessionCommand =
200+
| { kind: "anonymous" }
201+
| { kind: "named"; label: string }
202+
| { kind: "invalid" };
203+
204+
function parseNewSessionCommand(args: string): NewSessionCommand {
205+
const match = /^--name(?:\s+(.*))?$/su.exec(args.trim());
206+
if (!match) {
207+
return { kind: "anonymous" };
208+
}
209+
let label = (match[1] ?? "").trim();
210+
if (!label) {
211+
return { kind: "invalid" };
212+
}
213+
const quote = label[0];
214+
if (quote === '"' || quote === "'") {
215+
if (label.at(-1) !== quote) {
216+
return { kind: "invalid" };
217+
}
218+
label = label.slice(1, -1).trim();
219+
}
220+
return label ? { kind: "named", label } : { kind: "invalid" };
221+
}
222+
199223
export async function dispatchChatSlashCommand(
200224
host: ChatCommandHost,
201225
name: string,
@@ -211,9 +235,16 @@ export async function dispatchChatSlashCommand(
211235
setChatCommandError(host, "New Chat is unavailable.");
212236
return "failed";
213237
}
214-
const label = args.trim();
215-
await host.createChatSession(label ? { label } : undefined);
216-
return "completed";
238+
const command = parseNewSessionCommand(args);
239+
if (command.kind === "invalid") {
240+
setChatCommandError(host, "Usage: /new --name <title>");
241+
return "failed";
242+
}
243+
const created =
244+
command.kind === "named"
245+
? await host.createChatSession({ label: command.label })
246+
: await host.createChatSession();
247+
return created === false ? "failed" : "completed";
217248
}
218249
case "reset":
219250
await opts.sendResetMessage(args ? `/reset ${args}` : "/reset", opts);

‎ui/src/pages/chat/chat-pane.test.ts‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,18 @@ import type {
1212
TaskSuggestionsListResult,
1313
} from "../../../../packages/gateway-protocol/src/index.js";
1414
import type { GatewayBrowserClient } from "../../api/gateway.ts";
15+
import type { SessionsListResult } from "../../api/types.ts";
1516
import type { ApplicationContext } from "../../app/context.ts";
1617
import { buildCatalogSessionKey, type CatalogSessionKey } from "../../lib/sessions/catalog-key.ts";
17-
import type { SessionCapability } from "../../lib/sessions/index.ts";
18+
import { createSessionCapability, type SessionCapability } from "../../lib/sessions/index.ts";
1819
import "./chat-pane.ts";
1920
import type { ChatPageHost } from "./chat-state.ts";
2021
import { createSessionWorkspaceProps } from "./components/chat-session-workspace.ts";
2122
import type { SidebarContent } from "./components/chat-sidebar.ts";
2223

2324
type TestChatPane = HTMLElement & {
2425
active: boolean;
26+
applyGatewaySnapshot: (snapshot: ApplicationContext["gateway"]["snapshot"]) => void;
2527
chatState: { attach: (state: ChatPageHost) => void };
2628
context: ApplicationContext;
2729
state: ChatPageHost;
@@ -35,7 +37,11 @@ type TestChatPane = HTMLElement & {
3537
handleTaskSuggestionEvent: (event: TaskSuggestionEvent) => void;
3638
refreshTaskSuggestions: () => Promise<void>;
3739
taskSuggestions: TaskSuggestion[];
38-
onPaneSessionChange?: (paneId: string, sessionKey: string) => void;
40+
onPaneSessionChange?: (
41+
paneId: string,
42+
sessionKey: string,
43+
options?: { replace?: boolean },
44+
) => void;
3945
sessionKey: string;
4046
catalogSession: SessionCatalogSession | null;
4147
catalogItemMessage: (
@@ -94,6 +100,7 @@ function createSessionContext(
94100
hello: { features: { methods: ["taskSuggestions.list"] } },
95101
},
96102
},
103+
config: { current: { terminalEnabled: false } },
97104
agents: { state: { agentsList: null } },
98105
sessions,
99106
} as unknown as ApplicationContext;
@@ -140,6 +147,35 @@ function createTestChatPane(params: { client: GatewayBrowserClient; sessions: Se
140147
}
141148

142149
describe("chat pane initialization", () => {
150+
it("keeps the connected client while canonicalizing the initial main route", () => {
151+
const client = {} as GatewayBrowserClient;
152+
const sessions = {} as SessionCapability;
153+
const { pane, state } = createTestChatPane({ client, sessions });
154+
const navigate = vi.fn();
155+
const snapshot = {
156+
client,
157+
connected: true,
158+
hello: {
159+
snapshot: {
160+
sessionDefaults: {
161+
defaultAgentId: "main",
162+
mainKey: "main",
163+
mainSessionKey: "agent:main:main",
164+
},
165+
},
166+
},
167+
} as unknown as ApplicationContext["gateway"]["snapshot"];
168+
pane.sessionKey = "main";
169+
state.sessionKey = "main";
170+
pane.connectedClient = null;
171+
pane.onPaneSessionChange = navigate;
172+
173+
pane.applyGatewaySnapshot(snapshot);
174+
175+
expect(navigate).toHaveBeenCalledWith("single", "agent:main:main", { replace: true });
176+
expect(pane.connectedClient).toBe(client);
177+
});
178+
143179
it("sets the pane route before attaching outbox projection", () => {
144180
const pane = document.createElement("openclaw-chat-pane") as unknown as TestChatPane;
145181
const targetSessionKey = "agent:main:pane-b";
@@ -237,9 +273,60 @@ describe("chat pane session creation lifecycle", () => {
237273
await expect(pane.createSession({ label: "Research Plan" })).resolves.toBe(true);
238274
expect(sessions.create).toHaveBeenCalledWith(
239275
expect.objectContaining({ label: "Research Plan" }),
276+
expect.objectContaining({ onCreated: expect.any(Function) }),
240277
);
241278
});
242279

280+
it("hands the created key to navigation before list refresh retires the pane", async () => {
281+
const nextSessionKey = "agent:main:research-plan";
282+
const request = vi.fn(async (method: string) => {
283+
if (method === "sessions.create") {
284+
return { key: nextSessionKey };
285+
}
286+
if (method === "sessions.list") {
287+
return {
288+
ts: 1,
289+
path: "(multiple)",
290+
count: 1,
291+
defaults: { modelProvider: null, model: null, contextTokens: null },
292+
sessions: [{ key: nextSessionKey, kind: "direct", updatedAt: 1 }],
293+
} satisfies SessionsListResult;
294+
}
295+
throw new Error(`Unexpected request: ${method}`);
296+
});
297+
const client = { request } as unknown as GatewayBrowserClient;
298+
const sessions = createSessionCapability({
299+
snapshot: {
300+
client,
301+
connected: true,
302+
sessionKey: "agent:main:current",
303+
assistantAgentId: "main",
304+
hello: null,
305+
},
306+
subscribe: () => () => undefined,
307+
subscribeEvents: () => () => undefined,
308+
});
309+
const { pane } = createTestChatPane({ client, sessions });
310+
const navigate = vi.fn();
311+
pane.onPaneSessionChange = navigate;
312+
const stop = sessions.subscribe((state) => {
313+
if (state.loading) {
314+
Object.defineProperty(pane, "isConnected", {
315+
configurable: true,
316+
value: false,
317+
});
318+
}
319+
});
320+
321+
try {
322+
await expect(pane.createSession({ label: "Research Plan" })).resolves.toBe(true);
323+
expect(navigate).toHaveBeenCalledWith("single", nextSessionKey);
324+
} finally {
325+
stop();
326+
sessions.dispose();
327+
}
328+
});
329+
243330
it("drops a created session after a same-client reconnect", async () => {
244331
const created = createDeferred<string | null>();
245332
const sessions = {

‎ui/src/pages/chat/chat-pane.ts‎

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1086,13 +1086,33 @@ class ChatPane extends OpenClawLightDomElement {
10861086
state.lastError = null;
10871087
state.chatError = null;
10881088
const previousSessionKey = state.sessionKey;
1089-
const nextSessionKey = await sessions.create({
1090-
...params,
1091-
currentSessionKey: previousSessionKey,
1092-
agentId:
1093-
scopedAgentParamsForSession(state, previousSessionKey).agentId ??
1094-
resolveAgentIdFromSessionKey(previousSessionKey),
1095-
});
1089+
let createdSessionAdopted = false;
1090+
const adoptCreatedSession = (nextSessionKey: string) => {
1091+
if (!isCurrent() || state.sessionKey !== previousSessionKey || !canCreateChatSession(state)) {
1092+
return false;
1093+
}
1094+
this.chatState.captureCreatedSessionComposer(nextSessionKey);
1095+
this.onPaneSessionChange?.(this.paneId, nextSessionKey);
1096+
createdSessionAdopted = true;
1097+
return true;
1098+
};
1099+
const nextSessionKey = await sessions.create(
1100+
{
1101+
...params,
1102+
currentSessionKey: previousSessionKey,
1103+
agentId:
1104+
scopedAgentParamsForSession(state, previousSessionKey).agentId ??
1105+
resolveAgentIdFromSessionKey(previousSessionKey),
1106+
},
1107+
{
1108+
// sessions.create refreshes the list before resolving. Hand the key to
1109+
// the route first so that refresh-driven renders cannot retire this pane.
1110+
onCreated: (key) => void adoptCreatedSession(key),
1111+
},
1112+
);
1113+
if (createdSessionAdopted) {
1114+
return true;
1115+
}
10961116
if (!isCurrent()) {
10971117
return false;
10981118
}
@@ -1112,9 +1132,7 @@ class ChatPane extends OpenClawLightDomElement {
11121132
}
11131133
return false;
11141134
}
1115-
this.chatState.captureCreatedSessionComposer(nextSessionKey);
1116-
this.onPaneSessionChange?.(this.paneId, nextSessionKey);
1117-
return true;
1135+
return adoptCreatedSession(nextSessionKey);
11181136
};
11191137

11201138
private syncActiveBindings() {
@@ -1306,9 +1324,7 @@ class ChatPane extends OpenClawLightDomElement {
13061324
this.removeEventListener("focusin", this.handlePaneFocus);
13071325
});
13081326
const pageState = createPageState(this.context, chatState.createRenderLifecycle(), this);
1309-
pageState.createChatSession = async (params) => {
1310-
await this.createSession(params);
1311-
};
1327+
pageState.createChatSession = (params) => this.createSession(params);
13121328
pageState.exportCurrentChat = () =>
13131329
exportChatMarkdown(pageState.chatMessages, pageState.assistantName);
13141330
pageState.refreshCurrentSessionTools = async () => {
@@ -1560,6 +1576,10 @@ class ChatPane extends OpenClawLightDomElement {
15601576
canonicalRouteSessionKey &&
15611577
canonicalRouteSessionKey !== routeSessionKey
15621578
) {
1579+
// Route canonicalization retires this render before normal startup can
1580+
// bind the client. Keep lifecycle-guarded actions usable while the
1581+
// parent replaces the alias route with its canonical session key.
1582+
this.connectedClient = snapshot.client;
15631583
this.onPaneSessionChange?.(this.paneId, canonicalRouteSessionKey, { replace: true });
15641584
state.requestUpdate?.();
15651585
return;
@@ -1929,8 +1949,7 @@ class ChatPane extends OpenClawLightDomElement {
19291949
state.chatAttachments = next;
19301950
state.requestUpdate?.();
19311951
},
1932-
onSend: () =>
1933-
catalogKey ? void this.continueCatalogSession(catalogKey) : void state.handleSendChat(),
1952+
onSend: () => (catalogKey ? this.continueCatalogSession(catalogKey) : state.handleSendChat()),
19341953
onCompact: () => void state.handleSendChat("/compact"),
19351954
onOpenSessionCheckpoints: () => {
19361955
const search = new URLSearchParams({ session: state.sessionKey });

0 commit comments

Comments
 (0)