Skip to content

Commit d8d70cf

Browse files
authored
fix(ui): preserve worktree base branch across reconnects (#133744)
* fix(ui): preserve worktree base branch across reconnects * fix(ui): retain project selection during catalog reconnects * docs: leave workspace release notes in the pull request
1 parent 6d5c39e commit d8d70cf

6 files changed

Lines changed: 114 additions & 37 deletions

File tree

‎docs/web/control-ui.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,8 @@ The **+** in the sidebar's **Sessions** toolbar opens a full-page draft at `/new
307307

308308
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.
309309

310+
Gateway reconnects and Git verification retries preserve your edited base branch and worktree name. Choosing another folder or project clears those repository-specific details.
311+
310312
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.
311313

312314
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.

‎ui/src/pages/new-session/draft-place-browser.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ function createBrowser(request: (method: string) => Promise<unknown>, data?: New
6666
},
6767
);
6868
gateway.synchronize(context.gateway);
69+
const onProjectMissing = vi.fn();
6970
const browser = new DraftPlaceBrowser(
7071
host,
7172
gateway,
@@ -75,7 +76,7 @@ function createBrowser(request: (method: string) => Promise<unknown>, data?: New
7576
}),
7677
{
7778
requestUpdate: vi.fn(),
78-
onProjectMissing: vi.fn(),
79+
onProjectMissing,
7980
onSelectProject: vi.fn(),
8081
onApprovedListing: vi.fn(),
8182
querySelector: () => null,
@@ -89,6 +90,7 @@ function createBrowser(request: (method: string) => Promise<unknown>, data?: New
8990
});
9091
return {
9192
browser,
93+
onProjectMissing,
9294
gateway,
9395
client,
9496
context,
@@ -103,6 +105,33 @@ function createBrowser(request: (method: string) => Promise<unknown>, data?: New
103105
}
104106

105107
describe("DraftPlaceBrowser", () => {
108+
it.each(["disconnect", "failure"])(
109+
"retains the selected project until a catalog confirms its removal (%s)",
110+
async (unavailable) => {
111+
const project = { id: "project", displayName: "Project", repoRoot: "/project" };
112+
const request = vi.fn(async () => ({ projects: [project] }));
113+
const fixture = createBrowser(request);
114+
await fixture.browser.refreshProjects();
115+
fixture.browser.selectProject({ kind: "local", id: project.id });
116+
117+
if (unavailable === "disconnect") {
118+
fixture.context.gateway.snapshot.phase = "reconnecting";
119+
fixture.update();
120+
} else {
121+
request.mockRejectedValue(new Error("projects unavailable"));
122+
}
123+
await fixture.browser.refreshProjects();
124+
expect(fixture.browser.selectedProject()).toEqual(project);
125+
expect(fixture.onProjectMissing).not.toHaveBeenCalled();
126+
127+
fixture.context.gateway.snapshot.phase = "connected";
128+
request.mockResolvedValue({ projects: [] });
129+
fixture.update();
130+
await fixture.browser.refreshProjects();
131+
expect(fixture.onProjectMissing).toHaveBeenCalled();
132+
},
133+
);
134+
106135
it("tracks overlapping popover hides independently", () => {
107136
const { browser } = createBrowser(async () => ({}));
108137

‎ui/src/pages/new-session/draft-place-browser.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,11 @@ export class DraftPlaceBrowser {
8282
this.gateway.connectionEpoch,
8383
] as const,
8484
task: async ([client, advertised]) => {
85-
if (!client || !advertised) {
85+
// A disconnect has no catalog result and cannot retire the selected project.
86+
if (!client) {
87+
return initialState;
88+
}
89+
if (!advertised) {
8690
return { projects: [] } as ProjectsListResult;
8791
}
8892
return await (
@@ -99,9 +103,6 @@ export class DraftPlaceBrowser {
99103
this.callbacks.requestUpdate();
100104
},
101105
onError: () => {
102-
this.projectsValue = [];
103-
this.projectRecentsValue = undefined;
104-
this.callbacks.onProjectMissing();
105106
this.callbacks.requestUpdate();
106107
},
107108
});

‎ui/src/pages/new-session/draft-place-state.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,53 @@ function createRepositoryFixture(
8989
}
9090

9191
describe("DraftPlaceState repository selection", () => {
92+
it.each(["git", "unavailable", "rejected"] as const)(
93+
"preserves an edited base branch through reconnect discovery (%s)",
94+
async (result) => {
95+
const { state, request, persistPreference } = createRepositoryFixture({ workspaceGit: true });
96+
const git = { repositoryStatus: "git", branches: [], defaultBranch: "main" };
97+
request.mockResolvedValue(git);
98+
state.adoptAgentDefaults();
99+
await vi.waitFor(() => expect(state.repository.kind).toBe("git"));
100+
state.setBaseRef("my-branch");
101+
state.setWorktreeName("my-checkout");
102+
103+
state.invalidateGatewayDiscovery(false);
104+
expect(state.baseRef).toBe("my-branch");
105+
const discovery = createDeferred<WorktreesBranchesResult>();
106+
request.mockReturnValue(discovery.promise);
107+
state.adoptAgentDefaults();
108+
expect(state.baseRef).toBe("my-branch");
109+
if (result === "rejected") {
110+
discovery.reject(new Error("Git unavailable"));
111+
} else {
112+
discovery.resolve({ ...git, repositoryStatus: result });
113+
}
114+
await vi.waitFor(() =>
115+
expect(state.repository.kind).toBe(result === "git" ? "git" : "unavailable"),
116+
);
117+
expect(state.baseRef).toBe("my-branch");
118+
expect(state.worktreeName).toBe("my-checkout");
119+
120+
state.invalidateGatewayDiscovery(false);
121+
request.mockResolvedValue(git);
122+
state.adoptAgentDefaults();
123+
await vi.waitFor(() => expect(state.repository.kind).toBe("git"));
124+
expect(state.baseRef).toBe("my-branch");
125+
state.clearProjectSelection();
126+
await vi.waitFor(() => expect(state.repository.kind).toBe("git"));
127+
expect(state.baseRef).toBe("my-branch");
128+
state.applyFolder("/another-repo");
129+
await vi.waitFor(() => expect(state.repository.kind).toBe("git"));
130+
expect(state.baseRef).toBe("main");
131+
expect(state.worktreeName).toBe("");
132+
expect(persistPreference).toHaveBeenCalledWith("main", "/workspace", {
133+
baseRef: "",
134+
worktreeName: "",
135+
});
136+
},
137+
);
138+
92139
it("preserves edited details when identity preferences arrive after discovery", async () => {
93140
const { state, request, readPreference } = createRepositoryFixture({ workspaceGit: true });
94141
request.mockResolvedValue({ repositoryStatus: "git", branches: [], defaultBranch: "main" });

‎ui/src/pages/new-session/draft-place-state.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,10 @@ export class DraftPlaceState {
391391
}
392392

393393
clearProjectSelection() {
394+
// Catalog refresh errors also call this when the draft has no selected project.
395+
if (this.browser.projectId || this.browser.remoteProject) {
396+
this.repositoryState.clearDetails(true);
397+
}
394398
this.browser.clearProjectSelection();
395399
this.repositoryState.load();
396400
this.callbacks.requestUpdate();
@@ -521,6 +525,9 @@ export class DraftPlaceState {
521525
this.whereSelectedByUser = true;
522526
this.preferredWhereRestore = null;
523527
if ((deviceId || autoDevice) && !this.worktreeAvailable()) {
528+
if (this.folderValue !== this.workspacePath() || this.browser.projectId) {
529+
this.repositoryState.clearDetails(true);
530+
}
524531
this.folderValue = this.workspacePath();
525532
this.folderSelectedByUser = false;
526533
this.browser.clearProjectSelection();

‎ui/src/pages/new-session/draft-repository-state.ts‎

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,10 @@ function initialRepositoryState(snapshot: DraftRepositorySnapshot): DraftReposit
4141
export class DraftRepositoryController {
4242
private worktreeValue = false;
4343
private worktreeNameValue = "";
44-
private baseRefValue = "";
44+
private baseRefOverride: string | undefined;
4545
private repositoryValue: DraftRepositoryState = { kind: "idle" };
4646
private requestToken = 0;
47-
private baseRefEditGeneration = 0;
4847
private preferredWorktreeRestore = false;
49-
private preferredBaseRefRestore = "";
5048
private worktreeSelectedByUser = false;
5149
private detailsSelectedByUser = false;
5250

@@ -64,7 +62,9 @@ export class DraftRepositoryController {
6462
}
6563

6664
get baseRef(): string {
67-
return this.baseRefValue;
65+
// Discovery supplies defaults; reconnects never rewrite the operator's selection.
66+
const repository = this.repositoryValue.kind === "git" ? this.repositoryValue : undefined;
67+
return this.baseRefOverride ?? (repository?.defaultBranch || repository?.headBranch || "");
6868
}
6969

7070
get repository(): DraftRepositoryState {
@@ -85,43 +85,45 @@ export class DraftRepositoryController {
8585
this.preferredWorktreeRestore = preference?.worktree === true;
8686
}
8787
if (!this.detailsSelectedByUser) {
88-
this.preferredBaseRefRestore = preference?.baseRef ?? "";
88+
this.baseRefOverride = preference?.baseRef || undefined;
8989
this.worktreeNameValue = preference?.worktreeName ?? "";
9090
}
9191
if (!this.matchesCurrentRepo()) {
9292
// Retire the old folder's RPC before it can consume the new preference.
9393
this.invalidate();
9494
} else if (this.repositoryValue.kind !== "checking") {
95-
this.adoptResolvedRepository(
96-
this.repositoryValue,
97-
this.detailsSelectedByUser ? undefined : this.baseRefEditGeneration,
98-
);
95+
this.adoptResolvedRepository(this.repositoryValue);
9996
}
10097
}
10198

10299
reset() {
103100
this.invalidate();
104-
this.baseRefEditGeneration += 1;
105101
this.worktreeValue = false;
106-
this.worktreeNameValue = "";
102+
this.clearDetails();
107103
this.preferredWorktreeRestore = false;
108-
this.preferredBaseRefRestore = "";
109104
this.worktreeSelectedByUser = false;
105+
}
106+
107+
clearDetails(persist = false) {
108+
this.baseRefOverride = undefined;
109+
this.worktreeNameValue = "";
110110
this.detailsSelectedByUser = false;
111+
if (persist) {
112+
this.callbacks.persistPreference({ baseRef: "", worktreeName: "" });
113+
}
111114
}
112115

113116
invalidate() {
114117
this.requestToken += 1;
115118
this.repositoryValue = { kind: "idle" };
116-
this.baseRefValue = "";
117119
}
118120

119121
selectWorktree(value: boolean, clearName = true) {
120122
this.preferredWorktreeRestore = false;
121123
this.worktreeSelectedByUser = true;
122124
this.worktreeValue = value;
123125
if (clearName) {
124-
this.worktreeNameValue = "";
126+
this.clearDetails(true);
125127
}
126128
}
127129

@@ -132,6 +134,7 @@ export class DraftRepositoryController {
132134
rejectPreferredWorktree() {
133135
this.preferredWorktreeRestore = false;
134136
this.worktreeValue = false;
137+
this.clearDetails(true);
135138
}
136139

137140
toggle() {
@@ -153,9 +156,7 @@ export class DraftRepositoryController {
153156
if (submitting) {
154157
return;
155158
}
156-
this.baseRefEditGeneration += 1;
157-
this.baseRefValue = baseRef;
158-
this.preferredBaseRefRestore = "";
159+
this.baseRefOverride = baseRef;
159160
this.detailsSelectedByUser = true;
160161
this.callbacks.persistPreference({ baseRef });
161162
this.callbacks.requestUpdate();
@@ -193,16 +194,14 @@ export class DraftRepositoryController {
193194

194195
load() {
195196
const requestId = ++this.requestToken;
196-
const baseRefEditGeneration = this.baseRefEditGeneration;
197197
const snapshot = this.read();
198-
this.baseRefValue = "";
199198
const discovery = initialRepositoryState(snapshot);
200199
if (discovery.kind !== "checking") {
201-
return this.adoptResolvedRepository(discovery, baseRefEditGeneration);
200+
return this.adoptResolvedRepository(discovery);
202201
}
203202
const client = snapshot.gateway?.client;
204203
if (snapshot.gateway?.phase !== "connected" || !client) {
205-
return this.adoptResolvedRepository({ kind: "idle" }, baseRefEditGeneration);
204+
return this.adoptResolvedRepository({ kind: "idle" });
206205
}
207206
const { repoRoot } = discovery;
208207
this.repositoryValue = discovery;
@@ -225,21 +224,18 @@ export class DraftRepositoryController {
225224
...(result.headBranch ? { headBranch: result.headBranch } : {}),
226225
}
227226
: { kind: result?.repositoryStatus === "not_git" ? "direct" : "unavailable", repoRoot },
228-
baseRefEditGeneration,
229227
);
230228
})
231229
.catch(() => {
232230
if (requestId !== this.requestToken) {
233231
return;
234232
}
235-
this.adoptResolvedRepository({ kind: "unavailable", repoRoot }, baseRefEditGeneration);
233+
this.adoptResolvedRepository({ kind: "unavailable", repoRoot });
236234
});
237235
}
238236

239-
private adoptResolvedRepository(state: ResolvedRepository, baseRefEditGeneration?: number) {
240-
// Discovery owns restore/rejection for both immediate and RPC results;
241-
// Read the current preference: group defaults and user edits can arrive
242-
// while an RPC is pending.
237+
private adoptResolvedRepository(state: ResolvedRepository) {
238+
// Worktree preferences can arrive while discovery is pending.
243239
this.repositoryValue = state;
244240
if (state.kind === "direct") {
245241
if (!this.read().remotePlacement) {
@@ -253,11 +249,6 @@ export class DraftRepositoryController {
253249
this.worktreeValue = true;
254250
}
255251
this.preferredWorktreeRestore = false;
256-
if (state.kind === "git" && baseRefEditGeneration === this.baseRefEditGeneration) {
257-
this.baseRefValue =
258-
this.preferredBaseRefRestore || state.defaultBranch || state.headBranch || "";
259-
this.preferredBaseRefRestore = "";
260-
}
261252
this.callbacks.requestUpdate();
262253
}
263254
}

0 commit comments

Comments
 (0)