Skip to content

Commit 3d37bb4

Browse files
authored
fix(ui): explain empty chat exports (#129881)
1 parent 647414e commit 3d37bb4

7 files changed

Lines changed: 161 additions & 8 deletions

File tree

‎ui/src/e2e/chat-slash-command-ranking.e2e.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Control UI E2E tests cover slash command relevance and keyboard ordering.
22
import path from "node:path";
3+
import { text } from "node:stream/consumers";
34
import { expect, it } from "vitest";
45
import { installMockGateway } from "../test-helpers/control-ui-e2e.ts";
56
import { createControlUiE2eSuite } from "./control-ui-e2e-suite.test-support.ts";
@@ -9,6 +10,94 @@ const suite = createControlUiE2eSuite({
910
});
1011

1112
suite.define(() => {
13+
it.each(["/export-session", "/export"])(
14+
"shows an empty export result and retains staged attachments for %s",
15+
async (command) => {
16+
const artifactDir = process.env.OPENCLAW_UI_E2E_ARTIFACT_DIR?.trim();
17+
await suite.withPage({ viewport: { width: 1280, height: 900 } }, async ({ page }) => {
18+
const gateway = await installMockGateway(page, { historyMessages: [] });
19+
const downloads: string[] = [];
20+
page.on("download", (download) => downloads.push(download.suggestedFilename()));
21+
22+
await page.goto(`${suite.server.baseUrl}chat`);
23+
await gateway.waitForRequest("chat.startup");
24+
const composer = page.locator(".agent-chat__composer-combobox textarea");
25+
await composer.waitFor({ state: "visible" });
26+
await page.locator(".agent-chat__file-input").setInputFiles({
27+
name: "export-proof.txt",
28+
mimeType: "text/plain",
29+
buffer: Buffer.from("keep this staged"),
30+
});
31+
const attachment = page.locator(".chat-attachment-file__name", {
32+
hasText: "export-proof.txt",
33+
});
34+
await attachment.waitFor({ state: "visible" });
35+
36+
await composer.fill(command);
37+
if (artifactDir && command === "/export") {
38+
await page.screenshot({
39+
path: path.join(artifactDir, "empty-export-before.png"),
40+
fullPage: true,
41+
});
42+
}
43+
await page.getByRole("button", { name: "Send message" }).click();
44+
45+
await page
46+
.locator(".chat-thread-inner")
47+
.getByText("There are no messages to export yet.", { exact: true })
48+
.waitFor({ state: "visible" });
49+
if (artifactDir && command === "/export") {
50+
await page.screenshot({
51+
path: path.join(artifactDir, "empty-export-after.png"),
52+
fullPage: true,
53+
});
54+
}
55+
await expect.poll(() => composer.inputValue()).toBe("");
56+
expect(await attachment.isVisible()).toBe(true);
57+
expect(await gateway.getRequests("chat.send")).toHaveLength(0);
58+
expect(downloads).toEqual([]);
59+
});
60+
},
61+
);
62+
63+
it("downloads a populated conversation as Markdown without sending a chat request", async () => {
64+
await suite.withPage({ viewport: { width: 1280, height: 900 } }, async ({ page }) => {
65+
const question = "What can you export?";
66+
const answer = "A readable conversation.";
67+
const gateway = await installMockGateway(page, {
68+
historyMessages: [
69+
{ role: "user", content: question },
70+
{ role: "assistant", content: answer },
71+
],
72+
});
73+
74+
await page.goto(`${suite.server.baseUrl}chat`);
75+
await gateway.waitForRequest("chat.startup");
76+
await page.locator(".chat-thread-inner").getByText(answer, { exact: true }).waitFor({
77+
state: "visible",
78+
});
79+
80+
const composer = page.locator(".agent-chat__composer-combobox textarea");
81+
await composer.fill("/export");
82+
const downloadPromise = page.waitForEvent("download");
83+
await page.getByRole("button", { name: "Send message" }).click();
84+
const download = await downloadPromise;
85+
86+
expect(download.suggestedFilename()).toMatch(/^chat-OpenClaw-.+\.md$/);
87+
const stream = await download.createReadStream();
88+
if (!stream) {
89+
throw new Error("chat export did not provide a readable download");
90+
}
91+
const markdown = await text(stream);
92+
expect(markdown).toContain("# Chat with OpenClaw");
93+
expect(markdown).toContain("## You");
94+
expect(markdown).toContain(question);
95+
expect(markdown).toContain("## OpenClaw");
96+
expect(markdown).toContain(answer);
97+
expect(await gateway.getRequests("chat.send")).toHaveLength(0);
98+
});
99+
});
100+
12101
it("keeps visible search results and keyboard selection in relevance order", async () => {
13102
const artifactDir = process.env.OPENCLAW_UI_E2E_ARTIFACT_DIR?.trim();
14103
await suite.withPage(

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5197,6 +5197,7 @@ export const en: TranslationMap = {
51975197
stoppingCurrentRun: "Stopping current run...",
51985198
chatHistoryCleared: "Chat history cleared.",
51995199
exportingThread: "Exporting session...",
5200+
emptyExport: "There are no messages to export yet.",
52005201
unknownCommand: "Unknown command: `{command}`",
52015202
options: "Options: {options}.",
52025203
sessionUnavailable: "Session capability is unavailable",

‎ui/src/pages/chat/chat-commands.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { CommandsListResult } from "../../../../packages/gateway-protocol/s
33
import type { GatewayBrowserClient } from "../../api/gateway.ts";
44
import type { ModelCatalogEntry, SessionsListResult } from "../../api/types.ts";
55
import type { ApplicationGatewaySnapshot } from "../../app/gateway.ts";
6+
import { t } from "../../i18n/index.ts";
67
import { peekChatMetadata } from "../../lib/chat/chat-metadata-store.ts";
78
import type { ChatQueueItem } from "../../lib/chat/chat-types.ts";
89
import {
@@ -31,6 +32,7 @@ import { executeSlashCommand } from "./chat-command-executor.ts";
3132
import { clearChatHistory } from "./chat-history.ts";
3233
import { enqueuePendingRunMessage } from "./chat-queue.ts";
3334
import { readChatSessionActionAccess } from "./chat-session-action-access.ts";
35+
import type { ChatExportResult } from "./export.ts";
3436
import { handleAbortChat } from "./run-lifecycle.ts";
3537
import { scheduleChatScroll, type ChatScrollHost } from "./scroll.ts";
3638

@@ -76,7 +78,7 @@ export type ChatCommandHost = Parameters<typeof handleAbortChat>[0] &
7678
sessionsResultAgentId?: string | null;
7779
createChatSession?: () => Promise<boolean>;
7880
confirmConversationReset?: () => Promise<boolean>;
79-
exportCurrentChat?: () => Promise<void> | void;
81+
exportCurrentChat?: () => Promise<ChatExportResult> | ChatExportResult;
8082
refreshCurrentSessionTools?: () => Promise<void>;
8183
refreshCurrentChat?: () => Promise<void>;
8284
} & UiSessionDefaultsHost &
@@ -389,7 +391,10 @@ export async function dispatchChatSlashCommand(
389391
}
390392
break;
391393
case "export-session":
392-
await host.exportCurrentChat?.();
394+
if ((await host.exportCurrentChat?.()) === "empty") {
395+
injectCommandResult(host, t("chat.commandResults.emptyExport"));
396+
scheduleChatScroll(host, false, false, { contentChanged: true });
397+
}
393398
return "completed";
394399
}
395400

‎ui/src/pages/chat/chat-send-submit.test.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -442,15 +442,26 @@ describe("handleSendChat browser annotation context", () => {
442442

443443
describe("handleSendChat immediate local commands", () => {
444444
it.each(["/export-session", "/export"])(
445-
"preserves staged attachments while %s exports the chat",
445+
"shows an empty export outcome and preserves staged attachments for %s",
446446
async (command) => {
447447
const attachment = createStagedAttachment("export-att");
448-
const exportCurrentChat = vi.fn();
449-
const host = createImmediateCommandHost(command, attachment, { exportCurrentChat });
448+
const exportCurrentChat = vi.fn(() => "empty" as const);
449+
const afterCommit = vi.fn(() => () => undefined);
450+
const host = createImmediateCommandHost(command, attachment, {
451+
exportCurrentChat,
452+
renderLifecycle: { invalidate: vi.fn(), afterCommit },
453+
});
450454

451455
await handleSendChat(host);
452456

453457
expect(exportCurrentChat).toHaveBeenCalledOnce();
458+
expect(host.chatMessages).toEqual([
459+
expect.objectContaining({
460+
role: "system",
461+
content: "There are no messages to export yet.",
462+
}),
463+
]);
464+
expect(afterCommit).toHaveBeenCalledOnce();
454465
expect(host.chatMessage).toBe("");
455466
expect(host.chatAttachments).toEqual([attachment]);
456467
expect(getChatAttachmentDataUrl(attachment)).toBe(attachmentDataUrl);

‎ui/src/pages/chat/chat-state-host.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import type { ChatProps } from "./chat-view.ts";
2222
import type { BackgroundTasksHost } from "./components/chat-background-tasks.ts";
2323
import type { SessionWorkspaceHost } from "./components/chat-session-workspace.ts";
2424
import type { SidebarContent } from "./components/chat-sidebar.ts";
25+
import type { ChatExportResult } from "./export.ts";
2526
import type { ChatInputHistoryKeyInput, ChatInputHistoryKeyResult } from "./input-history.ts";
2627
import type { RenderLifecycle } from "./render-lifecycle.ts";
2728
import type { PendingChatAbort } from "./run-lifecycle.ts";
@@ -157,7 +158,7 @@ export type ChatPageHost = ChatHost &
157158
announceSessionSwitch?: (sessionKey: string, label: string) => void;
158159
createChatSession?: () => Promise<boolean>;
159160
confirmConversationReset?: () => Promise<boolean>;
160-
exportCurrentChat?: () => Promise<void> | void;
161+
exportCurrentChat?: () => Promise<ChatExportResult> | ChatExportResult;
161162
refreshCurrentSessionTools?: () => Promise<void>;
162163
refreshCurrentChat?: () => Promise<void>;
163164
refreshSessionPullRequests?: (options?: { refresh?: boolean }) => Promise<void>;

‎ui/src/pages/chat/export.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { exportChatMarkdown } from "./export.ts";
3+
4+
afterEach(() => {
5+
vi.restoreAllMocks();
6+
});
7+
8+
describe("exportChatMarkdown", () => {
9+
it("reports an empty transcript without creating a download", () => {
10+
const createObjectURL = vi.spyOn(URL, "createObjectURL");
11+
const click = vi.spyOn(HTMLAnchorElement.prototype, "click");
12+
13+
expect(exportChatMarkdown([], "OpenClaw")).toBe("empty");
14+
expect(createObjectURL).not.toHaveBeenCalled();
15+
expect(click).not.toHaveBeenCalled();
16+
});
17+
18+
it("downloads one readable Markdown file for a populated transcript", async () => {
19+
const createObjectURL = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:chat-export");
20+
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
21+
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
22+
23+
expect(
24+
exportChatMarkdown(
25+
[
26+
{ role: "user", content: "What can you export?", timestamp: 1_000 },
27+
{ role: "assistant", content: "A readable conversation.", timestamp: 2_000 },
28+
],
29+
"OpenClaw",
30+
),
31+
).toBe("downloaded");
32+
33+
expect(createObjectURL).toHaveBeenCalledOnce();
34+
expect(click).toHaveBeenCalledOnce();
35+
expect(revokeObjectURL).toHaveBeenCalledWith("blob:chat-export");
36+
const markdown = await (createObjectURL.mock.calls[0]![0] as Blob).text();
37+
expect(markdown).toContain("# Chat with OpenClaw");
38+
expect(markdown).toContain("## You");
39+
expect(markdown).toContain("What can you export?");
40+
expect(markdown).toContain("## OpenClaw");
41+
expect(markdown).toContain("A readable conversation.");
42+
});
43+
});

‎ui/src/pages/chat/export.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
import { timestampMsToIsoString } from "@openclaw/normalization-core/number-coercion";
33
import { extractTextCached } from "../../lib/chat/message-extract.ts";
44

5+
export type ChatExportResult = "downloaded" | "empty";
6+
57
/**
68
* Export chat history as markdown file.
79
*/
8-
export function exportChatMarkdown(messages: unknown[], assistantName: string): void {
10+
export function exportChatMarkdown(messages: unknown[], assistantName: string): ChatExportResult {
911
const markdown = buildChatMarkdown(messages, assistantName);
1012
if (!markdown) {
11-
return;
13+
return "empty";
1214
}
1315
const blob = new Blob([markdown], { type: "text/markdown" });
1416
const url = URL.createObjectURL(blob);
@@ -17,6 +19,7 @@ export function exportChatMarkdown(messages: unknown[], assistantName: string):
1719
link.download = `chat-${assistantName}-${Date.now()}.md`;
1820
link.click();
1921
URL.revokeObjectURL(url);
22+
return "downloaded";
2023
}
2124

2225
function buildChatMarkdown(messages: unknown[], assistantName: string): string | null {

0 commit comments

Comments
 (0)