Skip to content

Commit 70c87cc

Browse files
authored
fix(ui): open selected palette agents and follow visible result order (#130344)
1 parent 6fe0831 commit 70c87cc

5 files changed

Lines changed: 264 additions & 62 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,8 @@ export function renderApplicationShell(host: ShellViewHost) {
443443
${renderLazyElementModal(host.lazyCustomElements)}
444444
${isOptionalElementDefined(host.commandPaletteElement)
445445
? html`<openclaw-command-palette
446-
.onNavigate=${(routeId: RouteId) => host.navigate(routeId)}
446+
.onNavigate=${(routeId: RouteId, options?: ApplicationNavigationOptions) =>
447+
host.navigate(routeId, options)}
447448
.onSelectSession=${(sessionKey: string) => host.selectChatSession(sessionKey)}
448449
.onSlashCommand=${(command: string) => host.handleCommandPaletteSlashCommand(command)}
449450
></openclaw-command-palette>`

‎ui/src/components/command-palette-catalog-search.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ type CommandPaletteCatalogItem = {
3232
icon: IconName;
3333
category: CommandPaletteCatalogCategory;
3434
routeId: RouteId;
35+
agentId?: string;
3536
description?: string;
3637
searchText?: string;
3738
};
@@ -215,6 +216,7 @@ export function toCommandPaletteItems(
215216
icon: item.icon,
216217
category: item.category,
217218
action: `nav:${item.routeId}`,
219+
agentId: item.agentId,
218220
description: item.description,
219221
searchText: item.searchText,
220222
}));
@@ -298,6 +300,7 @@ export async function loadCommandPaletteCatalogItems(params: {
298300
icon: "bot" as const,
299301
category: "agents" as const,
300302
routeId: "agents" as const,
303+
agentId: agent.id,
301304
description: agent.id,
302305
searchText: [agent.id, agent.workspace, agent.model?.primary, agent.identity?.theme]
303306
.filter(Boolean)

‎ui/src/components/command-palette.test.ts‎

Lines changed: 128 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,13 @@ async function enterQuery(palette: CommandPalette, query: string) {
125125
await palette.updateComplete;
126126
}
127127

128+
function findPaletteOption(palette: CommandPalette, label: string, exact = false) {
129+
return [...palette.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => {
130+
const text = item.textContent?.replace(/\s+/g, " ").trim();
131+
return exact ? text === label : text?.includes(label);
132+
});
133+
}
134+
128135
describe("CommandPalette lifecycle", () => {
129136
let restoreDialogPolyfill: () => void;
130137

@@ -323,9 +330,7 @@ describe("CommandPalette lifecycle", () => {
323330
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
324331
await palette.updateComplete;
325332

326-
const metadataItem = palette.querySelector<HTMLElement>(
327-
"#cmd-palette-option-session-agent-main-metadata",
328-
);
333+
const metadataItem = findPaletteOption(palette, "Needle planning");
329334
expect(metadataItem?.textContent).toContain("Needle planning");
330335
metadataItem?.click();
331336
expect(palette.onSelectSession).toHaveBeenCalledWith("agent:main:metadata");
@@ -413,9 +418,7 @@ describe("CommandPalette lifecycle", () => {
413418
await enterQuery(palette, "reconciles");
414419
await vi.advanceTimersByTimeAsync(50);
415420
await vi.waitFor(() => expect(palette.textContent).toContain("Nightly invoices"));
416-
const item = palette.querySelector<HTMLElement>(
417-
"#cmd-palette-option-automation-nightly-invoices",
418-
);
421+
const item = findPaletteOption(palette, "Nightly invoices");
419422
item?.click();
420423
expect(palette.onNavigate).toHaveBeenCalledWith("cron");
421424

@@ -436,6 +439,120 @@ describe("CommandPalette lifecycle", () => {
436439
expect(list).not.toHaveBeenCalled();
437440
});
438441

442+
it.each(["click", "keyboard"])(
443+
"opens the selected catalog agent's encoded route by %s",
444+
async (method) => {
445+
const { gateway } = createGateway(true);
446+
const context = createContext(
447+
gateway,
448+
vi.fn(async () => null),
449+
);
450+
const { palette } = await mountPalette({
451+
...context,
452+
basePath: "/openclaw",
453+
agents: {
454+
...context.agents,
455+
ensureList: async () => ({
456+
defaultId: "main",
457+
mainKey: "main",
458+
scope: "per-sender",
459+
agents: [{ id: "reviewer.team", name: "Reviewer" }],
460+
}),
461+
},
462+
});
463+
await enterQuery(palette, "Reviewer");
464+
await vi.advanceTimersByTimeAsync(50);
465+
await palette.updateComplete;
466+
const item = palette.querySelector<HTMLElement>('[role="option"]');
467+
expect(item?.textContent).toContain("Reviewer");
468+
if (method === "click") {
469+
item?.click();
470+
} else {
471+
palette
472+
.querySelector("input")
473+
?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
474+
}
475+
expect(palette.onNavigate).toHaveBeenCalledWith("agents", {
476+
pathname: "/openclaw/settings/agents/reviewer%2Eteam",
477+
});
478+
expect(palette.isOpen).toBe(false);
479+
},
480+
);
481+
482+
it("moves the keyboard selection through catalog groups in visible order", async () => {
483+
const { gateway } = createGateway(true, {
484+
methods: ["cron.list"],
485+
request: vi.fn(async () => ({
486+
jobs: [{ id: "bravo", name: "Needle Bravo" }],
487+
})) as GatewayBrowserClient["request"],
488+
});
489+
const context = createContext(
490+
gateway,
491+
vi.fn(async () => null),
492+
);
493+
const { palette } = await mountPalette({
494+
...context,
495+
agents: {
496+
...context.agents,
497+
ensureList: async () => ({
498+
defaultId: "alpha",
499+
mainKey: "main",
500+
scope: "per-sender",
501+
agents: [
502+
{ id: "alpha", name: "Needle Alpha" },
503+
{ id: "charlie", name: "Needle Charlie" },
504+
],
505+
}),
506+
},
507+
});
508+
await enterQuery(palette, "Needle");
509+
await vi.advanceTimersByTimeAsync(50);
510+
await palette.updateComplete;
511+
const items = [...palette.querySelectorAll<HTMLElement>('[role="option"]')];
512+
expect(items.map((item) => item.textContent?.replace(/\s+/g, " ").trim())).toEqual([
513+
"Needle Alpha alpha",
514+
"Needle Charlie charlie",
515+
"Needle Bravo",
516+
]);
517+
for (const expectedIndex of [1, 2, 0]) {
518+
palette
519+
.querySelector("input")
520+
?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
521+
await palette.updateComplete;
522+
expect(palette.querySelector('[aria-selected="true"]')).toBe(items[expectedIndex]);
523+
}
524+
});
525+
526+
it.each(["agent:main:topic:thread", "agent:main:topic:\ud800"])(
527+
"keeps the active descendant bound for session key %j",
528+
async (key) => {
529+
const { gateway } = createGateway(true);
530+
const colon = createSessionResult(key, "Needle colon");
531+
const hyphen = createSessionResult("agent:main:topic-thread", "Needle hyphen");
532+
const { palette } = await mountPalette(
533+
createContext(
534+
gateway,
535+
vi.fn(async () => ({
536+
...colon,
537+
count: 2,
538+
sessions: [...colon.sessions, ...hyphen.sessions],
539+
})),
540+
),
541+
);
542+
await enterQuery(palette, "Needle");
543+
await vi.advanceTimersByTimeAsync(50);
544+
await palette.updateComplete;
545+
palette
546+
.querySelector("input")
547+
?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
548+
await palette.updateComplete;
549+
const active = palette.querySelector('[aria-selected="true"]');
550+
expect(active?.textContent).toContain("Needle hyphen");
551+
const activeId = palette.querySelector("input")?.getAttribute("aria-activedescendant");
552+
expect(document.getElementById(activeId ?? "")).toBe(active);
553+
},
554+
);
555+
439556
it("keeps bounded metadata pagination when transcript search is unavailable", async () => {
440557
const list = vi.fn<ApplicationContext<RouteId>["sessions"]["list"]>(async (options) => {
441558
const offset = options?.offset ?? 0;
@@ -527,7 +644,7 @@ describe("CommandPalette lifecycle", () => {
527644
);
528645
await enterQuery(palette, "plugins");
529646

530-
const item = palette.querySelector<HTMLButtonElement>("#cmd-palette-option-nav-plugins");
647+
const item = findPaletteOption(palette, "Plugins");
531648
expect(item?.textContent).toContain("Plugins");
532649
item?.click();
533650

@@ -550,9 +667,7 @@ describe("CommandPalette lifecycle", () => {
550667
palette.desktopAvailable = available;
551668
await enterQuery(palette, "desktop");
552669

553-
expect(palette.querySelectorAll("#cmd-palette-option-panel-desktop")).toHaveLength(
554-
expectedCount,
555-
);
670+
expect(findPaletteOption(palette, "Desktop", true) ? 1 : 0).toBe(expectedCount);
556671
},
557672
);
558673

@@ -570,7 +685,7 @@ describe("CommandPalette lifecycle", () => {
570685
const listener = (event: Event) => events.push(event as CustomEvent<DesktopPanelToggleDetail>);
571686
window.addEventListener(DESKTOP_PANEL_TOGGLE_EVENT, listener);
572687
try {
573-
palette.querySelector<HTMLElement>("#cmd-palette-option-panel-desktop")?.click();
688+
findPaletteOption(palette, "Desktop", true)?.click();
574689
} finally {
575690
window.removeEventListener(DESKTOP_PANEL_TOGGLE_EVENT, listener);
576691
}
@@ -595,9 +710,7 @@ describe("CommandPalette lifecycle", () => {
595710
palette.custodianAvailable = available;
596711
await enterQuery(palette, "openclaw");
597712

598-
expect(palette.querySelectorAll("#cmd-palette-option-panel-custodian")).toHaveLength(
599-
expectedCount,
600-
);
713+
expect(findPaletteOption(palette, "Ask OpenClaw", true) ? 1 : 0).toBe(expectedCount);
601714
},
602715
);
603716

@@ -616,7 +729,7 @@ describe("CommandPalette lifecycle", () => {
616729
events.push(event as CustomEvent<CustodianPanelToggleDetail>);
617730
window.addEventListener(CUSTODIAN_PANEL_TOGGLE_EVENT, listener);
618731
try {
619-
palette.querySelector<HTMLElement>("#cmd-palette-option-panel-custodian")?.click();
732+
findPaletteOption(palette, "Ask OpenClaw", true)?.click();
620733
} finally {
621734
window.removeEventListener(CUSTODIAN_PANEL_TOGGLE_EVENT, listener);
622735
}

‎ui/src/components/command-palette.ts‎

Lines changed: 28 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { html, nothing } from "lit";
55
import { property, state } from "lit/decorators.js";
66
import { ref } from "lit/directives/ref.js";
77
import type { SessionsSearchHit } from "../../../packages/gateway-protocol/src/index.js";
8-
import type { RouteId } from "../app-route-paths.ts";
8+
import { pathForAgentPanel, type RouteId } from "../app-route-paths.ts";
99
import { applicationContext, type ApplicationContext } from "../app/context.ts";
1010
import { hasOperatorAdminAccess } from "../app/operator-access.ts";
1111
import { t } from "../i18n/index.ts";
@@ -54,6 +54,7 @@ const SESSION_TRANSCRIPT_MAX_SESSION_KEYS = 200;
5454
const CATALOG_CACHE_TTL_MS = 30_000;
5555

5656
type CommandPaletteProps = {
57+
basePath: string;
5758
open: boolean;
5859
query: string;
5960
activeIndex: number;
@@ -65,30 +66,22 @@ type CommandPaletteProps = {
6566
onToggle: () => void;
6667
onQueryChange: (query: string) => void;
6768
onActiveIndexChange: (index: number) => void;
68-
onNavigate: (routeId: RouteId) => void;
69+
onNavigate?: ApplicationContext<RouteId>["navigate"];
6970
onSelectSession?: (sessionKey: string) => void;
7071
onSlashCommand?: (command: string) => void;
7172
desktopAvailable: boolean;
7273
custodianAvailable: boolean;
7374
onInputRef: (element: Element | undefined) => void;
7475
};
7576

76-
function filteredItems(
77-
query: string,
78-
includeSlashCommands = true,
79-
sessionItems: readonly PaletteItem[] = [],
80-
catalogItems: readonly PaletteItem[] = [],
81-
desktopAvailable = false,
82-
custodianAvailable = false,
83-
): PaletteItem[] {
84-
return filterCommandPaletteItems({
85-
query,
86-
includeSlashCommands,
87-
sessionItems,
88-
catalogItems,
89-
desktopAvailable,
90-
custodianAvailable,
91-
});
77+
function filteredItems(props: CommandPaletteProps): PaletteItem[] {
78+
// Keyboard selection and ARIA focus follow the same category order as the visible rows.
79+
return groupItems(
80+
filterCommandPaletteItems({
81+
...props,
82+
includeSlashCommands: Boolean(props.onSlashCommand),
83+
}),
84+
).flatMap(([, items]) => items);
9285
}
9386

9487
function groupItems(items: PaletteItem[]): Array<[string, PaletteItem[]]> {
@@ -107,7 +100,14 @@ const paletteListboxId = "cmd-palette-listbox";
107100

108101
function selectItem(item: PaletteItem, props: CommandPaletteProps) {
109102
if (item.action.startsWith("nav:")) {
110-
props.onNavigate(item.action.slice(4) as RouteId);
103+
const routeId = item.action.slice(4) as RouteId;
104+
if (item.agentId) {
105+
props.onNavigate?.(routeId, {
106+
pathname: pathForAgentPanel(item.agentId, null, props.basePath),
107+
});
108+
} else {
109+
props.onNavigate?.(routeId);
110+
}
111111
} else if (item.action.startsWith(SESSION_ACTION_PREFIX)) {
112112
props.onSelectSession?.(item.action.slice(SESSION_ACTION_PREFIX.length));
113113
} else if (item.action === "panel:desktop") {
@@ -132,14 +132,7 @@ function scrollActiveIntoView() {
132132
}
133133

134134
function handleKeydown(e: KeyboardEvent, props: CommandPaletteProps) {
135-
const items = filteredItems(
136-
props.query,
137-
Boolean(props.onSlashCommand),
138-
props.sessionItems,
139-
props.catalogItems,
140-
props.desktopAvailable,
141-
props.custodianAvailable,
142-
);
135+
const items = filteredItems(props);
143136
if (items.length === 0 && (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Enter")) {
144137
return;
145138
}
@@ -171,8 +164,8 @@ function handleKeydown(e: KeyboardEvent, props: CommandPaletteProps) {
171164
}
172165
}
173166

174-
function getOptionId(item: PaletteItem): string {
175-
return `cmd-palette-option-${item.id.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
167+
function getOptionId(index: number): string {
168+
return `cmd-palette-option-${index}`;
176169
}
177170

178171
function focusInput(el: Element | undefined) {
@@ -189,17 +182,10 @@ function renderCommandPalette(props: CommandPaletteProps) {
189182
if (!props.open) {
190183
return nothing;
191184
}
192-
const items = filteredItems(
193-
props.query,
194-
Boolean(props.onSlashCommand),
195-
props.sessionItems,
196-
props.catalogItems,
197-
props.desktopAvailable,
198-
props.custodianAvailable,
199-
);
185+
const items = filteredItems(props);
200186
const grouped = groupItems(items);
201187
const activeItem = items[props.activeIndex];
202-
const activeOptionId = activeItem ? getOptionId(activeItem) : nothing;
188+
const activeOptionId = activeItem ? getOptionId(props.activeIndex) : nothing;
203189
const paletteLabel = t("palette.placeholder");
204190

205191
return html`
@@ -265,7 +251,7 @@ function renderCommandPalette(props: CommandPaletteProps) {
265251
const isActive = globalIndex === props.activeIndex;
266252
return html`
267253
<div
268-
id=${getOptionId(item)}
254+
id=${getOptionId(globalIndex)}
269255
class="cmd-palette__item ${isActive ? "cmd-palette__item--active" : ""}"
270256
role="option"
271257
aria-selected=${isActive ? "true" : "false"}
@@ -299,7 +285,7 @@ function renderCommandPalette(props: CommandPaletteProps) {
299285
}
300286

301287
export class CommandPalette extends OpenClawLightDomContentsElement {
302-
@property({ attribute: false }) onNavigate?: (routeId: RouteId) => void;
288+
@property({ attribute: false }) onNavigate?: ApplicationContext<RouteId>["navigate"];
303289
@property({ attribute: false }) onSelectSession?: (sessionKey: string) => void;
304290
@property({ attribute: false }) onSlashCommand?: (command: string) => void;
305291
@property({ attribute: false }) desktopAvailable = false;
@@ -654,6 +640,7 @@ export class CommandPalette extends OpenClawLightDomContentsElement {
654640

655641
override render() {
656642
return renderCommandPalette({
643+
basePath: this.context?.basePath ?? "",
657644
open: this.open,
658645
query: this.query,
659646
activeIndex: this.activeIndex,
@@ -680,7 +667,7 @@ export class CommandPalette extends OpenClawLightDomContentsElement {
680667
onActiveIndexChange: (index) => {
681668
this.activeIndex = index;
682669
},
683-
onNavigate: (routeId) => this.onNavigate?.(routeId),
670+
onNavigate: this.onNavigate,
684671
onSelectSession: this.onSelectSession,
685672
onSlashCommand: this.onSlashCommand,
686673
onInputRef: this.handleInputRef,

0 commit comments

Comments
 (0)