Skip to content

Commit 6f56d79

Browse files
authored
fix(ui): survive route notFound at startup and stop silent chat draft loss (#120960)
1 parent b4564b0 commit 6f56d79

14 files changed

Lines changed: 348 additions & 91 deletions

‎ui/src/app-route-paths.test.ts‎

Lines changed: 115 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// @vitest-environment node
2-
import type { RouteLocation, RouterHistory } from "@openclaw/uirouter";
2+
import { notFound, type RouteLocation, type RouterHistory } from "@openclaw/uirouter";
33
import { describe, expect, it, vi } from "vitest";
44
import {
55
agentRouteFromPath,
@@ -194,6 +194,120 @@ describe("Dynamic route startup bridge", () => {
194194
route.component = originalComponent;
195195
}
196196
});
197+
198+
it("keeps a loader not-found state without rejecting startup", async () => {
199+
let location: RouteLocation = { pathname: "/", search: "", hash: "" };
200+
const history: RouterHistory = {
201+
location: () => location,
202+
push: vi.fn(),
203+
replace: vi.fn((next: RouteLocation) => {
204+
location = next;
205+
}),
206+
listen: () => () => undefined,
207+
};
208+
const router = createApplicationRouter();
209+
const route = router.getRoute("chat");
210+
if (!route) {
211+
throw new Error("Chat route missing");
212+
}
213+
const originalLoader = route.loader;
214+
const originalComponent = route.component;
215+
try {
216+
route.loader = () => notFound({ routeId: "chat" });
217+
route.component = async () => ({ render: () => null });
218+
219+
await expect(
220+
startApplicationRouter(router, history, "", {
221+
basePath: "",
222+
} as unknown as ApplicationContext),
223+
).resolves.toBeUndefined();
224+
225+
expect(location.pathname).toBe("/chat");
226+
expect(router.getState().status).toBe("notFound");
227+
expect(router.getState().matches[0]).toMatchObject({
228+
routeId: "chat",
229+
status: "notFound",
230+
error: { type: "notFound", data: { routeId: "chat" } },
231+
});
232+
} finally {
233+
router.stop();
234+
route.loader = originalLoader;
235+
route.component = originalComponent;
236+
}
237+
});
238+
239+
it("tolerates not-found from both dynamic startup navigations", async () => {
240+
const location: RouteLocation = {
241+
pathname: "/chat/main/01JSESSIONA",
242+
search: "",
243+
hash: "",
244+
};
245+
const history: RouterHistory = {
246+
location: () => location,
247+
push: vi.fn(),
248+
replace: vi.fn(),
249+
listen: () => () => undefined,
250+
};
251+
const router = createApplicationRouter();
252+
const route = router.getRoute("chat");
253+
if (!route) {
254+
throw new Error("Chat route missing");
255+
}
256+
const loader = vi.fn(() => notFound({ routeId: "chat" }));
257+
const originalLoader = route.loader;
258+
const originalComponent = route.component;
259+
try {
260+
route.loader = loader;
261+
route.component = async () => ({ render: () => null });
262+
263+
await expect(
264+
startApplicationRouter(router, history, "", {
265+
basePath: "",
266+
} as unknown as ApplicationContext),
267+
).resolves.toBeUndefined();
268+
269+
expect(loader).toHaveBeenCalledTimes(2);
270+
expect(router.getState().status).toBe("notFound");
271+
expect(router.getState().location).toEqual(location);
272+
} finally {
273+
router.stop();
274+
route.loader = originalLoader;
275+
route.component = originalComponent;
276+
}
277+
});
278+
279+
it("still rejects non-not-found startup failures", async () => {
280+
const failure = new Error("chat loader failed");
281+
const history: RouterHistory = {
282+
location: () => ({ pathname: "/chat", search: "", hash: "" }),
283+
push: vi.fn(),
284+
replace: vi.fn(),
285+
listen: () => () => undefined,
286+
};
287+
const router = createApplicationRouter();
288+
const route = router.getRoute("chat");
289+
if (!route) {
290+
throw new Error("Chat route missing");
291+
}
292+
const originalLoader = route.loader;
293+
const originalComponent = route.component;
294+
try {
295+
route.loader = () => {
296+
throw failure;
297+
};
298+
route.component = async () => ({ render: () => null });
299+
300+
await expect(
301+
startApplicationRouter(router, history, "", {
302+
basePath: "",
303+
} as unknown as ApplicationContext),
304+
).rejects.toBe(failure);
305+
} finally {
306+
router.stop();
307+
route.loader = originalLoader;
308+
route.component = originalComponent;
309+
}
310+
});
197311
});
198312

