Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: optimize agent window layout (#21644)

ecmadaodab4dd3f6cda
diff --git a/frontend/src/components/HumanizeTs.test.tsx b/frontend/src/components/HumanizeTs.test.tsx
index 1dd4d7a86d..aca8f4350a 100644
--- a/frontend/src/components/HumanizeTs.test.tsx
+++ b/frontend/src/components/HumanizeTs.test.tsx
@@ -154,6 +154,17 @@ describe("HumanizeTs", () => {
expect(formatters.formatAbsoluteDateTime).toHaveBeenCalledWith(1000000);
});
+ test("updates a calendar label at local midnight", () => {
+ vi.setSystemTime(new Date("2026-10-23T15:59:59Z"));
+ const tsMs = new Date("2026-10-23T02:03:00Z").getTime();
+ const { container, root } = mount();
+ act(() => root.render(<HumanizeTs mode="calendar" tsMs={tsMs} tooltip={false} />));
+ expect(container.textContent).toBe("Today 10:03 AM");
+
+ act(() => vi.advanceTimersByTime(1_000));
+ expect(container.textContent).toBe("Yesterday 10:03 AM");
+ });
+
test("renders one element, so layout classes reach the box that lays out", () => {
const { container, root } = mount();
act(() =>
diff --git a/frontend/src/components/HumanizeTs.tsx b/frontend/src/components/HumanizeTs.tsx
index dd30c8fd7b..b23e825638 100644
--- a/frontend/src/components/HumanizeTs.tsx
+++ b/frontend/src/components/HumanizeTs.tsx
@@ -5,6 +5,7 @@ import { useTimeReading } from "@/hooks/useTimeReading";
import { cn } from "@/lib/utils";
import {
absoluteTimeReading,
+ calendarTimeReading,
compactTimeReading,
type DateTimeSegments,
dateTimeSegments,
@@ -21,13 +22,18 @@ import {
*
* - `queue` — freshness-first work queues and feeds: relative age, switching to
* an absolute date at 30 days.
- * - `compact` — history rows scanned to locate a record: date and time to the
- * minute.
+ * - `calendar` — today or yesterday with local time, then date and time.
+ * - `compact` — local date and time to the minute, without seconds or timezone.
* - `operational` — a future time the reader acts on, so the timezone is named
* in the visible string rather than left to a hover.
* - `datetime` — a record whose time is the evidence: full precision inline.
*/
-export type TimeDisplayMode = "queue" | "compact" | "operational" | "datetime";
+export type TimeDisplayMode =
+ | "queue"
+ | "calendar"
+ | "compact"
+ | "operational"
+ | "datetime";
interface HumanizeTsProps {
/** The instant to show, in milliseconds; nothing renders without one. */
@@ -71,6 +77,7 @@ const MODES: Record<
}
> = {
queue: { label: queueTimeReading, Hidden: FullDateTime, hasTime: false },
+ calendar: { label: calendarTimeReading, Hidden: FullDateTime, hasTime: true },
compact: { label: compactTimeReading, Hidden: FullDateTime, hasTime: true },
operational: {
label: operationalTimeReading,
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 8704a49981..a5b0ad2b4c 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -22,7 +22,6 @@
}
},
"agent": {
- "active-only-chats": "View active chats",
"ai-not-configured": {
"configure": "Configure",
"contact-admin": "Contact your workspace admin to configure AI.",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 06c147585f..583ee25923 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -22,7 +22,6 @@
}
},
"agent": {
- "active-only-chats": "Ver chats activos",
"ai-not-configured": {
"configure": "Configurar",
"contact-admin": "Contacte al administrador de su espacio de trabajo para configurar la IA.",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 3dc8dde404..db722c5a7b 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -22,7 +22,6 @@
}
},
"agent": {
- "active-only-chats": "アクティブなチャットを表示",
"ai-not-configured": {
"configure": "設定",
"contact-admin": "ワークスペース管理者に AI の設定を依頼してください。",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 22c33915c7..446712c8e9 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -22,7 +22,6 @@
}
},
"agent": {
- "active-only-chats": "Xem các cuộc trò chuyện đang hoạt động",
"ai-not-configured": {
"configure": "Cấu hình",
"contact-admin": "Liên hệ quản trị viên không gian làm việc để cấu hình AI.",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 53c69c95ea..4e00baef47 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -22,7 +22,6 @@
}
},
"agent": {
- "active-only-chats": "查看活跃对话",
"ai-not-configured": {
"configure": "配置",
"contact-admin": "请联系工作区管理员配置 AI。",
diff --git a/frontend/src/modules/agent/components/AgentChat.test.tsx b/frontend/src/modules/agent/components/AgentChat.test.tsx
index 054fb2c7a8..606f6a71b8 100644
--- a/frontend/src/modules/agent/components/AgentChat.test.tsx
+++ b/frontend/src/modules/agent/components/AgentChat.test.tsx
@@ -1,7 +1,7 @@
import type { ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_ISSUE_DETAIL,
@@ -121,6 +121,10 @@ beforeEach(async () => {
({ AgentChat } = await import("./AgentChat"));
});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
describe("AgentChat", () => {
test("shows AI setup when the cached AI setting is disabled", () => {
mocks.getSettingByName.mockImplementation((name) => {
@@ -519,6 +523,42 @@ describe("AgentChat", () => {
unmount();
});
+ test("shows yesterday and the local time for a message from yesterday", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-22T04:03:00Z"));
+ useAgentStore.getState().addMessage({
+ role: "user",
+ content: "How do I connect a database?",
+ });
+ vi.setSystemTime(new Date("2026-10-23T04:03:00Z"));
+
+ const { container, render, unmount } = renderIntoContainer(<AgentChat />);
+ render();
+
+ const timestamp = container.querySelector("[data-agent-message-timestamp]");
+ expect(timestamp?.textContent).toBe("Yesterday 12:03 PM");
+
+ unmount();
+ });
+
+ test("shows today and the local time for a recent message", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-23T03:03:00Z"));
+ useAgentStore.getState().addMessage({
+ role: "user",
+ content: "How do I connect a database?",
+ });
+ vi.setSystemTime(new Date("2026-10-23T04:03:00Z"));
+
+ const { container, render, unmount } = renderIntoContainer(<AgentChat />);
+ render();
+
+ const timestamp = container.querySelector("[data-agent-message-timestamp]");
+ expect(timestamp?.textContent).toBe("Today 11:03 AM");
+
+ unmount();
+ });
+
test("renders a pending starter as one compact status instead of progress cards", () => {
const chat = useAgentStore.getState().ensureCurrentChat();
useAgentStore.getState().setChatStatus(chat.id, "running");
diff --git a/frontend/src/modules/agent/components/AgentChat.tsx b/frontend/src/modules/agent/components/AgentChat.tsx
index 51b6ad400b..8df49ce4d6 100644
--- a/frontend/src/modules/agent/components/AgentChat.tsx
+++ b/frontend/src/modules/agent/components/AgentChat.tsx
@@ -308,7 +308,7 @@ export function AgentChat({ className }: AgentChatProps) {
dateTime={new Date(msg.createdTs).toISOString()}
data-agent-message-timestamp
>
- <HumanizeTs tsMs={msg.createdTs} tooltip={false} />
+ <HumanizeTs tsMs={msg.createdTs} mode="calendar" tooltip={false} />
</time>
);
diff --git a/frontend/src/modules/agent/components/AgentInput.test.tsx b/frontend/src/modules/agent/components/AgentInput.test.tsx
index c32458cf75..c35c0c0e0e 100644
--- a/frontend/src/modules/agent/components/AgentInput.test.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.test.tsx
@@ -209,35 +209,6 @@ const setTextareaValue = (textarea: HTMLTextAreaElement, value: string) => {
descriptor?.set?.call(textarea, value);
};
-const stubAnimationFrames = () => {
- let nextFrameId = 0;
- const callbacks = new Map<number, FrameRequestCallback>();
-
- vi.stubGlobal(
- "requestAnimationFrame",
- vi.fn((callback: FrameRequestCallback) => {
- const frameId = ++nextFrameId;
- callbacks.set(frameId, callback);
- return frameId;
- })
- );
- vi.stubGlobal(
- "cancelAnimationFrame",
- vi.fn((frameId: number) => {
- callbacks.delete(frameId);
- })
- );
-
- return async () => {
- const currentCallbacks = [...callbacks.values()];
- callbacks.clear();
-
- await act(async () => {
- currentCallbacks.forEach((callback) => callback(performance.now()));
- });
- };
-};
-
beforeEach(async () => {
vi.stubGlobal("localStorage", createMockStorage());
const initialState = createAgentStore().getState();
@@ -336,7 +307,10 @@ describe("AgentInput", () => {
});
test("sends a queued Project Home message in its bound chat once", async () => {
- mocks.runAgentLoop.mockResolvedValue({ kind: "completed", totalTokensUsed: 0 });
+ mocks.runAgentLoop.mockResolvedValue({
+ kind: "completed",
+ totalTokensUsed: 0,
+ });
const page = { path: "/projects/billing", title: "Billing" };
const store = useAgentStore.getState();
const chat = store.createChat({ context: "projects/billing", page });
@@ -1693,7 +1667,7 @@ describe("AgentInput", () => {
}
});
- test("mounts mention suggestions into the agent layer root", async () => {
+ test("treats @ as ordinary text without loading page-element suggestions", async () => {
const suggestions: DomRefSuggestion[] = [
{
ref: "button.submit",
@@ -1704,6 +1678,7 @@ describe("AgentInput", () => {
},
];
mocks.lazyExtractDomRefSuggestions.mockResolvedValue(suggestions);
+ mocks.runAgentLoop.mockResolvedValue({ kind: "completed", totalTokensUsed: 0 });
const { render, unmount } = renderIntoContainer(<AgentInput />);
@@ -1715,11 +1690,28 @@ describe("AgentInput", () => {
await act(async () => {
setTextareaValue(textarea, "@");
+ textarea.setSelectionRange(1, 1);
textarea.dispatchEvent(new Event("input", { bubbles: true }));
});
- const agentRoot = document.getElementById("bb-react-layer-agent");
- expect(agentRoot?.querySelector("[data-agent-mention-list]")).toBeTruthy();
+ expect(mocks.lazyExtractDomRefSuggestions).not.toHaveBeenCalled();
+ expect(document.body.querySelector("[data-agent-mention-list]")).toBeNull();
+
+ await act(async () => {
+ textarea.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
+ );
+ await vi.waitFor(() => expect(mocks.runAgentLoop).toHaveBeenCalledOnce());
+ });
+ expect(
+ useAgentStore
+ .getState()
+ .getMessages(useAgentStore.getState().currentChatId!)
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: "user", content: "@" }),
+ ])
+ );
unmount();
});
@@ -1790,75 +1782,6 @@ describe("AgentInput", () => {
unmount();
});
- test("repositions mention suggestions when the textarea rect changes", async () => {
- const suggestions: DomRefSuggestion[] = [
- {
- ref: "button.submit",
- tag: "BUTTON",
- role: "button",
- label: "Submit",
- value: "",
- },
- ];
- mocks.lazyExtractDomRefSuggestions.mockResolvedValue(suggestions);
- const flushAnimationFrame = stubAnimationFrames();
-
- const { render, unmount } = renderIntoContainer(<AgentInput />);
-
- render();
-
- const textarea = document.body.querySelector(
- "textarea"
- ) as HTMLTextAreaElement;
-
- let rect = {
- bottom: 234,
- height: 34,
- left: 100,
- right: 400,
- top: 200,
- width: 300,
- x: 100,
- y: 200,
- toJSON: () => "",
- };
- vi.spyOn(textarea, "getBoundingClientRect").mockImplementation(
- () => rect as DOMRect
- );
-
- await act(async () => {
- setTextareaValue(textarea, "@");
- textarea.setSelectionRange(1, 1);
- textarea.dispatchEvent(new Event("input", { bubbles: true }));
- });
-
- const mentionList = document.body.querySelector(
- "[data-agent-mention-list]"
- ) as HTMLDivElement;
- expect(mentionList.style.left).toBe("100px");
- expect(mentionList.style.top).toBe("196px");
- expect(mentionList.style.width).toBe("300px");
-
- rect = {
- ...rect,
- bottom: 294,
- left: 160,
- right: 440,
- top: 260,
- width: 280,
- x: 160,
- y: 260,
- };
-
- await flushAnimationFrame();
-
- expect(mentionList.style.left).toBe("160px");
- expect(mentionList.style.top).toBe("256px");
- expect(mentionList.style.width).toBe("280px");
-
- unmount();
- });
-
test("shows a single-line overlay placeholder and hides it when typing", () => {
const { container, render, unmount } = renderIntoContainer(<AgentInput />);
@@ -1925,17 +1848,80 @@ describe("AgentInput", () => {
unmount();
});
- test("grows without a maximum height", () => {
+ test("caps textarea growth at the available composer height", () => {
const { container, render, unmount } = renderIntoContainer(<AgentInput />);
render();
const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
+ const composer = container.querySelector(
+ "[data-agent-input-row]"
+ )?.parentElement as HTMLDivElement;
Object.defineProperties(textarea, {
clientHeight: { configurable: true, value: 32 },
offsetHeight: { configurable: true, value: 34 },
scrollHeight: { configurable: true, value: 200 },
});
+ Object.defineProperties(composer, {
+ offsetHeight: { configurable: true, value: 90 },
+ });
+ Object.defineProperties(container, {
+ clientHeight: { configurable: true, value: 150 },
+ });
+ const getComputedStyleSpy = vi
+ .spyOn(window, "getComputedStyle")
+ .mockReturnValue({ minHeight: "34px" } as CSSStyleDeclaration);
+
+ act(() => {
+ setTextareaValue(textarea, "a\nb\nc\nd\ne\nf\ng");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ expect(textarea.style.height).toBe("94px");
+ expect(textarea.style.overflowY).toBe("auto");
+ getComputedStyleSpy.mockRestore();
+ unmount();
+ });
+
+ test("updates the textarea cap when the chat pane height changes", () => {
+ let resizeCallback: ResizeObserverCallback | undefined;
+ let observedElement: Element | undefined;
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallback = callback;
+ }
+
+ observe(element: Element) {
+ observedElement = element;
+ }
+
+ disconnect() {}
+ }
+ );
+
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ let chatPaneHeight = 300;
+ Object.defineProperty(container, "clientHeight", {
+ configurable: true,
+ get: () => chatPaneHeight,
+ });
+
+ render();
+
+ const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
+ const composer = container.querySelector(
+ "[data-agent-input-row]"
+ )?.parentElement as HTMLDivElement;
+ Object.defineProperties(textarea, {
+ clientHeight: { configurable: true, value: 32 },
+ offsetHeight: { configurable: true, value: 34 },
+ scrollHeight: { configurable: true, value: 200 },
+ });
+ Object.defineProperties(composer, {
+ offsetHeight: { configurable: true, value: 90 },
+ });
const getComputedStyleSpy = vi
.spyOn(window, "getComputedStyle")
.mockReturnValue({ minHeight: "34px" } as CSSStyleDeclaration);
@@ -1947,7 +1933,90 @@ describe("AgentInput", () => {
expect(textarea.style.height).toBe("202px");
expect(textarea.style.overflowY).toBe("hidden");
+ expect(resizeCallback).toBeTypeOf("function");
+ expect(observedElement).toBe(container);
+
+ chatPaneHeight = 150;
+ act(() => {
+ resizeCallback?.([], {} as ResizeObserver);
+ });
+
+ expect(textarea.style.height).toBe("94px");
+ expect(textarea.style.overflowY).toBe("auto");
getComputedStyleSpy.mockRestore();
unmount();
});
+
+ test("shrinks the textarea when composer chrome grows", () => {
+ let resizeCallback: ResizeObserverCallback | undefined;
+ const observedElements = new Set<Element>();
+ const disconnect = vi.fn();
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallback = callback;
+ }
+
+ observe(element: Element) {
+ observedElements.add(element);
+ }
+
+ disconnect() {
+ disconnect();
+ }
+ }
+ );
+
+ const { container, render, unmount } = renderIntoContainer(<AgentInput />);
+ Object.defineProperty(container, "clientHeight", {
+ configurable: true,
+ value: 300,
+ });
+
+ render();
+
+ const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
+ const composer = container.querySelector(
+ "[data-agent-input-row]"
+ )?.parentElement as HTMLDivElement;
+ let composerHeight = 90;
+ Object.defineProperties(textarea, {
+ clientHeight: { configurable: true, value: 32 },
+ offsetHeight: { configurable: true, value: 34 },
+ scrollHeight: { configurable: true, value: 200 },
+ });
+ Object.defineProperty(composer, "offsetHeight", {
+ configurable: true,
+ get: () => composerHeight,
+ });
+ const getComputedStyleSpy = vi
+ .spyOn(window, "getComputedStyle")
+ .mockReturnValue({ minHeight: "34px" } as CSSStyleDeclaration);
+
+ try {
+ act(() => {
+ setTextareaValue(textarea, "a\nb\nc\nd\ne\nf\ng");
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ expect(textarea.style.height).toBe("202px");
+ expect(textarea.style.overflowY).toBe("hidden");
+
+ composerHeight = 240;
+ act(() => {
+ if (observedElements.has(composer)) {
+ resizeCallback?.([], {} as ResizeObserver);
+ }
+ });
+
+ expect(textarea.style.height).toBe("94px");
+ expect(textarea.style.overflowY).toBe("auto");
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ unmount();
+ }
+
+ expect(disconnect).toHaveBeenCalledOnce();
+ });
});
diff --git a/frontend/src/modules/agent/components/AgentInput.tsx b/frontend/src/modules/agent/components/AgentInput.tsx
index 52f201b106..1f932e576e 100644
--- a/frontend/src/modules/agent/components/AgentInput.tsx
+++ b/frontend/src/modules/agent/components/AgentInput.tsx
@@ -1,24 +1,12 @@
-import {
- type CSSProperties,
- useCallback,
- useEffect,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { createPortal } from "react-dom";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { router } from "@/app/router";
import { Button } from "@/components/ui/button";
-import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/components/ui/layer";
import { Textarea } from "@/components/ui/textarea";
import { projectNamePrefix } from "@/lib/resourceName";
import { useAppStore } from "@/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
-import type { DomRefSuggestion } from "../dom";
-import { lazyExtractDomRefSuggestions } from "../dom";
import { runAgentLoop } from "../logic/agentLoop";
import {
getAgentAIConfigurationEnabled,
@@ -59,66 +47,17 @@ import { AgentContextPicker } from "./AgentContextPicker";
// Module-level map — survives across renders.
const runTokens = new Map<string, number>();
-// Module-level request token for dom ref suggestion loading.
-let domRefRequestToken = 0;
-
const tokenFormatter = new Intl.NumberFormat();
// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------
-const normalizeSearchText = (value?: string) =>
- value?.toLowerCase().trim() ?? "";
-
-const matchDomRefSuggestion = (suggestion: DomRefSuggestion, query: string) => {
- if (!query) return true;
- const normalizedQuery = normalizeSearchText(query);
- return [
- suggestion.ref,
- suggestion.tag,
- suggestion.role,
- suggestion.label,
- suggestion.value,
- ].some((value) => normalizeSearchText(value).includes(normalizedQuery));
-};
-
-const getDomRefQuery = (
- text: string,
- start: number,
- end: number
-): { query: string; start: number; end: number } | null => {
- if (start !== end) return null;
- const prefix = text.slice(0, start);
- const matches = prefix.match(/(^|\s)@([^\s@]*)$/);
- if (!matches) return null;
- return {
- query: matches[2] ?? "",
- start: start - matches[2].length - 1,
- end,
- };
-};
-
-const formatDomRefSuggestionMeta = (suggestion: DomRefSuggestion) =>
- [suggestion.tag.toLowerCase(), suggestion.role]
- .filter((value): value is string => Boolean(value))
- .join(" · ");
-
const getCurrentPageSnapshot = () => ({
path: router.currentRoute.value.fullPath,
title: document.title,
});
-const buildMentionListStyle = (rect: DOMRect): CSSProperties => ({
- left: rect.left,
- top: rect.top - 4,
- transform: "translateY(-100%)",
- width: rect.width,
-});
-
-const getMentionListStyleKey = (rect: DOMRect) =>
- `${rect.left}:${rect.top}:${rect.width}`;
-
interface RecentActivityEvent {
actor: string;
action: string;
@@ -249,12 +188,6 @@ const mergeOverviewEvidence = (
// Component
// ---------------------------------------------------------------------------
-interface DomRefMentionOption {
- label: string;
- value: string;
- suggestion: DomRefSuggestion;
-}
-
export function AgentInput() {
const { t, i18n } = useTranslation();
// Zustand selectors
@@ -374,19 +307,9 @@ export function AgentInput() {
// Local state
const [input, setInput] = useState("");
- const [selectionStart, setSelectionStart] = useState(0);
- const [selectionEnd, setSelectionEnd] = useState(0);
- const [domRefSuggestions, setDomRefSuggestions] = useState<
- DomRefSuggestion[]
- >([]);
- const [isMentionOpen, setIsMentionOpen] = useState(false);
- const [highlightIndex, setHighlightIndex] = useState(0);
- const [mentionListStyle, setMentionListStyle] =
- useState<CSSProperties | null>(null);
+ const composerRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
- const mentionListRef = useRef<HTMLDivElement>(null);
- const mentionListStyleKeyRef = useRef<string | null>(null);
// Derived values
const isInterrupted = Boolean(currentChat?.interrupted);
@@ -485,80 +408,6 @@ export function AgentInput() {
void blockWhenAIIsNotConfigured(chat.id);
}, [blockWhenAIIsNotConfigured, currentChatId]);
- // @-mention autocomplete
- const activeDomRefQuery = useMemo(
- () => getDomRefQuery(input, selectionStart, selectionEnd),
- [input, selectionStart, selectionEnd]
- );
-
- const filteredSuggestions = useMemo(() => {
- const query = activeDomRefQuery?.query ?? "";
- return domRefSuggestions.filter((s) => matchDomRefSuggestion(s, query));
- }, [domRefSuggestions, activeDomRefQuery]);
-
- const mentionOptions = useMemo<DomRefMentionOption[]>(
- () =>
- filteredSuggestions.map((suggestion) => ({
- label: `[${suggestion.ref}] ${suggestion.label}`,
- value: `[${suggestion.ref}]`,
- suggestion,
- })),
- [filteredSuggestions]
- );
-
- // Show/hide mention popover
- const showMention = isMentionOpen && mentionOptions.length > 0;
-
- useLayoutEffect(() => {
- if (!showMention) {
- mentionListStyleKeyRef.current = null;
- setMentionListStyle(null);
- return;
- }
-
- let isCancelled = false;
- let frameId = 0;
-
- const updateMentionListPosition = () => {
- const rect = textareaRef.current?.getBoundingClientRect();
- if (!rect) {
- if (mentionListStyleKeyRef.current !== null) {
- mentionListStyleKeyRef.current = null;
- setMentionListStyle(null);
- }
- } else {
- const nextStyleKey = getMentionListStyleKey(rect);
- if (nextStyleKey !== mentionListStyleKeyRef.current) {
- mentionListStyleKeyRef.current = nextStyleKey;
- setMentionListStyle(buildMentionListStyle(rect));
- }
- }
-
- if (!isCancelled) {
- frameId = requestAnimationFrame(updateMentionListPosition);
- }
- };
-
- updateMentionListPosition();
-
- return () => {
- isCancelled = true;
- cancelAnimationFrame(frameId);
- };
- }, [showMention]);
-
- // Reset highlight when options change
- useEffect(() => {
- setHighlightIndex(0);
- }, [mentionOptions.length]);
-
- // Close mention menu when chat starts running
- useEffect(() => {
- if (isCurrentChatRunning) {
- setIsMentionOpen(false);
- }
- }, [isCurrentChatRunning]);
-
// Reset input when chat/pendingAsk changes
useEffect(() => {
if (
@@ -576,32 +425,6 @@ export function AgentInput() {
currentPendingAsk?.defaultValue,
]);
- // Load dom ref suggestions when @ query is active
- useEffect(() => {
- if (!activeDomRefQuery) {
- setDomRefSuggestions([]);
- setIsMentionOpen(false);
- return;
- }
- setIsMentionOpen(true);
-
- // Only load once (when suggestions are empty)
- if (domRefSuggestions.length > 0) return;
-
- const requestToken = ++domRefRequestToken;
- void lazyExtractDomRefSuggestions().then((suggestions) => {
- if (requestToken !== domRefRequestToken) return;
- // Verify @ query is still active before updating suggestions
- const currentQuery = getDomRefQuery(
- textareaRef.current?.value ?? "",
- textareaRef.current?.selectionStart ?? 0,
- textareaRef.current?.selectionEnd ?? 0
- );
- if (!currentQuery) return;
- setDomRefSuggestions(suggestions);
- });
- }, [input, selectionStart, selectionEnd]);
-
const autoResize = useCallback(() => {
const el = textareaRef.current;
if (!el) return;
@@ -612,59 +435,37 @@ export function AgentInput() {
const minHeight =
Number.parseFloat(styles.minHeight) || el.getBoundingClientRect().height;
const borderHeight = el.offsetHeight - el.clientHeight;
- const nextHeight = Math.max(minHeight, el.scrollHeight + borderHeight);
+ const desiredHeight = Math.max(minHeight, el.scrollHeight + borderHeight);
+ const composer = composerRef.current;
+ const parent = composer?.parentElement;
+ const composerChrome = composer
+ ? Math.max(0, composer.offsetHeight - el.offsetHeight)
+ : 0;
+ const availableHeight = parent ? parent.clientHeight - composerChrome : 0;
+ const maxHeight =
+ availableHeight > 0
+ ? Math.max(minHeight, availableHeight)
+ : desiredHeight;
+ const nextHeight = Math.min(desiredHeight, maxHeight);
el.style.height = `${nextHeight}px`;
- el.style.overflowY = "hidden";
+ el.style.overflowY = desiredHeight > maxHeight ? "auto" : "hidden";
}, []);
useEffect(() => {
autoResize();
}, [input, autoResize]);
- // Selection tracking
- const updateSelection = useCallback(() => {
- const el = textareaRef.current;
- if (!el) return;
- setSelectionStart(el.selectionStart ?? 0);
- setSelectionEnd(el.selectionEnd ?? 0);
- }, []);
-
- // Select a mention option
- const selectMention = useCallback(
- (option: DomRefMentionOption) => {
- if (!activeDomRefQuery) return;
- const before = input.slice(0, activeDomRefQuery.start);
- const after = input.slice(activeDomRefQuery.end);
- const newValue = `${before}${option.value} ${after}`;
- setInput(newValue);
- setIsMentionOpen(false);
- setDomRefSuggestions([]);
-
- // Set cursor after the inserted mention
- const cursorPos = before.length + option.value.length + 1;
- requestAnimationFrame(() => {
- const el = textareaRef.current;
- if (el) {
- el.focus();
- el.setSelectionRange(cursorPos, cursorPos);
- setSelectionStart(cursorPos);
- setSelectionEnd(cursorPos);
- }
- });
- },
- [activeDomRefQuery, input]
- );
+ useEffect(() => {
+ const composer = composerRef.current;
+ const parent = composer?.parentElement;
+ if (!composer || !parent || typeof ResizeObserver === "undefined") return;
- // Scroll highlighted item into view
- const scrollHighlightedIntoView = useCallback((index: number) => {
- requestAnimationFrame(() => {
- const container = mentionListRef.current;
- if (!container) return;
- const items = container.querySelectorAll("[data-mention-option]");
- items[index]?.scrollIntoView({ block: "nearest" });
- });
- }, []);
+ const observer = new ResizeObserver(autoResize);
+ observer.observe(composer);
+ observer.observe(parent);
+ return () => observer.disconnect();
+ }, [autoResize]);
// ---------------------------------------------------------------------------
// Agent loop execution
@@ -1247,35 +1048,6 @@ export function AgentInput() {
const handleTextareaKeydown = useCallback(
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (showMention) {
- if (event.key === "ArrowDown") {
- event.preventDefault();
- const next = Math.min(highlightIndex + 1, mentionOptions.length - 1);
- setHighlightIndex(next);
- scrollHighlightedIntoView(next);
- return;
- }
- if (event.key === "ArrowUp") {
- event.preventDefault();
- const prev = Math.max(highlightIndex - 1, 0);
- setHighlightIndex(prev);
- scrollHighlightedIntoView(prev);
- return;
- }
- if (event.key === "Enter") {
- event.preventDefault();
- if (mentionOptions[highlightIndex]) {
- selectMention(mentionOptions[highlightIndex]);
- }
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- setIsMentionOpen(false);
- return;
- }
- }
-
if (
event.key === "Enter" &&
!event.shiftKey &&
@@ -1287,14 +1059,7 @@ export function AgentInput() {
void send();
}
},
- [
- showMention,
- highlightIndex,
- mentionOptions,
- selectMention,
- scrollHighlightedIntoView,
- send,
- ]
+ [send]
);
// ---------------------------------------------------------------------------
@@ -1302,7 +1067,7 @@ export function AgentInput() {
// ---------------------------------------------------------------------------
return (
- <div className="border-t p-3">
+ <div ref={composerRef} className="border-t p-3">
{/* Pending ask banner */}
{currentPendingAsk && (
<div className="mb-3 rounded-xs bg-warning/10 px-3 py-2 text-xs text-warning">
@@ -1423,64 +1188,9 @@ export function AgentInput() {
className="block h-9 min-h-9 w-full resize-none overflow-y-hidden rounded-xs border px-3 py-1.5 text-sm leading-5 outline-none focus:ring-1 focus:ring-accent disabled:opacity-50"
aria-label={inputPlaceholder}
disabled={isCurrentChatRunning || isAIConfigurationBlocked}
- onChange={(e) => {
- setInput(e.target.value);
- updateSelection();
- }}
- onClick={updateSelection}
- onKeyUp={updateSelection}
- onSelect={updateSelection}
+ onChange={(e) => setInput(e.target.value)}
onKeyDown={handleTextareaKeydown}
/>
-
- {/* Mention popover */}
- {showMention &&
- mentionListStyle &&
- createPortal(
- <div
- ref={mentionListRef}
- data-agent-mention-list
- className={`fixed ${LAYER_SURFACE_CLASS} max-h-80 overflow-y-auto rounded-xs border bg-background shadow-lg`}
- style={mentionListStyle}
- >
- {mentionOptions.map((option, index) => {
- const meta = formatDomRefSuggestionMeta(option.suggestion);
- return (
- <div
- key={option.value}
- data-mention-option
- className={`cursor-pointer px-3 py-2 ${
- index === highlightIndex
- ? "bg-accent/10"
- : "hover:bg-control-bg"
- }`}
- onMouseDown={(e) => {
- e.preventDefault();
- selectMention(option);
- }}
- onMouseEnter={() => setHighlightIndex(index)}
- >
- <div className="flex flex-col text-sm">
- <div className="flex items-center gap-x-2 text-main">
- <span className="font-medium">
- [{option.suggestion.ref}]
- </span>
- <span className="truncate">
- {option.suggestion.label}
- </span>
- </div>
- {meta && (
- <div className="mt-1 text-xs text-control-light">
- {meta}
- </div>
- )}
- </div>
- </div>
- );
- })}
- </div>,
- getLayerRoot("agent")
- )}
</div>
{loading ? (
diff --git a/frontend/src/modules/agent/components/AgentWindow.test.tsx b/frontend/src/modules/agent/components/AgentWindow.test.tsx
index 1168b002bb..244870d804 100644
--- a/frontend/src/modules/agent/components/AgentWindow.test.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.test.tsx
@@ -2,6 +2,7 @@ import type { ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { getLayerRoot } from "@/components/ui/layer";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { createAgentStore, useAgentStore } from "../store/agent";
@@ -228,49 +229,673 @@ describe("AgentWindow", () => {
}
});
- test("keeps the full chat sidebar when the agent window has room for it", () => {
+ test("shows navigation rail, chat list, and conversation together when the agent window has room", () => {
useAgentStore.setState({ size: { width: 750, height: 450 } });
const { render, unmount } = renderIntoContainer(<AgentWindow />);
render();
- expect(
- document.body.querySelector("[data-agent-chat-sidebar]")
- ).toBeInstanceOf(HTMLElement);
- expect(
- document.body.querySelector("[data-agent-compact-rail]")
- ).toBeNull();
+ try {
+ const body = document.body.querySelector("[data-agent-window-body]");
+ const rail = body?.querySelector("[data-agent-compact-rail]");
+ const list = body?.querySelector("[data-agent-chat-sidebar]");
+ const panels = body?.querySelector("[data-agent-chat-panels]");
+ expect(rail).toBeInstanceOf(HTMLElement);
+ expect(list).toBeInstanceOf(HTMLElement);
+ expect(panels).toBeInstanceOf(HTMLElement);
+ expect(rail).not.toContainElement(list as HTMLElement);
+ expect(body?.querySelector("[data-agent-compact-drawer]")).toBeNull();
+ } finally {
+ unmount();
+ }
+ });
- unmount();
+ test("switches the persistent chat list between active and archived chats from the rail", () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const rail = document.body.querySelector("[data-agent-compact-rail]");
+ const archiveButton = rail?.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ const chatsButton = rail?.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ expect(chatsButton).toBeInstanceOf(HTMLButtonElement);
+
+ act(() => archiveButton.click());
+ const archivedList = document.body.querySelector(
+ "[data-agent-chat-sidebar]"
+ );
+ expect(archivedList?.textContent).toContain("agent.archived-only-chats");
+ expect(
+ archivedList?.querySelector(`[data-agent-chat-row="${archivedChat.id}"]`)
+ ).toBeInstanceOf(HTMLElement);
+ expect(
+ archivedList?.querySelector(`[data-agent-chat-row="${activeChatId}"]`)
+ ).toBeNull();
+ expect(archivedList?.querySelector('[aria-label="agent.new-chat"]')).toBeNull();
+ expect(archivedList?.querySelector("[data-agent-new-chat-for-context]")).toBeNull();
+
+ act(() => chatsButton.click());
+ const activeList = document.body.querySelector("[data-agent-chat-sidebar]");
+ expect(activeList?.querySelector(`[data-agent-chat-row="${activeChatId}"]`)).toBeInstanceOf(
+ HTMLElement
+ );
+ expect(activeList?.querySelector(`[data-agent-chat-row="${archivedChat.id}"]`)).toBeNull();
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
+ } finally {
+ unmount();
+ }
+ });
+
+ test.each([
+ ["large", 750],
+ ["compact", 700],
+ ])("highlights the selected %s rail destination", async (_name, width) => {
+ useAgentStore.setState({ size: { width, height: 450 } });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const rail = document.body.querySelector("[data-agent-compact-rail]");
+ const chatsButton = rail?.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ const archiveButton = rail?.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+
+ if (width === 750) {
+ expect(chatsButton).toHaveAttribute("aria-current", "page");
+ } else {
+ expect(chatsButton).not.toHaveAttribute("aria-current");
+ }
+ expect(archiveButton).not.toHaveAttribute("aria-current");
+
+ act(() => archiveButton.click());
+ expect(chatsButton).not.toHaveAttribute("aria-current");
+ expect(archiveButton).toHaveAttribute("aria-current", "page");
+
+ if (width === 700) {
+ const closeButton = document.body.querySelector(
+ '[data-agent-compact-drawer] [aria-label="agent.close"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ closeButton.click();
+ await Promise.resolve();
+ });
+ expect(archiveButton).not.toHaveAttribute("aria-current");
+ }
+ } finally {
+ unmount();
+ }
+ });
+
+ test.each([
+ ["large", 750],
+ ["compact", 700],
+ ])("creates an active chat from the archived %s rail", async (_name, width) => {
+ useAgentStore.setState({ size: { width, height: 450 } });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+ const previousChatId = useAgentStore.getState().currentChatId;
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const rail = document.body.querySelector("[data-agent-compact-rail]");
+ const archiveButton = rail?.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ const newChatButton = rail?.querySelector(
+ '[aria-label="agent.new-chat"]'
+ ) as HTMLButtonElement;
+ expect(newChatButton).toBeInstanceOf(HTMLButtonElement);
+
+ act(() => archiveButton.click());
+ expect(rail?.querySelector('[aria-label="agent.new-chat"]')).toBe(
+ newChatButton
+ );
+
+ await act(async () => {
+ newChatButton.click();
+ await Promise.resolve();
+ });
+
+ const currentChatId = useAgentStore.getState().currentChatId;
+ expect(currentChatId).not.toBe(previousChatId);
+ expect(useAgentStore.getState().getChat(currentChatId!)?.archived).toBe(
+ false
+ );
+ if (width === 750) {
+ const list = document.body.querySelector("[data-agent-chat-sidebar]");
+ expect(list?.querySelector(`[data-agent-chat-row="${currentChatId}"]`)).toBeInstanceOf(
+ HTMLElement
+ );
+ expect(list?.querySelector(`[data-agent-chat-row="${archivedChat.id}"]`)).toBeNull();
+ } else {
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
+ const chatsButton = rail?.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ chatsButton.click();
+ await Promise.resolve();
+ });
+ expect(
+ document.body.querySelector(
+ `[data-agent-compact-drawer] [data-agent-chat-row="${currentChatId}"]`
+ )
+ ).toBeInstanceOf(HTMLElement);
+ }
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps the current conversation selected while the large rail switches list modes", () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const rail = document.body.querySelector("[data-agent-compact-rail]");
+ const archiveButton = rail?.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ const chatsButton = rail?.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+
+ act(() => archiveButton.click());
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+ expect(document.body.querySelector("[data-agent-chat-panels]")).not.toHaveAttribute(
+ "aria-hidden"
+ );
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
+
+ act(() => chatsButton.click());
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+ expect(
+ document.body.querySelector(
+ `[data-agent-chat-row="${activeChatId}"] [aria-current="true"]`
+ )
+ ).toBeInstanceOf(HTMLButtonElement);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps an unrelated active conversation selected when restoring and deleting archived chats", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ const restoredChat = useAgentStore.getState().createChat({
+ title: "Restore analytics",
+ archived: true,
+ select: false,
+ });
+ const deletedChat = useAgentStore.getState().createChat({
+ title: "Delete analytics",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const rail = document.body.querySelector("[data-agent-compact-rail]");
+ act(() =>
+ (
+ rail?.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement
+ ).click()
+ );
+
+ const openRowMenu = async (chatId: string) => {
+ const menuButton = document.body.querySelector(
+ `[data-agent-chat-row="${chatId}"] [data-agent-archived-chat-menu]`
+ ) as HTMLButtonElement;
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+ };
+
+ await openRowMenu(restoredChat.id);
+ act(() =>
+ (
+ getLayerRoot("agent").querySelector(
+ "[data-agent-unarchive-chat]"
+ ) as HTMLElement
+ ).click()
+ );
+ expect(useAgentStore.getState().getChat(restoredChat.id)?.archived).toBe(
+ false
+ );
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+
+ await openRowMenu(deletedChat.id);
+ act(() =>
+ (
+ getLayerRoot("agent").querySelector(
+ "[data-agent-delete-chat]"
+ ) as HTMLElement
+ ).click()
+ );
+ const confirmation = getLayerRoot("agent").querySelector(
+ "[data-agent-dialog-content]"
+ ) as HTMLElement;
+ const confirmButton = Array.from(
+ confirmation.querySelectorAll("button")
+ ).find((button) => button.textContent === "common.confirm");
+ act(() => confirmButton?.click());
+
+ expect(useAgentStore.getState().getChat(deletedChat.id)).toBeNull();
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+
+ act(() =>
+ (
+ rail?.querySelector('[aria-label="agent.chat-list-label"]') as HTMLButtonElement
+ ).click()
+ );
+ expect(
+ document.body.querySelector(
+ `[data-agent-chat-row="${activeChatId}"] [aria-current="true"]`
+ )
+ ).toBeInstanceOf(HTMLButtonElement);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps an unrelated active conversation selected when unarchiving all chats", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ archived: true,
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ act(() =>
+ (
+ document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement
+ ).click()
+ );
+ const menuButton = document.body.querySelector(
+ '[data-agent-chat-sidebar-actions] [aria-label="common.more"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+ act(() =>
+ (
+ getLayerRoot("agent").querySelector(
+ "[data-agent-unarchive-all-chats]"
+ ) as HTMLElement
+ ).click()
+ );
+
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps an unrelated active conversation selected when deleting all archived chats", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ archived: true,
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ act(() =>
+ (
+ document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement
+ ).click()
+ );
+ const menuButton = document.body.querySelector(
+ '[data-agent-chat-sidebar-actions] [aria-label="common.more"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+ act(() =>
+ (
+ getLayerRoot("agent").querySelector(
+ "[data-agent-delete-all-chats]"
+ ) as HTMLElement
+ ).click()
+ );
+ const confirmation = getLayerRoot("agent").querySelector(
+ "[data-agent-dialog-content]"
+ ) as HTMLElement;
+ const confirmButton = Array.from(
+ confirmation.querySelectorAll("button")
+ ).find((button) => button.textContent === "common.confirm");
+ act(() => confirmButton?.click());
+
+ expect(useAgentStore.getState().getChat(archivedChat.id)).toBeNull();
+ expect(useAgentStore.getState().currentChatId).toBe(activeChatId);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps an unrelated archived conversation selected when archiving active chats", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const firstActiveChatId = useAgentStore.getState().currentChatId!;
+ useAgentStore.getState().createChat({
+ title: "Second active",
+ select: false,
+ });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ archived: true,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ `[data-agent-chat-row="${firstActiveChatId}"] [data-agent-archive-chat]`
+ ) as HTMLButtonElement;
+ act(() => archiveButton.click());
+ expect(useAgentStore.getState().currentChatId).toBe(archivedChat.id);
+
+ const menuButton = document.body.querySelector(
+ '[data-agent-chat-sidebar-actions] [aria-label="common.more"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+ act(() =>
+ (
+ getLayerRoot("agent").querySelector(
+ "[data-agent-archive-all-chats]"
+ ) as HTMLElement
+ ).click()
+ );
+ expect(useAgentStore.getState().currentChatId).toBe(archivedChat.id);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("does not reveal the compact drawer when resizing an archived large list", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ act(() => archiveButton.click());
+ expect(document.body.querySelector("[data-agent-chat-sidebar]")).toBeInstanceOf(
+ HTMLElement
+ );
+
+ act(() => useAgentStore.setState({ size: { width: 700, height: 450 } }));
+ expect(document.body.querySelector("[data-agent-chat-sidebar]")).toBeNull();
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
+ expect(document.body.querySelector("[data-agent-chat-panels]")).not.toHaveAttribute(
+ "aria-hidden"
+ );
+
+ await act(async () => {
+ archiveButton.click();
+ await Promise.resolve();
+ });
+ expect(
+ document.body.querySelector(
+ `[data-agent-compact-drawer] [data-agent-chat-row="${archivedChat.id}"]`
+ )
+ ).toBeInstanceOf(HTMLElement);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("offers Restore and Delete in one archived chat row menu", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ act(() => archiveButton.click());
+
+ const list = document.body.querySelector("[data-agent-chat-sidebar]");
+ const row = list?.querySelector(
+ `[data-agent-chat-row="${archivedChat.id}"]`
+ );
+ const menuButton = row?.querySelector(
+ "[data-agent-archived-chat-menu]"
+ ) as HTMLButtonElement;
+ expect(menuButton).toBeInstanceOf(HTMLButtonElement);
+ expect(row?.querySelector("[data-agent-unarchive-chat]")).toBeNull();
+ expect(row?.querySelector("[data-agent-delete-chat]")).toBeNull();
+ expect(list?.querySelector('[aria-label="agent.new-chat"]')).toBeNull();
+ expect(list?.querySelector("[data-agent-new-chat-for-context]")).toBeNull();
+
+ await act(async () => {
+ menuButton.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ await Promise.resolve();
+ });
+
+ const agentRoot = getLayerRoot("agent");
+ expect(
+ agentRoot.querySelector("[data-agent-unarchive-chat]")
+ ).toBeInstanceOf(HTMLElement);
+ expect(agentRoot.querySelector("[data-agent-delete-chat]")).toBeInstanceOf(
+ HTMLElement
+ );
+ } finally {
+ unmount();
+ }
+ });
+
+ test("deletes an archived chat from the compact drawer row menu", async () => {
+ useAgentStore.setState({ size: { width: 700, height: 450 } });
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Delete archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ archiveButton.click();
+ await Promise.resolve();
+ });
+
+ const drawer = document.body.querySelector(
+ "[data-agent-compact-drawer]"
+ ) as HTMLElement;
+ const row = drawer.querySelector(
+ `[data-agent-chat-row="${archivedChat.id}"]`
+ ) as HTMLElement;
+ expect(row).toBeInstanceOf(HTMLElement);
+ const menuButton = row.querySelector(
+ "[data-agent-archived-chat-menu]"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+
+ const deleteButton = getLayerRoot("agent").querySelector(
+ "[data-agent-delete-chat]"
+ ) as HTMLElement;
+ expect(deleteButton).toBeInstanceOf(HTMLElement);
+ await act(async () => {
+ deleteButton.click();
+ await Promise.resolve();
+ });
+
+ const confirmation = getLayerRoot("agent").querySelector(
+ "[data-agent-dialog-content]"
+ ) as HTMLElement;
+ expect(confirmation?.textContent).toContain(
+ "agent.delete-chat-confirmation"
+ );
+ const confirmButton = Array.from(confirmation.querySelectorAll("button")).find(
+ (button) => button.textContent === "common.confirm"
+ );
+ act(() => confirmButton?.click());
+
+ expect(useAgentStore.getState().getChat(archivedChat.id)).toBeNull();
+ } finally {
+ unmount();
+ }
});
- test("renders the compact drawer outside the clipped rail panel", async () => {
+ test("renders the compact drawer as a bounded dialog", async () => {
useAgentStore.setState({ size: { width: 700, height: 450 } });
const { render, unmount } = renderIntoContainer(<AgentWindow />);
render();
- const listButton = document.body.querySelector(
- 'button[aria-label="agent.chat-list-label"]'
- ) as HTMLButtonElement;
- await act(async () => {
- listButton.click();
- await Promise.resolve();
- });
+ try {
+ const listButton = document.body.querySelector(
+ 'button[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
- const drawer = document.body.querySelector(
- "[data-agent-compact-drawer]"
- );
- const body = document.body.querySelector("[data-agent-window-body]");
- expect(drawer?.parentElement).toBe(body);
- expect(
- document.body.querySelector("[data-agent-compact-rail]")
- ).toBeInstanceOf(HTMLElement);
+ const drawer = document.body.querySelector(
+ "[data-agent-compact-drawer]"
+ ) as HTMLElement;
+ const body = document.body.querySelector(
+ "[data-agent-window-body]"
+ ) as HTMLDivElement;
+ expect(body).toContainElement(drawer);
+ expect(drawer).toHaveAttribute("role", "dialog");
+ expect(
+ document.body.querySelector("[data-agent-chat-panels]")
+ ).toHaveAttribute("aria-hidden", "true");
+ expect(
+ document.body.querySelector("[data-agent-chat-panels]")
+ ).toHaveAttribute("inert");
+ expect(
+ document.body.querySelector("[data-agent-window-header]")
+ ).toHaveAttribute("inert");
+ expect(
+ document.body.querySelector("[data-agent-compact-header-overlay]")
+ ).toBeNull();
+ expect(
+ document.body.querySelector("[data-agent-window-resize-zone]")
+ ).toBeNull();
+ expect(
+ document.body.querySelector("[data-agent-compact-rail]")
+ ).toBeInstanceOf(HTMLElement);
+ } finally {
+ unmount();
+ }
+ });
- unmount();
+ test("keeps an active critical layer accessible while the compact drawer is open", async () => {
+ useAgentStore.setState({ size: { width: 700, height: 450 } });
+ const criticalRoot = getLayerRoot("critical");
+ const criticalAction = document.createElement("button");
+ criticalAction.textContent = "Critical action";
+ criticalRoot.appendChild(criticalAction);
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const listButton = document.body.querySelector(
+ 'button[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+
+ await vi.waitFor(() => {
+ expect(criticalRoot).not.toHaveAttribute("aria-hidden");
+ expect(criticalRoot).not.toHaveAttribute("inert");
+ expect(criticalRoot).not.toHaveAttribute("data-base-ui-inert");
+ });
+ } finally {
+ unmount();
+ }
});
- test("layers the compact drawer above the chat panel and composer", async () => {
+ test("returns focus to the compact rail after Escape closes its drawer", async () => {
useAgentStore.setState({ size: { width: 700, height: 450 } });
const { render, unmount } = renderIntoContainer(<AgentWindow />);
@@ -279,32 +904,104 @@ describe("AgentWindow", () => {
const listButton = document.body.querySelector(
'button[aria-label="agent.chat-list-label"]'
) as HTMLButtonElement;
+ listButton.focus();
await act(async () => {
listButton.click();
await Promise.resolve();
});
try {
- const body = document.body.querySelector("[data-agent-window-body]");
- const panels = document.body.querySelector("[data-agent-chat-panels]");
const drawer = document.body.querySelector(
"[data-agent-compact-drawer]"
+ ) as HTMLElement;
+ expect(listButton.isConnected).toBe(true);
+ expect(drawer).toContainElement(document.activeElement as HTMLElement);
+
+ await act(async () => {
+ document.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
+ );
+ await Promise.resolve();
+ });
+
+ expect(
+ document.body.querySelector("[data-agent-compact-drawer]")
+ ).toBeNull();
+ expect(document.activeElement).toBe(listButton);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("closes the compact chat list after selecting another conversation", async () => {
+ useAgentStore.setState({ size: { width: 700, height: 450 } });
+ const otherChat = useAgentStore.getState().createChat({
+ title: "Review analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const listButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeInstanceOf(
+ HTMLElement
+ );
+
+ const rowButton = document.body.querySelector(
+ `[data-agent-compact-drawer] [data-agent-chat-row="${otherChat.id}"] button`
+ ) as HTMLButtonElement;
+ act(() => rowButton.click());
+
+ expect(useAgentStore.getState().currentChatId).toBe(otherChat.id);
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
+ expect(document.body.querySelector("[data-agent-chat-panels]")).toBeInstanceOf(
+ HTMLElement
);
- const overlay = document.body.querySelector(
- "[data-agent-compact-overlay]"
+ } finally {
+ unmount();
+ }
+ });
+
+ test("closes the compact chat list after creating a chat in a context group", async () => {
+ useAgentStore.setState({ size: { width: 700, height: 450 } });
+ useAgentStore.getState().createChat({
+ title: "Previous analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const listButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+
+ const newChatButton = document.body.querySelector(
+ '[data-agent-compact-drawer] [data-agent-new-chat-for-context="projects/analytics"]'
+ ) as HTMLButtonElement;
+ act(() => newChatButton.click());
+
+ const chatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/analytics"
);
- const input = document.body.querySelector('[data-testid="agent-input"]');
-
- expect(panels?.parentElement).toBe(body);
- expect(panels?.contains(input)).toBe(true);
- expect(panels?.className).toContain("relative");
- expect(panels?.className).toContain("z-0");
- expect(overlay?.parentElement).toBe(body);
- expect(overlay?.className).toContain("absolute");
- expect(overlay?.className).toContain("inset-0");
- expect(overlay?.className).toContain("z-1");
- expect(drawer?.parentElement).toBe(body);
- expect(drawer?.className).toContain("z-2");
+ expect(useAgentStore.getState().getMessages(chatId)).toEqual([]);
+ expect(document.body.querySelector("[data-agent-compact-drawer]")).toBeNull();
} finally {
unmount();
}
@@ -375,6 +1072,51 @@ describe("AgentWindow", () => {
unmount();
});
+ test("returns an archived mobile conversation to archived chats", () => {
+ useAgentStore.setState({ size: { width: 479, height: 450 } });
+ const activeChatId = useAgentStore.getState().currentChatId!;
+ const archivedChat = useAgentStore.getState().createChat({
+ title: "Archived mobile chat",
+ archived: true,
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const conversationBack = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => conversationBack.click());
+
+ const archiveButton = document.body.querySelector(
+ '[aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ act(() => archiveButton.click());
+
+ const archivedChatButton = document.body.querySelector(
+ `[data-agent-chat-row="${archivedChat.id}"] button`
+ ) as HTMLButtonElement;
+ act(() => archivedChatButton.click());
+
+ const archivedConversationBack = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => archivedConversationBack.click());
+
+ expect(
+ document.body.querySelector("[data-agent-mobile-chat-list]")
+ ).toBeInstanceOf(HTMLDivElement);
+ expect(
+ document.body.querySelector(`[data-agent-chat-row="${archivedChat.id}"]`)
+ ).toBeInstanceOf(HTMLDivElement);
+ expect(
+ document.body.querySelector(`[data-agent-chat-row="${activeChatId}"]`)
+ ).toBeNull();
+
+ unmount();
+ });
+
test("restores and deletes archived chats from the mobile archive view", () => {
useAgentStore.setState({ size: { width: 479, height: 450 } });
const store = useAgentStore.getState();
@@ -476,61 +1218,305 @@ describe("AgentWindow", () => {
) as HTMLButtonElement | null;
await act(async () => trigger?.click());
- const chatId = useAgentStore.getState().currentChatId!;
- expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
- "projects/orders"
- );
- expect(useAgentStore.getState().getMessages(chatId)).toEqual([]);
- unmount();
+ const chatId = useAgentStore.getState().currentChatId!;
+ expect(useAgentStore.getState().getChat(chatId)?.context).toBe(
+ "projects/orders"
+ );
+ expect(useAgentStore.getState().getMessages(chatId)).toEqual([]);
+ unmount();
+ });
+
+ test("keeps context groups in a stable workspace-first order", () => {
+ const store = useAgentStore.getState();
+ const legacyChat = store.createChat({
+ title: "Legacy chat",
+ select: false,
+ });
+ const workspaceChat = store.createChat({
+ title: "List databases",
+ context: "workspaces/acme",
+ select: false,
+ });
+ const analyticsChat = store.createChat({
+ title: "Investigate analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+ useAgentStore.setState((state) => ({
+ chats: state.chats.map((chat) => {
+ if (chat.id === legacyChat.id) return { ...chat, updatedTs: 4_000 };
+ if (chat.id === analyticsChat.id) return { ...chat, updatedTs: 3_000 };
+ if (chat.id === workspaceChat.id) return { ...chat, updatedTs: 2_000 };
+ return { ...chat, updatedTs: 1_000 };
+ }),
+ }));
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ const groups = Array.from(
+ document.body.querySelectorAll("[data-agent-chat-group]")
+ ) as HTMLDivElement[];
+ expect(groups.map((group) => group.dataset.agentChatGroup)).toEqual([
+ "workspaces/acme",
+ "projects/orders",
+ "projects/analytics",
+ "unscoped",
+ ]);
+ expect(groups[0]?.textContent).toContain("Acme workspace");
+ expect(groups[1]?.textContent).toContain("Order service");
+ expect(groups[2]?.textContent).toContain("Analytics");
+ expect(groups[3]?.textContent).toContain("agent.other-chats");
+ expect(groups[3]?.textContent).toContain("Legacy chat");
+ expect(
+ document.body.querySelector("[data-agent-chat-updated-ts]")
+ ).toBeNull();
+
+ unmount();
+ });
+
+ test.each([
+ { name: "large sidebar", width: 750, listSelector: "[data-agent-chat-sidebar]" },
+ { name: "compact drawer", width: 700, listSelector: "[data-agent-compact-drawer]" },
+ { name: "mobile chat list", width: 479, listSelector: "[data-agent-mobile-chat-list]" },
+ ])("exposes full clipped group and chat titles in the $name", async ({
+ width,
+ listSelector,
+ }) => {
+ useAgentStore.setState({ size: { width, height: 450 } });
+ const longTitle =
+ "How do I connect the orders database and review every pending change?";
+ const chat = useAgentStore.getState().createChat({
+ title: longTitle,
+ context: "projects/orders",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ if (width === 700) {
+ const listButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+ } else if (width === 479) {
+ const backButton = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => backButton.click());
+ }
+
+ const list = document.body.querySelector(listSelector) as HTMLElement;
+ const groupToggle = list.querySelector(
+ '[data-agent-chat-group-toggle="projects/orders"]'
+ ) as HTMLButtonElement;
+ const chatButton = list.querySelector(
+ `[data-agent-chat-row="${chat.id}"] button`
+ ) as HTMLButtonElement;
+ expect(groupToggle).toHaveAttribute("title", "Order service");
+ expect(chatButton).toHaveAttribute("title", longTitle);
+ } finally {
+ unmount();
+ }
+ });
+
+ test.each([
+ { name: "large sidebar", width: 750, listSelector: "[data-agent-chat-sidebar]" },
+ { name: "compact drawer", width: 700, listSelector: "[data-agent-compact-drawer]" },
+ { name: "mobile chat list", width: 479, listSelector: "[data-agent-mobile-chat-list]" },
+ ])("uses the full chat-list width for group and chat rows in the $name", async ({
+ width,
+ listSelector,
+ }) => {
+ useAgentStore.setState({ size: { width, height: 450 } });
+ const chat = useAgentStore.getState().createChat({
+ title: "Inspect analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ if (width === 700) {
+ const listButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+ } else if (width === 479) {
+ const backButton = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => backButton.click());
+ }
+
+ const list = document.body.querySelector(listSelector) as HTMLElement;
+ const header = list.querySelector(
+ '[data-agent-chat-group-header="projects/analytics"]'
+ ) as HTMLElement;
+ const children = list.querySelector(
+ '[data-agent-chat-group-children="projects/analytics"]'
+ ) as HTMLElement;
+ const row = children.querySelector(
+ `[data-agent-chat-row="${chat.id}"]`
+ ) as HTMLElement;
+
+ expect(header).toHaveClass("w-full");
+ expect(header).not.toHaveClass("px-2");
+ expect(children).not.toHaveClass("pl-7");
+ expect(row).toHaveClass("w-full");
+ expect(row).toHaveClass("pl-5");
+ } finally {
+ unmount();
+ }
+ });
+
+ test("toggles a group in the full chat sidebar", () => {
+ const chat = useAgentStore.getState().createChat({
+ title: "Investigate analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const toggle = document.body.querySelector(
+ '[data-agent-chat-group-toggle="projects/analytics"]'
+ ) as HTMLButtonElement;
+ const header = document.body.querySelector(
+ '[data-agent-chat-group-header="projects/analytics"]'
+ ) as HTMLDivElement;
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ const children = document.body.querySelector(
+ '[data-agent-chat-group-children="projects/analytics"]'
+ ) as HTMLDivElement;
+ const chatRow = document.body.querySelector(
+ `[data-agent-chat-row="${chat.id}"]`
+ ) as HTMLDivElement;
+ expect(header).toContainElement(toggle);
+ expect(header).not.toContainElement(children);
+ expect(children).not.toHaveClass("ml-8", "pl-4");
+ expect(children).toContainElement(chatRow);
+ expect(chatRow).toHaveClass("w-full", "py-2");
+ expect(toggle.querySelector("svg.lucide-folder-open")).toBeInstanceOf(
+ SVGElement
+ );
+ expect(toggle.querySelector("svg.lucide-chevron-right")).toBeNull();
+
+ act(() => toggle.click());
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(toggle.querySelector("svg.lucide-folder")).toBeInstanceOf(
+ SVGElement
+ );
+ expect(toggle.querySelector("svg.lucide-folder-open")).toBeNull();
+ expect(
+ document.body.querySelector(`[data-agent-chat-row="${chat.id}"]`)
+ ).toBeNull();
+
+ act(() => toggle.click());
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ expect(toggle.querySelector("svg.lucide-folder-open")).toBeInstanceOf(
+ SVGElement
+ );
+ expect(
+ document.body.querySelector(`[data-agent-chat-row="${chat.id}"]`)
+ ).toBeInstanceOf(HTMLDivElement);
+ } finally {
+ unmount();
+ }
+ });
+
+ test("toggles a group in the compact chat drawer", async () => {
+ useAgentStore.setState({ size: { width: 700, height: 450 } });
+ const chat = useAgentStore.getState().createChat({
+ title: "Investigate analytics",
+ context: "projects/analytics",
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const listButton = document.body.querySelector(
+ 'button[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ await act(async () => {
+ listButton.click();
+ await Promise.resolve();
+ });
+
+ const drawer = document.body.querySelector(
+ "[data-agent-compact-drawer]"
+ ) as HTMLElement;
+ expect(drawer).toBeInstanceOf(HTMLElement);
+ const toggle = drawer.querySelector(
+ '[data-agent-chat-group-toggle="projects/analytics"]'
+ ) as HTMLButtonElement;
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+
+ act(() => toggle.click());
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(drawer.querySelector(`[data-agent-chat-row="${chat.id}"]`)).toBeNull();
+ } finally {
+ unmount();
+ }
});
- test("keeps context groups in a stable workspace-first order", () => {
- const store = useAgentStore.getState();
- const legacyChat = store.createChat({
- title: "Legacy chat",
- select: false,
- });
- const workspaceChat = store.createChat({
- title: "List databases",
- context: "workspaces/acme",
- select: false,
- });
- const analyticsChat = store.createChat({
+ test("toggles a group in the mobile chat list", () => {
+ useAgentStore.setState({ size: { width: 479, height: 450 } });
+ const chat = useAgentStore.getState().createChat({
title: "Investigate analytics",
context: "projects/analytics",
select: false,
});
- useAgentStore.setState((state) => ({
- chats: state.chats.map((chat) => {
- if (chat.id === legacyChat.id) return { ...chat, updatedTs: 4_000 };
- if (chat.id === analyticsChat.id) return { ...chat, updatedTs: 3_000 };
- if (chat.id === workspaceChat.id) return { ...chat, updatedTs: 2_000 };
- return { ...chat, updatedTs: 1_000 };
- }),
- }));
-
const { render, unmount } = renderIntoContainer(<AgentWindow />);
render();
- const groups = Array.from(
- document.body.querySelectorAll("[data-agent-chat-group]")
- ) as HTMLDivElement[];
- expect(groups.map((group) => group.dataset.agentChatGroup)).toEqual([
- "workspaces/acme",
- "projects/orders",
- "projects/analytics",
- "unscoped",
- ]);
- expect(groups[0]?.textContent).toContain("Acme workspace");
- expect(groups[1]?.textContent).toContain("Order service");
- expect(groups[2]?.textContent).toContain("Analytics");
- expect(groups[3]?.textContent).toContain("agent.other-chats");
- expect(groups[3]?.textContent).toContain("Legacy chat");
- expect(
- document.body.querySelector("[data-agent-chat-updated-ts]")
- ).toBeNull();
+ try {
+ const back = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => back.click());
- unmount();
+ const list = document.body.querySelector(
+ "[data-agent-mobile-chat-list]"
+ ) as HTMLDivElement;
+ expect(list).toBeInstanceOf(HTMLDivElement);
+ const toggle = list.querySelector(
+ '[data-agent-chat-group-toggle="projects/analytics"]'
+ ) as HTMLButtonElement;
+ const header = list.querySelector(
+ '[data-agent-chat-group-header="projects/analytics"]'
+ ) as HTMLDivElement;
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ const children = list.querySelector(
+ '[data-agent-chat-group-children="projects/analytics"]'
+ ) as HTMLDivElement;
+ const chatRow = list.querySelector(
+ `[data-agent-chat-row="${chat.id}"]`
+ ) as HTMLDivElement;
+ expect(header).toContainElement(toggle);
+ expect(header).not.toContainElement(children);
+ expect(children).not.toHaveClass("ml-8", "pl-4");
+ expect(children).toContainElement(chatRow);
+ expect(chatRow).toHaveClass("w-full", "py-2");
+
+ act(() => toggle.click());
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(list.querySelector(`[data-agent-chat-row="${chat.id}"]`)).toBeNull();
+ } finally {
+ unmount();
+ }
});
test("creates a new chat in the selected context group", async () => {
@@ -549,6 +1535,12 @@ describe("AgentWindow", () => {
const { render, unmount } = renderIntoContainer(<AgentWindow />);
render();
+ const workspaceToggle = document.body.querySelector(
+ '[data-agent-chat-group-toggle="workspaces/acme"]'
+ ) as HTMLButtonElement;
+ act(() => workspaceToggle.click());
+ expect(workspaceToggle).toHaveAttribute("aria-expanded", "false");
+
const workspaceButton = document.body.querySelector(
'[data-agent-new-chat-for-context="workspaces/acme"]'
) as HTMLButtonElement | null;
@@ -560,6 +1552,16 @@ describe("AgentWindow", () => {
"workspaces/acme"
);
expect(useAgentStore.getState().getMessages(workspaceChatId)).toEqual([]);
+ expect(
+ document.body.querySelector(
+ '[data-agent-chat-group-toggle="workspaces/acme"]'
+ )
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(
+ document.body.querySelector(
+ `[data-agent-chat-row="${workspaceChatId}"]`
+ )
+ ).toBeInstanceOf(HTMLDivElement);
const projectButton = document.body.querySelector(
'[data-agent-new-chat-for-context="projects/analytics"]'
@@ -579,6 +1581,40 @@ describe("AgentWindow", () => {
unmount();
});
+ test.each([
+ ["large", 750],
+ ["mobile", 470],
+ ])("gives the %s group new-chat button a stronger hover background", (_layout, width) => {
+ useAgentStore.setState({ size: { width, height: 450 } });
+ useAgentStore.getState().createChat({
+ title: "Analytics chat",
+ context: "projects/analytics",
+ select: false,
+ });
+
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ if (width === 470) {
+ const backButton = document.body.querySelector(
+ '[aria-label="agent.chat-list-label"]'
+ ) as HTMLButtonElement;
+ act(() => backButton.click());
+ }
+
+ const groupHeader = document.body.querySelector(
+ '[data-agent-chat-group-header="projects/analytics"]'
+ );
+ const newChatButton = groupHeader?.querySelector(
+ '[data-agent-new-chat-for-context="projects/analytics"]'
+ );
+ expect(newChatButton).toHaveClass("hover:bg-control/25");
+ } finally {
+ unmount();
+ }
+ });
+
test("hides new-chat actions from the archived full sidebar", async () => {
useAgentStore.setState({ size: { width: 750, height: 450 } });
useAgentStore.getState().createChat({
@@ -591,24 +1627,11 @@ describe("AgentWindow", () => {
const { render, unmount } = renderIntoContainer(<AgentWindow />);
render();
- const moreButton = document.body.querySelector(
- "[aria-label='common.more']"
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
) as HTMLButtonElement;
- act(() => {
- moreButton.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- });
-
- const archivedModeButton = document.body.querySelector(
- "[data-agent-chat-list-mode]"
- ) as HTMLDivElement;
- await act(async () => {
- archivedModeButton.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- await Promise.resolve();
- });
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ act(() => archiveButton.click());
try {
const actions = document.body.querySelector(
@@ -630,7 +1653,114 @@ describe("AgentWindow", () => {
}
});
- test("hides the compact rail new-chat action while viewing archived chats", async () => {
+ test("only offers the destructive Archive all action in the active list menu", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const list = document.body.querySelector("[data-agent-chat-sidebar]");
+ const menuButton = list?.querySelector(
+ '[data-agent-chat-sidebar-actions] [aria-label="common.more"]'
+ ) as HTMLButtonElement;
+ expect(menuButton).toBeInstanceOf(HTMLButtonElement);
+
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+
+ const menu = getLayerRoot("agent").querySelector(
+ "[data-agent-dropdown-menu-content]"
+ ) as HTMLElement;
+ expect(menu).toBeInstanceOf(HTMLElement);
+ expect(menu.querySelectorAll('[role="menuitem"]')).toHaveLength(1);
+ expect(menu.querySelector("[data-agent-archive-all-chats]")).toHaveClass(
+ "text-error"
+ );
+ expect(menu.querySelector("[data-agent-chat-list-mode]")).toBeNull();
+ } finally {
+ unmount();
+ }
+ });
+
+ test("only offers Unarchive all and Delete all in the archived list menu", async () => {
+ useAgentStore.setState({ size: { width: 750, height: 450 } });
+ useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ act(() => archiveButton.click());
+ const list = document.body.querySelector("[data-agent-chat-sidebar]");
+ const menuButton = list?.querySelector(
+ '[data-agent-chat-sidebar-actions] [aria-label="common.more"]'
+ ) as HTMLButtonElement;
+ expect(menuButton).toBeInstanceOf(HTMLButtonElement);
+
+ await act(async () => {
+ menuButton.click();
+ await Promise.resolve();
+ });
+
+ const menu = getLayerRoot("agent").querySelector(
+ "[data-agent-dropdown-menu-content]"
+ ) as HTMLElement;
+ expect(menu).toBeInstanceOf(HTMLElement);
+ expect(menu.querySelectorAll('[role="menuitem"]')).toHaveLength(2);
+ expect(menu.querySelector("[data-agent-unarchive-all-chats]")).toBeInstanceOf(
+ HTMLElement
+ );
+ expect(menu.querySelector("[data-agent-delete-all-chats]")).toHaveClass(
+ "text-error"
+ );
+ expect(menu.querySelector("[data-agent-chat-list-mode]")).toBeNull();
+ } finally {
+ unmount();
+ }
+ });
+
+ test("toggles a group in archived chats", async () => {
+ const chat = useAgentStore.getState().createChat({
+ title: "Archived analytics",
+ context: "projects/analytics",
+ archived: true,
+ select: false,
+ });
+ const { render, unmount } = renderIntoContainer(<AgentWindow />);
+ render();
+
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ act(() => archiveButton.click());
+
+ const toggle = document.body.querySelector(
+ '[data-agent-chat-group-toggle="projects/analytics"]'
+ ) as HTMLButtonElement;
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+
+ act(() => toggle.click());
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(
+ document.body.querySelector(`[data-agent-chat-row="${chat.id}"]`)
+ ).toBeNull();
+ } finally {
+ unmount();
+ }
+ });
+
+ test("keeps the compact rail new-chat action while viewing archived chats", async () => {
useAgentStore.setState({ size: { width: 700, height: 450 } });
useAgentStore.getState().createChat({
title: "Archived analytics",
@@ -654,7 +1784,7 @@ describe("AgentWindow", () => {
const rail = document.body.querySelector("[data-agent-compact-rail]");
expect(
rail?.querySelector("[aria-label='agent.new-chat']")
- ).toBeNull();
+ ).toBeInstanceOf(HTMLButtonElement);
expect(
document.body.querySelector(
'[data-agent-new-chat-for-context="projects/analytics"]'
@@ -873,62 +2003,61 @@ describe("AgentWindow", () => {
render();
- const moreButton = document.body.querySelector(
- "[aria-label='common.more']"
- ) as HTMLButtonElement | null;
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ act(() => archiveButton.click());
- act(() => {
- moreButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
+ const row = document.body.querySelector(
+ `[data-agent-chat-row="${archivedChat.id}"]`
);
- });
-
- const agentRoot = document.getElementById("bb-react-layer-agent");
- const overlayRoot = document.getElementById("bb-react-layer-overlay");
-
- expect(
- agentRoot?.querySelector("[data-agent-dropdown-menu-content]")
- ).toBeInstanceOf(HTMLDivElement);
- expect(
- agentRoot?.querySelector("[data-agent-chat-list-mode]")
- ).toBeInstanceOf(HTMLDivElement);
- expect(
- overlayRoot?.querySelector("[data-agent-dropdown-menu-content]") ?? null
- ).toBeNull();
-
- const archivedModeButton = document.body.querySelector(
- "[data-agent-chat-list-mode]"
- ) as HTMLDivElement | null;
+ const menuButton = row?.querySelector(
+ "[data-agent-archived-chat-menu]"
+ ) as HTMLButtonElement;
+ expect(menuButton).toBeInstanceOf(HTMLButtonElement);
+ await act(async () => {
+ menuButton.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ await Promise.resolve();
+ });
- await act(async () => {
- archivedModeButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
+ const agentRoot = document.getElementById("bb-react-layer-agent");
+ const overlayRoot = document.getElementById("bb-react-layer-overlay");
+ expect(
+ agentRoot?.querySelector("[data-agent-dropdown-menu-content]")
+ ).toBeInstanceOf(HTMLDivElement);
+ expect(agentRoot?.querySelector("[data-agent-delete-chat]")).toBeInstanceOf(
+ HTMLElement
);
- await Promise.resolve();
- });
+ expect(
+ overlayRoot?.querySelector("[data-agent-dropdown-menu-content]") ?? null
+ ).toBeNull();
- const deleteButton = document.body.querySelector(
- "[data-agent-delete-chat]"
- ) as HTMLButtonElement | null;
+ const deleteButton = agentRoot?.querySelector(
+ "[data-agent-delete-chat]"
+ ) as HTMLElement;
+ await act(async () => {
+ deleteButton.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ await Promise.resolve();
+ });
- await act(async () => {
- deleteButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
+ expect(
+ agentRoot?.querySelector("[data-agent-dialog-content]")
+ ).toBeInstanceOf(HTMLDivElement);
+ expect(agentRoot?.textContent?.includes("agent.delete-chat-confirmation")).toBe(
+ true
);
- await Promise.resolve();
- });
-
- expect(
- agentRoot?.querySelector("[data-agent-dialog-content]")
- ).toBeInstanceOf(HTMLDivElement);
- expect(
- agentRoot?.textContent?.includes("agent.delete-chat-confirmation")
- ).toBe(true);
- expect(
- overlayRoot?.querySelector("[data-agent-dialog-content]") ?? null
- ).toBeNull();
-
- unmount();
+ expect(
+ overlayRoot?.querySelector("[data-agent-dialog-content]") ?? null
+ ).toBeNull();
+ } finally {
+ unmount();
+ }
});
test("mounts agent tooltip content into the agent layer root", async () => {
@@ -996,53 +2125,52 @@ describe("AgentWindow", () => {
render();
- const moreButton = document.body.querySelector(
- "[aria-label='common.more']"
- ) as HTMLButtonElement | null;
-
- act(() => {
- moreButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- });
-
- const archivedModeButton = document.body.querySelector(
- "[data-agent-chat-list-mode]"
- ) as HTMLDivElement | null;
-
- await act(async () => {
- archivedModeButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- await Promise.resolve();
- });
-
- const deleteButtons = Array.from(
- document.body.querySelectorAll("[data-agent-delete-chat]")
- ) as HTMLButtonElement[];
-
- expect(deleteButtons).toHaveLength(2);
+ try {
+ const archiveButton = document.body.querySelector(
+ '[data-agent-compact-rail] [aria-label="agent.archived-only-chats"]'
+ ) as HTMLButtonElement;
+ expect(archiveButton).toBeInstanceOf(HTMLButtonElement);
+ act(() => archiveButton.click());
- act(() => {
- deleteButtons[0]?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
+ const firstRow = document.body.querySelector(
+ `[data-agent-chat-row="${firstArchivedChat.id}"]`
);
- });
+ const menuButton = firstRow?.querySelector(
+ "[data-agent-archived-chat-menu]"
+ ) as HTMLButtonElement;
+ expect(menuButton).toBeInstanceOf(HTMLButtonElement);
+ await act(async () => {
+ menuButton.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ await Promise.resolve();
+ });
- const confirmButton = Array.from(
- document.body.querySelectorAll("button")
- ).find((button) => button.textContent === "common.confirm");
+ const deleteButton = document.body.querySelector(
+ "[data-agent-delete-chat]"
+ ) as HTMLElement;
+ expect(deleteButton).toBeInstanceOf(HTMLElement);
+ act(() => {
+ deleteButton.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
- act(() => {
- confirmButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- });
+ const confirmButton = Array.from(
+ document.body.querySelectorAll("button")
+ ).find((button) => button.textContent === "common.confirm");
- expect(useAgentStore.getState().getChat(firstArchivedChat.id)).toBeNull();
- expect(useAgentStore.getState().currentChatId).toBe(secondArchivedChat.id);
+ act(() => {
+ confirmButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
- unmount();
+ expect(useAgentStore.getState().getChat(firstArchivedChat.id)).toBeNull();
+ expect(useAgentStore.getState().currentChatId).toBe(secondArchivedChat.id);
+ } finally {
+ unmount();
+ }
});
test("keeps the running chat selected when archiving it from the active list", () => {
diff --git a/frontend/src/modules/agent/components/AgentWindow.tsx b/frontend/src/modules/agent/components/AgentWindow.tsx
index c4fe362fd8..a2c55447cc 100644
--- a/frontend/src/modules/agent/components/AgentWindow.tsx
+++ b/frontend/src/modules/agent/components/AgentWindow.tsx
@@ -1,9 +1,10 @@
+import { Dialog as BaseDialog } from "@base-ui/react/dialog";
import {
Archive,
- Building2,
ChevronLeft,
EllipsisVertical,
- FolderKanban,
+ Folder,
+ FolderOpen,
MessageSquare,
Plus,
Trash2,
@@ -11,6 +12,7 @@ import {
} from "lucide-react";
import {
type ReactNode,
+ type RefObject,
useCallback,
useEffect,
useLayoutEffect,
@@ -27,8 +29,16 @@ import {
Separator as PanelResizeHandle,
} from "react-resizable-panels";
import { Button } from "@/components/ui/button";
+import {
+ Collapsible,
+ CollapsiblePanel,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
-import { getLayerRoot } from "@/components/ui/layer";
+import {
+ getLayerRoot,
+ usePreserveHigherLayerAccess,
+} from "@/components/ui/layer";
import {
getProjectName,
projectNamePrefix,
@@ -49,7 +59,6 @@ import {
import {
MIN_HEIGHT,
MIN_MAIN_PANEL_WIDTH,
- MIN_SIDEBAR_WIDTH,
MIN_WIDTH,
WINDOW_MARGIN,
} from "../window";
@@ -71,7 +80,6 @@ import {
AgentDropdownMenu,
AgentDropdownMenuContent,
AgentDropdownMenuItem,
- AgentDropdownMenuSeparator,
AgentDropdownMenuTrigger,
} from "./ui/AgentDropdownMenu";
import { AgentTooltip } from "./ui/AgentTooltip";
@@ -96,6 +104,9 @@ const COMPACT_WINDOW_MAX_WIDTH = 719;
// Compact remains viable down to the 460px minimum agent-window width. Reserve
// the single-pane mobile flow for genuinely phone-sized agent windows.
const MOBILE_WINDOW_MAX_WIDTH = 479;
+const RAIL_WIDTH = 48;
+const MIN_CHAT_LIST_WIDTH = 240;
+const SIDEBAR_RESIZE_HANDLE_WIDTH = 4;
interface AgentChatGroup {
context?: string;
@@ -131,6 +142,10 @@ function groupChatsByContext(chats: AgentChatRecord[]): AgentChatGroup[] {
];
}
+function getChatGroupStateKey(context: string | undefined, archived: boolean) {
+ return `${archived ? "archived" : "active"}:${context ?? "unscoped"}`;
+}
+
export function AgentWindow() {
const { t } = useTranslation();
@@ -154,6 +169,7 @@ export function AgentWindow() {
const windowRef = useRef<HTMLDivElement>(null);
const bodyRef = useRef<HTMLDivElement>(null);
+ const compactPanelTriggerRef = useRef<HTMLElement | null>(null);
const renameInputRef = useRef<HTMLInputElement>(null);
const [viewportSize, setViewportSize] = useState({
@@ -173,7 +189,13 @@ export function AgentWindow() {
const [mobileScreen, setMobileScreen] = useState<
"chats" | "conversation" | "archived"
>("chats");
+ const [collapsedChatGroups, setCollapsedChatGroups] = useState<Set<string>>(
+ () => new Set()
+ );
const [isRenamingCurrentChat, setIsRenamingCurrentChat] = useState(false);
+ const [pendingDeleteChatId, setPendingDeleteChatId] = useState<string | null>(
+ null
+ );
const [
isDeleteAllArchivedChatsDialogOpen,
setIsDeleteAllArchivedChatsDialogOpen,
@@ -247,10 +269,13 @@ export function AgentWindow() {
const clampSidebarWidth = useCallback(
(width: number, windowWidth = displaySize.width) => {
const maxSW = Math.max(
- MIN_SIDEBAR_WIDTH,
- windowWidth - MIN_MAIN_PANEL_WIDTH
+ MIN_CHAT_LIST_WIDTH,
+ windowWidth -
+ RAIL_WIDTH -
+ MIN_MAIN_PANEL_WIDTH -
+ SIDEBAR_RESIZE_HANDLE_WIDTH
);
- const minSW = Math.min(MIN_SIDEBAR_WIDTH, maxSW);
+ const minSW = Math.min(MIN_CHAT_LIST_WIDTH, maxSW);
return Math.min(maxSW, Math.max(minSW, Math.round(width)));
},
[displaySize.width]
@@ -269,17 +294,27 @@ export function AgentWindow() {
};
const maxSidebarWidth = Math.max(
- MIN_SIDEBAR_WIDTH,
- displaySize.width - MIN_MAIN_PANEL_WIDTH
+ MIN_CHAT_LIST_WIDTH,
+ displaySize.width -
+ RAIL_WIDTH -
+ MIN_MAIN_PANEL_WIDTH -
+ SIDEBAR_RESIZE_HANDLE_WIDTH
);
- const minSidebarWidth = Math.min(MIN_SIDEBAR_WIDTH, maxSidebarWidth);
+ const minSidebarWidth = Math.min(MIN_CHAT_LIST_WIDTH, maxSidebarWidth);
const minMainPanelWidth = Math.min(
MIN_MAIN_PANEL_WIDTH,
- Math.max(1, displaySize.width - minSidebarWidth)
+ Math.max(
+ 1,
+ displaySize.width -
+ RAIL_WIDTH -
+ minSidebarWidth -
+ SIDEBAR_RESIZE_HANDLE_WIDTH
+ )
);
const isMobileWindow = displaySize.width <= MOBILE_WINDOW_MAX_WIDTH;
const isCompactWindow =
displaySize.width <= COMPACT_WINDOW_MAX_WIDTH && !isMobileWindow;
+ const isCompactDrawerOpen = isCompactWindow && compactPanel !== null;
// --- Derived chat data ---
@@ -505,25 +540,66 @@ export function AgentWindow() {
// --- Chat actions ---
+ const setChatGroupOpen = useCallback(
+ (
+ context: string | undefined,
+ open: boolean,
+ archived = showArchivedOnly
+ ) => {
+ const groupKey = getChatGroupStateKey(context, archived);
+ setCollapsedChatGroups((previous) => {
+ const isOpen = !previous.has(groupKey);
+ if (isOpen === open) return previous;
+
+ const next = new Set(previous);
+ if (open) {
+ next.delete(groupKey);
+ } else {
+ next.add(groupKey);
+ }
+ return next;
+ });
+ },
+ [showArchivedOnly]
+ );
+
const createChat = useCallback(() => {
if (isChatCreationDisabled) return;
+ const context = getCurrentChatContext();
+ setChatGroupOpen(context, true, false);
useAgentStore.getState().createChat({
page: getCurrentPageSnapshot(),
- context: getCurrentChatContext(),
+ context,
workspaceName: workspace?.name,
});
- }, [isChatCreationDisabled, getCurrentPageSnapshot, workspace?.name]);
+ setShowArchivedOnly(false);
+ if (isCompactWindow) setCompactPanel(null);
+ }, [
+ isChatCreationDisabled,
+ getCurrentPageSnapshot,
+ isCompactWindow,
+ setChatGroupOpen,
+ workspace?.name,
+ ]);
const createChatForContext = useCallback(
(context: string) => {
if (isChatCreationDisabled) return;
+ setChatGroupOpen(context, true, false);
useAgentStore.getState().createChat({
page: getCurrentPageSnapshot(),
context,
workspaceName: workspace?.name,
});
+ if (isCompactWindow) setCompactPanel(null);
},
- [isChatCreationDisabled, getCurrentPageSnapshot, workspace?.name]
+ [
+ isChatCreationDisabled,
+ getCurrentPageSnapshot,
+ isCompactWindow,
+ setChatGroupOpen,
+ workspace?.name,
+ ]
);
const handleChatRowClick = useCallback(
@@ -538,42 +614,56 @@ export function AgentWindow() {
cancelRenameCurrentChat();
}
useAgentStore.getState().setCurrentChat(chatId);
+ if (isCompactWindow) setCompactPanel(null);
},
- [isRenamingCurrentChat, beginRenameCurrentChat, cancelRenameCurrentChat]
+ [
+ isCompactWindow,
+ isRenamingCurrentChat,
+ beginRenameCurrentChat,
+ cancelRenameCurrentChat,
+ ]
);
const archiveChat = useCallback(
(chatId: string) => {
- const chat = useAgentStore.getState().chats.find((c) => c.id === chatId);
+ const store = useAgentStore.getState();
+ const chat = store.chats.find((c) => c.id === chatId);
if (!chat || chat.archived) return;
- useAgentStore.getState().archiveChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ const wasCurrentChat = store.currentChatId === chat.id;
+ store.archiveChat(chat.id);
+ if (wasCurrentChat) {
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
},
[ensureCurrentChatMatchesDisplayedMode]
);
const unarchiveChat = useCallback(
(chatId: string) => {
- const chat = useAgentStore.getState().chats.find((c) => c.id === chatId);
+ const store = useAgentStore.getState();
+ const chat = store.chats.find((c) => c.id === chatId);
if (!chat?.archived) return;
- useAgentStore.getState().unarchiveChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ const wasCurrentChat = store.currentChatId === chat.id;
+ store.unarchiveChat(chat.id);
+ if (wasCurrentChat) {
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
},
[ensureCurrentChatMatchesDisplayedMode]
);
const archiveAllChats = useCallback(() => {
if (isArchiveAllDisabled) return;
- const archivedCount = useAgentStore.getState().archiveAllActiveChats();
+ const store = useAgentStore.getState();
+ const currentChatWasActive = store.chats.some(
+ (chat) => chat.id === store.currentChatId && !chat.archived
+ );
+ const archivedCount = store.archiveAllActiveChats();
if (archivedCount === 0) return;
- cancelRenameCurrentChat();
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ if (currentChatWasActive) {
+ cancelRenameCurrentChat();
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
}, [
cancelRenameCurrentChat,
ensureCurrentChatMatchesDisplayedMode,
@@ -582,14 +672,16 @@ export function AgentWindow() {
const unarchiveAllChats = useCallback(() => {
if (isUnarchiveAllDisabled) return;
- const unarchivedCount = useAgentStore
- .getState()
- .unarchiveAllArchivedChats();
+ const store = useAgentStore.getState();
+ const currentChatWasArchived = store.chats.some(
+ (chat) => chat.id === store.currentChatId && chat.archived
+ );
+ const unarchivedCount = store.unarchiveAllArchivedChats();
if (unarchivedCount === 0) return;
- cancelRenameCurrentChat();
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ if (currentChatWasArchived) {
+ cancelRenameCurrentChat();
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
}, [
cancelRenameCurrentChat,
ensureCurrentChatMatchesDisplayedMode,
@@ -598,13 +690,17 @@ export function AgentWindow() {
const deleteAllArchivedChats = useCallback(() => {
if (isDeleteAllDisabled) return;
- const deletedCount = useAgentStore.getState().deleteAllArchivedChats();
+ const store = useAgentStore.getState();
+ const currentChatWasArchived = store.chats.some(
+ (chat) => chat.id === store.currentChatId && chat.archived
+ );
+ const deletedCount = store.deleteAllArchivedChats();
if (deletedCount === 0) return;
- cancelRenameCurrentChat();
setIsDeleteAllArchivedChatsDialogOpen(false);
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ if (currentChatWasArchived) {
+ cancelRenameCurrentChat();
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
}, [
cancelRenameCurrentChat,
ensureCurrentChatMatchesDisplayedMode,
@@ -616,23 +712,15 @@ export function AgentWindow() {
const store = useAgentStore.getState();
const chat = store.chats.find((c) => c.id === chatId);
if (!chat) return;
+ const wasCurrentChat = store.currentChatId === chat.id;
store.deleteChat(chat.id);
- ensureCurrentChatMatchesDisplayedMode({
- allowCreateWhenEmpty: false,
- });
+ if (wasCurrentChat) {
+ ensureCurrentChatMatchesDisplayedMode({ allowCreateWhenEmpty: false });
+ }
},
[ensureCurrentChatMatchesDisplayedMode]
);
- const toggleChatListMode = useCallback(() => {
- setShowArchivedOnly((prev) => !prev);
- }, []);
-
- // After showArchivedOnly changes, ensure current chat matches
- useEffect(() => {
- ensureCurrentChatMatchesDisplayedMode();
- }, [showArchivedOnly]);
-
const sidebarPanelRef = useRef<PanelImperativeHandle | null>(null);
const resizeCleanupRef = useRef<(() => void) | null>(null);
@@ -787,14 +875,17 @@ export function AgentWindow() {
// --- Sync sidebar width when window width changes ---
useEffect(() => {
- if (isCompactWindow) return;
+ if (isCompactWindow || isMobileWindow) return;
const store = useAgentStore.getState();
const windowWidth = displaySize.width;
const maxSW = Math.max(
- MIN_SIDEBAR_WIDTH,
- windowWidth - MIN_MAIN_PANEL_WIDTH
+ MIN_CHAT_LIST_WIDTH,
+ windowWidth -
+ RAIL_WIDTH -
+ MIN_MAIN_PANEL_WIDTH -
+ SIDEBAR_RESIZE_HANDLE_WIDTH
);
- const minSW = Math.min(MIN_SIDEBAR_WIDTH, maxSW);
+ const minSW = Math.min(MIN_CHAT_LIST_WIDTH, maxSW);
const clamped = Math.min(
maxSW,
Math.max(minSW, Math.round(store.sidebarWidth))
@@ -805,16 +896,16 @@ export function AgentWindow() {
});
store.saveWindowState();
}
- }, [displaySize.width, isCompactWindow]);
+ }, [displaySize.width, isCompactWindow, isMobileWindow]);
useEffect(() => {
- if (isCompactWindow) return;
+ if (isCompactWindow || isMobileWindow) return;
const panel = sidebarPanelRef.current;
if (!panel) return;
if (Math.round(panel.getSize().inPixels) !== clampedSidebarWidth) {
panel.resize(clampedSidebarWidth);
}
- }, [clampedSidebarWidth, isCompactWindow]);
+ }, [clampedSidebarWidth, isCompactWindow, isMobileWindow]);
useEffect(() => {
if (!isCompactWindow) setCompactPanel(null);
@@ -872,6 +963,10 @@ export function AgentWindow() {
setMobileScreen("archived");
}, []);
+ const returnToMobileChatList = useCallback(() => {
+ setMobileScreen(showArchivedOnly ? "archived" : "chats");
+ }, [showArchivedOnly]);
+
const createMobileChat = useCallback(
(context?: string) => {
if (context) {
@@ -894,12 +989,9 @@ export function AgentWindow() {
[cancelRenameCurrentChat]
);
- const renderCompactRail = (overlay = false) => (
+ const renderRail = () => (
<nav
- className={cn(
- "flex flex-col items-center gap-y-2 border-r border-block-border bg-control-bg py-3",
- overlay ? "absolute inset-y-0 left-0 z-3 w-12" : "size-full"
- )}
+ className="flex size-full flex-col items-center gap-y-2 border-r border-block-border bg-control-bg py-3"
data-agent-compact-rail
aria-label={t("agent.chat-list-label")}
>
@@ -907,39 +999,67 @@ export function AgentWindow() {
<Button
appearance="secondary"
size="xs"
- className="text-control-light hover:bg-control-bg-hover"
+ className={cn(
+ "hover:bg-control-bg-hover",
+ (isCompactWindow ? compactPanel === "chats" : !showArchivedOnly)
+ ? "bg-accent/10 text-accent"
+ : "text-control-light"
+ )}
aria-label={t("agent.chat-list-label")}
- onClick={() => {
+ aria-current={
+ (isCompactWindow ? compactPanel === "chats" : !showArchivedOnly)
+ ? "page"
+ : undefined
+ }
+ onClick={(event) => {
setShowArchivedOnly(false);
- setCompactPanel("chats");
+ if (isCompactWindow) {
+ compactPanelTriggerRef.current = event.currentTarget;
+ setCompactPanel("chats");
+ } else {
+ setCompactPanel(null);
+ }
}}
>
<MessageSquare className="size-3.5" aria-hidden="true" />
</Button>
</AgentTooltip>
- {!showArchivedOnly && (
- <AgentTooltip content={t("agent.new-chat")}>
- <Button
- appearance="secondary"
- size="xs"
- className="text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.new-chat")}
- disabled={isChatCreationDisabled}
- onClick={createChat}
- >
- <Plus className="size-3.5" aria-hidden="true" />
- </Button>
- </AgentTooltip>
- )}
- <AgentTooltip content={t("agent.archived-only-chats")}>
+ <AgentTooltip content={t("agent.new-chat")}>
<Button
appearance="secondary"
size="xs"
className="text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.new-chat")}
+ disabled={isChatCreationDisabled}
+ onClick={createChat}
+ >
+ <Plus className="size-3.5" aria-hidden="true" />
+ </Button>
+ </AgentTooltip>
+ <AgentTooltip content={t("agent.archived-only-chats")}>
+ <Button
+ appearance="secondary"
+ size="xs"
+ className={cn(
+ "hover:bg-control-bg-hover",
+ (isCompactWindow ? compactPanel === "archived" : showArchivedOnly)
+ ? "bg-accent/10 text-accent"
+ : "text-control-light"
+ )}
aria-label={t("agent.archived-only-chats")}
- onClick={() => {
+ aria-current={
+ (isCompactWindow ? compactPanel === "archived" : showArchivedOnly)
+ ? "page"
+ : undefined
+ }
+ onClick={(event) => {
setShowArchivedOnly(true);
- setCompactPanel("archived");
+ if (isCompactWindow) {
+ compactPanelTriggerRef.current = event.currentTarget;
+ setCompactPanel("archived");
+ } else {
+ setCompactPanel(null);
+ }
}}
>
<Archive className="size-3.5" aria-hidden="true" />
@@ -1013,614 +1133,759 @@ export function AgentWindow() {
</div>
</AgentDialogContent>
</AgentDialog>
- <div className="flex size-full flex-col overflow-hidden rounded-sm border border-block-border bg-background shadow-xl">
- {/* Header */}
- <div
- data-agent-window-header
- className="flex select-none items-center justify-between border-b bg-control-bg px-3 py-2"
- >
- <div className="flex min-w-0 items-center gap-x-2">
- {isMobileWindow && mobileScreen === "conversation" && (
+ <AgentDialog
+ open={pendingDeleteChatId !== null}
+ onOpenChange={(open) => {
+ if (!open) setPendingDeleteChatId(null);
+ }}
+ >
+ <AgentDialogContent className="max-w-sm p-6">
+ <AgentDialogTitle className="sr-only">
+ {t("common.confirm")}
+ </AgentDialogTitle>
+ <AgentDialogDescription>
+ {t("agent.delete-chat-confirmation")}
+ </AgentDialogDescription>
+ <div className="mt-6 flex justify-end gap-x-2">
+ <AgentDialogClose
+ render={
+ <Button appearance="outline" type="button">
+ {t("common.cancel")}
+ </Button>
+ }
+ />
+ <AgentDialogClose
+ render={
+ <Button type="button" variant="destructive">
+ {t("common.confirm")}
+ </Button>
+ }
+ onClick={() => {
+ if (pendingDeleteChatId) deleteChat(pendingDeleteChatId);
+ }}
+ />
+ </div>
+ </AgentDialogContent>
+ </AgentDialog>
+ <BaseDialog.Root
+ open={isCompactDrawerOpen}
+ modal="trap-focus"
+ onOpenChange={(open) => {
+ if (!open) setCompactPanel(null);
+ }}
+ >
+ <div className="flex size-full flex-col overflow-hidden rounded-sm border border-block-border bg-background shadow-xl">
+ {/* Header */}
+ <div
+ data-agent-window-header
+ aria-hidden={isCompactDrawerOpen || undefined}
+ inert={isCompactDrawerOpen || undefined}
+ className="relative flex select-none items-center justify-between border-b bg-control-bg px-3 py-2"
+ >
+ <div className="flex min-w-0 items-center gap-x-2">
+ {isMobileWindow && mobileScreen === "conversation" && (
+ <Button
+ appearance="secondary"
+ size="xs"
+ data-agent-window-action
+ className="-ml-1 text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.chat-list-label")}
+ onClick={(event) => {
+ event.stopPropagation();
+ returnToMobileChatList();
+ }}
+ >
+ <ChevronLeft className="size-4" aria-hidden="true" />
+ </Button>
+ )}
+ {isMobileWindow && mobileScreen === "archived" && (
+ <Button
+ appearance="secondary"
+ size="xs"
+ data-agent-window-action
+ className="-ml-1 text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.chat-list-label")}
+ onClick={(event) => {
+ event.stopPropagation();
+ openMobileChatList();
+ }}
+ >
+ <ChevronLeft className="size-4" aria-hidden="true" />
+ </Button>
+ )}
+ <span className="truncate text-sm font-medium">
+ {isMobileWindow && mobileScreen === "chats"
+ ? t("agent.chat-list-label")
+ : isMobileWindow && mobileScreen === "archived"
+ ? t("agent.archived-only-chats")
+ : t("agent.assistant-title")}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-1">
+ {isMobileWindow && mobileScreen === "chats" && (
+ <>
+ <AgentTooltip content={t("agent.archived-only-chats")}>
+ <Button
+ appearance="secondary"
+ size="xs"
+ data-agent-window-action
+ className="text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.archived-only-chats")}
+ onClick={(event) => {
+ event.stopPropagation();
+ openMobileArchivedChats();
+ }}
+ >
+ <Archive className="size-3.5" aria-hidden="true" />
+ </Button>
+ </AgentTooltip>
+ <AgentTooltip content={t("agent.new-chat")}>
+ <Button
+ appearance="secondary"
+ size="xs"
+ data-agent-window-action
+ className="text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.new-chat")}
+ disabled={isChatCreationDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ createMobileChat();
+ }}
+ >
+ <Plus className="size-3.5" aria-hidden="true" />
+ </Button>
+ </AgentTooltip>
+ </>
+ )}
<Button
appearance="secondary"
size="xs"
data-agent-window-action
- className="-ml-1 text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.chat-list-label")}
- onClick={(event) => {
- event.stopPropagation();
- openMobileChatList();
+ className="flex items-center justify-center rounded-xs text-control-placeholder hover:bg-control-bg-hover hover:text-control-light"
+ title={t("agent.minimize")}
+ onClick={(e) => {
+ e.stopPropagation();
+ useAgentStore.getState().minimize();
}}
>
- <ChevronLeft className="size-4" aria-hidden="true" />
+ &#8722;
</Button>
- )}
- {isMobileWindow && mobileScreen === "archived" && (
<Button
appearance="secondary"
size="xs"
data-agent-window-action
- className="-ml-1 text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.chat-list-label")}
- onClick={(event) => {
- event.stopPropagation();
- openMobileChatList();
+ className="flex items-center justify-center rounded-xs text-control-placeholder hover:bg-control-bg-hover hover:text-control-light"
+ title={t("agent.close")}
+ onClick={(e) => {
+ e.stopPropagation();
+ useAgentStore.getState().toggle();
}}
>
- <ChevronLeft className="size-4" aria-hidden="true" />
+ &#10005;
</Button>
- )}
- <span className="truncate text-sm font-medium">
- {isMobileWindow && mobileScreen === "chats"
- ? t("agent.chat-list-label")
- : isMobileWindow && mobileScreen === "archived"
- ? t("agent.archived-only-chats")
- : t("agent.assistant-title")}
- </span>
+ </div>
</div>
- <div className="flex items-center gap-x-1">
- {isMobileWindow && mobileScreen === "chats" && (
- <>
- <AgentTooltip content={t("agent.archived-only-chats")}>
- <Button
- appearance="secondary"
- size="xs"
- data-agent-window-action
- className="text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.archived-only-chats")}
- onClick={(event) => {
- event.stopPropagation();
- openMobileArchivedChats();
- }}
- >
- <Archive className="size-3.5" aria-hidden="true" />
- </Button>
- </AgentTooltip>
- <AgentTooltip content={t("agent.new-chat")}>
- <Button
- appearance="secondary"
- size="xs"
- data-agent-window-action
- className="text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.new-chat")}
- disabled={isChatCreationDisabled}
- onClick={(event) => {
- event.stopPropagation();
- createMobileChat();
- }}
- >
- <Plus className="size-3.5" aria-hidden="true" />
- </Button>
- </AgentTooltip>
- </>
- )}
- <Button
- appearance="secondary"
- size="xs"
- data-agent-window-action
- className="flex items-center justify-center rounded-xs text-control-placeholder hover:bg-control-bg-hover hover:text-control-light"
- title={t("agent.minimize")}
- onClick={(e) => {
- e.stopPropagation();
- useAgentStore.getState().minimize();
- }}
- >
- &#8722;
- </Button>
- <Button
- appearance="secondary"
- size="xs"
- data-agent-window-action
- className="flex items-center justify-center rounded-xs text-control-placeholder hover:bg-control-bg-hover hover:text-control-light"
- title={t("agent.close")}
- onClick={(e) => {
- e.stopPropagation();
- useAgentStore.getState().toggle();
- }}
- >
- &#10005;
- </Button>
- </div>
- </div>
- {/* Body */}
- <div
- ref={bodyRef}
- className="relative min-h-0 flex-1"
- data-agent-window-body
- >
- {isMobileWindow ? (
- mobileScreen === "conversation" ? (
- <div
- className="flex size-full flex-col bg-background"
- data-agent-mobile-conversation
- >
- <AgentChat className="min-h-0 flex-1" />
- <AgentInput />
- </div>
- ) : (
- <div
- className="size-full overflow-y-auto bg-control-bg"
- data-agent-mobile-chat-list
- >
- <div className="flex flex-col" data-agent-chat-list>
- {displayedChatGroups.map((group) => (
- <div
- key={group.context ?? "unscoped"}
- className="flex flex-col"
- data-agent-chat-group={group.context ?? "unscoped"}
- >
- <div className="flex min-w-0 items-center justify-between gap-x-2 px-3 pt-3 pb-1 text-xs font-medium text-control-light">
- {group.context ? (
- <div className="flex min-w-0 items-center gap-x-1.5">
- {group.context.startsWith(projectNamePrefix) ? (
- <FolderKanban className="size-3.5 shrink-0" />
- ) : (
- <Building2 className="size-3.5 shrink-0" />
- )}
- <span className="truncate">
- {getContextLabel(group.context)}
- </span>
- </div>
- ) : (
- <span className="truncate">
- {t("agent.other-chats")}
- </span>
- )}
- {group.context && !showArchivedOnly && (
- <AgentTooltip
- content={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
- >
- <Button
- appearance="secondary"
- size="xs"
- className="shrink-0 px-1 text-control-light hover:bg-control-bg-hover"
- aria-label={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
- data-agent-new-chat-for-context={group.context}
- disabled={isChatCreationDisabled}
- onClick={() => createMobileChat(group.context)}
- >
- <Plus className="size-3.5" aria-hidden="true" />
- </Button>
- </AgentTooltip>
- )}
- </div>
- {group.chats.map((chat) => (
- <div
- key={chat.id}
- className={cn(
- "flex items-center gap-x-2 px-3 py-2 text-sm",
- chat.id === currentChatId
- ? "bg-accent/10 text-accent"
- : "text-control"
- )}
- data-agent-chat-row={chat.id}
+ {/* Body */}
+ <div
+ ref={bodyRef}
+ className="relative min-h-0 flex-1"
+ data-agent-window-body
+ >
+ {isMobileWindow ? (
+ mobileScreen === "conversation" ? (
+ <div
+ className="flex size-full flex-col bg-background"
+ data-agent-mobile-conversation
+ >
+ <AgentChat className="min-h-0 flex-1" />
+ <AgentInput />
+ </div>
+ ) : (
+ <div
+ className="size-full overflow-y-auto bg-control-bg"
+ data-agent-mobile-chat-list
+ >
+ <div className="flex flex-col" data-agent-chat-list>
+ {displayedChatGroups.map((group) => {
+ const groupKey = getChatGroupStateKey(
+ group.context,
+ showArchivedOnly
+ );
+ const groupIsOpen = !collapsedChatGroups.has(groupKey);
+
+ return (
+ <Collapsible
+ key={group.context ?? "unscoped"}
+ open={groupIsOpen}
+ onOpenChange={(open) =>
+ setChatGroupOpen(group.context, open)
+ }
+ data-agent-chat-group={group.context ?? "unscoped"}
>
- <Button
- appearance="secondary"
- size="md"
- type="button"
- className="h-auto min-w-0 flex-1 justify-start p-0 text-left hover:bg-transparent"
- disabled={
- !useAgentStore.getState().canSelectChat(chat.id)
- }
- aria-current={
- chat.id === currentChatId ? "true" : undefined
+ <div
+ className="flex w-full min-w-0 items-center justify-between gap-x-2 pt-2 pb-1 text-sm font-medium text-control-light hover:bg-control-bg-hover"
+ data-agent-chat-group-header={
+ group.context ?? "unscoped"
}
- onClick={() => selectMobileChat(chat.id)}
>
- <span className="truncate font-medium">
- {getChatLabel(chat)}
- </span>
- </Button>
- {chat.archived ? (
- <>
- <SidebarIconButton
- tooltip={t("agent.unarchive-chat")}
- ariaLabel={t("agent.unarchive-chat")}
- dataAttr="data-agent-unarchive-chat"
- onClick={() => unarchiveChat(chat.id)}
- >
- <Undo2
- className="size-3.5"
+ <CollapsibleTrigger
+ className="h-7 w-auto min-w-0 flex-1 justify-start gap-x-2 rounded-none pr-1 pl-4 text-sm font-medium text-control-light hover:bg-transparent"
+ title={
+ group.context
+ ? getContextLabel(group.context)
+ : t("agent.other-chats")
+ }
+ data-agent-chat-group-toggle={
+ group.context ?? "unscoped"
+ }
+ >
+ {groupIsOpen ? (
+ <FolderOpen
+ className="size-4 shrink-0"
aria-hidden="true"
/>
- </SidebarIconButton>
- <ConfirmDialog
- message={t("agent.delete-chat-confirmation")}
- onConfirm={() => deleteChat(chat.id)}
- triggerLabel={t("agent.delete-chat")}
- triggerDataAttr="data-agent-delete-chat"
- triggerVariant="icon"
- >
- <Trash2
- className="size-3.5"
+ ) : (
+ <Folder
+ className="size-4 shrink-0"
aria-hidden="true"
/>
- </ConfirmDialog>
- </>
- ) : (
- <SidebarIconButton
- tooltip={t("agent.archive-chat")}
- ariaLabel={t("agent.archive-chat")}
- dataAttr="data-agent-archive-chat"
- onClick={() => archiveChat(chat.id)}
- >
- <Archive
- className="size-3.5"
- aria-hidden="true"
- />
- </SidebarIconButton>
- )}
- </div>
- ))}
- </div>
- ))}
- </div>
- </div>
- )
- ) : (
- <PanelGroup
- orientation="horizontal"
- className="relative z-0 size-full bg-background"
- data-agent-chat-panels
- onLayoutChanged={(_, meta) => {
- if (!isCompactWindow && meta.isUserInteraction)
- saveSidebarWidth();
- }}
- >
- {/* Sidebar */}
- <Panel
- key={isCompactWindow ? "compact" : "roomy"}
- id="agent-chat-sidebar"
- panelRef={sidebarPanelRef}
- defaultSize={isCompactWindow ? 48 : clampedSidebarWidth}
- minSize={isCompactWindow ? 48 : minSidebarWidth}
- maxSize={isCompactWindow ? 48 : maxSidebarWidth}
- groupResizeBehavior="preserve-pixel-size"
- className="relative"
- >
- {isCompactWindow && !compactPanel ? (
- renderCompactRail()
- ) : (
- <EscapePanelClip
- target={
- isCompactWindow && compactPanel ? bodyRef.current : null
- }
- >
- <aside
- className={cn(
- "flex size-full flex-col bg-control-bg",
- isCompactWindow &&
- "absolute inset-y-0 left-12 z-2 w-80 shadow-lg"
- )}
- data-agent-chat-sidebar={
- isCompactWindow ? undefined : true
- }
- data-agent-compact-drawer={
- isCompactWindow ? true : undefined
- }
- >
- {/* Sidebar header */}
- <div className="border-b border-block-border px-3 py-3">
- <div className="flex items-center justify-between gap-x-2">
- <h2 className="text-xs font-semibold uppercase tracking-wide text-control-light">
- {showArchivedOnly
- ? t("agent.archived-only-chats")
- : t("agent.chat-list-label")}
- </h2>
- {isCompactWindow ? (
- <Button
- appearance="secondary"
- size="xs"
- className="text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.close")}
- onClick={() => setCompactPanel(null)}
- >
- &#10005;
- </Button>
- ) : (
- <div
- className="flex items-center gap-x-1"
- data-agent-chat-sidebar-actions
- >
- {!showArchivedOnly && (
- <AgentTooltip content={t("agent.new-chat")}>
- <Button
- appearance="secondary"
- size="xs"
- className="px-1 text-control-light hover:bg-control-bg-hover"
- aria-label={t("agent.new-chat")}
- disabled={isChatCreationDisabled}
- onClick={createChat}
- >
- <Plus
- className="size-3.5"
- aria-hidden="true"
- />
- </Button>
- </AgentTooltip>
)}
- <AgentDropdownMenu>
- <AgentTooltip content={t("common.more")}>
- <AgentDropdownMenuTrigger
- className="inline-flex size-6 items-center justify-center rounded-xs text-control-light outline-hidden hover:bg-control-bg-hover focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50"
- aria-label={t("common.more")}
- onClick={(event) => event.stopPropagation()}
+ <span className="truncate">
+ {group.context
+ ? getContextLabel(group.context)
+ : t("agent.other-chats")}
+ </span>
+ </CollapsibleTrigger>
+ {group.context && !showArchivedOnly && (
+ <AgentTooltip
+ content={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
+ >
+ <Button
+ appearance="secondary"
+ size="xs"
+ className="mr-2 shrink-0 text-control-light hover:bg-control/25"
+ aria-label={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
+ data-agent-new-chat-for-context={
+ group.context
+ }
+ disabled={isChatCreationDisabled}
+ onClick={() =>
+ createMobileChat(group.context)
+ }
+ >
+ <Plus
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </Button>
+ </AgentTooltip>
+ )}
+ </div>
+ <CollapsiblePanel
+ className="p-0"
+ data-agent-chat-group-children={
+ group.context ?? "unscoped"
+ }
+ >
+ {group.chats.map((chat) => (
+ <div
+ key={chat.id}
+ className={cn(
+ "flex w-full items-center gap-x-2 py-2 pr-3 pl-5 text-sm transition-colors",
+ chat.id === currentChatId
+ ? "bg-accent/10 text-accent"
+ : "text-control hover:bg-control-bg-hover"
+ )}
+ data-agent-chat-row={chat.id}
+ >
+ <Button
+ appearance="secondary"
+ size="md"
+ type="button"
+ className="h-auto min-w-0 flex-1 justify-start p-0 text-left font-normal hover:bg-transparent"
+ title={getChatLabel(chat)}
+ disabled={
+ !useAgentStore
+ .getState()
+ .canSelectChat(chat.id)
+ }
+ aria-current={
+ chat.id === currentChatId
+ ? "true"
+ : undefined
+ }
+ onClick={() => selectMobileChat(chat.id)}
+ >
+ <span className="truncate">
+ {getChatLabel(chat)}
+ </span>
+ </Button>
+ {chat.archived ? (
+ <>
+ <SidebarIconButton
+ tooltip={t("agent.unarchive-chat")}
+ ariaLabel={t("agent.unarchive-chat")}
+ dataAttr="data-agent-unarchive-chat"
+ onClick={() => unarchiveChat(chat.id)}
+ >
+ <Undo2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ <ConfirmDialog
+ message={t(
+ "agent.delete-chat-confirmation"
+ )}
+ onConfirm={() => deleteChat(chat.id)}
+ triggerLabel={t("agent.delete-chat")}
+ triggerDataAttr="data-agent-delete-chat"
+ triggerVariant="icon"
+ >
+ <Trash2
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </ConfirmDialog>
+ </>
+ ) : (
+ <SidebarIconButton
+ tooltip={t("agent.archive-chat")}
+ ariaLabel={t("agent.archive-chat")}
+ dataAttr="data-agent-archive-chat"
+ onClick={() => archiveChat(chat.id)}
>
- <EllipsisVertical
+ <Archive
className="size-3.5"
aria-hidden="true"
/>
- </AgentDropdownMenuTrigger>
- </AgentTooltip>
- <AgentDropdownMenuContent>
- {showArchivedOnly ? (
- <>
- <AgentDropdownMenuItem
- data-agent-unarchive-all-chats
- disabled={isUnarchiveAllDisabled}
- onClick={(event) => {
- event.stopPropagation();
- unarchiveAllChats();
- }}
- >
- {t("agent.unarchive-all-chats")}
- </AgentDropdownMenuItem>
- <AgentDropdownMenuItem
- data-agent-delete-all-chats
- className="text-error data-highlighted:bg-error/10"
- disabled={isDeleteAllDisabled}
- onClick={(event) => {
- event.stopPropagation();
- setIsDeleteAllArchivedChatsDialogOpen(
- true
- );
- }}
- >
- {t("agent.delete-all-chats")}
- </AgentDropdownMenuItem>
- </>
- ) : (
- <AgentDropdownMenuItem
- data-agent-archive-all-chats
- disabled={isArchiveAllDisabled}
- onClick={(event) => {
- event.stopPropagation();
- archiveAllChats();
- }}
- >
- {t("agent.archive-all-chats")}
- </AgentDropdownMenuItem>
- )}
- <AgentDropdownMenuSeparator />
- <AgentDropdownMenuItem
- data-agent-chat-list-mode
- onClick={(event) => {
- event.stopPropagation();
- toggleChatListMode();
- }}
- >
- {showArchivedOnly
- ? t("agent.active-only-chats")
- : t("agent.archived-only-chats")}
- </AgentDropdownMenuItem>
- </AgentDropdownMenuContent>
- </AgentDropdownMenu>
- </div>
- )}
- </div>
- </div>
-
- {/* Chat list */}
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="flex flex-col" data-agent-chat-list>
- {displayedChatGroups.map((group) => (
- <div
- key={group.context ?? "unscoped"}
- className="flex flex-col"
- data-agent-chat-group={
- group.context ?? "unscoped"
- }
- >
- <div className="flex min-w-0 items-center justify-between gap-x-2 px-3 pt-3 pb-1 text-xs font-medium text-control-light">
- {group.context ? (
- <div className="flex min-w-0 items-center gap-x-1.5">
- {group.context.startsWith(
- projectNamePrefix
- ) ? (
- <FolderKanban className="size-3.5 shrink-0" />
- ) : (
- <Building2 className="size-3.5 shrink-0" />
- )}
- <span className="truncate">
- {getContextLabel(group.context)}
- </span>
- </div>
- ) : (
- <span className="truncate">
- {t("agent.other-chats")}
- </span>
+ </SidebarIconButton>
)}
- {group.context && !showArchivedOnly && (
- <AgentTooltip
- content={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
- >
+ </div>
+ ))}
+ </CollapsiblePanel>
+ </Collapsible>
+ );
+ })}
+ </div>
+ </div>
+ )
+ ) : (
+ <div className="flex size-full" data-agent-desktop-layout>
+ <div className="w-12 shrink-0">{renderRail()}</div>
+ <PanelGroup
+ orientation="horizontal"
+ className="relative z-0 min-w-0 flex-1 bg-background"
+ data-agent-chat-panels
+ aria-hidden={isCompactDrawerOpen || undefined}
+ inert={isCompactDrawerOpen || undefined}
+ onLayoutChanged={(_, meta) => {
+ if (!isCompactWindow && meta.isUserInteraction)
+ saveSidebarWidth();
+ }}
+ >
+ {/* Sidebar */}
+ <Panel
+ key={isCompactWindow ? "compact" : "roomy"}
+ id="agent-chat-sidebar"
+ panelRef={sidebarPanelRef}
+ defaultSize={isCompactWindow ? 0 : clampedSidebarWidth}
+ minSize={isCompactWindow ? 0 : minSidebarWidth}
+ maxSize={isCompactWindow ? 0 : maxSidebarWidth}
+ groupResizeBehavior="preserve-pixel-size"
+ className="relative"
+ >
+ {(!isCompactWindow || compactPanel) && (
+ <CompactDrawerPortal
+ compact={isCompactWindow}
+ container={bodyRef}
+ finalFocus={compactPanelTriggerRef}
+ title={
+ showArchivedOnly
+ ? t("agent.archived-only-chats")
+ : t("agent.chat-list-label")
+ }
+ >
+ <aside
+ className={cn(
+ "flex size-full flex-col bg-control-bg",
+ isCompactWindow && "shadow-lg"
+ )}
+ data-agent-chat-sidebar={
+ isCompactWindow ? undefined : true
+ }
+ data-agent-compact-drawer={
+ isCompactWindow ? true : undefined
+ }
+ >
+ {/* Sidebar header */}
+ <div className="border-b border-block-border px-3 py-3">
+ <div className="flex items-center justify-between gap-x-2">
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-control-light">
+ {showArchivedOnly
+ ? t("agent.archived-only-chats")
+ : t("agent.chat-list-label")}
+ </h2>
+ {isCompactWindow ? (
+ <AgentDialogClose
+ render={
<Button
appearance="secondary"
size="xs"
- className="shrink-0 px-1 text-control-light hover:bg-control-bg-hover"
- aria-label={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
- data-agent-new-chat-for-context={
- group.context
- }
- disabled={isChatCreationDisabled}
- onClick={() =>
- createChatForContext(group.context!)
- }
+ className="text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.close")}
>
- <Plus
- className="size-3.5"
- aria-hidden="true"
- />
+ &#10005;
</Button>
- </AgentTooltip>
- )}
- </div>
- {group.chats.map((chat) => (
+ }
+ />
+ ) : (
<div
- key={chat.id}
- className={`group w-full rounded-xs px-3 py-2 text-left text-sm transition-colors ${
- chat.id === currentChatId
- ? "bg-accent/10 text-accent"
- : "text-control hover:bg-control-bg-hover"
- }`}
- data-agent-chat-row={chat.id}
+ className="flex items-center gap-x-1"
+ data-agent-chat-sidebar-actions
>
- {chat.id === currentChatId &&
- isRenamingCurrentChat ? (
- <Input
- ref={renameInputRef}
- value={renamingTitle}
- onChange={(e) =>
- setRenamingTitle(e.target.value)
- }
- className="h-7 text-sm"
- placeholder={t(
- "agent.rename-chat-placeholder"
- )}
- data-agent-inline-rename-input
- onBlur={commitRenameCurrentChat}
- onKeyDown={onRenameKeydown}
- />
- ) : (
- <div className="flex items-center gap-x-2">
+ {!showArchivedOnly && (
+ <AgentTooltip content={t("agent.new-chat")}>
<Button
appearance="secondary"
- size="md"
- type="button"
- className="h-auto min-w-0 flex-1 flex-col items-start p-0 text-left whitespace-normal hover:bg-transparent disabled:cursor-not-allowed disabled:opacity-60"
- disabled={
- !useAgentStore
- .getState()
- .canSelectChat(chat.id)
+ size="xs"
+ className="px-1 text-control-light hover:bg-control-bg-hover"
+ aria-label={t("agent.new-chat")}
+ disabled={isChatCreationDisabled}
+ onClick={createChat}
+ >
+ <Plus
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </Button>
+ </AgentTooltip>
+ )}
+ <AgentDropdownMenu>
+ <AgentTooltip content={t("common.more")}>
+ <AgentDropdownMenuTrigger
+ className="inline-flex size-6 items-center justify-center rounded-xs text-control-light outline-hidden hover:bg-control-bg-hover focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50"
+ aria-label={t("common.more")}
+ onClick={(event) =>
+ event.stopPropagation()
}
- aria-current={
- chat.id === currentChatId
- ? "true"
- : undefined
+ >
+ <EllipsisVertical
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </AgentDropdownMenuTrigger>
+ </AgentTooltip>
+ <AgentDropdownMenuContent>
+ {showArchivedOnly ? (
+ <>
+ <AgentDropdownMenuItem
+ data-agent-unarchive-all-chats
+ disabled={isUnarchiveAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ unarchiveAllChats();
+ }}
+ >
+ {t("agent.unarchive-all-chats")}
+ </AgentDropdownMenuItem>
+ <AgentDropdownMenuItem
+ data-agent-delete-all-chats
+ className="text-error data-highlighted:bg-error/10"
+ disabled={isDeleteAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ setIsDeleteAllArchivedChatsDialogOpen(
+ true
+ );
+ }}
+ >
+ {t("agent.delete-all-chats")}
+ </AgentDropdownMenuItem>
+ </>
+ ) : (
+ <AgentDropdownMenuItem
+ data-agent-archive-all-chats
+ className="text-error data-highlighted:bg-error/10"
+ disabled={isArchiveAllDisabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ archiveAllChats();
+ }}
+ >
+ {t("agent.archive-all-chats")}
+ </AgentDropdownMenuItem>
+ )}
+ </AgentDropdownMenuContent>
+ </AgentDropdownMenu>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Chat list */}
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="flex flex-col" data-agent-chat-list>
+ {displayedChatGroups.map((group) => {
+ const groupKey = getChatGroupStateKey(
+ group.context,
+ showArchivedOnly
+ );
+ const groupIsOpen =
+ !collapsedChatGroups.has(groupKey);
+
+ return (
+ <Collapsible
+ key={group.context ?? "unscoped"}
+ open={groupIsOpen}
+ onOpenChange={(open) =>
+ setChatGroupOpen(group.context, open)
+ }
+ data-agent-chat-group={
+ group.context ?? "unscoped"
+ }
+ >
+ <div
+ className="flex w-full min-w-0 items-center justify-between gap-x-2 pt-2 pb-1 text-sm font-medium text-control-light hover:bg-control-bg-hover"
+ data-agent-chat-group-header={
+ group.context ?? "unscoped"
+ }
+ >
+ <CollapsibleTrigger
+ className="h-7 w-auto min-w-0 flex-1 justify-start gap-x-2 rounded-none pr-1 pl-4 text-sm font-medium text-control-light hover:bg-transparent"
+ title={
+ group.context
+ ? getContextLabel(group.context)
+ : t("agent.other-chats")
}
- onClick={() =>
- handleChatRowClick(chat.id)
+ data-agent-chat-group-toggle={
+ group.context ?? "unscoped"
}
>
- <div
- className="w-full truncate font-medium"
- data-agent-chat-title
- >
- {getChatLabel(chat)}
- </div>
- </Button>
- <div className="pointer-events-none flex shrink-0 items-center gap-x-2 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
- {chat.archived ? (
- <>
- <SidebarIconButton
- tooltip={t(
- "agent.unarchive-chat"
- )}
- ariaLabel={t(
- "agent.unarchive-chat"
- )}
- dataAttr="data-agent-unarchive-chat"
- onClick={() =>
- unarchiveChat(chat.id)
- }
- >
- <Undo2
- className="size-3.5"
- aria-hidden="true"
- />
- </SidebarIconButton>
- <ConfirmDialog
- message={t(
- "agent.delete-chat-confirmation"
- )}
- onConfirm={() =>
- deleteChat(chat.id)
- }
- triggerLabel={t(
- "agent.delete-chat"
- )}
- triggerDataAttr="data-agent-delete-chat"
- triggerVariant="icon"
- >
- <Trash2
- className="size-3.5"
- aria-hidden="true"
- />
- </ConfirmDialog>
- </>
+ {groupIsOpen ? (
+ <FolderOpen
+ className="size-4 shrink-0"
+ aria-hidden="true"
+ />
) : (
- <SidebarIconButton
- tooltip={t("agent.archive-chat")}
- ariaLabel={t("agent.archive-chat")}
- dataAttr="data-agent-archive-chat"
- onClick={() => archiveChat(chat.id)}
+ <Folder
+ className="size-4 shrink-0"
+ aria-hidden="true"
+ />
+ )}
+ <span className="truncate">
+ {group.context
+ ? getContextLabel(group.context)
+ : t("agent.other-chats")}
+ </span>
+ </CollapsibleTrigger>
+ {group.context && !showArchivedOnly && (
+ <AgentTooltip
+ content={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
+ >
+ <Button
+ appearance="secondary"
+ size="xs"
+ className="mr-2 shrink-0 text-control-light hover:bg-control/25"
+ aria-label={`${t("agent.new-chat")}: ${getContextLabel(group.context)}`}
+ data-agent-new-chat-for-context={
+ group.context
+ }
+ disabled={isChatCreationDisabled}
+ onClick={() =>
+ createChatForContext(
+ group.context!
+ )
+ }
>
- <Archive
+ <Plus
className="size-3.5"
aria-hidden="true"
/>
- </SidebarIconButton>
- )}
- </div>
+ </Button>
+ </AgentTooltip>
+ )}
</div>
- )}
- </div>
- ))}
+ <CollapsiblePanel
+ className="p-0"
+ data-agent-chat-group-children={
+ group.context ?? "unscoped"
+ }
+ >
+ {group.chats.map((chat) => (
+ <div
+ key={chat.id}
+ className={cn(
+ "group w-full py-2 pr-3 pl-5 text-left text-sm transition-colors",
+ chat.id === currentChatId
+ ? "bg-accent/10 text-accent"
+ : "text-control hover:bg-control-bg-hover"
+ )}
+ data-agent-chat-row={chat.id}
+ >
+ {chat.id === currentChatId &&
+ isRenamingCurrentChat ? (
+ <Input
+ ref={renameInputRef}
+ value={renamingTitle}
+ onChange={(e) =>
+ setRenamingTitle(e.target.value)
+ }
+ className="h-7 text-sm"
+ placeholder={t(
+ "agent.rename-chat-placeholder"
+ )}
+ data-agent-inline-rename-input
+ onBlur={commitRenameCurrentChat}
+ onKeyDown={onRenameKeydown}
+ />
+ ) : (
+ <div className="relative flex min-w-0 items-center">
+ <Button
+ appearance="secondary"
+ size="md"
+ type="button"
+ title={getChatLabel(chat)}
+ className={cn(
+ "h-auto min-w-0 flex-1 flex-col items-start p-0 text-left font-normal hover:bg-transparent disabled:cursor-not-allowed disabled:opacity-60",
+ chat.archived
+ ? "pr-7"
+ : "group-hover:pr-7 group-focus-within:pr-7"
+ )}
+ disabled={
+ !useAgentStore
+ .getState()
+ .canSelectChat(chat.id)
+ }
+ aria-current={
+ chat.id === currentChatId
+ ? "true"
+ : undefined
+ }
+ onClick={() =>
+ handleChatRowClick(chat.id)
+ }
+ >
+ <div
+ className="w-full truncate"
+ data-agent-chat-title
+ >
+ {getChatLabel(chat)}
+ </div>
+ </Button>
+ {chat.archived ? (
+ <AgentDropdownMenu>
+ <AgentDropdownMenuTrigger
+ className="absolute top-1/2 right-0 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-xs text-control-light outline-hidden hover:bg-control-bg-hover focus-visible:ring-2 focus-visible:ring-accent"
+ aria-label={t(
+ "common.more"
+ )}
+ data-agent-archived-chat-menu
+ onClick={(event) =>
+ event.stopPropagation()
+ }
+ >
+ <EllipsisVertical
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </AgentDropdownMenuTrigger>
+ <AgentDropdownMenuContent>
+ <AgentDropdownMenuItem
+ data-agent-unarchive-chat
+ onClick={(event) => {
+ event.stopPropagation();
+ unarchiveChat(chat.id);
+ }}
+ >
+ <Undo2
+ className="size-4"
+ aria-hidden="true"
+ />
+ {t(
+ "agent.unarchive-chat"
+ )}
+ </AgentDropdownMenuItem>
+ <AgentDropdownMenuItem
+ data-agent-delete-chat
+ className="text-error data-highlighted:bg-error/10"
+ onClick={(event) => {
+ event.stopPropagation();
+ setPendingDeleteChatId(
+ chat.id
+ );
+ }}
+ >
+ <Trash2
+ className="size-4"
+ aria-hidden="true"
+ />
+ {t("agent.delete-chat")}
+ </AgentDropdownMenuItem>
+ </AgentDropdownMenuContent>
+ </AgentDropdownMenu>
+ ) : (
+ <div className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
+ <SidebarIconButton
+ tooltip={t(
+ "agent.archive-chat"
+ )}
+ ariaLabel={t(
+ "agent.archive-chat"
+ )}
+ dataAttr="data-agent-archive-chat"
+ onClick={() =>
+ archiveChat(chat.id)
+ }
+ >
+ <Archive
+ className="size-3.5"
+ aria-hidden="true"
+ />
+ </SidebarIconButton>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ </CollapsiblePanel>
+ </Collapsible>
+ );
+ })}
</div>
- ))}
- </div>
- </div>
- </aside>
- </EscapePanelClip>
- )}
- </Panel>
-
- {!isCompactWindow && (
- <PanelResizeHandle
- data-agent-sidebar-resize
- className="group relative w-1 shrink-0 cursor-ew-resize bg-control-bg transition-colors hover:bg-accent/10"
- >
- <span className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-accent" />
- </PanelResizeHandle>
- )}
-
- {/* Main panel */}
- <Panel id="agent-chat-main" minSize={minMainPanelWidth}>
- <div className="relative flex size-full min-w-0 flex-col">
- <AgentChat className="min-h-0 flex-1" />
- <AgentInput />
- </div>
- </Panel>
- </PanelGroup>
- )}
- {isCompactWindow && compactPanel && (
- <Button
- type="button"
- appearance="secondary"
- size="xs"
- aria-label={t("agent.close")}
- className="absolute inset-0 z-1 h-auto rounded-none bg-overlay/50 hover:bg-overlay/50"
- data-agent-compact-overlay
- onClick={() => setCompactPanel(null)}
- />
- )}
- {isCompactWindow && compactPanel && renderCompactRail(true)}
+ </div>
+ </aside>
+ </CompactDrawerPortal>
+ )}
+ </Panel>
+
+ {!isCompactWindow && (
+ <PanelResizeHandle
+ data-agent-sidebar-resize
+ className="group relative w-1 shrink-0 cursor-ew-resize bg-control-bg transition-colors hover:bg-accent/10"
+ >
+ <span className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors group-hover:bg-accent" />
+ </PanelResizeHandle>
+ )}
+
+ {/* Main panel */}
+ <Panel id="agent-chat-main" minSize={minMainPanelWidth}>
+ <div className="relative flex size-full min-w-0 flex-col">
+ <AgentChat className="min-h-0 flex-1" />
+ <AgentInput />
+ </div>
+ </Panel>
+ </PanelGroup>
+ </div>
+ )}
+ </div>
</div>
- </div>
+ </BaseDialog.Root>
{canResizeWindow &&
+ !isCompactDrawerOpen &&
(Object.keys(resizeZoneClasses) as AnchoredResizeDirection[]).map(
(direction) => (
<div
@@ -1640,14 +1905,61 @@ export function AgentWindow() {
);
}
-function EscapePanelClip({
+function CompactDrawerPortal({
+ children,
+ compact,
+ container,
+ finalFocus,
+ title,
+}: Readonly<{
+ children: ReactNode;
+ compact: boolean;
+ container: RefObject<HTMLElement | null>;
+ finalFocus: RefObject<HTMLElement | null>;
+ title: string;
+}>) {
+ if (!compact) return children;
+
+ return (
+ <CompactDrawerModal
+ container={container}
+ finalFocus={finalFocus}
+ title={title}
+ >
+ {children}
+ </CompactDrawerModal>
+ );
+}
+
+function CompactDrawerModal({
children,
- target,
+ container,
+ finalFocus,
+ title,
}: Readonly<{
children: ReactNode;
- target: HTMLElement | null;
+ container: RefObject<HTMLElement | null>;
+ finalFocus: RefObject<HTMLElement | null>;
+ title: string;
}>) {
- return target ? createPortal(children, target) : children;
+ usePreserveHigherLayerAccess("agent");
+
+ return (
+ <BaseDialog.Portal container={container}>
+ <BaseDialog.Backdrop
+ className="absolute inset-y-0 right-0 left-12 z-1 bg-overlay/50"
+ data-agent-compact-overlay
+ />
+ <BaseDialog.Popup
+ className="absolute inset-y-0 left-12 z-2 flex w-80 outline-none"
+ data-agent-compact-drawer
+ finalFocus={finalFocus}
+ >
+ <BaseDialog.Title className="sr-only">{title}</BaseDialog.Title>
+ {children}
+ </BaseDialog.Popup>
+ </BaseDialog.Portal>
+ );
}
// --- Confirmation Dialog ---
diff --git a/frontend/src/utils/datetime.test.ts b/frontend/src/utils/datetime.test.ts
index a896667877..80d9d61aa1 100644
--- a/frontend/src/utils/datetime.test.ts
+++ b/frontend/src/utils/datetime.test.ts
@@ -21,6 +21,7 @@ const withLocale = (language: string, run: () => void) => {
import {
absoluteTimeReading,
+ calendarTimeReading,
compactTimeReading,
countdownReading,
dateTimeSegments,
@@ -159,6 +160,66 @@ describe("the compact reading", () => {
});
});
+describe("the calendar reading", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-23T04:03:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("shows today and yesterday with their local time, then the full date", () => {
+ expect(
+ calendarTimeReading.read(new Date("2026-10-23T03:03:00Z").getTime())
+ ).toBe("Today 11:03 AM");
+ expect(
+ calendarTimeReading.read(new Date("2026-10-22T04:53:00Z").getTime())
+ ).toBe("Yesterday 12:53 PM");
+ expect(
+ calendarTimeReading.read(new Date("2026-10-21T04:53:00Z").getTime())
+ ).toBe("Oct 21, 2026, 12:53 PM");
+ });
+
+ test("uses local calendar days rather than a rolling 24-hour age", () => {
+ vi.setSystemTime(new Date("2026-10-22T16:10:00Z"));
+ expect(
+ calendarTimeReading.read(new Date("2026-10-22T15:50:00Z").getTime())
+ ).toBe("Yesterday 11:50 PM");
+ });
+
+ test("changes at each local midnight and settles on the older date", () => {
+ const ts = new Date("2026-10-23T02:03:00Z").getTime();
+ vi.setSystemTime(new Date("2026-10-23T15:59:59Z"));
+ expect(calendarTimeReading.read(ts)).toBe("Today 10:03 AM");
+ expect(calendarTimeReading.nextChangeAt(ts)).toBe(
+ new Date("2026-10-23T16:00:00Z").getTime()
+ );
+
+ vi.setSystemTime(new Date("2026-10-23T16:00:00Z"));
+ expect(calendarTimeReading.read(ts)).toBe("Yesterday 10:03 AM");
+ expect(calendarTimeReading.nextChangeAt(ts)).toBe(
+ new Date("2026-10-24T16:00:00Z").getTime()
+ );
+
+ vi.setSystemTime(new Date("2026-10-24T16:00:00Z"));
+ expect(calendarTimeReading.read(ts)).toBe("Oct 23, 2026, 10:03 AM");
+ expect(calendarTimeReading.nextChangeAt(ts)).toBe(Number.POSITIVE_INFINITY);
+ });
+
+ test("localizes the calendar labels and time", () => {
+ withLocale("zh-CN", () => {
+ expect(
+ calendarTimeReading.read(new Date("2026-10-23T03:03:00Z").getTime())
+ ).toBe("今天 11:03");
+ expect(
+ calendarTimeReading.read(new Date("2026-10-22T04:53:00Z").getTime())
+ ).toBe("昨天 12:53");
+ });
+ });
+});
+
describe("the operational reading", () => {
// The value a reader is about to act on: 9am Shanghai, with a sub-minute
// tail of the kind a `now() + N days` expiration preset writes.
diff --git a/frontend/src/utils/datetime.ts b/frontend/src/utils/datetime.ts
index ee3aca7dbc..60392df415 100644
--- a/frontend/src/utils/datetime.ts
+++ b/frontend/src/utils/datetime.ts
@@ -147,6 +147,46 @@ function formatCompactDateTime(timestampMs: number): string {
}).format(timestampMs);
}
+function localDayBounds(nowMs: number) {
+ const today = new Date(nowMs);
+ today.setHours(0, 0, 0, 0);
+ const yesterday = new Date(today);
+ yesterday.setDate(today.getDate() - 1);
+ const tomorrow = new Date(today);
+ tomorrow.setDate(today.getDate() + 1);
+ return {
+ yesterdayStart: yesterday.getTime(),
+ todayStart: today.getTime(),
+ tomorrowStart: tomorrow.getTime(),
+ };
+}
+
+function formatCalendarDateTime(timestampMs: number): string {
+ const { yesterdayStart, todayStart, tomorrowStart } = localDayBounds(
+ Date.now()
+ );
+ const day =
+ timestampMs >= todayStart && timestampMs < tomorrowStart
+ ? 0
+ : timestampMs >= yesterdayStart && timestampMs < todayStart
+ ? -1
+ : undefined;
+ if (day === undefined) {
+ return formatCompactDateTime(timestampMs);
+ }
+
+ const locale = getActiveLocale();
+ const label = cachedFormatter(
+ "relative",
+ (language) => new Intl.RelativeTimeFormat(language, { numeric: "auto" })
+ ).format(day, "day");
+ const time = dateTimeFormatter("calendarTime", {
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(timestampMs);
+ return `${label.charAt(0).toLocaleUpperCase(locale)}${label.slice(1)} ${time}`;
+}
+
function formatOperationalDateTime(timestampMs: number): string {
return dateTimeFormatter("operational", {
month: "short",
@@ -255,6 +295,27 @@ export const queueTimeReading: TimeReading<number, string> = {
nextChangeAt: nextQueueTimeChangeAt,
};
+/** Local calendar-day labels become absolute after yesterday. */
+export const calendarTimeReading: TimeReading<number, string> = {
+ read: formatCalendarDateTime,
+ nextChangeAt: (timestampMs) => {
+ const nowMs = Date.now();
+ const { yesterdayStart, tomorrowStart } = localDayBounds(nowMs);
+ if (timestampMs < yesterdayStart) {
+ return Number.POSITIVE_INFINITY;
+ }
+ if (timestampMs < tomorrowStart) {
+ return tomorrowStart;
+ }
+ const targetDay = new Date(timestampMs);
+ targetDay.setHours(0, 0, 0, 0);
+ const startMs = targetDay.getTime();
+ return Number.isFinite(startMs) && startMs > nowMs
+ ? startMs
+ : Number.POSITIVE_INFINITY;
+ },
+};
+
// A rendering that says the same thing however long it is on screen: a reading
// whose boundary never arrives, so a display of one holds no subscription.
const fixedReading = (