Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8988 feat(layout): add a bottom bar and move quick chat into it (#10335)

Jiayuan Zhangaa1129990658
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
index 14a718c572..47c5b6d94d 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
@@ -66,6 +66,7 @@ vi.mock("@multica/views/platform", () => ({
}));
vi.mock("@multica/views/layout", () => ({
+ AppBottomBar: () => null,
AppRail: () => null,
AppShellProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
CompactNavSheet: () => null,
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index b0095e5133..87aae19536 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -12,6 +12,7 @@ import {
} from "@multica/ui/components/ui/sidebar";
import { ModalRegistry } from "@multica/views/modals/registry";
import {
+ AppBottomBar,
AppRail,
AppShellProvider,
CompactNavSheet,
@@ -141,8 +142,11 @@ function MainCanvas({
data-slot="main-canvas"
data-mc="page"
className={cn(
- "relative mr-2 mb-2 flex min-h-0 flex-1 flex-row overflow-hidden rounded-page bg-page-canvas shadow-[var(--page-shadow,var(--surface-shadow))] ring-1 ring-page-border",
+ "relative mr-2 flex min-h-0 flex-1 flex-row overflow-hidden rounded-page bg-page-canvas shadow-[var(--page-shadow,var(--surface-shadow))] ring-1 ring-page-border",
railMounted && !isCompact ? "ml-0" : "ml-2",
+ // In a workspace the bottom bar takes the place of the bottom margin
+ // from `md` up.
+ railMounted ? "mb-2 md:mb-0" : "mb-2",
)}
>
{railMounted && <SpacePanel />}
@@ -319,6 +323,7 @@ export function DesktopShell() {
{slug && <FloatingChat />}
{slug && <StarPrompt />}
</MainCanvas>
+ {slug && <AppBottomBar />}
</div>
</ShellRouteDataPrefetch>
</AppShellProvider>
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
index 6a1a67e558..cc964f6fa9 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
@@ -79,6 +79,7 @@ vi.mock("@multica/views/platform", () => ({
// Each workspace-scoped component gets a marker so the assertions can tell
// which of them the shell decided to mount.
vi.mock("@multica/views/layout", () => ({
+ AppBottomBar: () => <div data-testid="app-bottom-bar" />,
AppRail: () => <div data-testid="app-rail" />,
AppShellProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
CompactNavSheet: () => null,
@@ -164,6 +165,7 @@ describe("DesktopShell workspace gating", () => {
const { queryByRole, queryByTestId } = renderShell();
expect(queryByTestId("app-rail")).not.toBeNull();
+ expect(queryByTestId("app-bottom-bar")).not.toBeNull();
expect(queryByTestId("space-panel")).not.toBeNull();
expect(queryByTestId("search-command")).not.toBeNull();
expect(queryByTestId("title-bar-new-issue")).not.toBeNull();
@@ -201,6 +203,7 @@ describe("DesktopShell workspace gating", () => {
const { queryByTestId } = renderShell();
expect(queryByTestId("app-rail")).toBeNull();
+ expect(queryByTestId("app-bottom-bar")).toBeNull();
expect(queryByTestId("space-panel")).toBeNull();
expect(queryByTestId("search-command")).toBeNull();
expect(queryByTestId("title-bar-new-issue")).toBeNull();
diff --git a/docs/theming.md b/docs/theming.md
index 51685ab649..7e4299e788 100644
--- a/docs/theming.md
+++ b/docs/theming.md
@@ -171,6 +171,7 @@ those change without notice. Anchors, slots and hooks stay until the next
| `[data-mc="page"]` | The rounded canvas that holds the current page. |
| `[data-mc="window-toolbar"]` | Desktop only: the toolbar above the rail. |
| `[data-mc="tab-bar"]` | Desktop only: the tab strip above the page. |
+| `[data-mc="bottom-bar"]` | The status bar under the page, on windows wide enough to show it. |
| `[data-mc="issue-group-header"]` | A status group header in issue lists; `data-status` is the status key (`backlog`, `todo`, `in_progress`, `in_review`, `done`, `blocked`, `cancelled`, or a custom key). |
| `[data-mc="issue-row"]` | One issue in a list; `data-status`, `data-priority` (`urgent`, `high`, `medium`, `low`, `none`) and `data-assignee-type` (`member`, `agent`, `squad` or `none`). |
| `[data-mc="board-column"]` | One column on a board. |
@@ -246,8 +247,8 @@ that breaks them:
- Keep text readable in both modes (WCAG AA): `--foreground` and
`--muted-foreground` need 4.5:1 on every surface, `--brand` 4.5:1 on the
reading surfaces, the primary button label 4.5:1 on the button, and
- `--faint-foreground` 3:1. A frame (rules on the rail, window toolbar or
- tab bar) is checked against its own colours. The check follows `:root`,
+ `--faint-foreground` 3:1. A frame (rules on the rail, window toolbar,
+ tab bar or bottom bar) is checked against its own colours. The check follows `:root`,
`html`, the mode classes and option attributes the way the browser does,
with every option at its default; when a colour it measures is also set
somewhere else, such as inside `@media` or on `body`, it says so instead
@@ -316,7 +317,7 @@ and dark differ, both defaults are given.
| Variable | Default (light / dark) | Use |
| --- | --- | --- |
-| `--app-shell` | `oklch(0.964435 0.001327 286.375)` / `oklch(0.155 0.005 285.823)` | The frame around the page: rail, desktop toolbar and tab bar. |
+| `--app-shell` | `oklch(0.964435 0.001327 286.375)` / `oklch(0.155 0.005 285.823)` | The frame around the page: rail, bottom bar, desktop toolbar and tab bar. |
| `--page-canvas` | `oklch(0.988087 0 0)` / `oklch(0.18 0.005 285.823)` | The page that lists, boards and conversations sit on. |
| `--surface` | `oklch(1 0 0)` / `oklch(0.21 0.006 285.885)` | Bounded content groups: cards, board cards, panels. |
| `--surface-foreground` | `oklch(0.141 0.005 285.823)` / `oklch(0.985 0 0)` | Text on a surface. |
diff --git a/packages/core/appearance/anchors.ts b/packages/core/appearance/anchors.ts
index 74a8fac756..7284d81e7c 100644
--- a/packages/core/appearance/anchors.ts
+++ b/packages/core/appearance/anchors.ts
@@ -13,6 +13,7 @@ export const THEME_ANCHORS = {
page: "The rounded canvas that holds the current page.",
"window-toolbar": "Desktop only: the toolbar above the rail with history buttons.",
"tab-bar": "Desktop only: the tab strip above the page.",
+ "bottom-bar": "The status bar under the page, on windows wide enough to show it.",
"issue-group-header": "A status group header in issue lists; `data-status` is the status key.",
"issue-row":
"One issue in a list; `data-status`, `data-priority` and `data-assignee-type` (member, agent, squad or none).",
diff --git a/packages/core/appearance/built-in-themes.ts b/packages/core/appearance/built-in-themes.ts
index 8873ca0a41..f4b140edae 100644
--- a/packages/core/appearance/built-in-themes.ts
+++ b/packages/core/appearance/built-in-themes.ts
@@ -45,7 +45,7 @@ const POP_SIGNALS = {
coral: "oklch(0.8 0.13 30)",
};
-const POP_FRAME_ANCHORS = ':is([data-mc="app-rail"], [data-mc="window-toolbar"], [data-mc="tab-bar"])';
+const POP_FRAME_ANCHORS = ':is([data-mc="app-rail"], [data-mc="window-toolbar"], [data-mc="tab-bar"], [data-mc="bottom-bar"])';
const POP_STATUS_BLOCKS: [string, string][] = [
['[data-status="backlog"], [data-status="todo"]', "oklch(0.88 0.035 250)"],
['[data-status="in_progress"]', "oklch(0.84 0.13 68)"],
diff --git a/packages/core/appearance/theme-check.ts b/packages/core/appearance/theme-check.ts
index 88f212c92b..80aeb3b878 100644
--- a/packages/core/appearance/theme-check.ts
+++ b/packages/core/appearance/theme-check.ts
@@ -78,7 +78,7 @@ const FRAME_BACKGROUNDS = [
const GENERIC_FAMILY =
/^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|fangsong|ui-[a-z-]+)$/i;
const LATIN_STACKS = new Set(["font-ui", "font-content-latin"]);
-const FRAME_ANCHOR = /data-mc="(?:app-rail|window-toolbar|tab-bar)"/;
+const FRAME_ANCHOR = /data-mc="(?:app-rail|window-toolbar|tab-bar|bottom-bar)"/;
const isRecord = (v: unknown): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v);
diff --git a/packages/core/appearance/theme-variables.ts b/packages/core/appearance/theme-variables.ts
index 7593747230..3986593d6b 100644
--- a/packages/core/appearance/theme-variables.ts
+++ b/packages/core/appearance/theme-variables.ts
@@ -75,7 +75,7 @@ function section(name: ThemeVariableSection, entries: readonly Entry[]): ThemeVa
}
const COLORS: Entry[] = [
- ["app-shell", "The frame around the page: rail, desktop toolbar and tab bar."],
+ ["app-shell", "The frame around the page: rail, bottom bar, desktop toolbar and tab bar."],
["page-canvas", "The page that lists, boards and conversations sit on."],
["surface", "Bounded content groups: cards, board cards, panels."],
["surface-foreground", "Text on a surface."],
diff --git a/packages/core/appearance/themes.ts b/packages/core/appearance/themes.ts
index 63d64d679e..1d9df4bc12 100644
--- a/packages/core/appearance/themes.ts
+++ b/packages/core/appearance/themes.ts
@@ -113,11 +113,11 @@ export type ThemeTokens = Readonly<Record<string, string>>;
export interface BuiltInTheme extends Theme {
tokens: { light: ThemeTokens; dark: ThemeTokens };
- /** Tokens for what sits on the frame: the rail, desktop toolbar and tab bar. */
+ /** Tokens for what sits on the frame: the rail, desktop toolbar, tab bar and bottom bar. */
frame?: { light?: ThemeTokens; dark?: ThemeTokens };
}
-const FRAME_ANCHORS = ':is([data-mc="app-rail"], [data-mc="window-toolbar"], [data-mc="tab-bar"])';
+const FRAME_ANCHORS = ':is([data-mc="app-rail"], [data-mc="window-toolbar"], [data-mc="tab-bar"], [data-mc="bottom-bar"])';
/**
* The CSS a token table stands for: one line per rule, or with `readable`
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index cacb1c9b81..3a169b0e25 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -260,6 +260,72 @@ describe("chat store — floating window preference", () => {
});
});
+describe("chat store — bottom bar chips", () => {
+ const BAR_KEY = "multica:chat:bar";
+
+ it("keeps opened chats newest first, once each, and across a reload", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+
+ store.getState().keepChatInBar("a");
+ store.getState().keepChatInBar("b");
+ store.getState().keepChatInBar("a");
+
+ expect(store.getState().chatBarKept).toEqual(["b", "a"]);
+ expect(createChatStore({ storage }).getState().chatBarKept).toEqual(["b", "a"]);
+ });
+
+ it("closes a chip with the chat's activity, and forgets that when it is opened again", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+ store.getState().keepChatInBar("a");
+
+ store.getState().dismissChatFromBar("a", "2026-11-11T08:00:00Z");
+ expect(store.getState().chatBarKept).toEqual([]);
+ expect(store.getState().chatBarDismissed).toEqual({ a: "2026-11-11T08:00:00Z" });
+ expect(createChatStore({ storage }).getState().chatBarDismissed).toEqual({
+ a: "2026-11-11T08:00:00Z",
+ });
+
+ store.getState().keepChatInBar("a");
+ expect(store.getState().chatBarKept).toEqual(["a"]);
+ expect(store.getState().chatBarDismissed).toEqual({});
+ });
+
+ it("drops the oldest chips over the cap", () => {
+ const store = createChatStore({ storage: memStorage() });
+ for (let i = 0; i < 14; i++) store.getState().keepChatInBar(`s${i}`);
+
+ const kept = store.getState().chatBarKept;
+ expect(kept).toHaveLength(12);
+ expect(kept[0]).toBe("s13");
+ expect(kept).not.toContain("s0");
+ });
+
+ it("reads a malformed blob as empty", () => {
+ const storage = memStorage();
+ storage.setItem(BAR_KEY, JSON.stringify({ kept: "nope", dismissed: [1] }));
+ const state = createChatStore({ storage }).getState();
+
+ expect(state.chatBarKept).toEqual([]);
+ expect(state.chatBarDismissed).toEqual({});
+ });
+});
+
+describe("chat store — Ask Multica agent", () => {
+ it("has no preference by default, and persists one until it is cleared", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+ expect(store.getState().quickChatAgentId).toBeNull();
+
+ store.getState().setQuickChatAgentId("agent-1");
+ expect(createChatStore({ storage }).getState().quickChatAgentId).toBe("agent-1");
+
+ store.getState().setQuickChatAgentId(null);
+ expect(createChatStore({ storage }).getState().quickChatAgentId).toBeNull();
+ });
+});
+
// The ledger is what makes a durable draft restore (#5219) apply at most once.
// A consume request can be lost — retries exhausted, app closed mid-flight — and
// the row then comes back on the next fetch. Without a record that survives the
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index 2bfba088b7..350ffdf03b 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -74,6 +74,56 @@ const OPEN_KEY = "multica:chat:isOpen";
* be turned off from the Settings → Chat tab.
*/
const FLOATING_KEY = "multica:chat:floatingChatEnabled";
+/**
+ * The agent Ask Multica starts a new chat with, per workspace. Missing key =
+ * no preference: a new chat goes to the agent last chatted with.
+ */
+const QUICK_CHAT_AGENT_KEY = "multica:chat:quickChatAgentId";
+/**
+ * The chats kept as chips in the bottom bar, per workspace:
+ * `{ kept: sessionId[], dismissed: { [sessionId]: activity } }`.
+ *
+ * `kept` is every chat opened in the quick-chat window and not closed from the
+ * bar since, newest first. `dismissed` records the chat's last activity at the
+ * moment its chip was closed, so the chip stays away until the chat moves
+ * again; without it, closing the chip of an unread chat would do nothing.
+ */
+const CHAT_BAR_KEY = "multica:chat:bar";
+/** Chips are a working set, not a history: the oldest fall off. */
+const CHAT_BAR_MAX_KEPT = 12;
+const CHAT_BAR_MAX_DISMISSED = 50;
+
+interface ChatBarSlots {
+ kept: string[];
+ dismissed: Record<string, string>;
+}
+
+function readChatBar(storage: StorageAdapter, key: string): ChatBarSlots {
+ const empty: ChatBarSlots = { kept: [], dismissed: {} };
+ const raw = storage.getItem(key);
+ if (!raw) return empty;
+ try {
+ const parsed = JSON.parse(raw) as { kept?: unknown; dismissed?: unknown };
+ if (typeof parsed !== "object" || parsed === null) return empty;
+ const kept = Array.isArray(parsed.kept)
+ ? parsed.kept.filter((id): id is string => typeof id === "string")
+ : [];
+ const dismissed: Record<string, string> = {};
+ if (typeof parsed.dismissed === "object" && parsed.dismissed !== null) {
+ for (const [id, activity] of Object.entries(parsed.dismissed)) {
+ if (typeof activity === "string") dismissed[id] = activity;
+ }
+ }
+ return { kept, dismissed };
+ } catch {
+ return empty;
+ }
+}
+
+function writeChatBar(storage: StorageAdapter, key: string, slots: ChatBarSlots) {
+ if (slots.kept.length === 0 && Object.keys(slots.dismissed).length === 0) storage.removeItem(key);
+ else storage.setItem(key, JSON.stringify(slots));
+}
function readDrafts(storage: StorageAdapter, key: string): Record<string, string> {
const raw = storage.getItem(key);
@@ -309,6 +359,12 @@ export interface ChatState {
/** Project context for the next session. Existing sessions remain bound to
* their server-persisted project_id. */
selectedProjectId: string | null;
+ /** Settings preference: the agent Ask Multica starts a new chat with. */
+ quickChatAgentId: string | null;
+ /** Chats kept as chips in the bottom bar, newest first. */
+ chatBarKept: string[];
+ /** Chips closed from the bar: sessionId → the chat's activity at that moment. */
+ chatBarDismissed: Record<string, string>;
/** Drafts per session: sessionId (or DRAFT_NEW_SESSION) → markdown text. */
inputDrafts: Record<string, string>;
/** Attachment rows referenced by each input draft. */
@@ -328,6 +384,11 @@ export interface ChatState {
setActiveSession: (id: string | null) => void;
setSelectedAgentId: (id: string) => void;
setSelectedProjectId: (id: string | null) => void;
+ setQuickChatAgentId: (id: string | null) => void;
+ /** Give a chat a chip in the bottom bar. No-op when it already has one. */
+ keepChatInBar: (sessionId: string) => void;
+ /** Close a chat's chip until the chat moves past `activity`. */
+ dismissChatFromBar: (sessionId: string, activity: string) => void;
/** sessionId accepts a real session UUID or DRAFT_NEW_SESSION. */
setInputDraft: (sessionId: string, draft: string) => void;
/** Append a markdown fragment to a draft slot's text (upload write-back). */
@@ -388,12 +449,17 @@ export function createChatStore(options: ChatStoreOptions) {
initialAgentId,
);
+ const initialChatBar = readChatBar(storage, wsKey(CHAT_BAR_KEY));
+
const store = create<ChatState>((set, get) => ({
isOpen: initialIsOpen,
floatingChatEnabled: initialFloatingEnabled,
activeSessionId: storage.getItem(wsKey(SESSION_STORAGE_KEY)),
selectedAgentId: initialAgentId,
selectedProjectId: storage.getItem(wsKey(PROJECT_STORAGE_KEY)),
+ quickChatAgentId: storage.getItem(wsKey(QUICK_CHAT_AGENT_KEY)),
+ chatBarKept: initialChatBar.kept,
+ chatBarDismissed: initialChatBar.dismissed,
inputDrafts: initialDraftSlots.inputDrafts,
inputDraftAttachments: initialDraftSlots.inputDraftAttachments,
appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
@@ -440,6 +506,36 @@ export function createChatStore(options: ChatStoreOptions) {
else storage.removeItem(wsKey(PROJECT_STORAGE_KEY));
set({ selectedProjectId: id });
},
+ setQuickChatAgentId: (id) => {
+ logger.info("setQuickChatAgentId", { from: get().quickChatAgentId, to: id });
+ if (id) storage.setItem(wsKey(QUICK_CHAT_AGENT_KEY), id);
+ else storage.removeItem(wsKey(QUICK_CHAT_AGENT_KEY));
+ set({ quickChatAgentId: id });
+ },
+ keepChatInBar: (sessionId) => {
+ const { chatBarKept, chatBarDismissed } = get();
+ const wasDismissed = sessionId in chatBarDismissed;
+ if (chatBarKept.includes(sessionId) && !wasDismissed) return;
+ const kept = [sessionId, ...chatBarKept.filter((id) => id !== sessionId)].slice(
+ 0,
+ CHAT_BAR_MAX_KEPT,
+ );
+ const dismissed = { ...chatBarDismissed };
+ delete dismissed[sessionId];
+ writeChatBar(storage, wsKey(CHAT_BAR_KEY), { kept, dismissed });
+ set({ chatBarKept: kept, chatBarDismissed: dismissed });
+ },
+ dismissChatFromBar: (sessionId, activity) => {
+ const { chatBarKept, chatBarDismissed } = get();
+ const kept = chatBarKept.filter((id) => id !== sessionId);
+ // Re-insert so the entry is the newest, then drop the oldest over the cap.
+ const rest = Object.entries(chatBarDismissed).filter(([id]) => id !== sessionId);
+ const dismissed = Object.fromEntries(
+ [...rest, [sessionId, activity] as const].slice(-CHAT_BAR_MAX_DISMISSED),
+ );
+ writeChatBar(storage, wsKey(CHAT_BAR_KEY), { kept, dismissed });
+ set({ chatBarKept: kept, chatBarDismissed: dismissed });
+ },
// Append-only until the server confirms. There is deliberately no capacity
// cap: every entry in here is an UNconfirmed consume, and evicting one
// silently re-arms the restore it was suppressing — the row is still on the
@@ -651,6 +747,7 @@ export function createChatStore(options: ChatStoreOptions) {
const nextSession = storage.getItem(wsKey(SESSION_STORAGE_KEY));
const nextAgent = storage.getItem(wsKey(AGENT_STORAGE_KEY));
const nextProject = storage.getItem(wsKey(PROJECT_STORAGE_KEY));
+ const nextChatBar = readChatBar(storage, wsKey(CHAT_BAR_KEY));
// Drafts are namespaced per workspace, so the workspace being switched TO
// has its own legacy slots to fold — migrate against that workspace's own
// persisted agent, not the one we are leaving.
@@ -674,6 +771,9 @@ export function createChatStore(options: ChatStoreOptions) {
activeSessionId: nextSession,
selectedAgentId: nextAgent,
selectedProjectId: nextProject,
+ quickChatAgentId: storage.getItem(wsKey(QUICK_CHAT_AGENT_KEY)),
+ chatBarKept: nextChatBar.kept,
+ chatBarDismissed: nextChatBar.dismissed,
inputDrafts: nextDrafts,
inputDraftAttachments: nextDraftAttachments,
appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
diff --git a/packages/ui/icons/drawings/drawings.mjs b/packages/ui/icons/drawings/drawings.mjs
index a602e3fa0a..5819e76997 100644
--- a/packages/ui/icons/drawings/drawings.mjs
+++ b/packages/ui/icons/drawings/drawings.mjs
@@ -316,6 +316,9 @@ Object.assign(DRAWINGS, {
SkipForward: `<path class="b" d="${shape([[4.5, 4.5], [16.25, 12], [4.5, 19.5]])}"/><path d="M20.25 4v16"/>`,
Maximize: `<path d="${shape([[3.5, 8.5], [3.5, 3.5, 3], [8.5, 3.5]], false)}"/><path d="${shape([[15.5, 3.5], [20.5, 3.5, 3], [20.5, 8.5]], false)}"/>
<path d="${shape([[20.5, 15.5], [20.5, 20.5, 3], [15.5, 20.5]], false)}"/><path d="${shape([[8.5, 20.5], [3.5, 20.5, 3], [3.5, 15.5]], false)}"/>`,
+ Scan: `<path d="${shape([[3.25, 8.25], [3.25, 3.25, 3], [8.25, 3.25]], false)}"/><path d="${shape([[15.75, 3.25], [20.75, 3.25, 3], [20.75, 8.25]], false)}"/>
+ <path d="${shape([[20.75, 15.75], [20.75, 20.75, 3], [15.75, 20.75]], false)}"/><path d="${shape([[8.25, 20.75], [3.25, 20.75, 3], [3.25, 15.75]], false)}"/>
+ <path class="b" d="${rect(8.5, 8.5, 7, 7, 2.75)}"/>`,
Activity: `<path d="M2.75 12h3.5l2.75-7 6 14 2.75-7h3.5"/>`,
Waves: `<path d="${wave(6.75)}M${wave(12).slice(1)}M${wave(17.25).slice(1)}"/>`,
diff --git a/packages/ui/icons/glyphs.ts b/packages/ui/icons/glyphs.ts
index 654fc57f05..c504729db3 100644
--- a/packages/ui/icons/glyphs.ts
+++ b/packages/ui/icons/glyphs.ts
@@ -215,6 +215,7 @@ export const RotateCcw: IconNode = [["path",{"d":"M3.5 12a8.5 8.5 0 1 0 2.49-6.0
export const RotateCw: IconNode = [["path",{"d":"M20.5 12a8.5 8.5 0 1 1-2.49-6.01L19.5 7.5"}],["path",{"d":"M19.5 3.25 L19.5 7.5 C19.5 7.5 19.5 7.5 19.5 7.5 C19.5 7.5 19.5 7.5 19.5 7.5 L15.25 7.5"}]];
export const Rows3: IconNode = [["path",{"d":"M3 10 C3 6.5 3 5.05 4.02 4.02 C5.05 3 6.5 3 10 3 L14 3 C17.5 3 18.95 3 19.98 4.02 C21 5.05 21 6.5 21 10 L21 14 C21 17.5 21 18.95 19.98 19.98 C18.95 21 17.5 21 14 21 L10 21 C6.5 21 5.05 21 4.02 19.98 C3 18.95 3 17.5 3 14 Z","className":"icon-body"}],["path",{"d":"M3 9h18M3 15h18","className":"icon-cut"}]];
export const Save: IconNode = [["path",{"d":"M3.25 8.25 C3.25 5.75 3.25 4.71 3.98 3.98 C4.71 3.25 5.75 3.25 8.25 3.25 L15 3.25 C15.75 3.25 16.06 3.25 16.44 3.4 C16.81 3.56 17.03 3.78 17.56 4.31 L19.69 6.44 C20.22 6.97 20.44 7.19 20.6 7.56 C20.75 7.94 20.75 8.25 20.75 9 L20.75 15.75 C20.75 18.25 20.75 19.29 20.02 20.02 C19.29 20.75 18.25 20.75 15.75 20.75 L8.25 20.75 C5.75 20.75 4.71 20.75 3.98 20.02 C3.25 19.29 3.25 18.25 3.25 15.75 Z","className":"icon-body"}],["path",{"d":"M7.5 20.75 L7.5 15.5 C7.5 14.75 7.5 14.44 7.72 14.22 C7.94 14 8.25 14 9 14 L15 14 C15.75 14 16.06 14 16.28 14.22 C16.5 14.44 16.5 14.75 16.5 15.5 L16.5 20.75"}],["path",{"d":"M7.5 3.25 L7.5 6 C7.5 6.75 7.5 7.06 7.72 7.28 C7.94 7.5 8.25 7.5 9 7.5 L14 7.5"}]];
+export const Scan: IconNode = [["path",{"d":"M3.25 8.25 L3.25 5.75 C3.25 4.5 3.25 3.98 3.62 3.62 C3.98 3.25 4.5 3.25 5.75 3.25 L8.25 3.25"}],["path",{"d":"M15.75 3.25 L18.25 3.25 C19.5 3.25 20.02 3.25 20.39 3.62 C20.75 3.98 20.75 4.5 20.75 5.75 L20.75 8.25"}],["path",{"d":"M20.75 15.75 L20.75 18.25 C20.75 19.5 20.75 20.02 20.39 20.39 C20.02 20.75 19.5 20.75 18.25 20.75 L15.75 20.75"}],["path",{"d":"M8.25 20.75 L5.75 20.75 C4.5 20.75 3.98 20.75 3.62 20.39 C3.25 20.02 3.25 19.5 3.25 18.25 L3.25 15.75"}],["path",{"d":"M8.5 11.25 C8.5 9.88 8.5 9.31 8.9 8.9 C9.31 8.5 9.88 8.5 11.25 8.5 L12.75 8.5 C14.13 8.5 14.69 8.5 15.1 8.9 C15.5 9.31 15.5 9.88 15.5 11.25 L15.5 12.75 C15.5 14.13 15.5 14.69 15.1 15.1 C14.69 15.5 14.13 15.5 12.75 15.5 L11.25 15.5 C9.88 15.5 9.31 15.5 8.9 15.1 C8.5 14.69 8.5 14.13 8.5 12.75 Z","className":"icon-body"}]];
export const ScrollText: IconNode = [["path",{"d":"M9.75 3.25h9a2.25 2.25 0 0 1 0 4.5H16.5V18a2.75 2.75 0 0 1-2.75 2.75H5.5a2.25 2.25 0 0 1 0-4.5h1.75V5.75a2.5 2.5 0 0 1 2.5-2.5Z","className":"icon-body"}],["path",{"d":"M7.25 16.25h3.5c.97 0 1.75.78 1.75 1.75v.25"}],["path",{"d":"M10.5 8.5h2.75M10.5 12.25h2.75","className":"icon-cut"}]];
export const Search: IconNode = [["circle",{"cx":"11","cy":"11","r":"7.75","className":"icon-body"}],["path",{"d":"m16.75 16.75 4.5 4.5"}]];
export const Send: IconNode = [["path",{"d":"M19.34 3.75 C20.04 3.5 20.34 3.4 20.47 3.53 C20.6 3.66 20.5 3.96 20.25 4.66 L15 19.34 C14.75 20.04 14.65 20.34 14.48 20.35 C14.3 20.36 14.16 20.08 13.83 19.41 L11.02 13.79 C10.88 13.52 10.83 13.41 10.71 13.29 C10.59 13.17 10.48 13.12 10.21 12.98 L4.59 10.17 C3.92 9.84 3.64 9.7 3.65 9.52 C3.66 9.35 3.96 9.25 4.66 9 Z","className":"icon-body"}],["path",{"d":"M20.5 3.5 10.75 13.25"}]];
diff --git a/packages/ui/icons/index.ts b/packages/ui/icons/index.ts
index 5eeade56f8..e12e9de7df 100644
--- a/packages/ui/icons/index.ts
+++ b/packages/ui/icons/index.ts
@@ -244,6 +244,7 @@ export const RotateCcw = /* @__PURE__ */ createIcon("RotateCcw", glyph.RotateCcw
export const RotateCw = /* @__PURE__ */ createIcon("RotateCw", glyph.RotateCw);
export const Rows3 = /* @__PURE__ */ createIcon("Rows3", glyph.Rows3);
export const Save = /* @__PURE__ */ createIcon("Save", glyph.Save);
+export const Scan = /* @__PURE__ */ createIcon("Scan", glyph.Scan);
export const ScrollText = /* @__PURE__ */ createIcon("ScrollText", glyph.ScrollText);
export const Search = /* @__PURE__ */ createIcon("Search", glyph.Search);
export const SearchIcon = /* @__PURE__ */ createIcon("SearchIcon", glyph.Search);
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index c59ba34f6f..6437751c8d 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -8,9 +8,10 @@
* set from the active locale. */
@custom-variant cjk (&:is(:lang(zh), :lang(ja), :lang(ko)));
-/* The chat launcher overlays the dashboard's bottom-right corner on every
- * workspace page, so anything that runs to that corner has to stop short of
- * it. Named rather than spelled out at each site: the intent is legible, every
+/* Below `md` the chat launcher overlays the dashboard's bottom-right corner on
+ * every workspace page, so anything that runs to that corner has to stop short
+ * of it. From `md` up quick chat is in the bottom bar and the clearance is
+ * zero. Named rather than spelled out at each site: the intent is legible, every
* site that yields to the launcher is findable by these classes, and the
* distance stays derived from the launcher's own geometry.
*
diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.css
index d9e843e48c..dc82d7b6dc 100644
--- a/packages/ui/styles/tokens.css
+++ b/packages/ui/styles/tokens.css
@@ -172,9 +172,9 @@
--surface-shadow: 0 1px 2px rgb(15 23 42 / 0.04), 0 1px 1px rgb(15 23 42 / 0.03);
--floating-shadow: 0 16px 40px rgb(15 23 42 / 0.14), 0 3px 10px rgb(15 23 42 / 0.08);
- /* The chat launcher is an overlay pinned to the dashboard's bottom-right
- corner on every workspace page, so that corner is not available to page
- content. Its geometry lives here rather than in the button so that the
+ /* Below `md` the chat launcher is an overlay pinned to the dashboard's
+ bottom-right corner on every workspace page, so that corner is not
+ available to page content. Its geometry lives here rather than in the button so that the
clearance is derived from it: anything reaching that corner — a footer's
action buttons, a floating toolbar — reserves --chat-launcher-clearance
and stays correct if the launcher ever moves or changes size. */
@@ -273,6 +273,14 @@
--find-match-foreground: oklch(0.22 0.03 92);
}
+/* From `md` up quick chat lives in the bottom bar, outside the page card, and
+ the corner is free again. */
+@media (min-width: 48rem) {
+ :root {
+ --chat-launcher-clearance: 0px;
+ }
+}
+
.dark {
color-scheme: dark;
--app-shell: oklch(0.155 0.005 285.823);
diff --git a/packages/views/agents/create/create-agent-footer.tsx b/packages/views/agents/create/create-agent-footer.tsx
index cf07e95887..fb21672e08 100644
--- a/packages/views/agents/create/create-agent-footer.tsx
+++ b/packages/views/agents/create/create-agent-footer.tsx
@@ -8,8 +8,9 @@ import { AGENT_CREATE_STEP_COUNT, type AgentCreateStep } from "./create-shell";
/**
* The bar pinned under every creation step: where the reader is on the left,
- * the way out and the one way forward on the right. Its end padding keeps the
- * forward button clear of the chat launcher, which owns that corner.
+ * the way out and the one way forward on the right. Below `md` its end
+ * padding keeps the forward button clear of the chat launcher, which owns
+ * that corner there.
*/
export function CreateFlowFooter({
stepIndex,
@@ -24,7 +25,7 @@ export function CreateFlowFooter({
}) {
const { t } = useT("agents");
return (
- <footer className="pe-chat-launcher flex min-h-14 shrink-0 items-center gap-3 border-t bg-background py-3 pl-4">
+ <footer className="flex min-h-14 shrink-0 items-center gap-3 border-t bg-background py-3 pl-4 max-md:pe-chat-launcher md:pr-4">
<div className="flex min-w-0 flex-1 items-center gap-3">
{stepIndex ? (
<p className="shrink-0 text-caption text-muted-foreground">
diff --git a/packages/views/chat/components/chat-bar-history.tsx b/packages/views/chat/components/chat-bar-history.tsx
new file mode 100644
index 0000000000..b2441e8cba
--- /dev/null
+++ b/packages/views/chat/components/chat-bar-history.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { History, Loader2 } from "@multica/ui/icons";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { ChatSession } from "@multica/core/types";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+import { BOTTOM_BAR_ICON_ITEM_CLASS } from "../../layout/bottom-bar-styles";
+import { AppLink } from "../../navigation";
+import { chatActivity } from "./chat-bar-sessions";
+import { useFormatTimeAgo } from "./use-format-time-ago";
+
+/** Recent chats only: the Chat page is the full history. */
+const MAX_HISTORY = 30;
+const DAY_MS = 86_400_000;
+
+type HistoryGroup = "today" | "week" | "older";
+const GROUPS: HistoryGroup[] = ["today", "week", "older"];
+
+export function groupChatHistory(
+ sessions: ChatSession[],
+ now: Date,
+): { group: HistoryGroup; sessions: ChatSession[] }[] {
+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
+ const recent = sessions
+ .filter((session) => session.status !== "archived")
+ .sort((a, b) => Date.parse(chatActivity(b)) - Date.parse(chatActivity(a)))
+ .slice(0, MAX_HISTORY);
+ const byGroup = new Map<HistoryGroup, ChatSession[]>();
+ for (const session of recent) {
+ const at = Date.parse(chatActivity(session));
+ const group = at >= startOfToday ? "today" : at >= startOfToday - 7 * DAY_MS ? "week" : "older";
+ byGroup.set(group, [...(byGroup.get(group) ?? []), session]);
+ }
+ return GROUPS.flatMap((group) => {
+ const inGroup = byGroup.get(group);
+ return inGroup ? [{ group, sessions: inGroup }] : [];
+ });
+}
+
+/**
+ * The chat history, opened from the bottom bar. Picking a chat opens it in
+ * the quick-chat window; the rows carry `data-chat-anchor-trigger` so the
+ * window is placed above the chip that chat gets.
+ */
+export function ChatBarHistory({
+ sessions,
+ runningSessionIds,
+ onSelect,
+}: {
+ sessions: ChatSession[];
+ runningSessionIds: ReadonlySet<string>;
+ onSelect: (session: ChatSession) => void;
+}) {
+ const { t } = useT("chat");
+ const p = useWorkspacePaths();
+ const [open, setOpen] = useState(false);
+ const formatTimeAgo = useFormatTimeAgo();
+ // Grouped when the popover opens: "today" is read off the clock then.
+ const groups = useMemo(
+ () => (open ? groupChatHistory(sessions, new Date()) : []),
+ [open, sessions],
+ );
+ const label = t(($) => $.bar.history);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <TooltipHint label={label}>
+ <PopoverTrigger aria-label={label} className={BOTTOM_BAR_ICON_ITEM_CLASS}>
+ <History aria-hidden />
+ </PopoverTrigger>
+ </TooltipHint>
+ <PopoverContent
+ align="end"
+ side="top"
+ sideOffset={8}
+ aria-label={label}
+ className="max-h-[min(28rem,var(--available-height))] w-80 gap-0 overflow-hidden p-1 ring-foreground/15"
+ >
+ <div className="shrink-0 px-2 py-1.5 text-caption font-medium text-muted-foreground">
+ {label}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {groups.length === 0 && (
+ <div className="px-2 py-1.5 text-caption text-muted-foreground">
+ {t(($) => $.window.no_previous)}
+ </div>
+ )}
+ {groups.map(({ group, sessions: inGroup }) => (
+ <div
+ key={group}
+ role="group"
+ aria-label={t(($) => $.bar.history_group[group])}
+ className="border-t border-surface-border pt-1 pb-1 last:pb-0"
+ >
+ <div className="px-2 py-1 text-caption text-muted-foreground">
+ {t(($) => $.bar.history_group[group])}
+ </div>
+ {inGroup.map((session) => {
+ const running = runningSessionIds.has(session.id);
+ return (
+ <button
+ key={session.id}
+ type="button"
+ data-chat-anchor-trigger
+ onClick={() => {
+ onSelect(session);
+ setOpen(false);
+ }}
+ className="flex h-8 w-full min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-body outline-none transition-colors hover:bg-accent/60 focus-visible:bg-accent/60"
+ >
+ <span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center">
+ {running ? (
+ <Loader2 className="size-3.5 animate-spin text-muted-foreground" />
+ ) : session.has_unread ? (
+ <span className="size-1.5 rounded-full bg-brand" />
+ ) : null}
+ </span>
+ <span className={cn("min-w-0 flex-1 truncate", session.has_unread && "font-medium")}>
+ {session.title || t(($) => $.window.untitled)}
+ </span>
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {formatTimeAgo(chatActivity(session))}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ <div className="shrink-0 border-t border-surface-border pt-1">
+ <AppLink
+ href={p.chat()}
+ onClick={() => setOpen(false)}
+ className="flex h-8 items-center rounded-md px-2 text-body text-muted-foreground outline-none transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:bg-accent/60"
+ >
+ {t(($) => $.bar.all_chats)}
+ </AppLink>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/chat/components/chat-bar-sessions.test.ts b/packages/views/chat/components/chat-bar-sessions.test.ts
new file mode 100644
index 0000000000..b5a9e935ab
--- /dev/null
+++ b/packages/views/chat/components/chat-bar-sessions.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from "vitest";
+import type { ChatSession } from "@multica/core/types";
+import { chatActivity, selectChatBarSessions } from "./chat-bar-sessions";
+
+function session(id: string, minute: number, overrides: Partial<ChatSession> = {}): ChatSession {
+ const at = new Date(Date.UTC(2026, 10, 11, 8, minute)).toISOString();
+ return {
+ id,
+ workspace_id: "ws-1",
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: id,
+ status: "active",
+ has_unread: false,
+ created_at: at,
+ updated_at: at,
+ ...overrides,
+ };
+}
+
+const ids = (items: { session: ChatSession }[]) => items.map((item) => item.session.id);
+
+function select(
+ input: Partial<Parameters<typeof selectChatBarSessions>[0]> & { sessions: ChatSession[] },
+) {
+ return selectChatBarSessions({
+ runningSessionIds: new Set(),
+ openSessionId: null,
+ kept: [],
+ dismissed: {},
+ maxVisible: 4,
+ ...input,
+ });
+}
+
+describe("selectChatBarSessions", () => {
+ it("keeps only chats that are running, unread or open", () => {
+ const { visible, overflow } = select({
+ sessions: [
+ session("idle", 1),
+ session("running", 2),
+ session("unread", 3, { has_unread: true }),
+ session("open", 4),
+ ],
+ runningSessionIds: new Set(["running"]),
+ openSessionId: "open",
+ maxVisible: 4,
+ });
+
+ expect(ids(visible)).toEqual(["open", "unread", "running"]);
+ expect(visible.map((item) => [item.running, item.unread, item.open])).toEqual([
+ [false, false, true],
+ [false, true, false],
+ [true, false, false],
+ ]);
+ expect(overflow).toEqual([]);
+ });
+
+ it("keeps the chip of a chat that was opened here, after it is read and closed", () => {
+ const { visible } = select({
+ sessions: [session("opened", 1), session("never-opened", 2)],
+ kept: ["opened"],
+ });
+
+ expect(ids(visible)).toEqual(["opened"]);
+ });
+
+ it("hides a closed chip until its chat moves again", () => {
+ const quiet = session("closed", 1, { has_unread: true });
+ const moved = session("moved", 2, {
+ has_unread: true,
+ last_message: { created_at: new Date(Date.UTC(2026, 10, 11, 9)).toISOString() } as ChatSession["last_message"],
+ });
+ const { visible } = select({
+ sessions: [quiet, moved],
+ kept: ["closed"],
+ dismissed: { closed: chatActivity(quiet), moved: moved.updated_at },
+ });
+
+ expect(ids(visible)).toEqual(["moved"]);
+ });
+
+ it("shows the open chat even when its chip was closed", () => {
+ const closed = session("closed", 1);
+ const { visible } = select({
+ sessions: [closed],
+ openSessionId: "closed",
+ dismissed: { closed: chatActivity(closed) },
+ });
+
+ expect(ids(visible)).toEqual(["closed"]);
+ });
+
+ it("leaves archived chats out even when they are unread or running", () => {
+ const { visible } = select({
+ sessions: [
+ session("archived-unread", 1, { status: "archived", has_unread: true }),
+ session("archived-running", 2, { status: "archived" }),
+ ],
+ runningSessionIds: new Set(["archived-running"]),
+ openSessionId: null,
+ maxVisible: 4,
+ });
+
+ expect(visible).toEqual([]);
+ });
+
+ it("orders by creation, so a newer message does not reorder the chips", () => {
+ const { visible } = select({
+ sessions: [
+ session("older", 1, {
+ has_unread: true,
+ updated_at: new Date(Date.UTC(2026, 10, 11, 9)).toISOString(),
+ }),
+ session("newer", 2, { has_unread: true }),
+ ],
+ runningSessionIds: new Set(),
+ openSessionId: null,
+ maxVisible: 4,
+ });
+
+ expect(ids(visible)).toEqual(["newer", "older"]);
+ });
+
+ it("puts what does not fit into the overflow", () => {
+ const { visible, overflow } = select({
+ sessions: [1, 2, 3, 4].map((n) => session(`s${n}`, n, { has_unread: true })),
+ runningSessionIds: new Set(),
+ openSessionId: null,
+ maxVisible: 2,
+ });
+
+ expect(ids(visible)).toEqual(["s4", "s3"]);
+ expect(ids(overflow)).toEqual(["s2", "s1"]);
+ });
+
+ it("brings the open chat out of the overflow, because the window opens above its chip", () => {
+ const { visible, overflow } = select({
+ sessions: [1, 2, 3, 4].map((n) => session(`s${n}`, n, { has_unread: true })),
+ runningSessionIds: new Set(),
+ openSessionId: "s1",
+ maxVisible: 2,
+ });
+
+ expect(ids(visible)).toEqual(["s1", "s4"]);
+ expect(ids(overflow)).toEqual(["s3", "s2"]);
+ });
+
+ it("always has room for one chip", () => {
+ const { visible } = select({
+ sessions: [session("only", 1, { has_unread: true })],
+ runningSessionIds: new Set(),
+ openSessionId: null,
+ maxVisible: 0,
+ });
+
+ expect(ids(visible)).toEqual(["only"]);
+ });
+});
diff --git a/packages/views/chat/components/chat-bar-sessions.ts b/packages/views/chat/components/chat-bar-sessions.ts
new file mode 100644
index 0000000000..55ae2d71a1
--- /dev/null
+++ b/packages/views/chat/components/chat-bar-sessions.ts
@@ -0,0 +1,76 @@
+import type { ChatSession } from "@multica/core/types";
+
+export interface ChatBarSession {
+ session: ChatSession;
+ running: boolean;
+ unread: boolean;
+ /** The chat window is open on this session. */
+ open: boolean;
+}
+
+export interface ChatBarSessions {
+ visible: ChatBarSession[];
+ overflow: ChatBarSession[];
+}
+
+/** When a chat last moved; what a closed chip is compared against. */
+export function chatActivity(session: ChatSession): string {
+ return session.last_message?.created_at ?? session.updated_at;
+}
+
+/**
+ * Which chats the bottom bar shows. A chat gets a chip when it needs watching
+ * (a task is running, or a reply is unread) or was opened in the quick-chat
+ * window, and keeps it until the chip is closed. A closed chip comes back
+ * when its chat moves again, or is opened again.
+ *
+ * Chips are ordered by creation, newest first, so a chip keeps its place for
+ * the chat's whole life: ordering by activity would swap two running chats on
+ * every message. The open chat is always among the visible chips, because the
+ * window opens above its chip.
+ */
+export function selectChatBarSessions({
+ sessions,
+ runningSessionIds,
+ openSessionId,
+ kept,
+ dismissed,
+ maxVisible,
+}: {
+ sessions: ChatSession[];
+ runningSessionIds: ReadonlySet<string>;
+ /** The session the open window shows; null while the window is closed. */
+ openSessionId: string | null;
+ /** Chats opened in the quick-chat window. */
+ kept: readonly string[];
+ /** Closed chips: sessionId to the chat's activity when it was closed. */
+ dismissed: Readonly<Record<string, string>>;
+ maxVisible: number;
+}): ChatBarSessions {
+ const items = sessions
+ .filter((session) => session.status !== "archived")
+ .map((session) => ({
+ session,
+ running: runningSessionIds.has(session.id),
+ unread: session.has_unread,
+ open: session.id === openSessionId,
+ }))
+ .filter(
+ (item) =>
+ item.open ||
+ ((item.running || item.unread || kept.includes(item.session.id)) &&
+ dismissed[item.session.id] !== chatActivity(item.session)),
+ )
+ .sort(
+ (a, b) =>
+ new Date(b.session.created_at).getTime() - new Date(a.session.created_at).getTime(),
+ );
+
+ const limit = Math.max(1, maxVisible);
+ const openIndex = items.findIndex((item) => item.open);
+ if (openIndex >= limit) {
+ const [open] = items.splice(openIndex, 1);
+ if (open) items.unshift(open);
+ }
+ return { visible: items.slice(0, limit), overflow: items.slice(limit) };
+}
diff --git a/packages/views/chat/components/chat-bar.test.tsx b/packages/views/chat/components/chat-bar.test.tsx
new file mode 100644
index 0000000000..c537675ffe
--- /dev/null
+++ b/packages/views/chat/components/chat-bar.test.tsx
@@ -0,0 +1,259 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, screen, within } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { chatSessionsOptions, pendingChatTasksOptions } from "@multica/core/chat/queries";
+import type { ChatSession } from "@multica/core/types";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { renderWithI18n } from "../../test/i18n";
+import { ChatBar } from "./chat-bar";
+
+const WS = "ws-test";
+
+const h = vi.hoisted(() => ({
+ chat: {
+ isOpen: false,
+ activeSessionId: null as string | null,
+ selectedAgentId: "agent-1" as string | null,
+ quickChatAgentId: null as string | null,
+ chatBarKept: [] as string[],
+ chatBarDismissed: {} as Record<string, string>,
+ setOpen: vi.fn(),
+ setActiveSession: vi.fn(),
+ setSelectedAgentId: vi.fn(),
+ setSelectedProjectId: vi.fn(),
+ keepChatInBar: vi.fn(),
+ dismissChatFromBar: vi.fn(),
+ },
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (selector: (state: typeof h.chat) => unknown) => selector(h.chat),
+ { getState: () => h.chat },
+ ),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({ chat: () => "/acme/chat" }),
+}));
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: { getBaseUrl: () => "http://localhost" },
+}));
+
+const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+};
+
+function session(id: string, minute: number, overrides: Partial<ChatSession> = {}): ChatSession {
+ const at = new Date(Date.UTC(2026, 10, 11, 8, minute)).toISOString();
+ return {
+ id,
+ workspace_id: WS,
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: id,
+ status: "active",
+ has_unread: false,
+ created_at: at,
+ updated_at: at,
+ ...overrides,
+ };
+}
+
+function renderBar(sessions: ChatSession[], running: string[] = []) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ qc.setQueryData(chatSessionsOptions(WS).queryKey, sessions);
+ qc.setQueryData(pendingChatTasksOptions(WS).queryKey, {
+ tasks: running.map((id) => ({ task_id: `task-${id}`, status: "running", chat_session_id: id })),
+ });
+ return renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <NavigationProvider value={adapter}>
+ <ChatBar />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+}
+
+const SESSIONS = [
+ session("Read and done", 1),
+ session("Billing progress", 2, { agent_id: "agent-2" }),
+ session("Weekly report", 3, { has_unread: true }),
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.chat.isOpen = false;
+ h.chat.activeSessionId = null;
+ h.chat.selectedAgentId = "agent-1";
+ h.chat.quickChatAgentId = null;
+ h.chat.chatBarKept = [];
+ h.chat.chatBarDismissed = {};
+});
+
+describe("ChatBar", () => {
+ it("shows a chip for each running or unread chat, and none for the rest", () => {
+ renderBar(SESSIONS, [SESSIONS[1]!.id]);
+
+ expect(screen.getByRole("button", { name: "Billing progress, Running" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Weekly report, Unread" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Read and done/ })).not.toBeInTheDocument();
+ });
+
+ it("opens the chat window on the chip's chat, with that chat's agent", () => {
+ renderBar(SESSIONS, [SESSIONS[1]!.id]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Billing progress, Running" }));
+
+ expect(h.chat.setSelectedAgentId).toHaveBeenCalledWith("agent-2");
+ expect(h.chat.setActiveSession).toHaveBeenCalledWith("Billing progress");
+ expect(h.chat.keepChatInBar).toHaveBeenCalledWith("Billing progress");
+ expect(h.chat.setOpen).toHaveBeenCalledWith(true);
+ });
+
+ it("switches the open window to another chip's chat without closing it", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Billing progress";
+ h.chat.selectedAgentId = "agent-2";
+ renderBar(SESSIONS, [SESSIONS[1]!.id]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Weekly report, Unread" }));
+
+ expect(h.chat.setSelectedAgentId).toHaveBeenCalledWith("agent-1");
+ expect(h.chat.setActiveSession).toHaveBeenCalledWith("Weekly report");
+ expect(h.chat.setOpen).toHaveBeenCalledWith(true);
+ });
+
+ it("closes the window from the chip it is open on", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Weekly report";
+ renderBar(SESSIONS);
+
+ const chip = screen.getByRole("button", { name: "Weekly report, Unread" });
+ expect(chip).toHaveAttribute("aria-pressed", "true");
+ expect(screen.getByRole("button", { name: "Ask Multica" })).toHaveAttribute("aria-pressed", "false");
+
+ fireEvent.click(chip);
+
+ expect(h.chat.setOpen).toHaveBeenCalledWith(false);
+ expect(h.chat.setActiveSession).not.toHaveBeenCalled();
+ });
+
+ it("keeps the chip of a chat opened here once it is read and closed", () => {
+ h.chat.chatBarKept = ["Read and done"];
+ renderBar(SESSIONS);
+
+ expect(screen.getByRole("button", { name: "Read and done" })).toHaveAttribute("aria-pressed", "false");
+ });
+
+ it("gives whatever chat the window shows a chip", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Read and done";
+ renderBar(SESSIONS);
+
+ expect(screen.getByRole("button", { name: "Read and done" })).toHaveAttribute("aria-pressed", "true");
+ expect(h.chat.keepChatInBar).toHaveBeenCalledWith("Read and done");
+ });
+
+ it("closes a chip, and the window with it when it is open on that chat", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Weekly report";
+ renderBar(SESSIONS);
+
+ fireEvent.click(screen.getByRole("button", { name: "Close Weekly report" }));
+
+ expect(h.chat.setOpen).toHaveBeenCalledWith(false);
+ expect(h.chat.dismissChatFromBar).toHaveBeenCalledWith("Weekly report", SESSIONS[2]!.updated_at);
+ });
+
+ it("closes another chat's chip without touching the window", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Weekly report";
+ renderBar(SESSIONS, [SESSIONS[1]!.id]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Close Billing progress" }));
+
+ expect(h.chat.setOpen).not.toHaveBeenCalled();
+ expect(h.chat.dismissChatFromBar).toHaveBeenCalledWith("Billing progress", SESSIONS[1]!.updated_at);
+ });
+
+ it("starts a new chat from Ask Multica, leaving the open chat behind", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = "Weekly report";
+ renderBar(SESSIONS);
+
+ const ask = screen.getByRole("button", { name: "Ask Multica" });
+ expect(ask).toHaveAttribute("aria-pressed", "false");
+ fireEvent.click(ask);
+
+ expect(h.chat.setActiveSession).toHaveBeenCalledWith(null);
+ expect(h.chat.setSelectedProjectId).toHaveBeenCalledWith(null);
+ expect(h.chat.setOpen).toHaveBeenCalledWith(true);
+ expect(h.chat.setSelectedAgentId).not.toHaveBeenCalled();
+ });
+
+ it("starts the new chat with the agent set in Settings", () => {
+ h.chat.quickChatAgentId = "agent-9";
+ renderBar(SESSIONS);
+
+ fireEvent.click(screen.getByRole("button", { name: "Ask Multica" }));
+
+ expect(h.chat.setSelectedAgentId).toHaveBeenCalledWith("agent-9");
+ expect(h.chat.setActiveSession).toHaveBeenCalledWith(null);
+ });
+
+ it("closes the window from Ask Multica while it shows the new chat", () => {
+ h.chat.isOpen = true;
+ h.chat.activeSessionId = null;
+ renderBar(SESSIONS);
+
+ const ask = screen.getByRole("button", { name: "Ask Multica" });
+ expect(ask).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(ask);
+
+ expect(h.chat.setOpen).toHaveBeenCalledWith(false);
+ expect(h.chat.setActiveSession).not.toHaveBeenCalled();
+ });
+
+ it("opens a chat from the history, grouped by when it last moved", async () => {
+ vi.useFakeTimers({ toFake: ["Date"], now: new Date(2026, 10, 11, 20) });
+ try {
+ renderBar([
+ session("From today", 1, { updated_at: new Date(2026, 10, 11, 9).toISOString() }),
+ session("From this week", 2, { updated_at: new Date(2026, 10, 8, 9).toISOString() }),
+ session("From long ago", 3, { updated_at: new Date(2026, 6, 1, 9).toISOString() }),
+ session("Archived", 4, { status: "archived" }),
+ ]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Chat history" }));
+
+ const today = await screen.findByRole("group", { name: "Today" });
+ expect(within(today).getByRole("button", { name: /From today/ })).toBeInTheDocument();
+ expect(
+ within(screen.getByRole("group", { name: "Last 7 days" })).getByRole("button", { name: /From this week/ }),
+ ).toBeInTheDocument();
+ expect(
+ within(screen.getByRole("group", { name: "Older" })).getByRole("button", { name: /From long ago/ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Archived/ })).not.toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "All chats" })).toHaveAttribute("href", "/acme/chat");
+
+ fireEvent.click(screen.getByRole("button", { name: /From this week/ }));
+
+ expect(h.chat.keepChatInBar).toHaveBeenCalledWith("From this week");
+ expect(h.chat.setActiveSession).toHaveBeenCalledWith("From this week");
+ expect(h.chat.setOpen).toHaveBeenCalledWith(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/views/chat/components/chat-bar.tsx b/packages/views/chat/components/chat-bar.tsx
new file mode 100644
index 0000000000..b1b616a495
--- /dev/null
+++ b/packages/views/chat/components/chat-bar.tsx
@@ -0,0 +1,245 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Loader2, X } from "@multica/ui/icons";
+import { useChatStore } from "@multica/core/chat";
+import { chatSessionsOptions, pendingChatTasksOptions } from "@multica/core/chat/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { ChatSession } from "@multica/core/types";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { STAR_STROKE, starPath } from "@multica/ui/lib/multica-brand";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+import { BOTTOM_BAR_ITEM_CLASS } from "../../layout/bottom-bar-styles";
+import { ChatBarHistory } from "./chat-bar-history";
+import { chatActivity, selectChatBarSessions, type ChatBarSession } from "./chat-bar-sessions";
+
+const EMPTY_SESSIONS: ChatSession[] = [];
+const STAR = starPath(STAR_STROKE);
+
+/** The star from the Multica mark, in the text colour. */
+function MulticaStar() {
+ return (
+ <svg aria-hidden viewBox="0 0 100 100" fill="currentColor">
+ <path d={STAR} />
+ </svg>
+ );
+}
+const DEFAULT_MAX_CHIPS = 3;
+
+/**
+ * How many chips fit. The bar's other content (workspace status, Ask Multica,
+ * history) takes about 560px and a chip up to 170px; a narrow window gives up
+ * chips before it squeezes the status.
+ */
+function maxChipsForWidth(width: number): number {
+ return Math.min(4, Math.max(1, Math.floor((width - 560) / 170)));
+}
+
+function useMaxChips(ref: React.RefObject<HTMLElement | null>): number {
+ const [max, setMax] = useState(DEFAULT_MAX_CHIPS);
+ useEffect(() => {
+ const bar = ref.current?.parentElement;
+ if (!bar || typeof ResizeObserver === "undefined") return;
+ const update = () => {
+ // Unmeasured (hidden, or no layout): keep the default.
+ if (bar.clientWidth > 0) setMax(maxChipsForWidth(bar.clientWidth));
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(bar);
+ return () => observer.disconnect();
+ }, [ref]);
+ return max;
+}
+
+/**
+ * A chat's state, in a slot of one size whatever the state: a chip must not
+ * change width when its chat finishes or is read, or it would move the chips
+ * beside it and the window above it.
+ */
+function SessionMark({ item }: { item: ChatBarSession }) {
+ return (
+ <span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center">
+ {item.running ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <span
+ className={cn("size-1.5 rounded-full", item.unread ? "bg-brand" : "bg-faint-foreground")}
+ />
+ )}
+ </span>
+ );
+}
+
+/**
+ * Quick chat in the bottom bar: a chip per chat that needs watching or was
+ * opened here, then Ask Multica, which starts a new chat, and the history.
+ * The chat window opens above whichever control is pressed:
+ * `useChatWindowAnchor` finds it by `data-chat-anchor`, and re-places the
+ * window on a click that carries that attribute or `data-chat-anchor-trigger`.
+ */
+export function ChatBar() {
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const isOpen = useChatStore((s) => s.isOpen);
+ const activeSessionId = useChatStore((s) => s.activeSessionId);
+ const selectedAgentId = useChatStore((s) => s.selectedAgentId);
+ const quickChatAgentId = useChatStore((s) => s.quickChatAgentId);
+ const kept = useChatStore((s) => s.chatBarKept);
+ const dismissed = useChatStore((s) => s.chatBarDismissed);
+ const setOpen = useChatStore((s) => s.setOpen);
+ const setActiveSession = useChatStore((s) => s.setActiveSession);
+ const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);
+ const setSelectedProjectId = useChatStore((s) => s.setSelectedProjectId);
+ const keepChatInBar = useChatStore((s) => s.keepChatInBar);
+ const dismissChatFromBar = useChatStore((s) => s.dismissChatFromBar);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const maxVisible = useMaxChips(rootRef);
+
+ const { data: sessions = EMPTY_SESSIONS } = useQuery(chatSessionsOptions(wsId));
+ // Per-chat running state needs the task list, not the boolean the launcher
+ // reads. It is refetched on task lifecycle events only, never per message.
+ const { data: pending } = useQuery(pendingChatTasksOptions(wsId));
+ const runningSessionIds = useMemo(
+ () => new Set((pending?.tasks ?? []).map((task) => task.chat_session_id)),
+ [pending],
+ );
+
+ // Whatever the window shows gets a chip: a chat opened from the shortcut or
+ // the window's own history, or one that just got its first message.
+ const openSessionId = isOpen ? activeSessionId : null;
+ useEffect(() => {
+ if (openSessionId) keepChatInBar(openSessionId);
+ }, [openSessionId, keepChatInBar]);
+
+ const { visible, overflow } = useMemo(
+ () =>
+ selectChatBarSessions({ sessions, runningSessionIds, openSessionId, kept, dismissed, maxVisible }),
+ [sessions, runningSessionIds, openSessionId, kept, dismissed, maxVisible],
+ );
+ const openOnChip = visible.some((item) => item.open);
+ const askPressed = isOpen && !openOnChip;
+
+ const openSession = (session: ChatSession) => {
+ // A chat is bound to its agent, so opening it selects that agent too.
+ if (session.agent_id !== selectedAgentId) setSelectedAgentId(session.agent_id);
+ // Kept here, not left to the effect, so the chip is there to anchor the
+ // window by the time the click is measured.
+ keepChatInBar(session.id);
+ setActiveSession(session.id);
+ setOpen(true);
+ };
+
+ const toggleSession = (session: ChatSession) => {
+ if (isOpen && activeSessionId === session.id) setOpen(false);
+ else openSession(session);
+ };
+
+ const closeChip = (item: ChatBarSession) => {
+ if (item.open) setOpen(false);
+ dismissChatFromBar(item.session.id, chatActivity(item.session));
+ };
+
+ const askMultica = () => {
+ if (askPressed) {
+ setOpen(false);
+ return;
+ }
+ if (quickChatAgentId) setSelectedAgentId(quickChatAgentId);
+ setSelectedProjectId(null);
+ setActiveSession(null);
+ setOpen(true);
+ };
+
+ const titleOf = (session: ChatSession) => session.title || t(($) => $.window.untitled);
+ const stateOf = (item: ChatBarSession) =>
+ item.running ? t(($) => $.window.running) : item.unread ? t(($) => $.window.unread) : null;
+
+ const askLabel = t(($) => $.fab.default);
+
+ return (
+ <div ref={rootRef} data-slot="chat-bar" className="flex min-w-0 shrink-0 items-center gap-0.5">
+ {visible.map((item) => {
+ const title = titleOf(item.session);
+ const state = stateOf(item);
+ return (
+ <span key={item.session.id} className="group/chip relative flex shrink-0">
+ <TooltipHint label={state ? `${title} · ${state}` : title}>
+ <button
+ type="button"
+ data-chat-anchor={item.session.id}
+ aria-pressed={item.open}
+ aria-label={state ? `${title}, ${state}` : title}
+ onClick={() => toggleSession(item.session)}
+ className={cn(BOTTOM_BAR_ITEM_CLASS, "gap-1 pl-1.5")}
+ >
+ <SessionMark item={item} />
+ {/* The close button sits over the end of the title rather than
+ beside it, so showing it never changes the chip's width. */}
+ <span className="max-w-32 truncate group-focus-within/chip:[mask-image:linear-gradient(to_right,black_calc(100%-26px),transparent_calc(100%-14px))] group-hover/chip:[mask-image:linear-gradient(to_right,black_calc(100%-26px),transparent_calc(100%-14px))]">
+ {title}
+ </span>
+ </button>
+ </TooltipHint>
+ <button
+ type="button"
+ aria-label={t(($) => $.bar.close_chip, { title })}
+ onClick={() => closeChip(item)}
+ className="absolute top-1 right-1 flex size-4 cursor-pointer items-center justify-center rounded-sm text-muted-foreground opacity-0 outline-none transition-opacity hover:bg-surface-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-ring group-hover/chip:opacity-100 [&_svg]:size-3"
+ >
+ <X aria-hidden />
+ </button>
+ </span>
+ );
+ })}
+ {overflow.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={t(($) => $.bar.more, { count: overflow.length })}
+ className={cn(BOTTOM_BAR_ITEM_CLASS, "px-1.5 tabular-nums")}
+ >
+ +{overflow.length}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="top" sideOffset={8} className="max-w-72 min-w-48">
+ {overflow.map((item) => (
+ <DropdownMenuItem
+ key={item.session.id}
+ data-chat-anchor-trigger
+ onClick={() => openSession(item.session)}
+ >
+ <span className="flex shrink-0 [&_svg]:size-3.5">
+ <SessionMark item={item} />
+ </span>
+ <span className="min-w-0 truncate">{titleOf(item.session)}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {(visible.length > 0 || overflow.length > 0) && (
+ <span aria-hidden className="mx-1.5 h-3.5 w-px shrink-0 bg-surface-border" />
+ )}
+ <TooltipHint label={t(($) => $.window.new_chat_tooltip)}>
+ <button
+ type="button"
+ data-chat-anchor="new"
+ aria-pressed={askPressed}
+ onClick={askMultica}
+ className={BOTTOM_BAR_ITEM_CLASS}
+ >
+ <MulticaStar />
+ {askLabel}
+ </button>
+ </TooltipHint>
+ <ChatBarHistory sessions={sessions} runningSessionIds={runningSessionIds} onSelect={openSession} />
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-fab.tsx b/packages/views/chat/components/chat-fab.tsx
index afe0497660..b70d8066b6 100644
--- a/packages/views/chat/components/chat-fab.tsx
+++ b/packages/views/chat/components/chat-fab.tsx
@@ -17,13 +17,19 @@ import {
TooltipTrigger,
TooltipContent,
} from "@multica/ui/components/ui/tooltip";
+import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { ShortcutKeycaps } from "../../common/shortcut-keycaps";
import { useT } from "../../i18n";
const logger = createLogger("chat.ui");
+/**
+ * The floating launcher. From `md` up the bottom bar carries quick chat, so
+ * this is the launcher for narrow windows only.
+ */
export function ChatFab() {
const { t } = useT("chat");
+ const isMobile = useIsMobile();
const wsId = useWorkspaceId();
const isOpen = useChatStore((s) => s.isOpen);
const toggle = useChatStore((s) => s.toggle);
@@ -32,16 +38,16 @@ export function ChatFab() {
// clear it, hence the null case).
const shortcut = useShortcut("toggleChat");
const { data: sessions = [] } = useQuery(chatSessionsOptions(wsId));
- // FAB only needs a boolean "is anything running", and only while the window
- // is closed (when open, ChatWindow owns the detailed pending query). Gating
- // on `enabled: !isOpen` keeps the minimised button off the per-message
- // aggregate hot path entirely (MUL-4159).
+ // FAB only needs a boolean "is anything running", and only while it shows
+ // and the window is closed (when open, ChatWindow owns the detailed pending
+ // query). Gating on `enabled` keeps the minimised button off the
+ // per-message aggregate hot path entirely (MUL-4159).
const { data: hasPending } = useQuery({
...hasPendingChatTasksOptions(wsId),
- enabled: !isOpen,
+ enabled: !isOpen && isMobile,
});
- if (isOpen) return null;
+ if (isOpen || !isMobile) return null;
const unreadSessionCount = countUnreadChatSessions(sessions);
const isRunning = hasPending?.has_pending ?? false;
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 665742ee64..010143cede 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -731,6 +731,86 @@ describe("ChatInput @ context wiring", () => {
});
});
+describe("ChatInput page context", () => {
+ const page = {
+ id: "issue-1", label: "MUL-1", description: "Fix [the] cache", type: "issue" as const, group: "current" as const,
+ };
+ const sendButton = () => screen.getByRole("button", { name: /^Send/ });
+ const pageChip = () => document.querySelector('[data-slot="chat-page-context"]');
+
+ beforeEach(() => {
+ (useChatStore.getState() as unknown as { activeSessionId: string | null }).activeSessionId = "session-1";
+ });
+
+ it("offers nothing off an issue or project page", () => {
+ renderInput({ pageContext: null });
+ expect(screen.queryByRole("button", { name: "Add this page as context" })).not.toBeInTheDocument();
+ });
+
+ it("Tab in the editor attaches the page and sends it ahead of the message, once", async () => {
+ const onSend = vi.fn<ChatInputOnSend>((_content, _ids, commitInput) => {
+ commitInput();
+ return true;
+ });
+ renderInput({ onSend, pageContext: page });
+ const editor = screen.getByTestId("editor");
+
+ expect(fireEvent.keyDown(editor, { key: "Tab" })).toBe(false);
+ expect(pageChip()).toHaveTextContent("MUL-1Fix [the] cache");
+ expect(screen.getByRole("button", { name: "Add this page as context" })).toHaveAttribute("aria-pressed", "true");
+
+ fireEvent.change(editor, { target: { value: "why is this slow?" } });
+ fireEvent.click(sendButton());
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0]![0]).toBe("[MUL-1](mention://issue/issue-1)\n\nwhy is this slow?");
+ expect(pageChip()).toBeNull();
+ });
+
+ it("leaves Tab alone when the editor already used it, or it came from outside the editor", () => {
+ renderInput({ pageContext: page });
+ const editor = screen.getByTestId("editor");
+
+ editor.addEventListener("keydown", (event) => event.preventDefault(), { once: true });
+ fireEvent.keyDown(editor, { key: "Tab" });
+ fireEvent.keyDown(editor, { key: "Tab", shiftKey: true });
+ expect(fireEvent.keyDown(screen.getByRole("button", { name: "Add this page as context" }), { key: "Tab" })).toBe(true);
+ expect(pageChip()).toBeNull();
+ });
+
+ it("toggles from the button and drops the page when the page changes", () => {
+ const { rerender } = renderInput({ pageContext: page });
+
+ fireEvent.click(screen.getByRole("button", { name: "Add this page as context" }));
+ expect(pageChip()).not.toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Remove page context" }));
+ expect(pageChip()).toBeNull();
+
+ fireEvent.keyDown(screen.getByTestId("editor"), { key: "Tab" });
+ rerender(element({ pageContext: { ...page, id: "issue-2", label: "MUL-2" } }));
+ expect(pageChip()).toBeNull();
+ });
+
+ it.each([
+ ["another page", { ...page, id: "issue-2", label: "MUL-2" }],
+ ["a page with no context", null],
+ ])("does not send the page after leaving it for %s and coming back", async (_, away) => {
+ const onSend = vi.fn<ChatInputOnSend>(() => true);
+ const { rerender } = renderInput({ onSend, pageContext: page });
+ fireEvent.keyDown(screen.getByTestId("editor"), { key: "Tab" });
+ expect(pageChip()).not.toBeNull();
+
+ rerender(element({ onSend, pageContext: away }));
+ rerender(element({ onSend, pageContext: page }));
+ expect(pageChip()).toBeNull();
+ expect(screen.getByRole("button", { name: "Add this page as context" })).toHaveAttribute("aria-pressed", "false");
+
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "A new question" } });
+ fireEvent.click(sendButton());
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0]![0]).toBe("A new question");
+ });
+});
+
describe("ChatInput project context", () => {
type ChatProject = NonNullable<
React.ComponentProps<typeof ChatInput>["projects"]
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index c7cd0b266c..703fe250a1 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -2,7 +2,8 @@
import type { ReactNode } from "react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { TriangleAlert } from "@multica/ui/icons";
+import { Scan, TriangleAlert, X } from "@multica/ui/icons";
+import { IconButton } from "@multica/ui/components/common/icon-button";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import {
@@ -24,9 +25,10 @@ import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
import { useChatStore, DRAFT_NEW_SESSION } from "@multica/core/chat";
import { attachmentToDraftUpload, type DraftUpload } from "@multica/core/drafts";
import { createLogger } from "@multica/core/logger";
-import { useShortcut } from "@multica/core/shortcuts";
+import { useShortcut, type ShortcutChord } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../../common/shortcut-keycaps";
import type { MentionItem } from "../../editor/extensions/mention-suggestion";
+import { escapeMarkdownLabel } from "../../editor/utils/escape-markdown-label";
import type { Attachment, Project } from "@multica/core/types";
import { ProjectPicker } from "../../projects/components/project-picker";
import { ClearablePillButton } from "../../common/pill-button";
@@ -128,6 +130,9 @@ interface ChatInputProps {
leftAdornment?: ReactNode;
/** Chat @ suggestions: current/recent issue/project entries. */
contextItems?: MentionItem[];
+ /** The issue or project the page behind the composer shows. When set, the
+ * composer offers to send it with the next message (Tab, or the button). */
+ pageContext?: MentionItem | null;
/** Optional project context for the draft or current chat session. */
projects?: Project[];
projectId?: string | null;
@@ -154,6 +159,11 @@ interface ChatInputProps {
annotations?: Pick<ChatAnnotations, "draftKey" | "composer" | "editAnnotation">;
}
+const PAGE_CONTEXT_SHORTCUT = {
+ key: "Tab",
+ modifiers: { primary: false, control: false, meta: false, alt: false, shift: false },
+} satisfies ShortcutChord;
+
export function ChatInput({
onSend,
restoreDraftRequest,
@@ -172,6 +182,7 @@ export function ChatInput({
agentName,
leftAdornment,
contextItems,
+ pageContext,
projects = [],
projectId,
onProjectChange,
@@ -186,6 +197,7 @@ export function ChatInput({
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
+ const editorAreaRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<HTMLDivElement>(null);
const activeSessionId = useChatStore((s) => s.activeSessionId);
// Two keys with deliberately different concerns:
@@ -244,6 +256,19 @@ export function ChatInput({
const appliedConversationStarterIdRef = useRef<number | null>(null);
const editorKey = editorKeyOverride ?? CHAT_COMPOSER_EDITOR_KEY;
+ // Leaving the page drops what was attached to it, so coming back later
+ // starts without it.
+ const pageContextKey = pageContext ? `${pageContext.type}:${pageContext.id}` : null;
+ const [attachedPageKey, setAttachedPageKey] = useState<string | null>(null);
+ const [shownPageKey, setShownPageKey] = useState(pageContextKey);
+ if (shownPageKey !== pageContextKey) {
+ setShownPageKey(pageContextKey);
+ setAttachedPageKey(null);
+ }
+ const attachedPage = pageContext && attachedPageKey === pageContextKey ? pageContext : null;
+ const togglePageContext = () =>
+ setAttachedPageKey((current) => (current === pageContextKey ? null : pageContextKey));
+
// The draft whose document the editor instance is currently HOLDING.
//
// Normally identical to `draftKey`. The two diverge only while an in-flight
@@ -567,8 +592,13 @@ export function ChatInput({
draftKey: keyAtSend,
attachmentCount: uniqueActiveIds.length,
});
+ // The page goes ahead of the message as a mention, which is how chat
+ // already hands the agent an issue or project to read.
+ const sent = attachedPage
+ ? `[${escapeMarkdownLabel(attachedPage.label)}](mention://${attachedPage.type}/${attachedPage.id})\n\n${content}`
+ : content;
const accepted = await onSend(
- content,
+ sent,
uniqueActiveIds.length > 0 ? uniqueActiveIds : undefined,
commitInput,
draftAttachments.filter((attachment) => uniqueActiveIds.includes(attachment.id)),
@@ -578,6 +608,8 @@ export function ChatInput({
// retry. Only a commit — here or by the owner — clears it.
if (accepted === false) return false;
if (!committed) commitInput();
+ // Context is for the message it went with; the next one starts without.
+ if (attachedPage) setAttachedPageKey(null);
return true;
},
});
@@ -710,6 +742,18 @@ export function ChatInput({
noAgent && "pointer-events-none opacity-60",
)}
aria-disabled={noAgent || undefined}
+ onKeyDown={(event) => {
+ // Tab is the editor's when it wants it (list indent, the @ and /
+ // pickers): those handle the key first and prevent its default.
+ // Only an unclaimed Tab typed in the editor toggles the page.
+ if (
+ event.key !== "Tab" || event.shiftKey || event.altKey || event.metaKey || event.ctrlKey ||
+ event.defaultPrevented || event.nativeEvent.isComposing || !pageContext ||
+ !(event.target instanceof Node) || !editorAreaRef.current?.contains(event.target)
+ ) return;
+ event.preventDefault();
+ togglePageContext();
+ }}
>
{annotationDraftKey && annotations.length > 0 && (
<div className="px-3 pt-2">
@@ -717,6 +761,28 @@ export function ChatInput({
onEditAnnotation={(id) => annotationSlot.editAnnotation(id, true)} />
</div>
)}
+ {attachedPage && (
+ <div className="flex min-w-0 items-center px-3 pt-2">
+ <span
+ data-slot="chat-page-context"
+ className="inline-flex h-6 min-w-0 max-w-full items-center gap-1.5 rounded-md bg-surface-raised pr-0.5 pl-2 text-caption ring-1 ring-surface-border"
+ >
+ <Scan aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="shrink-0 font-medium text-foreground">{attachedPage.label}</span>
+ {attachedPage.type === "issue" && attachedPage.description && (
+ <span className="min-w-0 truncate text-muted-foreground">{attachedPage.description}</span>
+ )}
+ <button
+ type="button"
+ onClick={() => setAttachedPageKey(null)}
+ aria-label={t(($) => $.input.page_context_remove)}
+ className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-surface-hover hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <X aria-hidden className="size-3" />
+ </button>
+ </span>
+ </div>
+ )}
{selectedProject && (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-3 pt-2">
<div
@@ -749,7 +815,7 @@ export function ChatInput({
)}
</div>
)}
- <div className="flex-1 min-h-0 overflow-y-auto px-3 py-2">
+ <div ref={editorAreaRef} className="flex-1 min-h-0 overflow-y-auto px-3 py-2">
<ContentEditor
// See the editorKey / draftKey split note above — editor identity
// intentionally tracks neither the session nor the agent.
@@ -799,6 +865,18 @@ export function ChatInput({
</div>
)}
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
+ {pageContext && (
+ <IconButton
+ type="button"
+ aria-pressed={!!attachedPage}
+ onClick={togglePageContext}
+ label={t(($) => $.input.page_context_add)}
+ shortcut={<ShortcutKeycaps shortcut={PAGE_CONTEXT_SHORTCUT} decorative />}
+ className="text-muted-foreground aria-pressed:bg-accent aria-pressed:text-foreground"
+ >
+ <Scan />
+ </IconButton>
+ )}
<SubmitButton
onClick={submit}
disabled={hasNothingToSend || submitting || !!disabled || !!noAgent}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index fe5eaf01cf..aa0b7b8bb3 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -83,6 +83,8 @@ import { useChatContextItems } from "./use-chat-context-items";
import { useChatResize } from "./use-chat-resize";
import { useVisualViewportKeyboard } from "./use-visual-viewport-keyboard";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
+import { CHAT_WINDOW_INSET, useChatWindowAnchor } from "./use-chat-window-anchor";
+import { useFormatTimeAgo } from "./use-format-time-ago";
import {
hasInFlightPendingTask,
isStillOnComposeTarget,
@@ -92,7 +94,7 @@ import {
import { useChatProjectContextSupport } from "./use-chat-project-context-support";
import { createLogger } from "@multica/core/logger";
import type { Agent, Attachment, ChatMessage, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
-import { useLocale, useT } from "../../i18n";
+import { useT } from "../../i18n";
const uiLogger = createLogger("chat.ui");
const apiLogger = createLogger("chat.api");
@@ -750,7 +752,7 @@ export function ChatWindow() {
"absolute z-50 flex flex-col overflow-hidden bg-surface-raised @container",
isMobile
? "inset-x-0"
- : "right-2 rounded-xl shadow-[var(--floating-shadow)] ring-1 ring-surface-border",
+ : "rounded-xl shadow-[var(--floating-shadow)] ring-1 ring-foreground/15",
);
// Soft keyboards shrink only the *visual* viewport — the layout viewport
// (and this panel's bottom-anchored parent) keeps its full height, so
@@ -766,6 +768,7 @@ export function ChatWindow() {
// disappears from the style prop, so a conditional spread here would
// leave the keyboard geometry stuck on the DOM after the keyboard closes.
const keyboard = useVisualViewportKeyboard();
+ const anchorRight = useChatWindowAnchor(windowRef, isOpen, renderWidth, isDragging);
const containerStyle: React.CSSProperties = {
transformOrigin: "bottom right",
pointerEvents: isOpen ? "auto" : "none",
@@ -774,13 +777,15 @@ export function ChatWindow() {
// Full-screen panel anchored to the visible bottom edge;
// width/height live in the motion animate below.
top: "auto",
+ right: 0,
bottom: keyboard ? keyboard.occludedBottom : 0,
maxHeight: "none",
}
: {
// Floating card; only the anchor and the height cap live here.
top: "auto",
- bottom: keyboard ? keyboard.occludedBottom + 8 : 8,
+ right: anchorRight,
+ bottom: keyboard ? keyboard.occludedBottom + CHAT_WINDOW_INSET : CHAT_WINDOW_INSET,
maxHeight: keyboard ? keyboard.viewportHeight - 16 : "none",
}),
};
@@ -799,6 +804,7 @@ export function ChatWindow() {
: { width: renderWidth, height: renderHeight };
const contextItems = useChatContextItems(wsId);
+ const pageContext = contextItems.find((item) => item.group === "current") ?? null;
const queuedTasks = pendingTask?.queued_tasks ?? [];
const showRestore = isExpanded || isAtMax;
@@ -1007,6 +1013,7 @@ export function ChatWindow() {
/>
}
contextItems={contextItems}
+ pageContext={pageContext}
focusRequest={focusRequest}
annotations={annotations}
/>
@@ -1624,22 +1631,3 @@ function SessionDropdown({
</>
);
}
-
-function useFormatTimeAgo(): (dateStr: string) => string {
- const { t } = useT("chat");
- const locale = useLocale();
- return (dateStr: string) => {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMins = Math.floor(diffMs / 60000);
- const diffHours = Math.floor(diffMs / 3600000);
- const diffDays = Math.floor(diffMs / 86400000);
-
- if (diffMins < 1) return t(($) => $.session_history.time.just_now);
- if (diffMins < 60) return t(($) => $.session_history.time.minutes, { count: diffMins });
- if (diffHours < 24) return t(($) => $.session_history.time.hours, { count: diffHours });
- if (diffDays < 7) return t(($) => $.session_history.time.days, { count: diffDays });
- return date.toLocaleDateString(locale);
- };
-}
diff --git a/packages/views/chat/components/use-chat-window-anchor.test.tsx b/packages/views/chat/components/use-chat-window-anchor.test.tsx
new file mode 100644
index 0000000000..53b5c0d545
--- /dev/null
+++ b/packages/views/chat/components/use-chat-window-anchor.test.tsx
@@ -0,0 +1,188 @@
+import { act, fireEvent, render } from "@testing-library/react";
+import { useRef } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useChatResize } from "./use-chat-resize";
+import { useChatWindowAnchor } from "./use-chat-window-anchor";
+
+vi.mock("@multica/core/chat", async () => {
+ const { create } = await import("zustand");
+ const store = create<{
+ chatWidth: number;
+ chatHeight: number;
+ isExpanded: boolean;
+ setExpanded: (isExpanded: boolean) => void;
+ setChatSize: (chatWidth: number, chatHeight: number) => void;
+ }>((set) => ({
+ chatWidth: 420,
+ chatHeight: 500,
+ isExpanded: false,
+ setExpanded: (isExpanded) => set({ isExpanded }),
+ setChatSize: (chatWidth, chatHeight) => set({ chatWidth, chatHeight, isExpanded: false }),
+ }));
+ return { useChatStore: store, CHAT_MIN_W: 420, CHAT_MIN_H: 500 };
+});
+
+const CONTAINER = { left: 300, right: 1400 };
+const WINDOW_WIDTH = 420;
+
+function rect(left: number, width: number): DOMRect {
+ return { left, right: left + width, width, top: 0, bottom: 0, height: 0, x: left, y: 0, toJSON: () => ({}) };
+}
+
+function Harness({
+ isOpen,
+ pressed,
+ width = WINDOW_WIDTH,
+ isResizing = false,
+}: {
+ isOpen: boolean;
+ pressed: string | null;
+ width?: number;
+ isResizing?: boolean;
+}) {
+ const windowRef = useRef<HTMLDivElement>(null);
+ const right = useChatWindowAnchor(windowRef, isOpen, width, isResizing);
+ return (
+ <>
+ <div data-testid="container">
+ <div ref={windowRef} data-testid="window" data-right={right} />
+ </div>
+ <button data-chat-anchor="a" aria-pressed={pressed === "a"} />
+ <button data-chat-anchor="b" aria-pressed={pressed === "b"} />
+ </>
+ );
+}
+
+/** jsdom lays nothing out, so give the elements the hook measures a geometry. */
+function layOut(anchors: Record<string, number>) {
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.testid === "container") return rect(CONTAINER.left, CONTAINER.right - CONTAINER.left);
+ const anchor = this.dataset.chatAnchor;
+ if (anchor && anchor in anchors) return rect(anchors[anchor]!, 120);
+ return rect(0, 0);
+ });
+}
+
+const rightOf = (view: ReturnType<typeof render>) => Number(view.getByTestId("window").dataset.right);
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("useChatWindowAnchor", () => {
+ it("lines the window's left edge up with the pressed control", () => {
+ layOut({ a: 700, b: 1200 });
+ const view = render(<Harness isOpen pressed="a" />);
+
+ // left = 700, so right = 1400 - 700 - 420
+ expect(rightOf(view)).toBe(280);
+ });
+
+ it("pulls the window back inside the container when the control is near the edge", () => {
+ layOut({ a: 700, b: 1200 });
+ const view = render(<Harness isOpen pressed="b" />);
+
+ expect(rightOf(view)).toBe(8);
+ });
+
+ it("never starts left of the container", () => {
+ layOut({ a: 100, b: 1200 });
+ const view = render(<Harness isOpen pressed="a" />);
+
+ // left = 300 + 8
+ expect(rightOf(view)).toBe(1400 - 308 - WINDOW_WIDTH);
+ });
+
+ it("rests in the corner when no control is pressed or the bar is not laid out", () => {
+ layOut({});
+ const view = render(<Harness isOpen pressed={null} />);
+ expect(rightOf(view)).toBe(8);
+ view.unmount();
+
+ expect(rightOf(render(<Harness isOpen pressed="a" />))).toBe(8);
+ });
+
+ it("moves when the bar opens another chat, and stays put otherwise", () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => frames.push(cb));
+ layOut({ a: 700, b: 900 });
+ const view = render(<Harness isOpen pressed="a" />);
+ expect(rightOf(view)).toBe(280);
+
+ // The pressed control changing on its own (a chip appearing for the chat
+ // just started) must not move the window.
+ view.rerender(<Harness isOpen pressed="b" />);
+ expect(rightOf(view)).toBe(280);
+
+ act(() => {
+ view.container.querySelector<HTMLElement>('[data-chat-anchor="b"]')!.click();
+ frames.forEach((cb) => cb(0));
+ });
+ expect(rightOf(view)).toBe(1400 - 900 - WINDOW_WIDTH);
+ });
+
+ it("places the window again when its size changes, inside the container", () => {
+ layOut({ a: 700, b: 1200 });
+ const view = render(<Harness isOpen pressed="a" />);
+ expect(rightOf(view)).toBe(280);
+
+ // Expanded: no room right of the control, so it sits against the right inset.
+ view.rerender(<Harness isOpen pressed="a" width={990} />);
+ expect(rightOf(view)).toBe(8);
+
+ // Restored to a size other than the one it opened at: above its control again.
+ view.rerender(<Harness isOpen pressed="a" width={360} />);
+ expect(rightOf(view)).toBe(1400 - 700 - 360);
+ });
+
+ it("holds the right edge while the left edge is dragged, until the container stops it", () => {
+ layOut({ a: 700, b: 1200 });
+ const view = render(<Harness isOpen pressed="a" />);
+
+ view.rerender(<Harness isOpen pressed="a" width={600} isResizing />);
+ expect(rightOf(view)).toBe(280);
+
+ view.rerender(<Harness isOpen pressed="a" width={990} isResizing />);
+ // left held at the container's inset: 1400 - right - 990 = 308
+ expect(rightOf(view)).toBe(1100 - 8 - 990);
+
+ // Letting go does not move it.
+ view.rerender(<Harness isOpen pressed="a" width={990} />);
+ expect(rightOf(view)).toBe(1100 - 8 - 990);
+ });
+});
+
+describe("useChatWindowAnchor with useChatResize", () => {
+ function Window() {
+ const ref = useRef<HTMLDivElement>(null);
+ const { renderWidth, toggleExpand } = useChatResize(ref);
+ const right = useChatWindowAnchor(ref, true, renderWidth);
+ return (
+ <>
+ <div data-testid="container">
+ <div ref={ref} data-testid="window" style={{ width: renderWidth, right }}>
+ <button onClick={toggleExpand}>Expand</button>
+ </div>
+ </div>
+ <button data-chat-anchor="a" aria-pressed="true" />
+ </>
+ );
+ }
+
+ it("expanding a window opened from a chip on the left keeps it inside the container", () => {
+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(1100);
+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(800);
+ layOut({ a: 700 });
+ const view = render(<Window />);
+ const win = view.getByTestId("window");
+ const left = () => 1400 - Number.parseFloat(win.style.right) - Number.parseFloat(win.style.width);
+ expect(left()).toBe(700);
+
+ fireEvent.click(view.getByRole("button", { name: "Expand" }));
+ expect(Number.parseFloat(win.style.width)).toBe(990);
+ expect(left()).toBeGreaterThanOrEqual(308);
+
+ fireEvent.click(view.getByRole("button", { name: "Expand" }));
+ expect(left()).toBe(700);
+ });
+});
diff --git a/packages/views/chat/components/use-chat-window-anchor.ts b/packages/views/chat/components/use-chat-window-anchor.ts
new file mode 100644
index 0000000000..07e1c3a435
--- /dev/null
+++ b/packages/views/chat/components/use-chat-window-anchor.ts
@@ -0,0 +1,127 @@
+"use client";
+
+import { useLayoutEffect, useRef, useState } from "react";
+
+/** The window's inset from its container, and its resting place with no anchor. */
+export const CHAT_WINDOW_INSET = 8;
+
+/** The quick-chat group in the bottom bar. */
+const CHAT_BAR_SELECTOR = '[data-slot="chat-bar"]';
+/** The bottom-bar control the open window belongs to. */
+const PRESSED_ANCHOR_SELECTOR = '[data-chat-anchor][aria-pressed="true"]';
+/** Anything in the bar that opens or switches the window. */
+const ANCHOR_TRIGGER_SELECTOR = "[data-chat-anchor], [data-chat-anchor-trigger]";
+
+/**
+ * Where the floating chat window sits horizontally, as a `right` offset in its
+ * container. The window opens above the bottom-bar control that opened it: its
+ * left edge lines up with that control's, pulled back inside the container
+ * when there is no room. With no bar (below `md`) it rests in the corner.
+ *
+ * The window is placed when it opens, when the bar opens another chat in it,
+ * and when its container resizes; after that it follows its control if the
+ * bar's chips reflow. It stays put otherwise: a chip appearing for the chat
+ * just started must not move it under the person typing in it.
+ *
+ * `width` is the width the window is sized to, not the one it is animating
+ * through. A new size (expand, restore) places the window again. While
+ * `isResizing`, the dragged edge has to stay under the pointer, so the right
+ * edge holds and the window is only kept inside the container.
+ */
+export function useChatWindowAnchor(
+ windowRef: React.RefObject<HTMLElement | null>,
+ isOpen: boolean,
+ width: number,
+ isResizing = false,
+): number {
+ const [right, setRight] = useState(CHAT_WINDOW_INSET);
+ const widthRef = useRef(width);
+ widthRef.current = width;
+ const isResizingRef = useRef(isResizing);
+ isResizingRef.current = isResizing;
+ const placedRightRef = useRef(CHAT_WINDOW_INSET);
+ const measureRef = useRef<(() => void) | null>(null);
+
+ useLayoutEffect(() => {
+ if (!isOpen) return;
+ const win = windowRef.current;
+ const container = win?.parentElement;
+ if (!win || !container) return;
+
+ // The control the window was last placed above.
+ let placedAt: string | null = null;
+ const pressedAnchor = () => document.querySelector<HTMLElement>(PRESSED_ANCHOR_SELECTOR);
+
+ const measure = () => {
+ const anchor = pressedAnchor();
+ const anchorBox = anchor?.getBoundingClientRect();
+ placedAt = anchor?.dataset.chatAnchor ?? null;
+ // No bar, or a bar that is not laid out (display: none).
+ if (!anchorBox || anchorBox.width === 0) {
+ placedRightRef.current = CHAT_WINDOW_INSET;
+ setRight(CHAT_WINDOW_INSET);
+ return;
+ }
+ const box = container.getBoundingClientRect();
+ const width = widthRef.current;
+ const left = Math.min(
+ Math.max(anchorBox.left, box.left + CHAT_WINDOW_INSET),
+ box.right - CHAT_WINDOW_INSET - width,
+ );
+ placedRightRef.current = Math.max(CHAT_WINDOW_INSET, Math.round(box.right - left - width));
+ setRight(placedRightRef.current);
+ };
+
+ measureRef.current = measure;
+ measure();
+
+ // The click handler's state update has not rendered yet when this runs,
+ // so measure on the next frame, once the pressed control has moved.
+ let frame = 0;
+ const onClick = (event: MouseEvent) => {
+ if (!(event.target instanceof Element) || !event.target.closest(ANCHOR_TRIGGER_SELECTOR)) return;
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(measure);
+ };
+ document.addEventListener("click", onClick);
+
+ if (typeof ResizeObserver === "undefined") {
+ return () => {
+ measureRef.current = null;
+ cancelAnimationFrame(frame);
+ document.removeEventListener("click", onClick);
+ };
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(container);
+ // A chip leaving the bar (its chat was read) shifts the ones beside it.
+ // Follow the control the window is above, but not a change of control.
+ const barObserver = new ResizeObserver(() => {
+ if (pressedAnchor()?.dataset.chatAnchor === placedAt) measure();
+ });
+ const bar = document.querySelector(CHAT_BAR_SELECTOR);
+ if (bar) barObserver.observe(bar);
+
+ return () => {
+ measureRef.current = null;
+ cancelAnimationFrame(frame);
+ document.removeEventListener("click", onClick);
+ observer.disconnect();
+ barObserver.disconnect();
+ };
+ }, [windowRef, isOpen]);
+
+ useLayoutEffect(() => {
+ if (!isOpen) return;
+ if (!isResizingRef.current) {
+ measureRef.current?.();
+ return;
+ }
+ const container = windowRef.current?.parentElement;
+ if (!container) return;
+ const room = Math.round(container.getBoundingClientRect().width) - CHAT_WINDOW_INSET - width;
+ setRight(Math.max(CHAT_WINDOW_INSET, Math.min(placedRightRef.current, room)));
+ }, [windowRef, isOpen, width]);
+
+ return right;
+}
diff --git a/packages/views/chat/components/use-format-time-ago.ts b/packages/views/chat/components/use-format-time-ago.ts
new file mode 100644
index 0000000000..679830b959
--- /dev/null
+++ b/packages/views/chat/components/use-format-time-ago.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { useLocale, useT } from "../../i18n";
+
+/** How long ago a chat last moved, as the history lists show it. */
+export function useFormatTimeAgo(): (dateStr: string) => string {
+ const { t } = useT("chat");
+ const locale = useLocale();
+ return (dateStr: string) => {
+ const date = new Date(dateStr);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return t(($) => $.session_history.time.just_now);
+ if (diffMins < 60) return t(($) => $.session_history.time.minutes, { count: diffMins });
+ if (diffHours < 24) return t(($) => $.session_history.time.hours, { count: diffHours });
+ if (diffDays < 7) return t(($) => $.session_history.time.days, { count: diffDays });
+ return date.toLocaleDateString(locale);
+ };
+}
diff --git a/packages/views/layout/bottom-bar-styles.ts b/packages/views/layout/bottom-bar-styles.ts
new file mode 100644
index 0000000000..3b62f6a054
--- /dev/null
+++ b/packages/views/layout/bottom-bar-styles.ts
@@ -0,0 +1,9 @@
+/**
+ * A control in the bottom bar. The bar sits on the app shell like the rail,
+ * so its controls take the sidebar accent for the same reason (see
+ * `rail-styles.ts`).
+ */
+export const BOTTOM_BAR_ITEM_CLASS =
+ "inline-flex h-6 min-w-0 shrink-0 cursor-pointer items-center gap-1.5 rounded-md px-2 text-caption text-muted-foreground transition-colors outline-none hover:bg-sidebar-accent/70 hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-ring aria-pressed:bg-sidebar-accent aria-pressed:text-sidebar-accent-foreground data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground [&_svg]:size-3.5 [&_svg]:shrink-0";
+
+export const BOTTOM_BAR_ICON_ITEM_CLASS = `${BOTTOM_BAR_ITEM_CLASS} w-6 justify-center px-0`;
diff --git a/packages/views/layout/bottom-bar.test.tsx b/packages/views/layout/bottom-bar.test.tsx
new file mode 100644
index 0000000000..48e8d5459d
--- /dev/null
+++ b/packages/views/layout/bottom-bar.test.tsx
@@ -0,0 +1,115 @@
+import { screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { renderWithI18n } from "../test/i18n";
+import { AppBottomBar } from "./bottom-bar";
+
+interface TeamStatus {
+ working: { id: string }[];
+ stuck: { id: string }[];
+ byAgent: Map<string, { queuedCount: number }>;
+}
+
+const h = vi.hoisted(() => ({
+ chat: { floatingChatEnabled: true },
+ isMobile: false,
+ workspace: { id: "ws-test" } as { id: string } | null,
+ team: { working: [], stuck: [], byAgent: new Map() } as TeamStatus,
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (selector: (state: typeof h.chat) => unknown) => selector(h.chat),
+ { getState: () => h.chat },
+ ),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => h.workspace,
+ useWorkspacePaths: () => ({ chat: () => "/acme/chat", agents: () => "/acme/agents" }),
+}));
+vi.mock("@multica/ui/hooks/use-mobile", () => ({ useIsMobile: () => h.isMobile }));
+vi.mock("./panels/team-status", () => ({ useTeamAgentStatus: () => h.team }));
+vi.mock("./app-shell-context", () => ({ useAppShell: () => null }));
+vi.mock("../chat/components/chat-bar", () => ({ ChatBar: () => <div data-testid="chat-bar" /> }));
+vi.mock("../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,
+}));
+
+function renderBar(pathname = "/acme/issues") {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname,
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ };
+ return renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <AppBottomBar />
+ </NavigationProvider>,
+ );
+}
+
+beforeEach(() => {
+ h.chat.floatingChatEnabled = true;
+ h.isMobile = false;
+ h.workspace = { id: "ws-test" };
+ h.team = { working: [], stuck: [], byAgent: new Map() };
+});
+
+describe("AppBottomBar", () => {
+ it("shows quick chat and no team status while the team is idle", () => {
+ renderBar();
+
+ expect(screen.getByRole("contentinfo", { name: "Status bar" })).toBeInTheDocument();
+ expect(screen.getByTestId("chat-bar")).toBeInTheDocument();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+
+ it("counts the agents that are working and links to the team", () => {
+ h.team.working = [{ id: "a1" }, { id: "a2" }, { id: "a3" }, { id: "a4" }];
+ renderBar();
+
+ const link = screen.getByRole("link", { name: "4 agents working" });
+ expect(link).toHaveAttribute("href", "/acme/agents");
+ // The avatar stack is capped; the count carries the rest.
+ expect(screen.getAllByTestId(/^avatar-/)).toHaveLength(3);
+ });
+
+ it("adds up the tasks waiting on offline runtimes across agents", () => {
+ h.team.stuck = [{ id: "a1" }, { id: "a2" }];
+ h.team.byAgent = new Map([
+ ["a1", { queuedCount: 2 }],
+ ["a2", { queuedCount: 1 }],
+ ]);
+ renderBar();
+
+ expect(
+ screen.getByRole("link", { name: "3 tasks waiting on an offline runtime" }),
+ ).toHaveAttribute("href", "/acme/agents");
+ });
+
+ it("drops quick chat on the Chat tab, which already shows it full-page", () => {
+ renderBar("/acme/chat");
+ expect(screen.queryByTestId("chat-bar")).not.toBeInTheDocument();
+ expect(screen.getByRole("contentinfo")).toBeInTheDocument();
+ });
+
+ it("drops quick chat when the floating chat preference is off", () => {
+ h.chat.floatingChatEnabled = false;
+ renderBar();
+
+ expect(screen.queryByTestId("chat-bar")).not.toBeInTheDocument();
+ });
+
+ it("renders nothing on a narrow window or without a workspace", () => {
+ h.isMobile = true;
+ expect(renderBar().container).toBeEmptyDOMElement();
+
+ h.isMobile = false;
+ h.workspace = null;
+ expect(renderBar().container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/views/layout/bottom-bar.tsx b/packages/views/layout/bottom-bar.tsx
new file mode 100644
index 0000000000..87165f0270
--- /dev/null
+++ b/packages/views/layout/bottom-bar.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { TriangleAlert } from "@multica/ui/icons";
+import { useChatStore } from "@multica/core/chat";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useIsMobile } from "@multica/ui/hooks/use-mobile";
+import { ChatBar } from "../chat/components/chat-bar";
+import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";
+import { ActorAvatar } from "../common/actor-avatar";
+import { useT } from "../i18n";
+import { AppLink, useNavigation } from "../navigation";
+import { useAppShell } from "./app-shell-context";
+import { BOTTOM_BAR_ITEM_CLASS } from "./bottom-bar-styles";
+import { useTeamAgentStatus } from "./panels/team-status";
+
+const MAX_WORKING_AVATARS = 3;
+
+/**
+ * What the team is doing, at a glance: how many agents are working, and work
+ * that cannot start because its runtime is offline. Both lead to Team, which
+ * names the agents. Renders nothing while the team is idle.
+ */
+function TeamStatus({ wsId }: { wsId: string }) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const shell = useAppShell();
+ const { working, stuck, byAgent } = useTeamAgentStatus(wsId);
+ const teamHref = shell?.spaceHref("team", p.agents()) ?? p.agents();
+ const waitingTasks = stuck.reduce(
+ (total, agent) => total + (byAgent.get(agent.id)?.queuedCount ?? 0),
+ 0,
+ );
+
+ return (
+ <div className="flex min-w-0 items-center gap-1">
+ {working.length > 0 && (
+ <AppLink href={teamHref} className={BOTTOM_BAR_ITEM_CLASS}>
+ <span aria-hidden className="flex shrink-0 -space-x-1">
+ {working.slice(0, MAX_WORKING_AVATARS).map((agent) => (
+ <ActorAvatar
+ key={agent.id}
+ actorType="agent"
+ actorId={agent.id}
+ size="xs"
+ profileLink={false}
+ className="ring-[1.5px] ring-app-shell"
+ />
+ ))}
+ </span>
+ <span className="truncate">
+ {t(($) => $.bottom_bar.working, { count: working.length })}
+ </span>
+ </AppLink>
+ )}
+ {waitingTasks > 0 && (
+ <AppLink
+ href={teamHref}
+ className="inline-flex h-[22px] min-w-0 items-center gap-1.5 rounded-md bg-page-canvas pr-2 pl-1.5 text-caption font-medium text-foreground ring-1 ring-surface-border outline-none transition-colors hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <TriangleAlert aria-hidden className="size-3.5 shrink-0 text-warning" />
+ <span className="truncate">{t(($) => $.panels.team.stuck, { count: waitingTasks })}</span>
+ </AppLink>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The bar under the content card: workspace status on the left, quick chat on
+ * the right. It sits on the app shell, in the strip the card's bottom margin
+ * used to take. Below `md` there is no bar and quick chat is the floating
+ * launcher.
+ */
+export function AppBottomBar() {
+ const { t } = useT("layout");
+ const wsId = useCurrentWorkspace()?.id;
+ const isMobile = useIsMobile();
+ const floatingChatEnabled = useChatStore((s) => s.floatingChatEnabled);
+ const { pathname } = useNavigation();
+ const chatPath = useWorkspacePaths().chat();
+
+ if (!wsId || isMobile) return null;
+ // Same gates as the floating window: the Settings preference, and the Chat
+ // tab, which already shows the conversation full-page.
+ const showChat = floatingChatEnabled && !isFloatingChatRouteSuppressed(pathname, chatPath);
+
+ return (
+ <footer
+ aria-label={t(($) => $.bottom_bar.label)}
+ data-slot="app-bottom-bar"
+ data-mc="bottom-bar"
+ // pr: the card's mr-2 plus a gutter that puts the last icon on the same
+ // column as the page header's trailing action.
+ className="hidden h-8 shrink-0 items-center justify-between gap-4 pr-[18px] pl-3 md:flex"
+ >
+ <TeamStatus wsId={wsId} />
+ {showChat && <ChatBar />}
+ </footer>
+ );
+}
diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsx
index 81f0f17dd4..5738dd6285 100644
--- a/packages/views/layout/dashboard-layout.tsx
+++ b/packages/views/layout/dashboard-layout.tsx
@@ -6,6 +6,7 @@ import { AppearanceSync } from "../common/appearance-sync";
import { ModalRegistry } from "../modals/registry";
import { SourceBackfillModal } from "../onboarding";
import { AppRail } from "./app-rail";
+import { AppBottomBar } from "./bottom-bar";
import { AppShellProvider } from "./app-shell-context";
import { CompactNavSheet } from "./compact-nav-sheet";
import { DashboardGuard } from "./dashboard-guard";
@@ -25,12 +26,13 @@ interface DashboardLayoutProps {
/**
* The content card: the space panel and the page share one surface on the
- * app shell, split by a single hairline. Below `md` the card is the whole
+ * app shell, split by a single hairline. From `md` up the bottom bar sits
+ * under it, in place of a bottom margin; below `md` the card is the whole
* window. Desktop builds the same card in its own layout, under the tab bar.
*/
export function AppShellCard({ children }: { children: ReactNode }) {
return (
- <main data-mc="page" className="relative flex min-w-0 flex-1 flex-row overflow-hidden bg-page-canvas md:my-2 md:mr-2 md:rounded-page md:shadow-[var(--page-shadow,var(--surface-shadow))] md:ring-1 md:ring-page-border">
+ <main data-mc="page" className="relative flex min-h-0 min-w-0 flex-1 flex-row overflow-hidden bg-page-canvas md:mt-2 md:mr-2 md:rounded-page md:shadow-[var(--page-shadow,var(--surface-shadow))] md:ring-1 md:ring-page-border">
<SpacePanel />
<div className="relative flex min-w-0 flex-1 flex-col overflow-hidden">{children}</div>
</main>
@@ -59,13 +61,16 @@ export function DashboardLayout({
<WorkspacePresencePrefetch />
<AppRail className="hidden md:flex" />
<CompactNavSheet />
- <AppShellCard>
- <NavigationProgress />
- {children}
- <ModalRegistry />
- <SourceBackfillModal />
- {extra}
- </AppShellCard>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <AppShellCard>
+ <NavigationProgress />
+ {children}
+ <ModalRegistry />
+ <SourceBackfillModal />
+ {extra}
+ </AppShellCard>
+ <AppBottomBar />
+ </div>
</ShellRouteDataPrefetch>
</AppShellProvider>
</SidebarProvider>
diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.ts
index e203f9fa29..4837dee946 100644
--- a/packages/views/layout/index.ts
+++ b/packages/views/layout/index.ts
@@ -1,4 +1,5 @@
export { AppRail } from "./app-rail";
+export { AppBottomBar } from "./bottom-bar";
export { AppShellProvider, useAppShell } from "./app-shell-context";
export { CompactNavSheet } from "./compact-nav-sheet";
export { ShellRouteDataPrefetch } from "./route-data-prefetch";
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 1dd711e4a8..23cc0d6f07 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -13,7 +13,21 @@
"unread_other": "{{count}} unread chats",
"default": "Ask Multica"
},
+ "bar": {
+ "history": "Chat history",
+ "history_group": {
+ "today": "Today",
+ "week": "Last 7 days",
+ "older": "Older"
+ },
+ "close_chip": "Close {{title}}",
+ "all_chats": "All chats",
+ "more_one": "{{count}} more chat",
+ "more_other": "{{count}} more chats"
+ },
"input": {
+ "page_context_add": "Add this page as context",
+ "page_context_remove": "Remove page context",
"placeholder_no_agent": "Create an agent to start chatting",
"placeholder_archived": "This session is archived",
"placeholder_archived_agent": "This agent has been archived",
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index f0d2386ffa..d206c03799 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -110,6 +110,11 @@
"in_other_window": "Other window",
"all_workspaces_open": "Every workspace is already open in a window"
},
+ "bottom_bar": {
+ "label": "Status bar",
+ "working_one": "{{count}} agent working",
+ "working_other": "{{count}} agents working"
+ },
"panels": {
"work": {
"my_agents": "My agents' work",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index f9ef0f7797..f7d0908eee 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -471,7 +471,10 @@
},
"chat": {
"floating_label": "Floating chat window",
- "floating_hint": "Show the floating chat button on every page."
+ "floating_hint": "Show the floating chat button on every page.",
+ "ask_agent_label": "Ask Multica agent",
+ "ask_agent_hint": "The agent a new chat from the bottom bar starts with, in this workspace.",
+ "ask_agent_last_used": "Last used"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/es/chat.json b/packages/views/locales/es/chat.json
index 3668aca1a3..46a138bb49 100644
--- a/packages/views/locales/es/chat.json
+++ b/packages/views/locales/es/chat.json
@@ -13,7 +13,21 @@
"unread_other": "{{count}} chats sin leer",
"default": "Pregunta a Multica"
},
+ "bar": {
+ "history": "Historial de chats",
+ "history_group": {
+ "today": "Hoy",
+ "week": "Últimos 7 días",
+ "older": "Anteriores"
+ },
+ "close_chip": "Cerrar {{title}}",
+ "all_chats": "Todos los chats",
+ "more_one": "{{count}} chat más",
+ "more_other": "{{count}} chats más"
+ },
"input": {
+ "page_context_add": "Añadir esta página como contexto",
+ "page_context_remove": "Quitar el contexto de la página",
"placeholder_no_agent": "Crea un agente para empezar a chatear",
"placeholder_archived": "Esta sesión está archivada",
"placeholder_archived_agent": "Este agente se ha archivado",
diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.json
index 114a890a20..952612e5e7 100644
--- a/packages/views/locales/es/layout.json
+++ b/packages/views/locales/es/layout.json
@@ -110,6 +110,11 @@
"in_other_window": "Otra ventana",
"all_workspaces_open": "Todos los espacios de trabajo ya están abiertos en una ventana"
},
+ "bottom_bar": {
+ "label": "Barra de estado",
+ "working_one": "{{count}} agente trabajando",
+ "working_other": "{{count}} agentes trabajando"
+ },
"panels": {
"work": {
"my_agents": "Trabajo de mis agentes",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index ca39c7abf4..02730d2a30 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -453,7 +453,10 @@
},
"chat": {
"floating_label": "Ventana de chat flotante",
- "floating_hint": "Muestra el botón de chat flotante en todas las páginas."
+ "floating_hint": "Muestra el botón de chat flotante en todas las páginas.",
+ "ask_agent_label": "Agente de Preguntar a Multica",
+ "ask_agent_hint": "El agente con el que empieza un chat nuevo desde la barra inferior, en este espacio de trabajo.",
+ "ask_agent_last_used": "El último usado"
},
"issue": {
"description": "Elige qué campos mantiene cada diálogo de creación en su barra de herramientas. Los campos ocultos siguen disponibles en el menú ⋯ y reaparecen mientras tengan un valor.",
diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.json
index 8738d25b48..0a8fbab96a 100644
--- a/packages/views/locales/fr/chat.json
+++ b/packages/views/locales/fr/chat.json
@@ -13,7 +13,21 @@
"unread_other": "{{count}} discussions non lues",
"default": "Demander à Multica"
},
+ "bar": {
+ "history": "Historique des discussions",
+ "history_group": {
+ "today": "Aujourd'hui",
+ "week": "7 derniers jours",
+ "older": "Plus anciennes"
+ },
+ "close_chip": "Fermer {{title}}",
+ "all_chats": "Toutes les discussions",
+ "more_one": "{{count}} autre discussion",
+ "more_other": "{{count}} autres discussions"
+ },
"input": {
+ "page_context_add": "Ajouter cette page comme contexte",
+ "page_context_remove": "Retirer le contexte de la page",
"placeholder_no_agent": "Créez un agent pour commencer à discuter",
"placeholder_archived": "Cette session est archivée",
"placeholder_archived_agent": "Cet agent a été archivé",
diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.json
index 6a9519bc0b..e71eb66a2f 100644
--- a/packages/views/locales/fr/layout.json
+++ b/packages/views/locales/fr/layout.json
@@ -110,6 +110,11 @@
"in_other_window": "Autre fenêtre",
"all_workspaces_open": "Chaque espace de travail est déjà ouvert dans une fenêtre"
},
+ "bottom_bar": {
+ "label": "Barre d'état",
+ "working_one": "{{count}} agent au travail",
+ "working_other": "{{count}} agents au travail"
+ },
"panels": {
"work": {
"my_agents": "Travail de mes agents",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index bc3f5ee99a..0b286cc38f 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -471,7 +471,10 @@
},
"chat": {
"floating_label": "Fenêtre de discussion flottante",
- "floating_hint": "Afficher le bouton de chat flottant sur chaque page."
+ "floating_hint": "Afficher le bouton de chat flottant sur chaque page.",
+ "ask_agent_label": "Agent de Demander à Multica",
+ "ask_agent_hint": "L'agent avec lequel démarre une nouvelle discussion depuis la barre du bas, dans cet espace de travail.",
+ "ask_agent_last_used": "Dernier utilisé"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 4f2e3e9967..f59517a44e 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -12,7 +12,20 @@
"unread_other": "未読のチャット {{count}}件",
"default": "Multica に質問"
},
+ "bar": {
+ "history": "チャット履歴",
+ "history_group": {
+ "today": "今日",
+ "week": "過去 7 日間",
+ "older": "それ以前"
+ },
+ "close_chip": "{{title}} を閉じる",
+ "all_chats": "すべてのチャット",
+ "more_other": "他 {{count}} 件のチャット"
+ },
"input": {
+ "page_context_add": "このページをコンテキストに追加",
+ "page_context_remove": "ページのコンテキストを削除",
"placeholder_no_agent": "チャットを始めるにはエージェントを作成してください",
"placeholder_archived": "このセッションはアーカイブされています",
"placeholder_archived_agent": "このエージェントはアーカイブされています",
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index b00bd89429..39e87605b7 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -109,6 +109,10 @@
"in_other_window": "別ウィンドウ",
"all_workspaces_open": "すべてのワークスペースがすでにウィンドウで開いています"
},
+ "bottom_bar": {
+ "label": "ステータスバー",
+ "working_other": "{{count}} 体のエージェントが作業中"
+ },
"panels": {
"work": {
"my_agents": "マイエージェントの作業",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 742e9ddbf4..2e45e6f5a5 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -467,7 +467,10 @@
},
"chat": {
"floating_label": "フローティングチャット",
- "floating_hint": "すべてのページにフローティングチャットボタンを表示します。"
+ "floating_hint": "すべてのページにフローティングチャットボタンを表示します。",
+ "ask_agent_label": "「Multica に聞く」のエージェント",
+ "ask_agent_hint": "このワークスペースで、下部バーから始める新しいチャットの相手になるエージェント。",
+ "ask_agent_last_used": "最後に使用したエージェント"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 7337f4df63..c2482eaad3 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -12,7 +12,20 @@
"unread_other": "읽지 않은 채팅 {{count}}개",
"default": "Multica에 묻기"
},
+ "bar": {
+ "history": "채팅 기록",
+ "history_group": {
+ "today": "오늘",
+ "week": "지난 7일",
+ "older": "이전"
+ },
+ "close_chip": "{{title}} 닫기",
+ "all_chats": "모든 채팅",
+ "more_other": "채팅 {{count}}개 더 보기"
+ },
"input": {
+ "page_context_add": "이 페이지를 컨텍스트로 추가",
+ "page_context_remove": "페이지 컨텍스트 제거",
"placeholder_no_agent": "채팅을 시작하려면 에이전트를 만드세요",
"placeholder_archived": "보관된 세션입니다",
"placeholder_archived_agent": "보관된 에이전트입니다",
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index 42e4055e07..91f806da7d 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -109,6 +109,10 @@
"in_other_window": "다른 창",
"all_workspaces_open": "모든 워크스페이스가 이미 창에 열려 있습니다"
},
+ "bottom_bar": {
+ "label": "상태 표시줄",
+ "working_other": "에이전트 {{count}}개 작업 중"
+ },
"panels": {
"work": {
"my_agents": "내 에이전트의 작업",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 4e3f8866a0..c7667340e7 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -467,7 +467,10 @@
},
"chat": {
"floating_label": "플로팅 채팅 창",
- "floating_hint": "모든 페이지에 플로팅 채팅 버튼을 표시합니다."
+ "floating_hint": "모든 페이지에 플로팅 채팅 버튼을 표시합니다.",
+ "ask_agent_label": "Multica에게 묻기 에이전트",
+ "ask_agent_hint": "이 워크스페이스에서 하단 바로 시작하는 새 채팅의 에이전트입니다.",
+ "ask_agent_last_used": "마지막으로 사용한 에이전트"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/ru/chat.json b/packages/views/locales/ru/chat.json
index 0b7b0a7715..5c4cb1784b 100644
--- a/packages/views/locales/ru/chat.json
+++ b/packages/views/locales/ru/chat.json
@@ -15,7 +15,23 @@
"unread_few": "{{count}} непрочитанных чата",
"unread_many": "{{count}} непрочитанных чатов"
},
+ "bar": {
+ "history": "История чатов",
+ "history_group": {
+ "today": "Сегодня",
+ "week": "Последние 7 дней",
+ "older": "Ранее"
+ },
+ "close_chip": "Закрыть {{title}}",
+ "all_chats": "Все чаты",
+ "more_one": "Ещё {{count}} чат",
+ "more_few": "Ещё {{count}} чата",
+ "more_many": "Ещё {{count}} чатов",
+ "more_other": "Ещё {{count}} чата"
+ },
"input": {
+ "page_context_add": "Добавить эту страницу в контекст",
+ "page_context_remove": "Убрать контекст страницы",
"placeholder_no_agent": "Создайте агента, чтобы начать общение",
"placeholder_archived": "Эта сессия архивирована",
"placeholder_archived_agent": "Этот агент был архивирован",
diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.json
index d901ad68bc..c06bb067fb 100644
--- a/packages/views/locales/ru/layout.json
+++ b/packages/views/locales/ru/layout.json
@@ -86,6 +86,13 @@
"pin_workspace": "Закрепить рабочее пространство",
"unpin_workspace": "Открепить рабочее пространство"
},
+ "bottom_bar": {
+ "label": "Строка состояния",
+ "working_one": "{{count}} агент работает",
+ "working_few": "{{count}} агента работают",
+ "working_many": "{{count}} агентов работают",
+ "working_other": "{{count}} агента работают"
+ },
"panels": {
"work": {
"my_agents": "Работа моих агентов",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index cb237eeeca..50f27d7a73 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -478,7 +478,10 @@
},
"chat": {
"floating_label": "Плавающее окно чата",
- "floating_hint": "Показывать кнопку плавающего чата на каждой странице."
+ "floating_hint": "Показывать кнопку плавающего чата на каждой странице.",
+ "ask_agent_label": "Агент для «Спросить Multica»",
+ "ask_agent_hint": "Агент, с которым начинается новый чат из нижней панели в этом рабочем пространстве.",
+ "ask_agent_last_used": "Последний использованный"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 5c18790d9d..f7f8c383d1 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -12,7 +12,20 @@
"unread_other": "{{count}} 条未读对话",
"default": "问 Multica"
},
+ "bar": {
+ "history": "对话历史",
+ "history_group": {
+ "today": "今天",
+ "week": "过去 7 天",
+ "older": "更早"
+ },
+ "close_chip": "关闭 {{title}}",
+ "all_chats": "全部对话",
+ "more_other": "另外 {{count}} 个对话"
+ },
"input": {
+ "page_context_add": "将当前页面添加为上下文",
+ "page_context_remove": "移除页面上下文",
"placeholder_no_agent": "创建一个智能体后才能开始对话",
"placeholder_archived": "此会话已归档",
"placeholder_archived_agent": "该智能体已归档",
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index 38f2a98b45..097d57597c 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -109,6 +109,10 @@
"in_other_window": "其他窗口",
"all_workspaces_open": "所有工作区都已在窗口中打开"
},
+ "bottom_bar": {
+ "label": "状态栏",
+ "working_other": "{{count}} 个智能体正在工作"
+ },
"panels": {
"work": {
"my_agents": "我的智能体在做",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index a566799cfb..d0a89786ba 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -467,7 +467,10 @@
},
"chat": {
"floating_label": "悬浮聊天窗",
- "floating_hint": "在每个页面显示悬浮聊天按钮。"
+ "floating_hint": "在每个页面显示悬浮聊天按钮。",
+ "ask_agent_label": "「问 Multica」的智能体",
+ "ask_agent_hint": "在此工作区从底栏发起新对话时使用的智能体。",
+ "ask_agent_last_used": "上次使用的"
},
"issue": {
"opening": {
diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.json
index 7b03ff2cfd..2c7425ece8 100644
--- a/packages/views/locales/zh-Hant/chat.json
+++ b/packages/views/locales/zh-Hant/chat.json
@@ -12,7 +12,20 @@
"unread_other": "{{count}} 條未讀對話",
"default": "問 Multica"
},
+ "bar": {
+ "history": "對話記錄",
+ "history_group": {
+ "today": "今天",
+ "week": "過去 7 天",
+ "older": "更早"
+ },
+ "close_chip": "關閉 {{title}}",
+ "all_chats": "全部對話",
+ "more_other": "另外 {{count}} 個對話"
+ },
"input": {
+ "page_context_add": "將目前頁面加入為上下文",
+ "page_context_remove": "移除頁面上下文",
"placeholder_no_agent": "建立一個 AI 代理後才能開始對話",
"placeholder_archived": "此會話已歸檔",
"placeholder_archived_agent": "該 AI 代理已歸檔",
diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.json
index 629c848eb6..43b66cd35e 100644
--- a/packages/views/locales/zh-Hant/layout.json
+++ b/packages/views/locales/zh-Hant/layout.json
@@ -109,6 +109,10 @@
"in_other_window": "其他視窗",
"all_workspaces_open": "所有工作區都已在視窗中開啟"
},
+ "bottom_bar": {
+ "label": "狀態列",
+ "working_other": "{{count}} 個 AI 代理正在工作"
+ },
"panels": {
"work": {
"my_agents": "我的 AI 代理在做",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 40bd804bd1..1dd1af9713 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -467,7 +467,10 @@
},
"chat": {
"floating_label": "懸浮聊天窗",
- "floating_hint": "在每個頁面顯示懸浮聊天按鈕。"
+ "floating_hint": "在每個頁面顯示懸浮聊天按鈕。",
+ "ask_agent_label": "「問 Multica」的 AI 代理",
+ "ask_agent_hint": "在此工作區從底部列發起新對話時使用的 AI 代理。",
+ "ask_agent_last_used": "上次使用的"
},
"issue": {
"opening": {
diff --git a/packages/views/settings/components/preferences-tab.test.tsx b/packages/views/settings/components/preferences-tab.test.tsx
index 1215575493..9ededb20dc 100644
--- a/packages/views/settings/components/preferences-tab.test.tsx
+++ b/packages/views/settings/components/preferences-tab.test.tsx
@@ -62,6 +62,9 @@ vi.mock("@multica/core/chat", () => ({
),
}));
+// Reads the workspace's agents; covered by its own test.
+vi.mock("./quick-chat-agent-row", () => ({ QuickChatAgentRow: () => null }));
+
vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }),
}));
diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsx
index 281e3546bb..8737e3d6e0 100644
--- a/packages/views/settings/components/preferences-tab.tsx
+++ b/packages/views/settings/components/preferences-tab.tsx
@@ -47,6 +47,7 @@ import { browserTimezone, timezoneOptions } from "../../common/timezone-select";
import { useLanguageSwitch } from "../../common/use-language-switch";
import { SegmentedToggle } from "../../common/segmented-toggle";
import { useT } from "../../i18n";
+import { QuickChatAgentRow } from "./quick-chat-agent-row";
import {
SettingsCard,
SettingsRow,
@@ -86,6 +87,7 @@ export function PreferencesTab() {
<StickyCommentBarRow />
<RunningAgentReplyRow />
<FloatingChatRow />
+ <QuickChatAgentRow />
</SettingsCard>
</SettingsSection>
diff --git a/packages/views/settings/components/quick-chat-agent-row.test.tsx b/packages/views/settings/components/quick-chat-agent-row.test.tsx
new file mode 100644
index 0000000000..fca9d1ec74
--- /dev/null
+++ b/packages/views/settings/components/quick-chat-agent-row.test.tsx
@@ -0,0 +1,143 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Agent } from "@multica/core/types";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { renderWithI18n } from "../../test/i18n";
+import { QuickChatAgentRow } from "./quick-chat-agent-row";
+
+const WS = "ws-test";
+
+const h = vi.hoisted(() => ({
+ chat: {
+ floatingChatEnabled: true,
+ quickChatAgentId: null as string | null,
+ setQuickChatAgentId: vi.fn(),
+ },
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (selector: (state: typeof h.chat) => unknown) => selector(h.chat),
+ { getState: () => h.chat },
+ ),
+}));
+vi.mock("@multica/core/auth", () => {
+ const state = { user: { id: "user-1" } };
+ return {
+ useAuthStore: Object.assign(
+ (selector: (s: typeof state) => unknown) => selector(state),
+ { getState: () => state },
+ ),
+ };
+});
+vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "ws-test" }) }));
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: { getBaseUrl: () => "http://localhost" },
+}));
+
+function agent(id: string, name: string, overrides: Partial<Agent> = {}): Agent {
+ return {
+ id,
+ name,
+ owner_id: "user-1",
+ workspace_id: WS,
+ runtime_id: "runtime-1",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "sonnet",
+ skills: [],
+ created_at: new Date(0).toISOString(),
+ updated_at: new Date(0).toISOString(),
+ archived_at: null,
+ archived_by: null,
+ ...overrides,
+ };
+}
+
+function renderRow() {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ qc.setQueryData(agentListOptions(WS).queryKey, [
+ agent("agent-1", "Kepler"),
+ agent("agent-2", "Vega"),
+ agent("agent-3", "Retired", { archived_at: new Date(0).toISOString() }),
+ ]);
+ qc.setQueryData(memberListOptions(WS).queryKey, [
+ {
+ id: "member-1",
+ workspace_id: WS,
+ user_id: "user-1",
+ role: "owner",
+ created_at: new Date(0).toISOString(),
+ name: "Dev",
+ email: "dev@localhost",
+ avatar_url: null,
+ },
+ ]);
+ return renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <QuickChatAgentRow />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.chat.floatingChatEnabled = true;
+ h.chat.quickChatAgentId = null;
+});
+
+describe("QuickChatAgentRow", () => {
+ it("is unset by default and saves the agent that is picked", async () => {
+ const user = userEvent.setup();
+ renderRow();
+
+ const select = screen.getByRole("combobox", { name: "Ask Multica agent" });
+ expect(select).toHaveTextContent("Last used");
+
+ await user.click(select);
+ expect(screen.queryByRole("option", { name: "Retired" })).not.toBeInTheDocument();
+ await user.click(await screen.findByRole("option", { name: "Vega" }));
+
+ expect(h.chat.setQuickChatAgentId).toHaveBeenCalledWith("agent-2");
+ });
+
+ it("shows the saved agent and clears it with Last used", async () => {
+ h.chat.quickChatAgentId = "agent-1";
+ const user = userEvent.setup();
+ renderRow();
+
+ const select = screen.getByRole("combobox", { name: "Ask Multica agent" });
+ expect(select).toHaveTextContent("Kepler");
+
+ await user.click(select);
+ await user.click(await screen.findByRole("option", { name: "Last used" }));
+
+ expect(h.chat.setQuickChatAgentId).toHaveBeenCalledWith(null);
+ });
+
+ it("reads as unset when the saved agent is archived", () => {
+ h.chat.quickChatAgentId = "agent-3";
+ renderRow();
+
+ expect(screen.getByRole("combobox", { name: "Ask Multica agent" })).toHaveTextContent("Last used");
+ });
+
+ it("is disabled while the floating chat is off", () => {
+ h.chat.floatingChatEnabled = false;
+ renderRow();
+
+ expect(screen.getByRole("combobox", { name: "Ask Multica agent" })).toBeDisabled();
+ });
+});
diff --git a/packages/views/settings/components/quick-chat-agent-row.tsx b/packages/views/settings/components/quick-chat-agent-row.tsx
new file mode 100644
index 0000000000..e6f0421414
--- /dev/null
+++ b/packages/views/settings/components/quick-chat-agent-row.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import { useChatStore } from "@multica/core/chat";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { useT } from "../../i18n";
+import { canAssignAgent } from "../../issues/components/pickers/assignee-picker";
+import { SettingsRow } from "./settings-layout";
+
+const LAST_USED_AGENT = "last-used";
+
+/**
+ * The agent Ask Multica starts a new chat with. Unset, a new chat goes to the
+ * agent last chatted with. Stored on this device per workspace, like the
+ * chat's other selections.
+ */
+export function QuickChatAgentRow() {
+ const { t } = useT("settings");
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const user = useAuthStore((s) => s.user);
+ const enabled = useChatStore((s) => s.floatingChatEnabled);
+ const agentId = useChatStore((s) => s.quickChatAgentId);
+ const setAgentId = useChatStore((s) => s.setQuickChatAgentId);
+ const { data: agents = [] } = useQuery({ ...agentListOptions(wsId), enabled: !!wsId });
+ const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled: !!wsId });
+ const role = members.find((member) => member.user_id === user?.id)?.role;
+
+ const options = useMemo(
+ () => [
+ { value: LAST_USED_AGENT, label: t(($) => $.chat.ask_agent_last_used) },
+ ...agents
+ .filter((agent) => !agent.archived_at && canAssignAgent(agent, user?.id, role))
+ .map((agent) => ({ value: agent.id, label: agent.name })),
+ ],
+ [agents, user?.id, role, t],
+ );
+ // An agent that was archived or is no longer open to this member is not a
+ // choice any more; the row then reads as unset, which is how chat treats it.
+ const value = options.some((option) => option.value === agentId) ? agentId! : LAST_USED_AGENT;
+ const label = t(($) => $.chat.ask_agent_label);
+
+ return (
+ <SettingsRow label={label} description={t(($) => $.chat.ask_agent_hint)} size="select">
+ <Select
+ items={options}
+ value={value}
+ disabled={!enabled}
+ onValueChange={(next) => {
+ if (next) setAgentId(next === LAST_USED_AGENT ? null : next);
+ }}
+ >
+ <SelectTrigger size="sm" className="w-full" aria-label={label}>
+ <SelectValue>{options.find((option) => option.value === value)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ );
+}