199313
describe("Agent panel route paths", () => {

‎ui/src/app-routes.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type {
33
PageDefinition,
44
RouteLocation,
55
RouteMatch,
6+
RouteNotFound,
67
Router,
78
RouterHistory,
89
} from "@openclaw/uirouter";
@@ -163,6 +164,23 @@ function sameRouteLocation(left: RouteLocation, right: RouteLocation): boolean {
163164
);
164165
}
165166

167+
function isRouteNotFound(error: unknown): error is RouteNotFound {
168+
return (
169+
typeof error === "object" && error !== null && "type" in error && error.type === "notFound"
170+
);
171+
}
172+
173+
async function tolerateRouteNotFound(navigation: Promise<void>): Promise<void> {
174+
try {
175+
await navigation;
176+
} catch (error) {
177+
// uirouter commits not-found state before rethrowing; the outlet owns its recovery UI.
178+
if (!isRouteNotFound(error)) {
179+
throw error;
180+
}
181+
}
182+
}
183+
166184
export async function startApplicationRouter(
167185
router: ApplicationRouter,
168186
history: RouterHistory,
@@ -206,12 +224,14 @@ export async function startApplicationRouter(
206224
listener(next);
207225
}),
208226
};
209-
await router.start(applicationHistory, basePath, context);
227+
await tolerateRouteNotFound(router.start(applicationHistory, basePath, context));
210228
if (initialDynamicRoute && sameRouteLocation(history.location(), location)) {
211229
// Replace the synthetic exact-match location with the real browser path
212230
// before the shell renders. A loader-visible redirect wins if it already
213231
// moved history while startup was still resolving.
214-
await router.navigate(initialDynamicRoute[0], context, { history: "none" }, location);
232+
await tolerateRouteNotFound(
233+
router.navigate(initialDynamicRoute[0], context, { history: "none" }, location),
234+
);
215235
}
216236
}
217237

‎ui/src/app/app-host.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ type ShellSessionNavigationState = {
240240
routeState: { routeId?: RouteId };
241241
navigate: (routeId: RouteId) => void;
242242
handleCommandPaletteSlashCommand: (command: string) => void;
243-
replaceChatWithCurrentSession: () => void;
243+
replaceChatWithCurrentSession: () => boolean;
244244
};
245245

246246
function committedRouterState(
@@ -494,11 +494,11 @@ describe("OpenClaw shell route session commits", () => {
494494
shell.activeSessionKey = "main";
495495
shell.routeState = { routeId: "chat" };
496496

497-
shell.replaceChatWithCurrentSession();
497+
expect(shell.replaceChatWithCurrentSession()).toBe(false);
498498
expect(replace).not.toHaveBeenCalled();
499499

500500
snapshot.phase = "connected";
501-
shell.replaceChatWithCurrentSession();
501+
expect(shell.replaceChatWithCurrentSession()).toBe(true);
502502
expect(replace).toHaveBeenCalledWith("chat", { pathname: "/chat/research" });
503503
});
504504

‎ui/src/app/app-host.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ class OpenClawShell
424424
}
425425

426426
replaceChatWithCurrentSession() {
427-
this.shellNavigation.replaceChatWithCurrentSession();
427+
return this.shellNavigation.replaceChatWithCurrentSession();
428428
}
429429

