Skip to content

Commit 67afd98

Browse files
authored
refactor(ui): consolidate icons, formatters, and confirms (#118250)
* refactor(ui): consolidate small shared components * test(ui): wait for confirmation proof animation * test(ui): avoid unbound request assertion
1 parent 5aae66f commit 67afd98

38 files changed

Lines changed: 775 additions & 734 deletions
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* @vitest-environment jsdom */
2+
3+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
4+
import { getRenderedModalDialog, installDialogPolyfill } from "../test-helpers/modal-dialog.ts";
5+
import { showConfirmDialog } from "./confirm-dialog.ts";
6+
7+
let restoreDialogPolyfill: () => void;
8+
9+
function findButton(label: string): HTMLButtonElement {
10+
const button = [...document.body.querySelectorAll("button")].find(
11+
(candidate) => candidate.textContent?.trim() === label,
12+
);
13+
if (!(button instanceof HTMLButtonElement)) {
14+
throw new Error(`Expected ${label} button`);
15+
}
16+
return button;
17+
}
18+
19+
describe("showConfirmDialog", () => {
20+
beforeEach(() => {
21+
restoreDialogPolyfill = installDialogPolyfill();
22+
});
23+
24+
afterEach(() => {
25+
document.body.replaceChildren();
26+
restoreDialogPolyfill();
27+
});
28+
29+
it("renders accessible copy and resolves the selected action", async () => {
30+
const result = showConfirmDialog({
31+
title: "Delete thread?",
32+
message: "This cannot be undone.",
33+
details: "thread-1",
34+
confirmLabel: "Delete",
35+
danger: true,
36+
});
37+
const { modal, dialog } = await getRenderedModalDialog(document.body);
38+
39+
expect(dialog.getAttribute("aria-label")).toBe("Delete thread?");
40+
expect(dialog.getAttribute("aria-description")).toBe("This cannot be undone.");
41+
expect(modal.textContent).toContain("thread-1");
42+
expect(findButton("Delete").classList.contains("danger")).toBe(true);
43+
44+
findButton("Delete").click();
45+
46+
await expect(result).resolves.toBe(true);
47+
expect(document.body.querySelector("openclaw-modal-dialog")).toBeNull();
48+
});
49+
50+
it("treats modal dismissal as cancellation", async () => {
51+
const result = showConfirmDialog({ message: "Continue?" });
52+
const { modal } = await getRenderedModalDialog(document.body);
53+
54+
modal.dispatchEvent(new CustomEvent("modal-cancel"));
55+
56+
await expect(result).resolves.toBe(false);
57+
});
58+
59+
it("removes the dialog and cancels when its owner aborts", async () => {
60+
const controller = new AbortController();
61+
const result = showConfirmDialog({ message: "Continue?", signal: controller.signal });
62+
await getRenderedModalDialog(document.body);
63+
64+
controller.abort();
65+
66+
await expect(result).resolves.toBe(false);
67+
expect(document.body.querySelector("openclaw-modal-dialog")).toBeNull();
68+
});
69+
70+
it("rejects a reentrant confirmation instead of stacking or replaying it", async () => {
71+
const first = showConfirmDialog({ title: "First", message: "First action" });
72+
const second = showConfirmDialog({ title: "Second", message: "Second action" });
73+
await getRenderedModalDialog(document.body);
74+
75+
expect(document.body.textContent).toContain("First");
76+
expect(document.body.textContent).not.toContain("Second");
77+
await expect(second).resolves.toBe(false);
78+
findButton("Cancel").click();
79+
await expect(first).resolves.toBe(false);
80+
});
81+
});
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Control UI helper presents Promise-based confirmation without relying on a native dialog bridge.
2+
import { html, nothing, render } from "lit";
3+
import { t } from "../i18n/index.ts";
4+
import "./modal-dialog.ts";
5+
6+
export type ConfirmDialogOptions = {
7+
title?: string;
8+
message: string;
9+
details?: string;
10+
confirmLabel?: string;
11+
cancelLabel?: string;
12+
danger?: boolean;
13+
signal?: AbortSignal;
14+
};
15+
16+
let confirmationActive = false;
17+
18+
function presentConfirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
19+
if (options.signal?.aborted) {
20+
return Promise.resolve(false);
21+
}
22+
const host = document.createElement("div");
23+
document.body.append(host);
24+
return new Promise((resolve) => {
25+
let settled = false;
26+
const finish = (confirmed: boolean) => {
27+
if (settled) {
28+
return;
29+
}
30+
settled = true;
31+
options.signal?.removeEventListener("abort", handleAbort);
32+
render(nothing, host);
33+
host.remove();
34+
resolve(confirmed);
35+
};
36+
const handleAbort = () => finish(false);
37+
options.signal?.addEventListener("abort", handleAbort, { once: true });
38+
const title = options.title ?? t("common.confirm");
39+
render(
40+
html`
41+
<openclaw-modal-dialog
42+
label=${title}
43+
description=${options.message}
44+
@modal-cancel=${() => finish(false)}
45+
>
46+
<div class="exec-approval-card">
47+
<div class="exec-approval-header">
48+
<div>
49+
<div class="exec-approval-title">${title}</div>
50+
<div class="exec-approval-sub" style="white-space: pre-line">
51+
${options.message}
52+
</div>
53+
</div>
54+
</div>
55+
${options.details
56+
? html`<div class="exec-approval-command mono">${options.details}</div>`
57+
: nothing}
58+
<div class="exec-approval-actions">
59+
<button
60+
type="button"
61+
class="btn ${options.danger ? "danger" : "primary"}"
62+
@click=${() => finish(true)}
63+
>
64+
${options.confirmLabel ?? t("common.confirm")}
65+
</button>
66+
<button type="button" class="btn" autofocus @click=${() => finish(false)}>
67+
${options.cancelLabel ?? t("common.cancel")}
68+
</button>
69+
</div>
70+
</div>
71+
</openclaw-modal-dialog>
72+
`,
73+
host,
74+
);
75+
});
76+
}
77+
78+
/** Native confirms block reentrancy; reject a second request instead of replaying it later. */
79+
export function showConfirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
80+
if (confirmationActive) {
81+
return Promise.resolve(false);
82+
}
83+
confirmationActive = true;
84+
return presentConfirmDialog(options).finally(() => {
85+
confirmationActive = false;
86+
});
87+
}

