Skip to content

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

Go

MUL-4432: add DM button on agent detail page (#5289)

Jiayuan Zhang3bd69bdaa2ec
diff --git a/packages/core/permissions/use-resource-permissions.ts b/packages/core/permissions/use-resource-permissions.ts
index df3ef3cac6..02fa1285be 100644
--- a/packages/core/permissions/use-resource-permissions.ts
+++ b/packages/core/permissions/use-resource-permissions.ts
@@ -34,15 +34,21 @@ export function useAgentPermissions(
): {
canEdit: Decision;
canAssign: Decision;
+ isLoading: boolean;
} {
- const { userId, role } = useCurrentMember(wsId);
+ const { userId, role, isLoading } = useCurrentMember(wsId);
const ctx = { userId, role };
+ // While the member query is in flight, `role` is null and the rules below
+ // would misread a legitimate member as denied (e.g. `not_member` for a
+ // public_to+workspace agent). Callers with always-clickable affordances
+ // must treat `isLoading` as "undetermined", not as a deny.
if (agent === null) {
- return { canEdit: PENDING, canAssign: PENDING };
+ return { canEdit: PENDING, canAssign: PENDING, isLoading };
}
return {
canEdit: canEditAgent(agent, ctx),
canAssign: canAssignAgentToIssue(agent, ctx),
+ isLoading,
};
}
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
new file mode 100644
index 0000000000..27fe4073c3
--- /dev/null
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -0,0 +1,211 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Agent } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enAgents from "../../locales/en/agents.json";
+import {
+ NavigationProvider,
+ type NavigationAdapter,
+} from "../../navigation";
+
+const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
+
+// The DM tests exercise the header action wiring plus the real permission
+// rules (via auth + member fixtures); the tabbed body and avatar/presence
+// widgets are irrelevant weight, so they're stubbed.
+vi.mock("./agent-overview-pane", () => ({
+ AgentOverviewPane: () => <div>agent-overview-pane</div>,
+}));
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => <div>actor-avatar</div>,
+}));
+vi.mock("./agent-presence-indicator", () => ({
+ AgentPresenceIndicator: () => null,
+}));
+
+const agentsRef = vi.hoisted(() => ({ current: [] as unknown[] }));
+const membersRef = vi.hoisted(() => ({ current: [] as unknown[] }));
+// When set, the member query never resolves — the "membership still loading"
+// window in which the DM decision is undetermined.
+const membersPendingRef = vi.hoisted(() => ({ current: false }));
+const currentUserRef = vi.hoisted(() => ({
+ current: { id: "user-1" } as { id: string } | null,
+}));
+const mockToastError = vi.hoisted(() => vi.fn());
+const mockModalOpen = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+vi.mock("@multica/core/agents", () => ({
+ useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: (wsId: string) => ({
+ queryKey: ["agents", wsId],
+ queryFn: () => Promise.resolve(agentsRef.current),
+ }),
+ memberListOptions: (wsId: string) => ({
+ queryKey: ["members", wsId],
+ queryFn: () =>
+ membersPendingRef.current
+ ? new Promise(() => {})
+ : Promise.resolve(membersRef.current),
+ }),
+ workspaceKeys: { agents: (wsId: string) => ["agents", wsId] },
+}));
+vi.mock("@multica/core/runtimes", () => ({
+ runtimeListOptions: (wsId: string) => ({
+ queryKey: ["runtimes", wsId],
+ queryFn: () => Promise.resolve([]),
+ }),
+}));
+vi.mock("@multica/core/auth", () => {
+ type AuthState = { user: { id: string } | null };
+ const state = (): AuthState => ({ user: currentUserRef.current });
+ const useAuthStore = Object.assign(
+ (selector?: (s: AuthState) => unknown) =>
+ selector ? selector(state()) : state(),
+ { getState: state },
+ );
+ return { useAuthStore };
+});
+vi.mock("@multica/core/modals", () => ({
+ useModalStore: Object.assign(vi.fn(), {
+ getState: () => ({ open: mockModalOpen }),
+ }),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ agents: () => "/acme/agents",
+ chat: () => "/acme/chat",
+ }),
+}));
+vi.mock("@multica/core/api", () => {
+ class ApiError extends Error {
+ status: number;
+ constructor(status: number, message: string) {
+ super(message);
+ this.status = status;
+ }
+ }
+ return {
+ api: { getAgent: vi.fn(() => Promise.reject(new ApiError(404, "not found"))) },
+ ApiError,
+ };
+});
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: mockToastError },
+}));
+
+import { AgentDetailPage } from "./agent-detail-page";
+
+const baseAgent: Agent = {
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Lambda",
+ 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: "",
+ owner_id: "user-2",
+ skills: [],
+ created_at: "2026-05-28T00:00:00Z",
+ updated_at: "2026-05-28T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+function renderPage() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const push = vi.fn();
+ const navigation: NavigationAdapter = {
+ push,
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/agents/agent-1",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (path) => path,
+ };
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <NavigationProvider value={navigation}>
+ <QueryClientProvider client={queryClient}>
+ <AgentDetailPage agentId="agent-1" />
+ </QueryClientProvider>
+ </NavigationProvider>
+ </I18nProvider>,
+ );
+ return { push };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ currentUserRef.current = { id: "user-1" };
+ membersRef.current = [{ user_id: "user-1", role: "member" }];
+ membersPendingRef.current = false;
+ agentsRef.current = [baseAgent];
+});
+
+describe("AgentDetailPage DM button", () => {
+ it("navigates to the chat deep link when the user can chat with the agent", async () => {
+ const { push } = renderPage();
+ fireEvent.click(await screen.findByRole("button", { name: "DM" }));
+ expect(push).toHaveBeenCalledWith("/acme/chat?agent=agent-1");
+ expect(mockToastError).not.toHaveBeenCalled();
+ });
+
+ it("shows a toast instead of navigating when the user lacks chat access", async () => {
+ // Post-MUL-3963 a workspace admin can VIEW another member's private agent
+ // but can no longer invoke (chat with) it — the exact case where the DM
+ // button must explain itself rather than navigate.
+ agentsRef.current = [
+ { ...baseAgent, permission_mode: "private", invocation_targets: [] },
+ ];
+ membersRef.current = [{ user_id: "user-1", role: "admin" }];
+ const { push } = renderPage();
+ fireEvent.click(await screen.findByRole("button", { name: "DM" }));
+ expect(mockToastError).toHaveBeenCalledWith(
+ "You don't have access to chat with this agent.",
+ );
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("disables DM while membership is resolving instead of toasting a false deny", async () => {
+ // Review P2: a pending member query collapses role to null, which the
+ // rules read as not_member — a legitimate public_to+workspace member
+ // would get a wrong "no access" toast. Undetermined must disable, not deny.
+ membersPendingRef.current = true;
+ const { push } = renderPage();
+ const dm = await screen.findByRole("button", { name: "DM" });
+ expect(dm).toBeDisabled();
+ fireEvent.click(dm);
+ expect(mockToastError).not.toHaveBeenCalled();
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("hides the DM button on an archived agent", async () => {
+ agentsRef.current = [
+ { ...baseAgent, archived_at: "2026-06-01T00:00:00Z" },
+ ];
+ renderPage();
+ // The archived banner is the signal the page has settled past loading.
+ await screen.findByText(/This agent is archived/);
+ expect(screen.queryByRole("button", { name: "DM" })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index cbae661f50..8e7bb6ffb2 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -7,6 +7,7 @@ import {
Bot,
Clock3,
Lock,
+ MessageSquare,
MoreHorizontal,
Plus,
Server,
@@ -106,7 +107,11 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
// signature handles the not-found / loading case internally so the early
// returns below don't violate the rules of hooks. Backend gates archive
// and restore identically to edit, so a single `canEdit` covers them all.
- const { canAssign, canEdit } = useAgentPermissions(agent, wsId);
+ const {
+ canAssign,
+ canEdit,
+ isLoading: permissionsLoading,
+ } = useAgentPermissions(agent, wsId);
const [confirmArchive, setConfirmArchive] = useState(false);
@@ -253,6 +258,20 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
? members.find((m) => m.user_id === agent.owner_id) ?? null
: null;
+ // Chat shares the invocation gate with assignment (MUL-3963): starting a
+ // chat triggers agent runs. The button stays visible either way — a denied
+ // click explains itself instead of the affordance silently missing. While
+ // membership is still resolving the decision is undetermined, so the button
+ // is disabled rather than toasting a false "no access" at a real member.
+ const handleDm = () => {
+ if (permissionsLoading) return;
+ if (!canAssign.allowed) {
+ toast.error(t(($) => $.detail.dm_no_permission_toast));
+ return;
+ }
+ navigation.push(`${paths.chat()}?agent=${agent.id}`);
+ };
+
return (
<div className="flex flex-1 min-h-0 flex-col">
<DetailHeader
@@ -262,6 +281,8 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
backHref={paths.agents()}
canAssign={canAssign.allowed}
canArchive={canEdit.allowed}
+ dmPending={permissionsLoading}
+ onDm={handleDm}
onAssign={() =>
useModalStore
.getState()
@@ -367,6 +388,8 @@ function DetailHeader({
backHref,
canAssign,
canArchive,
+ dmPending,
+ onDm,
onAssign,
onArchive,
}: {
@@ -376,6 +399,8 @@ function DetailHeader({
backHref: string;
canAssign: boolean;
canArchive: boolean;
+ dmPending: boolean;
+ onDm: () => void;
onAssign: () => void;
onArchive: () => void;
}) {
@@ -437,6 +462,18 @@ function DetailHeader({
</div>
<div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
+ {!isArchived && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={dmPending}
+ onClick={onDm}
+ >
+ <MessageSquare className="h-4 w-4" aria-hidden="true" />
+ {t(($) => $.detail.dm)}
+ </Button>
+ )}
{!isArchived && canAssign && (
<Button type="button" size="sm" onClick={onAssign}>
<Plus className="h-4 w-4" aria-hidden="true" />
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsx
new file mode 100644
index 0000000000..8c14cb7103
--- /dev/null
+++ b/packages/views/chat/chat-page.test.tsx
@@ -0,0 +1,309 @@
+// @vitest-environment jsdom
+
+import { StrictMode } from "react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { Agent } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../locales/en/common.json";
+import enChat from "../locales/en/chat.json";
+import {
+ NavigationProvider,
+ type NavigationAdapter,
+} from "../navigation";
+
+const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };
+
+// These tests target the page-level URL wiring (`?agent=` / `?session=`), so
+// the conversation internals are stubbed and the controller is replaced with
+// a ref-driven fake the tests can steer. The thread-list stub stays
+// interactive: selecting a thread is the user action that must supersede a
+// pending `?agent=` intent.
+vi.mock("./components/chat-message-list", () => ({
+ ChatMessageList: () => <div>chat-message-list</div>,
+ ChatMessageSkeleton: () => <div>chat-message-skeleton</div>,
+}));
+vi.mock("./components/chat-input", () => ({
+ ChatInput: () => <div>chat-input</div>,
+}));
+vi.mock("./components/chat-thread-list", () => ({
+ ChatThreadList: ({
+ onSelectSession,
+ }: {
+ onSelectSession: (s: { id: string; agent_id: string }) => void;
+ }) => (
+ <button
+ type="button"
+ onClick={() => onSelectSession({ id: "session-9", agent_id: "agent-9" })}
+ >
+ select-thread
+ </button>
+ ),
+}));
+vi.mock("./components/chat-session-header", () => ({
+ ChatSessionHeader: () => <div>chat-session-header</div>,
+}));
+vi.mock("./components/chat-empty-state", () => ({
+ EmptyState: () => <div>chat-empty-state</div>,
+}));
+vi.mock("./components/new-chat-button", () => ({
+ NewChatButton: () => <div>new-chat-button</div>,
+}));
+vi.mock("./components/offline-banner", () => ({
+ OfflineBanner: () => null,
+}));
+vi.mock("./components/no-agent-banner", () => ({
+ NoAgentBanner: () => null,
+}));
+vi.mock("./components/archived-agent-banner", () => ({
+ ArchivedAgentBanner: () => null,
+}));
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+}));
+vi.mock("@multica/ui/components/ui/resizable", () => ({
+ ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ ResizablePanel: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ ResizableHandle: () => null,
+}));
+vi.mock("@multica/ui/hooks/use-mobile", () => ({
+ useIsMobile: () => false,
+}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({ chat: () => "/acme/chat" }),
+}));
+
+// The store mock is REACTIVE like real Zustand: setActiveSession replaces the
+// snapshot and notifies subscribers, and the controller mock subscribes via
+// useSyncExternalStore. A plain mutable ref would let React bail out of
+// committing the post-effect re-render (no React state changed), leaving the
+// DOM frozen on the first commit — which silently hides exactly the class of
+// bug the StrictMode regression below exists to catch.
+const storeRef = vi.hoisted(() => ({
+ current: { activeSessionId: null as string | null },
+}));
+const storeListeners = vi.hoisted(() => new Set<() => void>());
+const availableAgentsRef = vi.hoisted(() => ({ current: [] as Agent[] }));
+const agentsSettledRef = vi.hoisted(() => ({ current: true }));
+const mockStartNewChat = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+const mockSetActiveSession = vi.hoisted(() =>
+ vi.fn((id: string | null) => {
+ storeRef.current = { ...storeRef.current, activeSessionId: id };
+ storeListeners.forEach((l) => l());
+ }),
+);
+const subscribeToStore = vi.hoisted(() => (cb: () => void) => {
+ storeListeners.add(cb);
+ return () => storeListeners.delete(cb);
+});
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: mockToastError },
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (selector?: (s: { activeSessionId: string | null }) => unknown) =>
+ selector ? selector(storeRef.current) : storeRef.current,
+ { getState: () => storeRef.current },
+ ),
+}));
+
+vi.mock("./components/use-chat-controller", async () => {
+ const { useSyncExternalStore } = await import("react");
+ return {
+ useChatController: () => ({
+ wsId: "ws-1",
+ user: { id: "user-1" },
+ agents: availableAgentsRef.current,
+ availableAgents: availableAgentsRef.current,
+ agentsSettled: agentsSettledRef.current,
+ sessions: [],
+ activeSessionId: useSyncExternalStore(
+ subscribeToStore,
+ () => storeRef.current,
+ ).activeSessionId,
+ selectedAgentId: null,
+ currentSession: null,
+ isSessionArchived: false,
+ isAgentArchived: false,
+ activeAgent: availableAgentsRef.current[0] ?? null,
+ noAgent: false,
+ availability: "online",
+ messages: [],
+ pendingTask: null,
+ pendingTaskId: null,
+ showSkeleton: false,
+ hasMessages: false,
+ firstItemIndex: 0,
+ hasOlderMessages: false,
+ isFetchingOlderMessages: false,
+ fetchOlderMessages: vi.fn(),
+ restoreDraftRequest: null,
+ handleRestoreDraftConsumed: vi.fn(),
+ focusInputRequest: 0,
+ handleSend: vi.fn(),
+ handleStop: vi.fn(),
+ handleUploadFile: vi.fn(),
+ handleNewChat: vi.fn(),
+ handleStartNewChat: mockStartNewChat,
+ handleSelectSession: vi.fn(),
+ advanceSelectionAfterArchive: vi.fn(),
+ archiveSession: vi.fn(),
+ setActiveSession: mockSetActiveSession,
+ setSelectedAgentId: vi.fn(),
+ }),
+ };
+});
+
+import { ChatPage } from "./chat-page";
+
+const agent: Agent = {
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Lambda",
+ 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: "",
+ owner_id: "user-2",
+ skills: [],
+ created_at: "2026-05-28T00:00:00Z",
+ updated_at: "2026-05-28T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+const NO_ACCESS_MSG = "You don't have access to chat with this agent.";
+
+function renderPage(search: string, { strict = false } = {}) {
+ const replace = vi.fn();
+ const navigation: NavigationAdapter = {
+ push: vi.fn(),
+ replace,
+ back: vi.fn(),
+ pathname: "/acme/chat",
+ searchParams: new URLSearchParams(search),
+ getShareableUrl: (path) => path,
+ };
+ // A fresh element per render — reusing one element object lets React bail
+ // out of re-rendering, which would make the rerender-based tests vacuous.
+ const makeUi = () => {
+ const page = (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <NavigationProvider value={navigation}>
+ <ChatPage />
+ </NavigationProvider>
+ </I18nProvider>
+ );
+ return strict ? <StrictMode>{page}</StrictMode> : page;
+ };
+ const view = render(makeUi());
+ return { replace, rerender: () => view.rerender(makeUi()) };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ storeRef.current = { activeSessionId: null };
+ storeListeners.clear();
+ availableAgentsRef.current = [agent];
+ agentsSettledRef.current = true;
+});
+
+describe("ChatPage ?agent= deep link", () => {
+ it("starts a new chat with the linked agent and strips the param", () => {
+ const { replace } = renderPage("agent=agent-1");
+ expect(mockStartNewChat).toHaveBeenCalledTimes(1);
+ expect(mockStartNewChat).toHaveBeenCalledWith(agent);
+ expect(replace).toHaveBeenCalledWith("/acme/chat");
+ // composingNew opened the conversation pane instead of the neutral prompt.
+ expect(screen.getByText("chat-input")).toBeInTheDocument();
+ });
+
+ it("consumes the intent only once even while the param is still in the URL", () => {
+ // navigation.replace is async in real adapters — the param outlives the
+ // consuming render. The real controller also allocates a fresh
+ // availableAgents array every render (it filters), so the effect re-runs;
+ // only the consumed-intent guard stops a second chat from starting.
+ const { rerender } = renderPage("agent=agent-1");
+ availableAgentsRef.current = [agent];
+ rerender();
+ expect(mockStartNewChat).toHaveBeenCalledTimes(1);
+ });
+
+ it("stays pending without a toast while the agent/member queries load", () => {
+ availableAgentsRef.current = [];
+ agentsSettledRef.current = false;
+ const { replace } = renderPage("agent=agent-1");
+ expect(mockStartNewChat).not.toHaveBeenCalled();
+ expect(mockToastError).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it("waits for the agent list to resolve before consuming the intent", () => {
+ availableAgentsRef.current = [];
+ agentsSettledRef.current = false;
+ const { replace, rerender } = renderPage("agent=agent-1");
+ expect(mockStartNewChat).not.toHaveBeenCalled();
+ availableAgentsRef.current = [agent];
+ agentsSettledRef.current = true;
+ rerender();
+ expect(mockStartNewChat).toHaveBeenCalledWith(agent);
+ expect(replace).toHaveBeenCalledWith("/acme/chat");
+ });
+
+ it("toasts and strips the param once the list settles without the agent", () => {
+ // Revoked access, archived agent, or a bad id: a settled miss must
+ // explain itself and consume the intent so a later refetch that surfaces
+ // the agent cannot auto-start a chat without a fresh click.
+ const { replace, rerender } = renderPage("agent=other-agent");
+ expect(mockStartNewChat).not.toHaveBeenCalled();
+ expect(mockToastError).toHaveBeenCalledWith(NO_ACCESS_MSG);
+ expect(replace).toHaveBeenCalledWith("/acme/chat");
+ expect(screen.queryByText("chat-input")).not.toBeInTheDocument();
+ rerender();
+ expect(mockToastError).toHaveBeenCalledTimes(1);
+ });
+
+ it("lets an explicit thread selection supersede a still-pending intent", () => {
+ // Deferred-intent race (review P1): the user picks a thread while the
+ // agent/member queries are still loading; when they settle, the stale
+ // deep link must NOT fire and clobber that selection.
+ availableAgentsRef.current = [];
+ agentsSettledRef.current = false;
+ const { replace, rerender } = renderPage("agent=agent-1");
+ fireEvent.click(screen.getByRole("button", { name: "select-thread" }));
+ availableAgentsRef.current = [agent];
+ agentsSettledRef.current = true;
+ rerender();
+ expect(mockStartNewChat).not.toHaveBeenCalled();
+ expect(mockToastError).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it("opens the compose pane under StrictMode with a persisted previous session", () => {
+ // StrictMode replays mount effects with render-captured values (review
+ // P2): the composingNew reset must read the LIVE store value, or the
+ // stale persisted session re-closes the pane the intent just opened —
+ // while the consumed-intent guard rightly refuses to fire again.
+ storeRef.current = { activeSessionId: "old-session" };
+ const { replace } = renderPage("agent=agent-1", { strict: true });
+ expect(mockStartNewChat).toHaveBeenCalledTimes(1);
+ expect(replace).toHaveBeenCalledWith("/acme/chat");
+ expect(screen.getByText("chat-input")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index b2002642e5..102a6cd073 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useDefaultLayout } from "react-resizable-panels";
import { ArrowLeft, MessageSquare } from "lucide-react";
+import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
import {
ResizablePanelGroup,
@@ -36,7 +37,9 @@ import { ArchivedAgentBanner } from "./components/archived-agent-banner";
* Selection is URL-addressable via `?session=<id>` so a thread can be
* deep-linked, opened from a notification, and survive refresh. The chat
* store's `activeSessionId` stays the source of truth (both surfaces read
- * it); the URL is kept in sync in both directions.
+ * it); the URL is kept in sync in both directions. `?agent=<id>` is the
+ * complementary one-shot deep link for a NEW chat: it starts a fresh compose
+ * bound to that agent and is then stripped from the URL.
*
* Starting a chat is where the agent is chosen: the header ⊕ opens an agent
* picker (see NewChatButton), so the compose box no longer needs its own
@@ -52,6 +55,7 @@ export function ChatPage() {
const c = useChatController({ isActive: true });
const urlSession = searchParams.get("session") || null;
+ const urlAgent = searchParams.get("agent") || null;
// "Composing a brand-new chat" — the user hit ⊕ but hasn't sent yet, so no
// session exists. On mobile this decides list-vs-conversation; on desktop the
@@ -59,7 +63,12 @@ export function ChatPage() {
// real session takes over.
const [composingNew, setComposingNew] = useState(false);
useEffect(() => {
- if (c.activeSessionId) setComposingNew(false);
+ // Read the LIVE store value for the same reason as the session sync
+ // effects below: under StrictMode's double-invoke this effect replays
+ // with the render-captured snapshot, and a stale non-null session (a
+ // persisted chat the URL→store effect already cleared) would revert the
+ // composingNew=true that the later `?agent=` intent effect just set.
+ if (useChatStore.getState().activeSessionId) setComposingNew(false);
}, [c.activeSessionId]);
// Two-way sync between the URL (`?session=`) and the chat store's
@@ -95,7 +104,20 @@ export function ChatPage() {
id: "multica_chat_layout",
});
+ // `?agent=` intent bookkeeping. The ref holds the param value already
+ // consumed (or superseded) so the effect below fires at most once per deep
+ // link — it also bridges the async window between replace() and the
+ // searchParams actually dropping the param. Any explicit user action must
+ // supersede a still-pending intent: agent/member queries can resolve late,
+ // and a deferred intent firing after the user picked a thread (or started
+ // another chat) would clobber that choice.
+ const consumedAgentIntent = useRef<string | null>(null);
+ const supersedeAgentIntent = () => {
+ if (urlAgent) consumedAgentIntent.current = urlAgent;
+ };
+
const handleSelect = (session: ChatSession) => {
+ supersedeAgentIntent();
c.handleSelectSession(session);
setComposingNew(false);
};
@@ -106,6 +128,7 @@ export function ChatPage() {
// the list, which reads more naturally than being thrown into an unrelated
// conversation full-screen. Archiving any other chat leaves the view put.
const handleArchive = (session: ChatSession) => {
+ supersedeAgentIntent();
if (session.id === c.activeSessionId) {
if (isMobile) {
c.setActiveSession(null);
@@ -118,11 +141,45 @@ export function ChatPage() {
};
const startNewChat = (agent: Agent | null) => {
+ // A manual ⊕ pick outranks a pending deep link; when called FROM the
+ // intent effect the ref is already set to this param, so this is a no-op.
+ supersedeAgentIntent();
if (agent) c.handleStartNewChat(agent);
else c.handleNewChat();
setComposingNew(true);
};
+ // URL → new chat: `?agent=<id>` is the deep link used by "DM" entry points
+ // (e.g. the agent detail page) to land on a fresh compose bound to that
+ // agent. The permission-filtered agent list loads async, so the intent is
+ // consumed on the render where the agent resolves, then the param is
+ // stripped so refresh / the session sync above don't replay it. The ref
+ // resets once the param is gone so a later identical deep link fires again.
+ // A settled miss (access revoked, agent archived, bad id) is a denial: it
+ // explains itself with a toast and consumes the intent so a later refetch
+ // that surfaces the agent cannot start a chat without a fresh click. While
+ // the queries are still loading the intent simply stays pending.
+ useEffect(() => {
+ if (!urlAgent) {
+ consumedAgentIntent.current = null;
+ return;
+ }
+ if (consumedAgentIntent.current === urlAgent) return;
+ const agent = c.availableAgents.find((a) => a.id === urlAgent);
+ if (agent) {
+ consumedAgentIntent.current = urlAgent;
+ startNewChat(agent);
+ replace(wsPaths.chat());
+ return;
+ }
+ if (c.agentsSettled) {
+ consumedAgentIntent.current = urlAgent;
+ toast.error(t(($) => $.page.agent_link_no_access));
+ replace(wsPaths.chat());
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- consume when the URL param or the resolving agent list changes
+ }, [urlAgent, c.availableAgents, c.agentsSettled]);
+
const newChatButton = (
<NewChatButton
agents={c.availableAgents}
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index cc5839fef2..74aedea202 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -203,8 +203,12 @@ export function useChatController(opts?: { isActive?: boolean }) {
const setActiveSession = useChatStore((s) => s.setActiveSession);
const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);
const user = useAuthStore((s) => s.user);
- const { data: agents = [] } = useQuery(agentListOptions(wsId));
- const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: agents = [], isSuccess: agentsLoaded } = useQuery(
+ agentListOptions(wsId),
+ );
+ const { data: members = [], isSuccess: membersLoaded } = useQuery(
+ memberListOptions(wsId),
+ );
const { data: sessions = [], isSuccess: sessionsLoaded } = useQuery(
chatSessionsOptions(wsId),
);
@@ -265,6 +269,13 @@ export function useChatController(opts?: { isActive?: boolean }) {
const availableAgents = agents.filter(
(a) => !a.archived_at && canAssignAgent(a, user?.id, memberRole),
);
+ // `availableAgents` is only trustworthy once BOTH queries above succeeded:
+ // the permission filter reads the member role, so agents-without-members
+ // misreports a public_to agent as unavailable. Consumers that must tell
+ // "still loading" apart from "settled and not available" (the `?agent=`
+ // deep link) gate on this instead of sniffing list emptiness. Query errors
+ // deliberately keep this false — a failed fetch is not a permission verdict.
+ const agentsSettled = agentsLoaded && membersLoaded;
// The agent bound to the OPEN session, resolved from the full agent list
// (archived included, since agentListOptions passes include_archived). An
@@ -655,6 +666,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
user,
agents,
availableAgents,
+ agentsSettled,
sessions,
activeSessionId,
selectedAgentId,
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 07a8e90edf..afac8c57ef 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -144,6 +144,8 @@
"archive_failed_toast": "Failed to archive agent",
"agent_restored_toast": "Agent restored",
"restore_failed_toast": "Failed to restore agent",
+ "dm": "DM",
+ "dm_no_permission_toast": "You don't have access to chat with this agent.",
"assign_work": "Assign work",
"more_actions_aria": "Agent actions",
"updated": "Updated {{when}}"
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 0dde77d11d..1aae491205 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -1,7 +1,8 @@
{
"page": {
"title": "Chat",
- "select_prompt": "Pick a conversation, or start a new one with +"
+ "select_prompt": "Pick a conversation, or start a new one with +",
+ "agent_link_no_access": "You don't have access to chat with this agent."
},
"fab": {
"running": "Multica is working...",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index a8335cd429..0af8b1b0dc 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -128,6 +128,8 @@
"archive_failed_toast": "エージェントをアーカイブできませんでした",
"agent_restored_toast": "エージェントを復元しました",
"restore_failed_toast": "エージェントを復元できませんでした",
+ "dm": "DM",
+ "dm_no_permission_toast": "このエージェントとチャットする権限がありません。",
"assign_work": "作業を割り当てる",
"more_actions_aria": "エージェントの操作",
"updated": "{{when}}に更新"
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 3f77c7bf2f..a945a93991 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -1,7 +1,8 @@
{
"page": {
"title": "チャット",
- "select_prompt": "会話を選ぶか、+ で新規作成してください"
+ "select_prompt": "会話を選ぶか、+ で新規作成してください",
+ "agent_link_no_access": "このエージェントとチャットする権限がありません。"
},
"fab": {
"running": "Multica が作業中です...",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index cdcb796596..cf3af40b93 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -136,6 +136,8 @@
"archive_failed_toast": "에이전트를 보관하지 못했습니다",
"agent_restored_toast": "에이전트를 복원했습니다",
"restore_failed_toast": "에이전트를 복원하지 못했습니다",
+ "dm": "DM",
+ "dm_no_permission_toast": "이 에이전트와 채팅할 권한이 없습니다.",
"assign_work": "작업 할당",
"more_actions_aria": "에이전트 작업",
"updated": "{{when}} 업데이트됨"
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 7128b58a9f..7ac9974f32 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -1,7 +1,8 @@
{
"page": {
"title": "채팅",
- "select_prompt": "대화를 선택하거나 +로 새로 시작하세요"
+ "select_prompt": "대화를 선택하거나 +로 새로 시작하세요",
+ "agent_link_no_access": "이 에이전트와 채팅할 권한이 없습니다."
},
"fab": {
"running": "Multica가 작업 중입니다...",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index b0e037712b..8e54dbbb24 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -136,6 +136,8 @@
"archive_failed_toast": "归档智能体失败",
"agent_restored_toast": "已恢复智能体",
"restore_failed_toast": "恢复智能体失败",
+ "dm": "私信",
+ "dm_no_permission_toast": "你没有权限与该智能体聊天。",
"assign_work": "分配工作",
"more_actions_aria": "智能体操作",
"updated": "{{when}}更新"
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 3647b1f1f1..b7afa89e56 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -1,7 +1,8 @@
{
"page": {
"title": "聊天",
- "select_prompt": "选择一个对话,或点 + 新建"
+ "select_prompt": "选择一个对话,或点 + 新建",
+ "agent_link_no_access": "你没有权限与该智能体聊天。"
},
"fab": {
"running": "Multica 正在工作...",