430430
recoverDeletedActiveSession(sessionState: ApplicationContext["sessions"]["state"]) {

‎ui/src/app/app-shell-navigation.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,14 @@ export class ShellNavigationOwner {
8787
);
8888
}
8989

90-
replaceChatWithCurrentSession(): void {
90+
replaceChatWithCurrentSession(): boolean {
9191
const context = this.host.context;
9292
const sessionKey = this.host.activeSessionKey.trim();
93-
if (
94-
!context ||
95-
(!parseAgentSessionKey(sessionKey) && context.gateway.snapshot.phase !== "connected")
96-
) {
97-
return;
93+
if (!context) {
94+
return true;
95+
}
96+
if (!parseAgentSessionKey(sessionKey) && context.gateway.snapshot.phase !== "connected") {
97+
return false;
9898
}
9999
const face = this.host.routeState.routeId === "dashboard" ? "dashboard" : "chat";
100100
const sessionWasDeleted = (context.sessions.state.deletedSessions ?? []).some(
@@ -138,7 +138,7 @@ export class ShellNavigationOwner {
138138
// Gateway rejects deletion of a live main session. If an orphaned event
139139
// still names that fallback, replacing the same route would retry forever.
140140
if (sessionWasDeleted && replacementSessionKey === sessionKey) {
141-
return;
141+
return true;
142142
}
143143
if (replacementSessionKey !== sessionKey) {
144144
// Commit the replacement to both selection owners before navigating;
@@ -154,6 +154,7 @@ export class ShellNavigationOwner {
154154
face,
155155
sessionNavigationTarget({ context, face, sessionKey: replacementSessionKey }).options,
156156
);
157+
return true;
157158
}
158159

159160
recoverDeletedActiveSession(sessionState: ApplicationContext["sessions"]["state"]): void {

‎ui/src/app/app-shell-view.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export interface ShellViewHost {
7676
openNewSession(agentId: string, target?: NewSessionTarget): void;
7777
openPalette(): void;
7878
refreshControlUi(): void;
79-
replaceChatWithCurrentSession(): void;
79+
replaceChatWithCurrentSession(): boolean;
8080
resizeNavigation(splitRatio: number): void;
8181
selectChatSession(sessionKey: string, agentId?: string | null): void;
8282
storedOutboxScopeHost(context: ApplicationContext<RouteId>): StoredOutboxScopeHost;
@@ -457,6 +457,7 @@ export function renderApplicationShell(host: ShellViewHost) {
457457
.router=${runtime.router}
458458
.retryContext=${context}
459459
.onNotFound=${() => host.replaceChatWithCurrentSession()}
460+
.notFoundRecoveryReady=${gatewayConnected}
460461
></openclaw-router-outlet>
461462
</main>
462463
<openclaw-terminal-panel

‎ui/src/app/bootstrap-location.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,9 @@ export async function resolveInitialApplicationLocation(params: {
117117
if (!isDefaultChatLanding(params.location, params.basePath, routeIdFromPath)) {
118118
return params.location;
119119
}
120-
// Explicit routes must start immediately; only the implicit persisted-session
121-
// landing needs gateway defaults before its agent can be made authoritative.
122-
if (params.sessionKey.trim() && !parseAgentSessionKey(params.sessionKey)) {
120+
// Explicit routes must start immediately; only the implicit session landing
121+
// needs gateway defaults before its key and agent can be made authoritative.
122+
if (!parseAgentSessionKey(params.sessionKey)) {
123123
await waitForGatewayClient(params.gateway, params.signal);
124124
}
125125
const defaults = {
@@ -129,7 +129,7 @@ export async function resolveInitialApplicationLocation(params: {
129129
return normalizeInitialApplicationLocation(
130130
params.location,
131131
params.basePath,
132-
params.sessionKey,
132+
params.sessionKey.trim() || params.gateway.snapshot.sessionKey,
133133
resolveUiDefaultAgentId(defaults),
134134
resolveUiConfiguredMainKey(defaults),
135135
);

0 commit comments

Comments
 (0)