‎ui/src/components/icons.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,46 @@ export const icons = {
4141
<line x1="16" x2="8" y1="13" y2="13" />
4242
<line x1="16" x2="8" y1="17" y2="17" />
4343
<line x1="10" x2="8" y1="9" y2="9" />`),
44+
file: strokeIcon(svg` <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
45+
<polyline points="14 2 14 8 20 8" />`),
46+
mail: strokeIcon(svg` <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
47+
<polyline points="22,6 12,13 2,6" />`),
48+
star: strokeIcon(
49+
svg`<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />`,
50+
),
51+
wandSparkles: strokeIcon(svg` <path d="M15 4V2" />
52+
<path d="M15 16v-2" />
53+
<path d="M8 9h2" />
54+
<path d="M20 9h2" />
55+
<path d="M17.8 11.8 19 13" />
56+
<path d="M15 9h0" />
57+
<path d="M17.8 6.2 19 5" />
58+
<path d="m3 21 9-9" />
59+
<path d="M12.2 6.2 11 5" />`),
60+
chrome: strokeIcon(svg` <circle cx="12" cy="12" r="10" />
61+
<circle cx="12" cy="12" r="4" />
62+
<line x1="21.17" y1="8" x2="12" y2="8" />
63+
<line x1="3.95" y1="6.06" x2="8.54" y2="14" />
64+
<line x1="10.88" y1="21.94" x2="15.46" y2="14" />`),
65+
panelsTopLeft: strokeIcon(svg` <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
66+
<line x1="3" y1="9" x2="21" y2="9" />
67+
<line x1="9" y1="21" x2="9" y2="9" />`),
68+
box: strokeIcon(svg` <path
69+
d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"
70+
/>
71+
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
72+
<line x1="12" y1="22.08" x2="12" y2="12" />`),
73+
music: strokeIcon(svg` <path d="M9 18V5l12-2v13" />
74+
<circle cx="6" cy="18" r="3" />
75+
<circle cx="18" cy="16" r="3" />`),
76+
asterisk: strokeIcon(svg` <path d="M12 2v6" />
77+
<path d="m4.93 10.93 4.24 4.24" />
78+
<path d="M2 12h6" />
79+
<path d="m4.93 13.07 4.24-4.24" />
80+
<path d="M12 22v-6" />
81+
<path d="m19.07 13.07-4.24-4.24" />
82+
<path d="M22 12h-6" />
83+
<path d="m19.07 10.93-4.24 4.24" />`),
4484
zap: strokeIcon(svg`<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />`),
4585
monitor: strokeIcon(svg` <rect width="20" height="14" x="2" y="3" rx="2" />
4686
<line x1="8" x2="16" y1="21" y2="21" />

‎ui/src/e2e/session-management.archive.e2e.test.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ import {
1515

1616
const suite = createSessionManagementE2eSuite();
1717

18+
async function confirmDelete(page: import("playwright").Page, proofName?: string) {
19+
const dialog = page.locator("openclaw-modal-dialog").last();
20+
const nativeDialog = dialog.locator("wa-dialog").locator("dialog");
21+
await expect
22+
.poll(() => nativeDialog.evaluate((element) => getComputedStyle(element).opacity))
23+
.toBe("1");
24+
if (proofName) {
25+
await captureUiProof(page, proofName);
26+
}
27+
await dialog.getByRole("button", { name: "Delete", exact: true }).click();
28+
}
29+
1830
suite.define(() => {
1931
it("deletes every archived thread exactly once when the paged roster reorders", async () => {
2032
const context = await suite.browser.newContext({
@@ -53,8 +65,8 @@ suite.define(() => {
5365
sessionsListResponse(archived, { totalCount: 3 }),
5466
],
5567
});
56-
page.once("dialog", (dialog) => void dialog.accept());
5768
await remove.click();
69+
await confirmDelete(page, "styled-confirm-delete-archived.png");
5870

5971
await expect
6072
.poll(async () =>
@@ -108,11 +120,11 @@ suite.define(() => {
108120
await expect.poll(() => page.locator(".data-table-bulk-bar").count()).toBe(0);
109121

110122
await rowFor("Bravo").locator('input[type="checkbox"]').check();
111-
page.once("dialog", (dialog) => void dialog.accept());
112123
await page
113124
.locator(".data-table-bulk-bar")
114125
.getByRole("button", { name: "Delete", exact: true })
115126
.click();
127+
await confirmDelete(page);
116128
await gateway.waitForRequest("sessions.delete");
117129

118130
await expect
@@ -522,8 +534,6 @@ suite.define(() => {
522534
},
523535
sessionKey: "agent:main:main",
524536
});
525-
page.on("dialog", (dialog) => void dialog.accept());
526-
527537
try {
528538
await page.goto(`${suite.server.baseUrl}sessions?status=archived`);
529539
const row = page.locator(".session-data-row").filter({ hasText: "Research notes" });
@@ -533,6 +543,7 @@ suite.define(() => {
533543
await activateMenuItem(
534544
page.locator("openclaw-session-menu").getByRole("menuitem", { name: "Delete…" }),
535545
);
546+
await confirmDelete(page);
536547

537548
const request = await gateway.waitForRequest("sessions.delete");
538549
expect(requireRecord(request.params)).toMatchObject({

‎ui/src/e2e/session-management.operator-scopes.e2e.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ const archived = sessionRow(
1414
{ archived: true },
1515
);
1616

17+
async function confirmDelete(page: import("playwright").Page) {
18+
await page
19+
.locator("openclaw-modal-dialog")
20+
.last()
21+
.getByRole("button", { name: "Delete", exact: true })
22+
.click();
23+
}
24+
1725
async function openArchivedPage(operatorScopes: string[]) {
1826
const context = await suite.browser.newContext({
1927
locale: "en-US",
@@ -43,9 +51,9 @@ suite.define(() => {
4351
"operator.write",
4452
]);
4553
try {
46-
page.on("dialog", (dialog) => void dialog.accept());
4754
await expect.poll(() => deleteAll.isEnabled()).toBe(true);
4855
await deleteAll.click();
56+
await confirmDelete(page);
4957

5058
await expect(gateway.waitForRequest("sessions.delete")).resolves.toMatchObject({
5159
params: {

‎ui/src/i18n/locales/en.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -840,10 +840,15 @@ export const en: TranslationMap = {
840840
restoreSession: "Restore thread",
841841
stopCloudWorker: "Stop cloud worker…",
842842
stopCloudWorkerConfirm: 'Stop the cloud worker for "{session}"?',
843+
stopCloudWorkerConfirmAction: "Stop worker",
843844
deleteSessionMenu: "Delete…",
844845
deleteSessionCount: "Delete {count}…",
845846
deleteSessionConfirm: 'Delete "{session}" and its transcript?',
846847
deleteSessionsConfirm: "Delete {count} threads and their transcripts?",
848+
deleteSelectedConfirmOne:
849+
"Delete 1 thread?\n\nThis will delete the thread entry and archive its transcript.",
850+
deleteSelectedConfirm:
851+
"Delete {count} threads?\n\nThis will delete the thread entries and archive their transcripts.",
847852
groupBy: "Group by",
848853
groupByNone: "None",
849854
groupByCategory: "Custom groups",
@@ -877,7 +882,10 @@ export const en: TranslationMap = {
877882
noCheckpoints: "No compaction checkpoints recorded for this thread.",
878883
noSummary: "No summary captured.",
879884
branchFromCheckpoint: "Branch from checkpoint",
885+
branchCheckpointConfirm: "Create a new child thread from this compacted checkpoint?",
880886
restoreCheckpoint: "Restore checkpoint",
887+
restoreCheckpointConfirm:
888+
"Restore this thread to the selected compacted checkpoint?\n\nThis replaces the current active transcript for the session key.",
881889
},
882890
agents: {
883891
noAgents: "No agents",
@@ -3105,12 +3113,6 @@ export const en: TranslationMap = {
31053113
workflowHeading: "How the agent will use it",
31063114
applicabilityHeading: "When the agent should use it",
31073115
},
3108-
relative: {
3109-
secondsAgo: "{count}s ago",
3110-
minutesAgo: "{count} minutes ago",
3111-
hoursAgo: "{count}h ago",
3112-
daysAgo: "{count}d ago",
3113-
},
31143116
},
31153117
activity: {
31163118
title: "Activity",
@@ -3762,10 +3764,10 @@ export const en: TranslationMap = {
37623764
resetDiaryComplete: "Removed {count} backfilled dream diary entries.",
37633765
clearReplayedComplete: "Cleared {count} replayed short-term entries.",
37643766
complete: "Dream diary action complete.",
3765-
confirmRepair:
3766-
"Repair Dream Cache? This archives derived dream cache files and rebuilds them from clean inputs. Your dream diary stays untouched.",
3767-
confirmDedupe:
3768-
"Dedupe Dream Diary? This rewrites DREAMS.md and removes only exact duplicate diary entries.",
3767+
confirmRepairDescription:
3768+
"This archives derived dream cache files and rebuilds them from clean inputs. Your dream diary stays untouched.",
3769+
confirmDedupeDescription:
3770+
"This rewrites DREAMS.md and removes only exact duplicate diary entries.",
37693771
archivePathCopied: "Archive path copied.",
37703772
archivePathCopyFailed: "Could not copy archive path.",
37713773
updateFailed: "Could not update dreaming settings.",

‎ui/src/lib/agents/display.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,18 @@ describe("formatBytes", () => {
163163
expect(formatBytes(12 * 1024)).toBe("12 KB");
164164
expect(formatBytes(2 * 1024 * 1024)).toBe("2.0 MB");
165165
});
166+
167+
it("supports caller-owned fallback, unit cap, and precision", () => {
168+
const options = {
169+
fallback: "0 B",
170+
maxUnit: "kilo" as const,
171+
fractionDigits: (_value: number, unit: "byte" | "kilo" | "mega" | "giga" | "tera") =>
172+
unit === "byte" ? null : 1,
173+
};
174+
expect(formatBytes(Number.NaN, options)).toBe("0 B");
175+
expect(formatBytes(12 * 1024, options)).toBe("12.0 KB");
176+
expect(formatBytes(1024 * 1024, options)).toBe("1024.0 KB");
177+
});
166178
});
167179

168180
describe("resolveEffectiveModelFallbacks", () => {

0 commit comments

Comments
 (0)