Skip to content

Commit f67bdbb

Browse files
feat: add readable managed worktree names (#114488)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 0090768 commit f67bdbb

15 files changed

Lines changed: 521 additions & 43 deletions

‎docs/concepts/managed-worktrees.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Each worktree lives at:
1717
<openclaw-state-dir>/worktrees/<repo-fingerprint>/<name>
1818
```
1919

20-
The repository fingerprint is the first 16 hexadecimal characters of a SHA-256 hash over the canonical git common directory and origin URL. A supplied name must match `[a-z0-9][a-z0-9-]{0,63}`. Without a name, OpenClaw generates `wt-` followed by eight random hexadecimal characters.
20+
The repository fingerprint is the first 16 hexadecimal characters of a SHA-256 hash over the canonical git common directory and origin URL. A supplied name must match `[a-z0-9][a-z0-9-]{0,63}`. Without a name, OpenClaw generates a readable crustacean-themed name such as `brisk-lobster`. Inferred names already occupied by another owner, local branch, or unmanaged path get a numeric suffix such as `brisk-lobster-2`.
2121

2222
OpenClaw creates branch `openclaw/<name>` at the requested base ref. Without a base ref, it fetches `origin`, uses the remote default branch when available, and falls back to local `HEAD` when the repository is offline or has no usable remote.
2323

@@ -45,7 +45,7 @@ A nonzero exit aborts creation and removes the new worktree and branch. This is
4545

4646
## Session worktrees
4747

48-
Start an isolated chat from a Git-backed folder with a worktree session: on the Control UI's New session page, use the **Place** picker to choose a Gateway source folder, then select **Worktree** (with an optional base branch and worktree name). The choice appears only after the Gateway confirms that the selected folder is a Git checkout; ordinary folders run directly and show no Git isolation control. iOS exposes the same choice from Chat actions, and Android exposes it beside New Chat, when the active agent workspace is Git-backed.
48+
Start an isolated chat from a Git-backed folder with a worktree session: on the Control UI's New session page, use the **Place** picker to choose a Gateway source folder, then select **Worktree** (with an optional base branch and worktree name). When the name is omitted, OpenClaw derives it from the explicit session label or the concise title generated from the first message, then falls back to a crustacean-themed name. The choice appears only after the Gateway confirms that the selected folder is a Git checkout; ordinary folders run directly and show no Git isolation control. iOS exposes the same choice from Chat actions, and Android exposes it beside New Chat, when the active agent workspace is Git-backed.
4949

5050
Coding agents can also call `spawn_task` when they discover confirmed follow-up work outside the current task. The Control UI shows a suggestion chip without starting anything, while a Gateway-backed TUI shows an interactive prompt with the same actions. Selecting **Start in worktree** creates a fresh session-owned worktree from the suggested project and sends the self-contained prompt as its first turn; dismissing the suggestion leaves the repository untouched. Suggestions and their IDs are ephemeral and do not survive a Gateway restart.
5151

@@ -55,7 +55,7 @@ The resulting managed worktree is owned by the session, and every agent run in t
5555

5656
`sessions.create` may include an absolute `cwd` to run directly in another Gateway folder, to choose the source checkout together with `worktree: true`, or to set a paired node's working directory. Every explicit host path requires `operator.admin`; ordinary worktree chat creation remains `operator.write` and stays anchored to the configured workspace.
5757

58-
`sessions.create` also accepts `worktreeBaseRef` and `worktreeName` alongside `worktree: true` to pick the base ref and the worktree name (the branch becomes `openclaw/<name>`); both stay at `operator.write`. The created worktree is returned in the create result and persisted on the session row as `worktree: { id, branch, repoRoot }`, so session lists can show the checkout and branch. Deleting a session reports a preserved dirty checkout as `worktreePreserved` instead of silently leaving it behind.
58+
`sessions.create` also accepts `worktreeBaseRef` and `worktreeName` alongside `worktree: true` to pick the base ref and the worktree name (the branch becomes `openclaw/<name>`); both stay at `operator.write`. If `worktreeName` is omitted, the session label or generated first-message title supplies the readable branch name, with a crustacean-themed fallback. The created worktree is returned in the create result and persisted on the session row as `worktree: { id, branch, repoRoot }`, so session lists can show the checkout and branch. Deleting a session reports a preserved dirty checkout as `worktreePreserved` instead of silently leaving it behind.
5959

6060
## Snapshots, cleanup, and restore
6161

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ methods. Treat this as feature discovery, not a full enumeration of
573573
- `sessions.preview` returns bounded transcript previews for specific session keys.
574574
- `sessions.describe` returns one gateway session row for an exact session key.
575575
- `sessions.resolve` resolves or canonicalizes a session target.
576-
- `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. 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).
576+
- `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).
577577
- `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.
578578
- `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.
579579
- `sessions.send` sends a message into an existing session.

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ The macOS app keeps its native link-browser sidebar for links clicked in the das
422422
- During an active send and the final history refresh, the chat view keeps local optimistic user/assistant messages visible if `chat.history` briefly returns an older snapshot; the canonical transcript replaces those local messages once the Gateway history catches up.
423423
- Live `chat` events are delivery state, while `chat.history` is rebuilt from the durable session transcript. After tool-final events the Control UI reloads history and merges only a small optimistic tail; the transcript boundary is documented in [WebChat](/web/webchat).
424424
- `chat.inject` appends an assistant note to the session transcript and broadcasts a `chat` event for UI-only updates (no agent run, no channel delivery).
425-
- The sidebar lists every loaded active session by agent section and pinned/channel/work/custom/Chats buckets with a single New Session action that opens the draft dialog. Opening a visible row moves only the highlight. Sessions can be dropped onto Pinned to pin them, or onto a custom group or Chats to move them; custom groups are collapsible and drag-reorderable, group names and order sync through the gateway, and collapsed state stays in the browser. A new dashboard session asynchronously gets a concise generated title from its first non-command message; explicit names and authenticated sender identity remain separate, so account names are never used as generated titles. Set `agents.defaults.utilityModel` (or `agents.entries.*.utilityModel`) to route this separate model call to a lower-cost model; if that distinct model fails, title generation retries once with the primary model. Expanding another agent section browses that agent's sessions without leaving the open chat.
425+
- The sidebar lists every loaded active session by agent section and pinned/channel/work/custom/Chats buckets with a single New Session action that opens the draft dialog. Opening a visible row moves only the highlight. Sessions can be dropped onto Pinned to pin them, or onto a custom group or Chats to move them; custom groups are collapsible and drag-reorderable, group names and order sync through the gateway, and collapsed state stays in the browser. A new dashboard session asynchronously gets a concise generated title from its first non-command message; explicit names and authenticated sender identity remain separate, so account names are never used as generated titles. When New Session creates a worktree without an explicit worktree name, OpenClaw also uses the session label or generated title for its branch name, falling back to a readable crustacean-themed name. Set `agents.defaults.utilityModel` (or `agents.entries.*.utilityModel`) to route this separate model call to a lower-cost model; if that distinct model fails, title generation retries once with the primary model. Expanding another agent section browses that agent's sessions without leaving the open chat.
426426
- Thread search lives in the command palette (⌘K, or the search button in the top-left control cluster): typing a query follows a bounded number of matching pages across agents, filters internal child/cron rows, and lists visible matches next to navigation commands. The Threads page keeps the exhaustive searchable list with filters.
427427
- Each sidebar row keeps direct pin access plus a full context menu for unread state, rename, fork, grouping, archive, and delete. Multi-selected rows (Cmd/Ctrl-click, Shift-click for ranges) get a batch menu covering unread state, grouping, archive, and delete; batch archive/delete stays disabled unless every selected session is archivable. An active run and an agent's main session cannot be archived. Archiving or deleting the currently selected session switches Chat back to that agent's main session.
428428
- In the macOS app, the OpenClaw mark uses the otherwise-empty native titlebar strip next to the window controls instead of consuming a sidebar row.

‎src/agents/session-slug.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* Verifies deterministic choices, collision numbering, and fallback suffixes.
44
*/
55
import { beforeEach, describe, expect, it, vi } from "vitest";
6-
import { createSessionSlug } from "./session-slug.js";
6+
import { createCrustaceanSlug, createSessionSlug } from "./session-slug.js";
77

88
const randomMocks = vi.hoisted(() => ({
99
generateSecureInt: vi.fn(),
@@ -24,6 +24,11 @@ describe("session slug", () => {
2424
expect(slug).toBe("amber-atlas");
2525
});
2626

27+
it("generates a crustacean-themed slug for worktrees", () => {
28+
randomMocks.generateSecureInt.mockReturnValue(0);
29+
expect(createCrustaceanSlug()).toBe("amber-barnacle");
30+
});
31+
2732
it("adds a numeric suffix when the base slug is taken", () => {
2833
randomMocks.generateSecureInt.mockReturnValue(0);
2934
const slug = createSessionSlug((id) => id === "amber-atlas");

‎src/agents/session-slug.ts‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,19 @@ const SLUG_NOUNS = [
107107
"zephyr",
108108
];
109109

110+
const CRUSTACEAN_NOUNS = [
111+
"barnacle",
112+
"claw",
113+
"crab",
114+
"crayfish",
115+
"krill",
116+
"langoustine",
117+
"lobster",
118+
"prawn",
119+
"shrimp",
120+
"shell",
121+
];
122+
110123
function randomChoice(values: string[], fallback: string) {
111124
return values[generateSecureInt(values.length)] ?? fallback;
112125
}
@@ -121,20 +134,21 @@ function createFallbackSuffix(length: number): string {
121134
return suffix;
122135
}
123136

124-
function createSlugBase(words = 2) {
125-
const parts = [randomChoice(SLUG_ADJECTIVES, "steady"), randomChoice(SLUG_NOUNS, "harbor")];
137+
function createSlugBase(words = 2, nouns = SLUG_NOUNS) {
138+
const parts = [randomChoice(SLUG_ADJECTIVES, "steady"), randomChoice(nouns, "harbor")];
126139
if (words > 2) {
127-
parts.push(randomChoice(SLUG_NOUNS, "reef"));
140+
parts.push(randomChoice(nouns, "reef"));
128141
}
129142
return parts.join("-");
130143
}
131144

132145
function createAvailableSlug(
133146
words: number,
134147
isIdTaken: (id: string) => boolean,
148+
nouns = SLUG_NOUNS,
135149
): string | undefined {
136150
for (let attempt = 0; attempt < 12; attempt += 1) {
137-
const base = createSlugBase(words);
151+
const base = createSlugBase(words, nouns);
138152
if (!isIdTaken(base)) {
139153
return base;
140154
}
@@ -162,3 +176,18 @@ export function createSessionSlug(isTaken?: (id: string) => boolean): string {
162176
const fallback = `${createSlugBase(3)}-${createFallbackSuffix(3)}`;
163177
return isIdTaken(fallback) ? `${fallback}-${Date.now().toString(36)}` : fallback;
164178
}
179+
180+
/** Creates a human-readable crustacean-themed slug for unnamed worktrees. */
181+
export function createCrustaceanSlug(isTaken?: (id: string) => boolean): string {
182+
const isIdTaken = isTaken ?? (() => false);
183+
const twoWord = createAvailableSlug(2, isIdTaken, CRUSTACEAN_NOUNS);
184+
if (twoWord) {
185+
return twoWord;
186+
}
187+
const threeWord = createAvailableSlug(3, isIdTaken, CRUSTACEAN_NOUNS);
188+
if (threeWord) {
189+
return threeWord;
190+
}
191+
const fallback = `${createSlugBase(3, CRUSTACEAN_NOUNS)}-${createFallbackSuffix(3)}`;
192+
return isIdTaken(fallback) ? `${fallback}-${Date.now().toString(36)}` : fallback;
193+
}

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { describe, expect, it } from "vitest";
2+
import { slugifyWorktreeTitle, worktreeNameAllocationFamily } from "./name.js";
3+
4+
describe("slugifyWorktreeTitle", () => {
5+
it.each([
6+
["Fix agent selection menu", "fix-agent-selection-menu"],
7+
["Crème brûlée & release prep", "creme-brulee-and-release-prep"],
8+
[' Title: "Worktree names" ', "title-worktree-names"],
9+
])("slugifies %s", (title, expected) => {
10+
expect(slugifyWorktreeTitle(title)).toBe(expected);
11+
});
12+
13+
it("truncates at the worktree contract limit without a trailing dash", () => {
14+
expect(slugifyWorktreeTitle(`${"a".repeat(63)} two`)).toBe("a".repeat(63));
15+
});
16+
17+
it("returns undefined when a title has no ASCII slug characters", () => {
18+
expect(slugifyWorktreeTitle("🦞 日本語")).toBeUndefined();
19+
});
20+
21+
it("joins numeric and dash-truncated names into the same allocation family", () => {
22+
const base = `${"a".repeat(58)}-${"b".repeat(5)}`;
23+
const thousandthCandidate = `${"a".repeat(58)}-1000`;
24+
25+
expect(worktreeNameAllocationFamily(base)).toBe("a".repeat(58));
26+
expect(worktreeNameAllocationFamily(thousandthCandidate)).toBe("a".repeat(58));
27+
expect(worktreeNameAllocationFamily("task-2-3")).toBe("task");
28+
});
29+
});

‎src/agents/worktrees/name.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const WORKTREE_NAME_MAX_LENGTH = 64;
2+
const WORKTREE_ALLOCATION_FAMILY_LENGTH = 59;
3+
4+
/** Converts a short human-readable title into a valid managed-worktree name. */
5+
export function slugifyWorktreeTitle(title: string): string | undefined {
6+
const slug = title
7+
.normalize("NFKD")
8+
.replace(/\p{M}/gu, "")
9+
.toLowerCase()
10+
.replace(/&/g, " and ")
11+
.replace(/[^a-z0-9]+/g, "-")
12+
.replace(/^-+|-+$/g, "")
13+
.slice(0, WORKTREE_NAME_MAX_LENGTH)
14+
.replace(/-+$/g, "");
15+
return slug || undefined;
16+
}
17+
18+
/** Maps names that can converge after a `-1000` suffix into one allocation lane. */
19+
export function worktreeNameAllocationFamily(name: string): string {
20+
let base = name;
21+
while (/-\d+$/.test(base)) {
22+
base = base.replace(/-\d+$/, "");
23+
}
24+
return (base || name).slice(0, WORKTREE_ALLOCATION_FAMILY_LENGTH).replace(/-+$/g, "");
25+
}

0 commit comments

Comments
 (0)