Skip to content

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

Go

MUL-5150: add project context to Chat (#5765)

Jiayuan Zhanga3fe6d91dd02
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 9673a2fe28..9780f1ec83 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2084,7 +2084,11 @@ export class ApiClient {
return this.fetch(`/api/chat/sessions/${id}`);
}
- async createChatSession(data: { agent_id: string; title?: string }): Promise<ChatSession> {
+ async createChatSession(data: {
+ agent_id: string;
+ title?: string;
+ project_id?: string | null;
+ }): Promise<ChatSession> {
return this.fetch("/api/chat/sessions", {
method: "POST",
body: JSON.stringify(data),
@@ -2095,7 +2099,10 @@ export class ApiClient {
await this.fetch(`/api/chat/sessions/${id}`, { method: "DELETE" });
}
- async updateChatSession(id: string, data: { title: string }): Promise<ChatSession> {
+ async updateChatSession(
+ id: string,
+ data: { title: string } | { project_id: string | null },
+ ): Promise<ChatSession> {
return this.fetch(`/api/chat/sessions/${id}`, {
method: "PATCH",
body: JSON.stringify(data),
diff --git a/packages/core/chat/mutations.test.tsx b/packages/core/chat/mutations.test.tsx
index df582fe62a..3f75b9e395 100644
--- a/packages/core/chat/mutations.test.tsx
+++ b/packages/core/chat/mutations.test.tsx
@@ -8,7 +8,11 @@ import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
-import { useConsumeChatDraftRestore, useSetChatSessionArchived } from "./mutations";
+import {
+ useConsumeChatDraftRestore,
+ useSetChatSessionArchived,
+ useSetChatSessionProject,
+} from "./mutations";
import { chatKeys } from "./queries";
import type { ChatSession } from "../types";
@@ -126,6 +130,68 @@ describe("useSetChatSessionArchived", () => {
});
});
+describe("useSetChatSessionProject", () => {
+ let qc: QueryClient;
+ let updateChatSession: ReturnType<
+ typeof vi.fn<
+ (
+ id: string,
+ data: { title: string } | { project_id: string | null },
+ ) => Promise<ChatSession>
+ >
+ >;
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ updateChatSession = vi.fn();
+ setApiInstance({ updateChatSession } as unknown as ApiClient);
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("optimistically removes the project from the existing session", async () => {
+ updateChatSession.mockResolvedValue(makeSession({ project_id: null }));
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ project_id: "project-1" }),
+ ]);
+
+ const { result } = renderHook(() => useSetChatSessionProject(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ sessionId: "s1", projectId: null });
+ });
+
+ expect(updateChatSession).toHaveBeenCalledWith("s1", { project_id: null });
+ expect(qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!.project_id).toBeNull();
+ });
+
+ it("rolls the project back when the update fails", async () => {
+ updateChatSession.mockRejectedValue(new Error("boom"));
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ project_id: "project-1" }),
+ ]);
+
+ const { result } = renderHook(() => useSetChatSessionProject(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await expect(
+ result.current.mutateAsync({ sessionId: "s1", projectId: null }),
+ ).rejects.toThrow("boom");
+ });
+
+ expect(
+ qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!.project_id,
+ ).toBe("project-1");
+ });
+});
+
// The consume DELETE is the last step of a durable draft restore (#5219), and
// mutations are `retry: false` app-wide — a single dropped request would leave
// the row behind, to be re-offered later. The endpoint is idempotent, so this
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index c273e3819a..4d1959fbab 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -101,8 +101,12 @@ export function useCreateChatSession() {
const wsId = useWorkspaceId();
return useMutation({
- mutationFn: (data: { agent_id: string; title?: string }) => {
- logger.info("createChatSession.start", { agent_id: data.agent_id, titleLength: data.title?.length ?? 0 });
+ mutationFn: (data: { agent_id: string; title?: string; project_id?: string | null }) => {
+ logger.info("createChatSession.start", {
+ agent_id: data.agent_id,
+ project_id: data.project_id,
+ titleLength: data.title?.length ?? 0,
+ });
return api.createChatSession(data);
},
onSuccess: (session) => {
@@ -192,6 +196,45 @@ export function useUpdateChatSession() {
});
}
+/**
+ * Changes the project context of an existing chat without replacing the
+ * session. The optimistic patch keeps the context chip in place while the
+ * server validates the soft project reference; failures restore the old row.
+ */
+export function useSetChatSessionProject() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: (data: { sessionId: string; projectId: string | null }) => {
+ logger.info("setChatSessionProject.start", data);
+ return api.updateChatSession(data.sessionId, { project_id: data.projectId });
+ },
+ onMutate: async ({ sessionId, projectId }) => {
+ await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
+
+ const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
+ const patch = (old?: ChatSession[]) =>
+ old?.map((session) =>
+ session.id === sessionId ? { ...session, project_id: projectId } : session,
+ );
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
+
+ return { prevSessions };
+ },
+ onError: (err, vars, ctx) => {
+ logger.error("setChatSessionProject.error.rollback", {
+ sessionId: vars.sessionId,
+ err,
+ });
+ if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
+ },
+ });
+}
+
/**
* Pins or unpins a chat. Optimistically flips `pinned` and re-sorts the cached
* list (pinned first, then by activity) so the row jumps to / from the top
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index 3e11ef04e2..aa39e28421 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -169,6 +169,20 @@ describe("chat store — open/closed default", () => {
});
});
+describe("chat store — selected project", () => {
+ it("persists and clears the next chat's project per workspace", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+
+ store.getState().setSelectedProjectId("project-1");
+ expect(storage.getItem("multica:chat:selectedProjectId")).toBe("project-1");
+ expect(createChatStore({ storage }).getState().selectedProjectId).toBe("project-1");
+
+ store.getState().setSelectedProjectId(null);
+ expect(storage.getItem("multica:chat:selectedProjectId")).toBeNull();
+ });
+});
+
describe("chat store — draft attachments", () => {
let store: ReturnType<typeof createChatStore>;
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index 5bdea3dfb6..b706917f2b 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -7,6 +7,7 @@ import { createLogger } from "../logger";
const logger = createLogger("chat.store");
const AGENT_STORAGE_KEY = "multica:chat:selectedAgentId";
+const PROJECT_STORAGE_KEY = "multica:chat:selectedProjectId";
const SESSION_STORAGE_KEY = "multica:chat:activeSessionId";
/** Drafts are stored as one JSON blob per workspace: { [sessionId]: text }. */
const DRAFTS_KEY = "multica:chat:drafts";
@@ -293,6 +294,9 @@ export interface ChatState {
floatingChatEnabled: boolean;
activeSessionId: string | null;
selectedAgentId: string | null;
+ /** Project context for the next session. Existing sessions remain bound to
+ * their server-persisted project_id. */
+ selectedProjectId: string | null;
/** Drafts per session: sessionId (or DRAFT_NEW_SESSION) → markdown text. */
inputDrafts: Record<string, string>;
/** Attachment rows referenced by each input draft. */
@@ -310,6 +314,7 @@ export interface ChatState {
setFloatingChatEnabled: (enabled: boolean) => void;
setActiveSession: (id: string | null) => void;
setSelectedAgentId: (id: string) => void;
+ setSelectedProjectId: (id: string | null) => void;
/** sessionId accepts a real session UUID or DRAFT_NEW_SESSION. */
setInputDraft: (sessionId: string, draft: string) => void;
setInputDraftAttachments: (sessionId: string, attachments: Attachment[]) => void;
@@ -364,6 +369,7 @@ export function createChatStore(options: ChatStoreOptions) {
floatingChatEnabled: initialFloatingEnabled,
activeSessionId: storage.getItem(wsKey(SESSION_STORAGE_KEY)),
selectedAgentId: initialAgentId,
+ selectedProjectId: storage.getItem(wsKey(PROJECT_STORAGE_KEY)),
inputDrafts: initialDraftSlots.inputDrafts,
inputDraftAttachments: initialDraftSlots.inputDraftAttachments,
appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
@@ -404,6 +410,12 @@ export function createChatStore(options: ChatStoreOptions) {
storage.setItem(wsKey(AGENT_STORAGE_KEY), id);
set({ selectedAgentId: id });
},
+ setSelectedProjectId: (id) => {
+ logger.info("setSelectedProjectId", { from: get().selectedProjectId, to: id });
+ if (id) storage.setItem(wsKey(PROJECT_STORAGE_KEY), id);
+ else storage.removeItem(wsKey(PROJECT_STORAGE_KEY));
+ set({ selectedProjectId: id });
+ },
// 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
@@ -521,6 +533,7 @@ export function createChatStore(options: ChatStoreOptions) {
registerForWorkspaceRehydration(() => {
const nextSession = storage.getItem(wsKey(SESSION_STORAGE_KEY));
const nextAgent = storage.getItem(wsKey(AGENT_STORAGE_KEY));
+ const nextProject = storage.getItem(wsKey(PROJECT_STORAGE_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.
@@ -535,12 +548,15 @@ export function createChatStore(options: ChatStoreOptions) {
nextSession,
prevAgent: store.getState().selectedAgentId,
nextAgent,
+ prevProject: store.getState().selectedProjectId,
+ nextProject,
draftCount: Object.keys(nextDrafts).length,
draftAttachmentCount: Object.keys(nextDraftAttachments).length,
});
store.setState({
activeSessionId: nextSession,
selectedAgentId: nextAgent,
+ selectedProjectId: nextProject,
inputDrafts: nextDrafts,
inputDraftAttachments: nextDraftAttachments,
appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index 4242ddc2bb..63cf3b11ae 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -175,6 +175,21 @@ describe("applyChatSessionUpdatedToCache", () => {
};
}
+ it("applies an explicit null project_id from another tab", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ project_id: "project-1" }),
+ ]);
+
+ applyChatSessionUpdatedToCache(qc, WS_ID, {
+ chat_session_id: "s1",
+ project_id: null,
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.project_id).toBeNull();
+ });
+
// MUL-4360 cross-tab: chatSessionsOptions is staleTime: Infinity, so a stale
// cache in another tab never self-heals. When an archive event lands there,
// the row's unread must be forced to 0 to match the archive mutation and the
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index b360872b0a..e9988b02c8 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -193,6 +193,7 @@ function patchLatestChatMessagePage(
type ChatSessionUpdatedPayload = {
chat_session_id: string;
title?: string;
+ project_id?: string | null;
pinned?: boolean;
status?: "active" | "archived";
updated_at?: string;
@@ -227,6 +228,7 @@ export function applyChatSessionUpdatedToCache(
? {
...s,
title: payload.title ?? s.title,
+ ...("project_id" in payload ? { project_id: payload.project_id } : {}),
pinned: payload.pinned ?? s.pinned,
status: payload.status ?? s.status,
updated_at: payload.updated_at ?? s.updated_at,
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index ad38379a5a..c0a069ac63 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -31,6 +31,9 @@ export interface ChatSession {
workspace_id: string;
agent_id: string;
creator_id: string;
+ /** Durable project context for every turn in this session. Null when the
+ * conversation uses workspace context only; optional for older servers. */
+ project_id?: string | null;
title: string;
status: "active" | "archived";
/** True when the session has any unread assistant replies. List-only.
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index b0b17e8432..3ebe7567e1 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -149,6 +149,15 @@ export function ChatPage() {
setComposingNew(true);
};
+ const changeProjectContext = (projectId: string | null) => {
+ if (projectId === c.activeProjectId) return;
+ c.handleProjectChange(projectId);
+ // Removing a project stays in the current conversation. Choosing a
+ // project for an existing conversation starts a clean session, and mobile
+ // must remain in the compose pane after activeSessionId is cleared.
+ if (!c.currentSession || projectId !== null) 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
@@ -259,6 +268,10 @@ export function ChatPage() {
noAgent={c.noAgent}
agentArchived={c.isAgentArchived}
agentName={c.activeAgent?.name}
+ projects={c.projects}
+ projectId={c.activeProjectId}
+ onProjectChange={changeProjectContext}
+ isProjectUpdating={c.isProjectUpdating}
focusRequest={c.focusInputRequest}
/>
</div>
diff --git a/packages/views/chat/components/chat-add-menu.tsx b/packages/views/chat/components/chat-add-menu.tsx
index 064c6ce91e..a7e8371e4d 100644
--- a/packages/views/chat/components/chat-add-menu.tsx
+++ b/packages/views/chat/components/chat-add-menu.tsx
@@ -1,20 +1,29 @@
"use client";
import { useRef } from "react";
-import { Plus, Image as ImageIcon } from "lucide-react";
+import { Check, FolderKanban, Image as ImageIcon, Plus, X } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
+import type { Project } from "@multica/core/types";
+import { ProjectIcon } from "../../projects/components/project-icon";
import { useT } from "../../i18n";
interface ChatAddMenuProps {
/** Called with each selected file — the caller routes it through the
* editor's upload extension, same path as paste / drag-drop. */
- onSelectFile: (file: File) => void;
+ onSelectFile?: (file: File) => void;
+ projects?: Project[];
+ projectId?: string | null;
+ onSelectProject?: (projectId: string | null) => void;
disabled?: boolean;
}
@@ -24,7 +33,13 @@ interface ChatAddMenuProps {
* leaving room for future add-actions (agents, skills, tools) under one entry
* point without crowding the input bar.
*/
-export function ChatAddMenu({ onSelectFile, disabled }: ChatAddMenuProps) {
+export function ChatAddMenu({
+ onSelectFile,
+ projects = [],
+ projectId,
+ onSelectProject,
+ disabled,
+}: ChatAddMenuProps) {
const { t } = useT("chat");
const inputRef = useRef<HTMLInputElement>(null);
@@ -32,7 +47,7 @@ export function ChatAddMenu({ onSelectFile, disabled }: ChatAddMenuProps) {
const files = Array.from(e.target.files ?? []);
if (files.length === 0) return;
e.target.value = "";
- for (const file of files) onSelectFile(file);
+ for (const file of files) onSelectFile?.(file);
};
return (
@@ -54,19 +69,55 @@ export function ChatAddMenu({ onSelectFile, disabled }: ChatAddMenuProps) {
}
/>
<DropdownMenuContent align="start" side="top" sideOffset={6}>
- <DropdownMenuItem onClick={() => inputRef.current?.click()}>
- <ImageIcon />
- {t(($) => $.input.upload_file)}
- </DropdownMenuItem>
+ {onSelectFile && (
+ <DropdownMenuItem onClick={() => inputRef.current?.click()}>
+ <ImageIcon />
+ {t(($) => $.input.upload_file)}
+ </DropdownMenuItem>
+ )}
+ {onSelectProject && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <FolderKanban />
+ {t(($) => $.input.project_context)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 min-w-52 overflow-y-auto">
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ onClick={() => onSelectProject(project.id)}
+ >
+ <ProjectIcon project={project} size="md" />
+ <span className="min-w-0 flex-1 truncate">{project.title}</span>
+ {project.id === projectId && <Check className="ml-auto" />}
+ </DropdownMenuItem>
+ ))}
+ {projects.length === 0 && (
+ <div className="px-2 py-1.5 text-xs text-muted-foreground">
+ {t(($) => $.input.no_projects)}
+ </div>
+ )}
+ {projectId && <DropdownMenuSeparator />}
+ {projectId && (
+ <DropdownMenuItem onClick={() => onSelectProject(null)}>
+ <X />
+ {t(($) => $.input.remove_project_context)}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
</DropdownMenuContent>
</DropdownMenu>
- <input
- ref={inputRef}
- type="file"
- multiple
- className="hidden"
- onChange={handleChange}
- />
+ {onSelectFile && (
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={handleChange}
+ />
+ )}
</>
);
}
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index b5f7c2031c..2f51abdf6a 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -1,4 +1,4 @@
-import { forwardRef, useEffect, useRef, useImperativeHandle } from "react";
+import { cloneElement, forwardRef, useEffect, useRef, useImperativeHandle } from "react";
import { beforeEach, describe, it, expect, vi } from "vitest";
import { act, render, screen, fireEvent, waitFor } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -144,6 +144,33 @@ vi.mock("../../editor", async () => ({
}),
}));
+vi.mock("../../projects/components/project-picker", () => ({
+ ProjectPicker: ({
+ projectId,
+ onUpdate,
+ triggerRender,
+ disabled,
+ }: {
+ projectId: string;
+ onUpdate: (updates: { project_id: string | null }) => void;
+ triggerRender: React.ReactElement<{
+ onClick?: () => void;
+ children?: React.ReactNode;
+ "data-project-picker-disabled"?: string;
+ }>;
+ disabled?: boolean;
+ }) =>
+ // Surface the `disabled` prop ChatInput passes so a test can assert the
+ // shared picker (and thus its keyboard clear control) is locked mid-send.
+ // The real keyboard-inertness of that control is covered against the real
+ // ProjectPicker in project-picker.test.tsx.
+ cloneElement(triggerRender, {
+ onClick: () => onUpdate({ project_id: null }),
+ children: projectId,
+ "data-project-picker-disabled": disabled ? "true" : "false",
+ }),
+}));
+
// Mock chat store with an in-memory implementation that supports both
// (selector) calls and getState().
vi.mock("@multica/core/chat", () => {
@@ -372,6 +399,121 @@ describe("ChatInput @ context wiring", () => {
});
});
+describe("ChatInput project context", () => {
+ type ChatProject = NonNullable<
+ React.ComponentProps<typeof ChatInput>["projects"]
+ >[number];
+ const sampleProject: ChatProject = {
+ id: "project-alpha",
+ workspace_id: "ws-1",
+ title: "Project Alpha",
+ description: null,
+ icon: "📘",
+ status: "planned",
+ priority: "none",
+ lead_type: null,
+ lead_id: null,
+ start_date: null,
+ due_date: null,
+ created_at: new Date(0).toISOString(),
+ updated_at: new Date(0).toISOString(),
+ issue_count: 0,
+ done_count: 0,
+ resource_count: 0,
+ };
+
+ it("renders the selected project chip and forwards context changes", () => {
+ const onProjectChange = vi.fn();
+ renderInput({
+ projects: [sampleProject],
+ projectId: "project-alpha",
+ onProjectChange,
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "Change project context" }));
+
+ expect(onProjectChange).toHaveBeenCalledWith(null);
+ });
+
+ it("allows removing project context while the agent is running", () => {
+ const onProjectChange = vi.fn();
+ renderInput({
+ projects: [sampleProject],
+ projectId: "project-alpha",
+ onProjectChange,
+ isRunning: true,
+ });
+
+ const projectControl = screen.getByRole("button", {
+ name: "Change project context",
+ });
+ expect(projectControl).not.toBeDisabled();
+ fireEvent.click(projectControl);
+ expect(onProjectChange).toHaveBeenCalledWith(null);
+ });
+
+ it("locks the project control while a send is in flight so a mid-send switch cannot retarget the session", async () => {
+ // A brand-new chat creates its session row lazily during send, bound to
+ // the project selected at click time. If the user could switch project
+ // while that create is in flight, the session would be created against the
+ // old project while the UI already shows the new one — the agent would
+ // then receive a project/repo context the user no longer intends
+ // (MUL-5150). The control must stay locked for the whole send, not only
+ // once the agent is running.
+ let resolveSend: (accepted: boolean) => void;
+ const sendPromise = new Promise<boolean>((res) => {
+ resolveSend = res;
+ });
+ const onSend = vi.fn<ChatInputOnSend>(() => sendPromise);
+ const onProjectChange = vi.fn();
+ renderInput({
+ projects: [sampleProject],
+ projectId: "project-alpha",
+ onProjectChange,
+ onSend,
+ });
+
+ // Interactive before send starts.
+ expect(
+ screen.getByRole("button", { name: "Change project context" }),
+ ).not.toBeDisabled();
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "slow network" },
+ });
+ let sendBtn: HTMLElement;
+ await waitFor(() => {
+ const buttons = screen.getAllByRole("button");
+ sendBtn = buttons[buttons.length - 1]!;
+ expect(sendBtn).not.toBeDisabled();
+ });
+ fireEvent.click(sendBtn!);
+
+ // Send pending → project control locked; a click cannot fire a change.
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Change project context" }),
+ ).toBeDisabled(),
+ );
+ // ChatInput also propagates the lock to the shared ProjectPicker so its
+ // internal clear button (a keyboard-reachable path the wrapper's
+ // pointer-events-none does not cover) is disabled too. The clear control's
+ // keyboard-inertness itself is covered against the real ProjectPicker in
+ // project-picker.test.tsx.
+ expect(
+ screen.getByRole("button", { name: "Change project context" }),
+ ).toHaveAttribute("data-project-picker-disabled", "true");
+ fireEvent.click(screen.getByRole("button", { name: "Change project context" }));
+ expect(onProjectChange).not.toHaveBeenCalled();
+
+ // Resolve the pending send so the promise doesn't dangle past the test.
+ await act(async () => {
+ resolveSend!(true);
+ await sendPromise;
+ });
+ });
+});
+
describe("ChatInput attachment wiring", () => {
it("routes dropped files through the editor's upload handler", async () => {
const { onUploadFile } = renderInput();
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 5bfdfdb3d5..fdb8a50bc3 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -17,7 +17,8 @@ import { createLogger } from "@multica/core/logger";
import { formatShortcut, useShortcut } from "@multica/core/shortcuts";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import type { MentionItem } from "../../editor/extensions/mention-suggestion";
-import type { Attachment } from "@multica/core/types";
+import type { Attachment, Project } from "@multica/core/types";
+import { ProjectPicker } from "../../projects/components/project-picker";
import { useT } from "../../i18n";
const logger = createLogger("chat.ui");
@@ -95,6 +96,11 @@ interface ChatInputProps {
leftAdornment?: ReactNode;
/** Chat @ suggestions: current/recent issue/project entries. */
contextItems?: MentionItem[];
+ /** Optional project context for the draft or current chat session. */
+ projects?: Project[];
+ projectId?: string | null;
+ onProjectChange?: (projectId: string | null) => void;
+ isProjectUpdating?: boolean;
/** Monotonic nonce bumped by the owner whenever the compose box should grab
* keyboard focus — currently on "new chat" so the user can type right away.
* 0 (the initial value) is inert, so a plain deep-link open never steals
@@ -122,6 +128,10 @@ export function ChatInput({
agentName,
leftAdornment,
contextItems,
+ projects = [],
+ projectId,
+ onProjectChange,
+ isProjectUpdating,
focusRequest,
draftKeyOverride,
editorKeyOverride,
@@ -488,6 +498,16 @@ export function ChatInput({
: t(($) => $.input.placeholder_default);
const uploadEnabled = !!onUploadFile && !disabled && !noAgent;
+ // Lock only while the send request itself is creating/resolving the target
+ // session. Once accepted, its project can still be detached while agent work
+ // continues: changing session metadata does not cancel or move that task.
+ const projectSelectionEnabled =
+ !!onProjectChange &&
+ !disabled &&
+ !noAgent &&
+ !isSubmitting &&
+ !isProjectUpdating;
+ const selectedProject = projects.find((project) => project.id === projectId);
return (
<div
@@ -527,6 +547,31 @@ export function ChatInput({
)}
aria-disabled={noAgent || undefined}
>
+ {selectedProject && (
+ <div className="px-3 pt-2">
+ <div
+ className={cn(
+ "inline-flex max-w-full",
+ !projectSelectionEnabled && "pointer-events-none opacity-60",
+ )}
+ >
+ <ProjectPicker
+ projectId={selectedProject.id}
+ onUpdate={(updates) => onProjectChange?.(updates.project_id ?? null)}
+ disabled={!projectSelectionEnabled}
+ triggerRender={
+ <button
+ type="button"
+ disabled={!projectSelectionEnabled}
+ aria-label={t(($) => $.input.change_project_context)}
+ title={t(($) => $.input.change_project_context)}
+ className="flex h-6 max-w-56 items-center gap-1.5 rounded-full border border-surface-border bg-surface-raised px-2 pr-7 text-xs font-medium text-foreground transition-colors hover:bg-accent/60"
+ />
+ }
+ />
+ </div>
+ </div>
+ )}
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-2">
<ContentEditor
// See the editorKey / draftKey split note above — editor identity
@@ -559,11 +604,16 @@ export function ChatInput({
showBubbleMenu
/>
</div>
- {(uploadEnabled || leftAdornment) && (
+ {(uploadEnabled || projectSelectionEnabled || leftAdornment) && (
<div className="absolute bottom-1.5 left-1.5 flex items-center gap-1">
- {uploadEnabled && (
+ {(uploadEnabled || projectSelectionEnabled) && (
<ChatAddMenu
- onSelectFile={(file) => editorRef.current?.uploadFile(file)}
+ onSelectFile={uploadEnabled
+ ? (file) => editorRef.current?.uploadFile(file)
+ : undefined}
+ projects={projects}
+ projectId={projectId}
+ onSelectProject={projectSelectionEnabled ? onProjectChange : undefined}
/>
)}
{leftAdornment}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 133fa2ddef..18a25b3132 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -16,6 +16,7 @@ import { toast } from "sonner";
import { useWorkspaceId } from "@multica/core/hooks";
import { useAuthStore } from "@multica/core/auth";
import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { projectListOptions } from "@multica/core/projects/queries";
import { canAssignAgent } from "@multica/views/issues/components";
import { api } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
@@ -44,6 +45,7 @@ import {
useCreateChatSession,
useMarkChatSessionRead,
useSetChatSessionArchived,
+ useSetChatSessionProject,
useUpdateChatSession,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
@@ -54,7 +56,11 @@ import { ChatInput } from "./chat-input";
import { ChatResizeHandles } from "./chat-resize-handles";
import { useChatContextItems } from "./use-chat-context-items";
import { useChatResize } from "./use-chat-resize";
-import { hasOptimisticInFlight, isStillOnComposeTarget } from "./use-chat-controller";
+import {
+ hasOptimisticInFlight,
+ isStillOnComposeTarget,
+ planProjectContextChange,
+} from "./use-chat-controller";
import { createLogger } from "@multica/core/logger";
import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatPendingTask, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
import { useT } from "../../i18n";
@@ -137,9 +143,11 @@ export function ChatWindow() {
const isOpen = useChatStore((s) => s.isOpen);
const activeSessionId = useChatStore((s) => s.activeSessionId);
const selectedAgentId = useChatStore((s) => s.selectedAgentId);
+ const selectedProjectId = useChatStore((s) => s.selectedProjectId);
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 user = useAuthStore((s) => s.user);
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
@@ -148,6 +156,9 @@ export function ChatWindow() {
const { data: sessions = [], isSuccess: sessionsLoaded } = useQuery(
chatSessionsOptions(wsId),
);
+ const { data: projects = [], isSuccess: projectsLoaded } = useQuery(
+ projectListOptions(wsId),
+ );
const {
data: rawMessagePages,
isLoading: messagesLoading,
@@ -213,10 +224,24 @@ export function ChatWindow() {
? sessions.find((s) => s.id === activeSessionId)
: null;
const isSessionArchived = currentSession?.status === "archived";
+ const candidateProjectId = currentSession
+ ? currentSession.project_id ?? null
+ : selectedProjectId;
+ const activeProjectId = candidateProjectId &&
+ (!projectsLoaded || projects.some((project) => project.id === candidateProjectId))
+ ? candidateProjectId
+ : null;
+
+ useEffect(() => {
+ if (!projectsLoaded || !selectedProjectId) return;
+ if (projects.some((project) => project.id === selectedProjectId)) return;
+ setSelectedProjectId(null);
+ }, [projectsLoaded, projects, selectedProjectId, setSelectedProjectId]);
const qc = useQueryClient();
const createSession = useCreateChatSession();
const markRead = useMarkChatSessionRead();
+ const setSessionProject = useSetChatSessionProject();
const currentMember = members.find((m) => m.user_id === user?.id);
const memberRole = currentMember?.role;
@@ -367,6 +392,7 @@ export function ChatWindow() {
const session = await createSession.mutateAsync({
agent_id: activeAgent.id,
title: titleSeed.slice(0, 50),
+ project_id: activeProjectId,
});
return session.id;
} finally {
@@ -376,7 +402,15 @@ export function ChatWindow() {
sessionPromiseRef.current = promise;
return promise;
},
- [activeSessionId, activeAgent, createSession, sessions, sessionsLoaded, qc],
+ [
+ activeSessionId,
+ activeAgent,
+ activeProjectId,
+ createSession,
+ sessions,
+ sessionsLoaded,
+ qc,
+ ],
);
const handleUploadFile = useCallback(
@@ -643,11 +677,25 @@ export function ChatWindow() {
previousSessionId: activeSessionId,
});
setSelectedAgentId(agent.id);
+ // Preserve an explicitly chosen project while composing an unsent chat,
+ // but never inherit project context from the historical session being
+ // left behind.
+ setSelectedProjectId(currentSession ? null : activeProjectId);
// Reset session when switching agent
setActiveSession(null);
requestInputFocus();
},
- [activeAgent, selectedAgentId, activeSessionId, setSelectedAgentId, setActiveSession, requestInputFocus],
+ [
+ activeAgent,
+ selectedAgentId,
+ activeSessionId,
+ activeProjectId,
+ currentSession,
+ setSelectedAgentId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ],
);
const handleNewChat = useCallback(() => {
@@ -655,9 +703,16 @@ export function ChatWindow() {
previousSessionId: activeSessionId,
previousPendingTask: pendingTaskId,
});
+ setSelectedProjectId(null);
setActiveSession(null);
requestInputFocus();
- }, [activeSessionId, pendingTaskId, setActiveSession, requestInputFocus]);
+ }, [
+ activeSessionId,
+ pendingTaskId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ]);
const handleSelectSession = useCallback(
(session: ChatSession) => {
@@ -676,6 +731,47 @@ export function ChatWindow() {
[activeAgent, setSelectedAgentId, setActiveSession],
);
+ const handleProjectChange = useCallback(
+ (projectId: string | null) => {
+ if (projectId === activeProjectId) return;
+ uiLogger.info("selectProjectContext", {
+ from: activeProjectId,
+ to: projectId,
+ previousSessionId: activeSessionId,
+ });
+ const plan = planProjectContextChange({
+ targetProjectId: projectId,
+ activeSessionId,
+ currentSession: currentSession ?? null,
+ });
+ switch (plan.kind) {
+ case "awaitSession":
+ return;
+ case "detachCurrent":
+ setSessionProject.mutate({ sessionId: plan.sessionId, projectId: null });
+ break;
+ case "startFreshChat":
+ setSelectedAgentId(plan.agentId);
+ setSelectedProjectId(plan.projectId);
+ setActiveSession(null);
+ break;
+ case "setDraftProject":
+ setSelectedProjectId(plan.projectId);
+ break;
+ }
+ requestInputFocus();
+ }, [
+ activeProjectId,
+ activeSessionId,
+ currentSession,
+ setSessionProject,
+ setSelectedAgentId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ],
+ );
+
const handleMinimize = useCallback(() => {
uiLogger.info("minimize (close)", {
activeSessionId,
@@ -839,6 +935,12 @@ export function ChatWindow() {
noAgent={noAgent}
agentArchived={isAgentArchived}
agentName={activeAgent?.name}
+ projects={projects}
+ projectId={activeProjectId}
+ onProjectChange={handleProjectChange}
+ isProjectUpdating={
+ setSessionProject.isPending || (!!activeSessionId && !currentSession)
+ }
leftAdornment={
<AgentDropdown
agents={availableAgents}
diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.ts
index 96fa59b2d6..86c6bfc40f 100644
--- a/packages/views/chat/components/use-chat-controller.test.ts
+++ b/packages/views/chat/components/use-chat-controller.test.ts
@@ -2,7 +2,11 @@ import { describe, it, expect } from "vitest";
import { QueryClient, type InfiniteData } from "@tanstack/react-query";
import { chatKeys } from "@multica/core/chat/queries";
import type { ChatMessage, ChatMessagesPage, ChatPendingTask } from "@multica/core/types";
-import { hasOptimisticInFlight, isStillOnComposeTarget } from "./use-chat-controller";
+import {
+ hasOptimisticInFlight,
+ isStillOnComposeTarget,
+ planProjectContextChange,
+} from "./use-chat-controller";
// hasOptimisticInFlight is the discriminator the stale-session self-heal uses
// to EXEMPT a just-created session (awaiting the list refetch) from being
@@ -89,3 +93,58 @@ describe("isStillOnComposeTarget", () => {
expect(isStillOnComposeTarget(null, sid)).toBe(false);
});
});
+
+// The project-switch decision, shared by BOTH chat surfaces (the chat tab's
+// controller and the floating ChatWindow) so the stale-agent rule cannot drift.
+// Regression (MUL-5150 review): switching an existing session to another
+// project opens a fresh chat, and that chat MUST bind to the open session's
+// agent — not the stored `selectedAgentId`, which can be a stale preference for
+// a different agent (open session belongs to agent B while the persisted pick
+// is still agent A). Without pinning, the lazily-created session and its first
+// send would land on agent A.
+describe("planProjectContextChange", () => {
+ const sessionB = { id: "sB", agent_id: "agent-b" };
+
+ it("waits when an active session id is set but its row has not loaded yet", () => {
+ expect(
+ planProjectContextChange({
+ targetProjectId: "project-x",
+ activeSessionId: "sB",
+ currentSession: null,
+ }),
+ ).toEqual({ kind: "awaitSession" });
+ });
+
+ it("detaches in place when the current session's project is removed", () => {
+ expect(
+ planProjectContextChange({
+ targetProjectId: null,
+ activeSessionId: "sB",
+ currentSession: sessionB,
+ }),
+ ).toEqual({ kind: "detachCurrent", sessionId: "sB" });
+ });
+
+ it("starts a fresh chat pinned to the open session's agent, ignoring a stale selectedAgentId", () => {
+ // The stale `selectedAgentId` never reaches this function — the plan pins
+ // the fresh chat to the open session's agent by construction, which is
+ // exactly what stops the switch from binding to the wrong agent.
+ expect(
+ planProjectContextChange({
+ targetProjectId: "project-x",
+ activeSessionId: "sB",
+ currentSession: sessionB,
+ }),
+ ).toEqual({ kind: "startFreshChat", agentId: "agent-b", projectId: "project-x" });
+ });
+
+ it("only adjusts the new-chat draft project when there is no open session", () => {
+ expect(
+ planProjectContextChange({
+ targetProjectId: "project-x",
+ activeSessionId: null,
+ currentSession: null,
+ }),
+ ).toEqual({ kind: "setDraftProject", projectId: "project-x" });
+ });
+});
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index b471e62fcd..64a5f83d51 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
-import type { Agent, ChatSession } from "@multica/core/types";
+import type { Agent, ChatSession, Project } from "@multica/core/types";
interface QueuedRestore {
id: string;
@@ -14,12 +14,16 @@ const h = vi.hoisted(() => {
const store = {
activeSessionId: null as string | null,
selectedAgentId: null as string | null,
+ selectedProjectId: null as string | null,
setActiveSession: vi.fn((id: string | null) => {
store.activeSessionId = id;
}),
setSelectedAgentId: vi.fn((id: string | null) => {
store.selectedAgentId = id;
}),
+ setSelectedProjectId: vi.fn((id: string | null) => {
+ store.selectedProjectId = id;
+ }),
appliedDraftRestoreIds: [] as string[],
markDraftRestoreApplied: vi.fn((id: string) => {
if (!store.appliedDraftRestoreIds.includes(id)) {
@@ -59,10 +63,12 @@ const h = vi.hoisted(() => {
// Foreground gate for the auto mark-read effect; tests flip it.
appForeground: { value: true },
consumeRestoreMutate: vi.fn(),
+ setProjectMutate: vi.fn(),
removeFromCaches: vi.fn(),
// useQuery reads these so each test can vary the loaded data.
sessions: [] as ChatSession[],
agents: [] as Agent[],
+ projects: [] as Project[],
draftRestores: null as
| { restores: { id: string; chat_session_id: string; content: string }[] }
| null,
@@ -78,6 +84,9 @@ vi.mock("@multica/core/workspace/queries", () => ({
agentListOptions: () => ({ queryKey: ["agents"] }),
memberListOptions: () => ({ queryKey: ["members"] }),
}));
+vi.mock("@multica/core/projects/queries", () => ({
+ projectListOptions: () => ({ queryKey: ["projects"] }),
+}));
vi.mock("@multica/views/issues/components", () => ({ canAssignAgent: () => true }));
vi.mock("@multica/core/api", () => ({
api: { sendChatMessage: vi.fn(), cancelTaskById: vi.fn() },
@@ -96,6 +105,10 @@ vi.mock("@multica/core/chat/mutations", () => ({
useCreateChatSession: () => ({ mutateAsync: h.createSessionMutate }),
useMarkChatSessionRead: () => ({ mutate: h.markReadMutate }),
useSetChatSessionArchived: () => ({ mutate: h.archivedMutate }),
+ useSetChatSessionProject: () => ({
+ mutate: h.setProjectMutate,
+ isPending: false,
+ }),
useConsumeChatDraftRestore: () => ({ mutate: h.consumeRestoreMutate }),
}));
vi.mock("../../common/use-app-foreground", () => ({
@@ -127,6 +140,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
return { data: [{ user_id: "user-1", role: "admin" }] };
}
if (key.includes("sessions")) return { data: h.sessions, isSuccess: true };
+ if (key.includes("projects")) return { data: h.projects, isSuccess: true };
if (key.includes("draft-restores")) return { data: h.draftRestores };
return { data: null };
},
@@ -178,17 +192,232 @@ const sC = makeSession({ id: "sC", agent_id: "agent-a", updated_at: "2026-07-08T
function setup(activeSessionId: string | null, sessions: ChatSession[], agents: Agent[]) {
h.store.activeSessionId = activeSessionId;
h.store.selectedAgentId = null;
+ h.store.selectedProjectId = null;
h.sessions = sessions;
h.agents = agents;
+ h.projects = [];
const { result } = renderHook(() => useChatController());
// Ignore any render-time store writes (self-heal etc.); we assert only the
// effect of the call under test.
h.store.setActiveSession.mockClear();
h.store.setSelectedAgentId.mockClear();
+ h.store.setSelectedProjectId.mockClear();
h.archivedMutate.mockClear();
return result;
}
+describe("useChatController project context", () => {
+ const project = {
+ id: "project-a",
+ workspace_id: "ws-1",
+ title: "Project Alpha",
+ } as Project;
+ const otherProject = {
+ id: "project-b",
+ workspace_id: "ws-1",
+ title: "Project Beta",
+ } as Project;
+
+ beforeEach(() => {
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+ h.createSessionMutate.mockClear();
+ h.setProjectMutate.mockClear();
+ h.createSessionMutate.mockResolvedValue({ id: "new-session" });
+ });
+
+ afterEach(() => {
+ h.store.selectedProjectId = null;
+ h.projects = [];
+ });
+
+ it("removes the project from the current chat without leaving it", () => {
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: "agent-a",
+ project_id: project.id,
+ });
+ h.store.activeSessionId = projectSession.id;
+ h.store.selectedProjectId = project.id;
+ h.sessions = [projectSession];
+ h.agents = [agentA];
+ h.projects = [project];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleProjectChange(null));
+
+ expect(h.setProjectMutate).toHaveBeenCalledWith({
+ sessionId: projectSession.id,
+ projectId: null,
+ });
+ expect(h.store.setSelectedProjectId).not.toHaveBeenCalled();
+ expect(h.store.setActiveSession).not.toHaveBeenCalled();
+ });
+
+ it("starts a fresh chat when switching an existing chat to another project", () => {
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: "agent-a",
+ project_id: project.id,
+ });
+ h.store.activeSessionId = projectSession.id;
+ h.store.selectedProjectId = project.id;
+ h.sessions = [projectSession];
+ h.agents = [agentA];
+ h.projects = [project, otherProject];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleProjectChange(otherProject.id));
+
+ expect(h.setProjectMutate).not.toHaveBeenCalled();
+ expect(h.store.setSelectedProjectId).toHaveBeenCalledWith(otherProject.id);
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(null);
+ });
+
+ it("pins the fresh chat to the open session's agent when selectedAgentId is stale", () => {
+ // The open session belongs to agent B, but the persisted preference is
+ // still agent A. Switching to another project clears the active session,
+ // which would otherwise drop selection back to the stale agent A and send
+ // the lazily-created chat to the wrong agent (MUL-5150 regression). The
+ // switch must first sync selectedAgentId to the open session's agent.
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: agentB.id,
+ project_id: project.id,
+ });
+ h.store.activeSessionId = projectSession.id;
+ h.store.selectedAgentId = agentA.id; // stale preference for a different agent
+ h.store.selectedProjectId = project.id;
+ h.sessions = [projectSession];
+ h.agents = [agentA, agentB];
+ h.projects = [project, otherProject];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedAgentId.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleProjectChange(otherProject.id));
+
+ expect(h.store.setSelectedAgentId).toHaveBeenCalledWith(agentB.id);
+ expect(h.store.setSelectedProjectId).toHaveBeenCalledWith(otherProject.id);
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(null);
+ });
+
+ it("does not write project changes into the new-chat draft while an active session resolves", () => {
+ h.store.activeSessionId = "loading-session";
+ h.store.selectedProjectId = project.id;
+ h.sessions = [];
+ h.agents = [agentA];
+ h.projects = [project];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleProjectChange(null));
+
+ expect(h.setProjectMutate).not.toHaveBeenCalled();
+ expect(h.store.setSelectedProjectId).not.toHaveBeenCalled();
+ expect(h.store.setActiveSession).not.toHaveBeenCalled();
+ });
+
+ it("persists the selected project when lazy-creating a session", async () => {
+ h.store.activeSessionId = null;
+ h.store.selectedAgentId = agentA.id;
+ h.store.selectedProjectId = project.id;
+ h.sessions = [];
+ h.agents = [agentA];
+ h.projects = [project];
+ vi.mocked(api.sendChatMessage).mockResolvedValue({
+ message_id: "message-1",
+ task_id: "task-1",
+ created_at: new Date(0).toISOString(),
+ } as Awaited<ReturnType<typeof api.sendChatMessage>>);
+
+ const { result } = renderHook(() => useChatController());
+ await act(async () => {
+ await result.current.handleSend("hello", undefined, vi.fn());
+ });
+
+ expect(h.createSessionMutate).toHaveBeenCalledWith(
+ expect.objectContaining({ project_id: project.id }),
+ );
+ });
+
+ it("does not inherit the current session project when starting a new chat", () => {
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: "agent-a",
+ project_id: project.id,
+ });
+ h.store.activeSessionId = projectSession.id;
+ h.store.selectedProjectId = project.id;
+ h.sessions = [projectSession];
+ h.agents = [agentA, agentB];
+ h.projects = [project];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleStartNewChat(agentB));
+
+ expect(h.store.setSelectedProjectId).toHaveBeenCalledWith(null);
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(null);
+ });
+
+ it("clears the current session project when using the plain new-chat action", () => {
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: "agent-a",
+ project_id: project.id,
+ });
+ h.store.activeSessionId = projectSession.id;
+ h.store.selectedProjectId = project.id;
+ h.sessions = [projectSession];
+ h.agents = [agentA];
+ h.projects = [project];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleNewChat());
+
+ expect(h.store.setSelectedProjectId).toHaveBeenCalledWith(null);
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(null);
+ });
+
+ it("keeps a historical session project out of the next-chat draft state", () => {
+ const projectSession = makeSession({
+ id: "project-session",
+ agent_id: "agent-a",
+ project_id: project.id,
+ });
+ h.store.activeSessionId = null;
+ h.store.selectedProjectId = null;
+ h.sessions = [projectSession];
+ h.agents = [agentA];
+ h.projects = [project];
+
+ const { result } = renderHook(() => useChatController());
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedProjectId.mockClear();
+
+ act(() => result.current.handleSelectSession(projectSession));
+
+ expect(h.store.setSelectedProjectId).not.toHaveBeenCalled();
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(projectSession.id);
+ });
+});
+
describe("useChatController.advanceSelectionAfterArchive", () => {
beforeEach(() => {
h.store.setActiveSession.mockClear();
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 76520ce4ed..5cee60514a 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -11,6 +11,7 @@ import { toast } from "sonner";
import { useWorkspaceId } from "@multica/core/hooks";
import { useAuthStore } from "@multica/core/auth";
import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { projectListOptions } from "@multica/core/projects/queries";
import { canAssignAgent } from "@multica/views/issues/components";
import { api, dispatchReasonCode } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
@@ -28,6 +29,7 @@ import {
import {
useCreateChatSession,
useMarkChatSessionRead,
+ useSetChatSessionProject,
useSetChatSessionArchived,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
@@ -86,6 +88,51 @@ export function isStillOnComposeTarget(
return liveActiveSessionId === sentFromSessionId;
}
+/**
+ * Decide what a project-context change should do, given the open session.
+ *
+ * - `awaitSession`: an active session id is set but its row has not loaded
+ * yet. Bail so a persisted selection resolving before its sessions query
+ * cannot misfile a project change into the new-chat draft.
+ * - `detachCurrent`: removing context from the open session — safe in place,
+ * it only changes what future turns receive.
+ * - `startFreshChat`: switching to a DIFFERENT project. A fresh chat is
+ * started so the old project's provider memory / reused workdir cannot
+ * bleed in. It must stay bound to the agent whose session we are leaving
+ * (`agentId`): clearing the active session otherwise drops selection back
+ * to the stored `selectedAgentId`, which can be a stale preference for a
+ * different agent, sending the lazily-created session to the wrong agent.
+ * - `setDraftProject`: no open session, so this only adjusts the new-chat
+ * draft's project.
+ *
+ * Shared by both send chains — the chat tab's controller and the floating
+ * ChatWindow — so the stale-agent rule cannot drift between the two surfaces.
+ */
+export type ProjectContextChange =
+ | { kind: "awaitSession" }
+ | { kind: "detachCurrent"; sessionId: string }
+ | { kind: "startFreshChat"; agentId: string; projectId: string }
+ | { kind: "setDraftProject"; projectId: string | null };
+
+export function planProjectContextChange(input: {
+ targetProjectId: string | null;
+ activeSessionId: string | null;
+ currentSession: { id: string; agent_id: string } | null;
+}): ProjectContextChange {
+ if (input.activeSessionId) {
+ if (!input.currentSession) return { kind: "awaitSession" };
+ if (input.targetProjectId === null) {
+ return { kind: "detachCurrent", sessionId: input.currentSession.id };
+ }
+ return {
+ kind: "startFreshChat",
+ agentId: input.currentSession.agent_id,
+ projectId: input.targetProjectId,
+ };
+ }
+ return { kind: "setDraftProject", projectId: input.targetProjectId };
+}
+
// True when a session has an in-flight optimistic write — an `optimistic-`
// message or a pending task in the cache. That is the signal of a just-created
// (or actively-sending) session still awaiting server confirmation, before the
@@ -195,8 +242,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
const wsId = useWorkspaceId();
const activeSessionId = useChatStore((s) => s.activeSessionId);
const selectedAgentId = useChatStore((s) => s.selectedAgentId);
+ const selectedProjectId = useChatStore((s) => s.selectedProjectId);
const setActiveSession = useChatStore((s) => s.setActiveSession);
const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);
+ const setSelectedProjectId = useChatStore((s) => s.setSelectedProjectId);
const user = useAuthStore((s) => s.user);
const { data: agents = [], isSuccess: agentsLoaded } = useQuery(
agentListOptions(wsId),
@@ -207,6 +256,9 @@ export function useChatController(opts?: { isActive?: boolean }) {
const { data: sessions = [], isSuccess: sessionsLoaded } = useQuery(
chatSessionsOptions(wsId),
);
+ const { data: projects = [], isSuccess: projectsLoaded } = useQuery(
+ projectListOptions(wsId),
+ );
const {
data: rawMessagePages,
isLoading: messagesLoading,
@@ -256,10 +308,28 @@ export function useChatController(opts?: { isActive?: boolean }) {
? sessions.find((s) => s.id === activeSessionId)
: null;
const isSessionArchived = currentSession?.status === "archived";
+ const candidateProjectId = currentSession
+ ? currentSession.project_id ?? null
+ : selectedProjectId;
+ const activeProjectId = candidateProjectId &&
+ (!projectsLoaded || projects.some((project) => project.id === candidateProjectId))
+ ? candidateProjectId
+ : null;
+
+ // A project may be deleted on another client while this workspace's next
+ // chat preference is still persisted locally. Normalize it as soon as the
+ // authoritative project list settles so a future send cannot carry a stale
+ // selection.
+ useEffect(() => {
+ if (!projectsLoaded || !selectedProjectId) return;
+ if (projects.some((project) => project.id === selectedProjectId)) return;
+ setSelectedProjectId(null);
+ }, [projectsLoaded, projects, selectedProjectId, setSelectedProjectId]);
const qc = useQueryClient();
const createSession = useCreateChatSession();
const markRead = useMarkChatSessionRead();
+ const setSessionProject = useSetChatSessionProject();
const setArchived = useSetChatSessionArchived();
const currentMember = members.find((m) => m.user_id === user?.id);
@@ -363,6 +433,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
const session = await createSession.mutateAsync({
agent_id: activeAgent.id,
title: deriveChatTitle(titleSeed),
+ project_id: activeProjectId,
});
return session.id;
} finally {
@@ -372,7 +443,15 @@ export function useChatController(opts?: { isActive?: boolean }) {
sessionPromiseRef.current = promise;
return promise;
},
- [activeSessionId, activeAgent, createSession, sessions, sessionsLoaded, qc],
+ [
+ activeSessionId,
+ activeAgent,
+ activeProjectId,
+ createSession,
+ sessions,
+ sessionsLoaded,
+ qc,
+ ],
);
// Self-heal a dangling `activeSessionId`. Once the sessions list has loaded
@@ -626,9 +705,19 @@ export function useChatController(opts?: { isActive?: boolean }) {
previousSessionId: activeSessionId,
previousPendingTask: pendingTaskId,
});
+ // A fresh chat has no project unless the user explicitly chooses one.
+ // The open session's project is server-owned history, not a default for
+ // the next session.
+ setSelectedProjectId(null);
setActiveSession(null);
requestInputFocus();
- }, [activeSessionId, pendingTaskId, setActiveSession, requestInputFocus]);
+ }, [
+ activeSessionId,
+ pendingTaskId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ]);
// Start a fresh chat bound to a chosen agent. Unlike handleSelectAgent this
// does not no-op when the agent is unchanged — "new chat" always clears the
@@ -641,14 +730,21 @@ export function useChatController(opts?: { isActive?: boolean }) {
previousSessionId: activeSessionId,
});
setSelectedAgentId(agent.id);
+ setSelectedProjectId(null);
setActiveSession(null);
requestInputFocus();
},
- [activeSessionId, setSelectedAgentId, setActiveSession, requestInputFocus],
+ [
+ activeSessionId,
+ setSelectedAgentId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ],
);
const handleSelectSession = useCallback(
- (session: { id: string; agent_id: string }) => {
+ (session: { id: string; agent_id: string; project_id?: string | null }) => {
// Sessions are bound 1:1 to an agent — picking a session from a
// different agent implicitly switches the agent too.
if (activeAgent && session.agent_id !== activeAgent.id) {
@@ -664,6 +760,47 @@ export function useChatController(opts?: { isActive?: boolean }) {
[activeAgent, setSelectedAgentId, setActiveSession],
);
+ const handleProjectChange = useCallback(
+ (projectId: string | null) => {
+ if (projectId === activeProjectId) return;
+ uiLogger.info("selectProjectContext", {
+ from: activeProjectId,
+ to: projectId,
+ previousSessionId: activeSessionId,
+ });
+ const plan = planProjectContextChange({
+ targetProjectId: projectId,
+ activeSessionId,
+ currentSession: currentSession ?? null,
+ });
+ switch (plan.kind) {
+ case "awaitSession":
+ return;
+ case "detachCurrent":
+ setSessionProject.mutate({ sessionId: plan.sessionId, projectId: null });
+ break;
+ case "startFreshChat":
+ setSelectedAgentId(plan.agentId);
+ setSelectedProjectId(plan.projectId);
+ setActiveSession(null);
+ break;
+ case "setDraftProject":
+ setSelectedProjectId(plan.projectId);
+ break;
+ }
+ requestInputFocus();
+ }, [
+ activeProjectId,
+ activeSessionId,
+ currentSession,
+ setSessionProject,
+ setSelectedAgentId,
+ setSelectedProjectId,
+ setActiveSession,
+ requestInputFocus,
+ ],
+ );
+
// Archiving the chat currently in view would otherwise strand the
// conversation pane on a now read-only, "dangling" session. Mirror the Inbox
// list: advance selection to the next chat in the (sorted, non-archived)
@@ -701,8 +838,12 @@ export function useChatController(opts?: { isActive?: boolean }) {
availableAgents,
agentsSettled,
sessions,
+ projects,
activeSessionId,
selectedAgentId,
+ activeProjectId,
+ isProjectUpdating:
+ setSessionProject.isPending || (!!activeSessionId && !currentSession),
currentSession,
isSessionArchived,
isAgentArchived,
@@ -731,6 +872,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
handleNewChat,
handleStartNewChat,
handleSelectSession,
+ handleProjectChange,
advanceSelectionAfterArchive,
archiveSession,
// store setters (for surfaces that sync selection to the URL, etc.)
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 5b7f268fa7..b326f94ed9 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -22,7 +22,11 @@
"send_blocked_toast": "Message not sent — you no longer have permission to use this agent",
"attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment.",
"add_tooltip": "Add",
- "upload_file": "Image or files"
+ "upload_file": "Image or files",
+ "project_context": "Project context",
+ "change_project_context": "Change project context",
+ "remove_project_context": "Remove project context",
+ "no_projects": "No projects yet"
},
"message_list": {
"show_details": "Show details",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 75f3277b5f..4569c60e46 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -21,7 +21,11 @@
"send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
"attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。",
"add_tooltip": "追加",
- "upload_file": "画像・ファイル"
+ "upload_file": "画像・ファイル",
+ "project_context": "プロジェクトコンテキスト",
+ "change_project_context": "プロジェクトコンテキストを変更",
+ "remove_project_context": "プロジェクトコンテキストを削除",
+ "no_projects": "プロジェクトがまだありません"
},
"message_list": {
"show_details": "詳細を表示",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index aaed57e118..c63f0e3fb8 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -21,7 +21,11 @@
"send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
"attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요.",
"add_tooltip": "추가",
- "upload_file": "이미지 또는 파일"
+ "upload_file": "이미지 또는 파일",
+ "project_context": "프로젝트 컨텍스트",
+ "change_project_context": "프로젝트 컨텍스트 변경",
+ "remove_project_context": "프로젝트 컨텍스트 제거",
+ "no_projects": "아직 프로젝트가 없습니다"
},
"message_list": {
"show_details": "세부 정보 보기",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 640def09fa..e59a675223 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -21,7 +21,11 @@
"send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
"attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。",
"add_tooltip": "添加",
- "upload_file": "图片或文件"
+ "upload_file": "图片或文件",
+ "project_context": "项目上下文",
+ "change_project_context": "更改项目上下文",
+ "remove_project_context": "移除项目上下文",
+ "no_projects": "还没有项目"
},
"message_list": {
"show_details": "查看详情",
diff --git a/packages/views/projects/components/project-picker.test.tsx b/packages/views/projects/components/project-picker.test.tsx
index 63a397bead..aefd3d5879 100644
--- a/packages/views/projects/components/project-picker.test.tsx
+++ b/packages/views/projects/components/project-picker.test.tsx
@@ -1,6 +1,6 @@
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
import enProjects from "../../locales/en/projects.json";
@@ -58,8 +58,78 @@ describe("ProjectPicker", () => {
.find((button) => button.className.includes("group-hover/project:opacity-100"));
expect(clear).toBeDefined();
expect(clear!.className).toContain("group-hover/project:opacity-100");
+ expect(clear!.className).toContain("size-3.5");
+ expect(clear!.className).toContain("hover:bg-muted-foreground/20");
+ expect(clear!.className).not.toContain("bg-background/95");
+ expect(clear!.className).not.toContain("inset-y-0");
+ expect(clear!.className).not.toContain("w-7");
await user.click(clear!);
expect(onUpdate).toHaveBeenCalledWith({ project_id: null });
});
+
+ it("clears via keyboard activation when enabled", async () => {
+ // Other callers (issue/create/autopilot) rely on the clear control staying
+ // reachable by keyboard, not just hover. Enabling must not regress that.
+ const user = userEvent.setup();
+ const onUpdate = vi.fn();
+
+ render(
+ <I18nProvider locale="en" resources={{ en: { projects: enProjects } }}>
+ <ProjectPicker
+ projectId="project-1"
+ onUpdate={onUpdate}
+ triggerRender={<PillButton />}
+ />
+ </I18nProvider>,
+ );
+
+ const clear = screen
+ .getAllByRole("button", { name: "Remove from project" })
+ .find((button) => button.className.includes("group-hover/project:opacity-100"));
+ expect(clear).toBeDefined();
+ expect(clear).not.toBeDisabled();
+
+ clear!.focus();
+ expect(clear).toHaveFocus();
+ await user.keyboard("{Enter}");
+ expect(onUpdate).toHaveBeenCalledWith({ project_id: null });
+ });
+
+ it("locks the inline clear control against pointer and keyboard when disabled", () => {
+ // Regression (MUL-5150): the outer wrapper's `pointer-events-none` only
+ // blocks the mouse. The inline clear button stayed in the tab order, so a
+ // keyboard user could Tab to it and press Enter to detach the project while
+ // a chat send was in flight — retargeting the lazily-created session. The
+ // explicit `disabled` capability must remove it from the tab order and make
+ // both pointer and keyboard activation inert.
+ const onUpdate = vi.fn();
+
+ render(
+ <I18nProvider locale="en" resources={{ en: { projects: enProjects } }}>
+ <ProjectPicker
+ projectId="project-1"
+ onUpdate={onUpdate}
+ disabled
+ triggerRender={<PillButton />}
+ />
+ </I18nProvider>,
+ );
+
+ const clear = screen
+ .getAllByRole("button", { name: "Remove from project" })
+ .find((button) => button.className.includes("group-hover/project:opacity-100"));
+ expect(clear).toBeDefined();
+ expect(clear).toBeDisabled();
+
+ // A disabled control cannot receive focus, so it is not tabbable.
+ clear!.focus();
+ expect(clear).not.toHaveFocus();
+
+ // Neither keyboard activation nor a direct click may mutate the selection.
+ fireEvent.keyDown(clear!, { key: "Enter" });
+ fireEvent.keyDown(clear!, { key: " " });
+ fireEvent.click(clear!);
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/views/projects/components/project-picker.tsx b/packages/views/projects/components/project-picker.tsx
index 5096229a0e..253874f848 100644
--- a/packages/views/projects/components/project-picker.tsx
+++ b/packages/views/projects/components/project-picker.tsx
@@ -6,6 +6,7 @@ import { useQuery } from "@tanstack/react-query";
import { projectListOptions } from "@multica/core/projects/queries";
import { useWorkspaceId } from "@multica/core/hooks";
import type { UpdateIssueRequest } from "@multica/core/types";
+import { cn } from "@multica/ui/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
@@ -24,6 +25,7 @@ export function ProjectPicker({
defaultOpen = false,
open: controlledOpen,
onOpenChange,
+ disabled = false,
}: {
projectId: string | null;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
@@ -34,6 +36,13 @@ export function ProjectPicker({
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
+ /** Read-only lock. When true the trigger, the menu, and the inline clear
+ * button are all disabled and out of the tab order, so no project-context
+ * mutation can fire — pointer OR keyboard. Callers that must freeze the
+ * selection during a transient window (an in-flight chat send) pass this;
+ * every other caller keeps the default hover/keyboard clear behavior since
+ * it defaults to false. */
+ disabled?: boolean;
}) {
const { t } = useT("projects");
const wsId = useWorkspaceId();
@@ -45,14 +54,23 @@ export function ProjectPicker({
// callers wiring `open={cond ? true : undefined}` (create-issue dialog)
// would leave the popup stuck open after selecting a project.
const [internalOpen, setInternalOpen] = useState(defaultOpen);
- const open = controlledOpen ?? internalOpen;
- const setOpen = onOpenChange ?? setInternalOpen;
+ // A disabled picker can never be open, and no interaction may reopen it.
+ const open = disabled ? false : controlledOpen ?? internalOpen;
+ const setOpen = disabled ? () => {} : onOpenChange ?? setInternalOpen;
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<div className="group/project relative inline-flex min-w-0">
<DropdownMenuTrigger
- className={triggerRender ? undefined : "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden"}
+ disabled={disabled}
+ className={
+ triggerRender
+ ? undefined
+ : cn(
+ "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden",
+ current && "pr-5",
+ )
+ }
render={triggerRender}
>
{current ? (
@@ -65,15 +83,16 @@ export function ProjectPicker({
{current && (
<button
type="button"
+ disabled={disabled}
aria-label={t(($) => $.picker.remove)}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onUpdate({ project_id: null });
}}
- className="pointer-events-none absolute inset-y-0 right-0 flex w-7 items-center justify-center rounded-r-full bg-background/95 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover/project:pointer-events-auto group-hover/project:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100"
+ className="pointer-events-none absolute right-1 top-1/2 flex size-3.5 -translate-y-1/2 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-[background-color,color,opacity] hover:bg-muted-foreground/20 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none group-hover/project:pointer-events-auto group-hover/project:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 disabled:pointer-events-none disabled:opacity-0 disabled:group-hover/project:opacity-0"
>
- <X className="size-3" />
+ <X className="size-2.5" />
</button>
)}
</div>
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index ab3ef32bdc..96f3ddb597 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -120,7 +120,7 @@ type TaskContextForEnv struct {
AgentSkills []SkillContextForEnv
DisabledRuntimeSkills []RuntimeSkillRefForEnv
Repos []RepoContextForEnv // workspace repos available for checkout
- ProjectID string // issue's project, when present
+ ProjectID string // active project for this task, when present
ProjectTitle string // human-readable project title
ProjectDescription string // durable project-level context, rendered into the brief's Project Context section
ProjectResources []ProjectResourceForEnv // resources attached to the project
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index 67200ab567..f740c7a982 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -250,6 +250,65 @@ func TestPrepareWithProjectResources(t *testing.T) {
}
}
+func TestChatProjectContextInjectedIntoRuntimeBrief(t *testing.T) {
+ t.Parallel()
+
+ ctx := TaskContextForEnv{
+ ChatSessionID: "chat-project-context",
+ ProjectID: "22222222-3333-4444-5555-666666666666",
+ ProjectTitle: "Project Beta",
+ ProjectDescription: "Use the beta repository and follow the beta rollout plan.",
+ ProjectResources: []ProjectResourceForEnv{
+ {
+ ID: "33333333-4444-5555-6666-777777777777",
+ ResourceType: "github_repo",
+ ResourceRef: json.RawMessage(`{"url":"https://github.com/org/beta"}`),
+ },
+ },
+ }
+
+ for _, tc := range []struct {
+ provider string
+ filename string
+ }{
+ {provider: "claude", filename: "CLAUDE.md"},
+ {provider: "codex", filename: "AGENTS.md"},
+ } {
+ tc := tc
+ t.Run(tc.provider, func(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ if _, err := InjectRuntimeConfig(dir, tc.provider, ctx); err != nil {
+ t.Fatalf("InjectRuntimeConfig: %v", err)
+ }
+ content, err := os.ReadFile(filepath.Join(dir, tc.filename))
+ if err != nil {
+ t.Fatalf("read %s: %v", tc.filename, err)
+ }
+ s := string(content)
+ for _, want := range []string{
+ "## Project Context",
+ "Project Beta",
+ "Use the beta repository and follow the beta rollout plan.",
+ "https://github.com/org/beta",
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("%s missing chat project context %q", tc.filename, want)
+ }
+ }
+ for _, banned := range []string{
+ "This issue belongs to",
+ "## Issue Metadata",
+ "## Sub-issue Creation",
+ } {
+ if strings.Contains(s, banned) {
+ t.Errorf("%s chat brief contains issue-only text %q", tc.filename, banned)
+ }
+ }
+ })
+ }
+}
+
// When the issue's project has its own github_repo resources, those should be
// the only repos rendered in the meta-skill — workspace-level repos must not
// leak into the agent prompt to avoid confusing it about which repo to use.
diff --git a/server/internal/daemon/execenv/runtime_config_kind.go b/server/internal/daemon/execenv/runtime_config_kind.go
index 00d3d378d9..435ecbc6aa 100644
--- a/server/internal/daemon/execenv/runtime_config_kind.go
+++ b/server/internal/daemon/execenv/runtime_config_kind.go
@@ -49,13 +49,12 @@ func classifyTask(ctx TaskContextForEnv) taskKind {
// hasIssueContext returns true for the kinds that operate on a real Multica
// issue and therefore can read / pin issue-scoped state. The slim
-// dispatcher gates these three sections on this predicate:
+// dispatcher gates these two sections on this predicate:
//
-// - Project Context
// - Issue Metadata
// - Sub-issue Creation
//
-// All three are meaningless on the issue-less kinds (chat / quick-create /
+// Both are meaningless on the issue-less kinds (chat / quick-create /
// autopilot run-only) and would either render an empty body or steer the
// agent into a guaranteed-failed CLI call. Note this is a kind-based
// predicate, not a check on ctx.IssueID — comment- / assignment-triggered
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index dca5ea4a6e..c0d2201017 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -285,18 +285,20 @@ func writeRepositories(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("\n")
}
-// writeProjectContext emits the Project Context section when the issue
-// belongs to a project.
+// writeProjectContext emits the Project Context section when the task carries
+// an active project. Project context is independent of the task surface: an
+// issue inherits it from its project, while a chat receives it from the
+// project selected on the chat session.
func writeProjectContext(b *strings.Builder, ctx TaskContextForEnv) {
if ctx.ProjectID == "" && len(ctx.ProjectResources) == 0 {
return
}
b.WriteString("## Project Context\n\n")
if ctx.ProjectTitle != "" {
- fmt.Fprintf(b, "This issue belongs to **%s**.\n\n", ctx.ProjectTitle)
+ fmt.Fprintf(b, "The active project for this task is **%s**.\n\n", ctx.ProjectTitle)
}
if desc := strings.TrimSpace(ctx.ProjectDescription); desc != "" {
- b.WriteString("Project description — durable context the project owner set for every task in this project:\n\n")
+ b.WriteString("Project description — durable context the project owner set for work in this project:\n\n")
b.WriteString(desc)
b.WriteString("\n\n")
}
@@ -623,7 +625,7 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
// Available Commands | full | full | full | minimal | full
// Comment Formatting | ✓ | ✓ | — | — | —
// Repositories | △ | △ | △ | — | △
-// Project Context | △ | △ | — | — | —
+// Project Context | △ | △ | △ | △ | △
// Issue Metadata | ✓ | ✓ | — | — | —
// Instruction Precedence| — | ✓ | — | — | —
// Sub-issue Creation | ✓ | ✓ | — | — | —
@@ -663,8 +665,9 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {
writeRepositories(&b, ctx)
}
+ writeProjectContext(&b, ctx)
+
if kind.hasIssueContext() {
- writeProjectContext(&b, ctx)
writeIssueMetadata(&b)
}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 0b4da92ad1..54a1fcb234 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -71,7 +71,7 @@ type Task struct {
Agent *AgentData `json:"agent,omitempty"`
ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // per-run app capabilities mounted through runtime MCP overlays
Repos []RepoData `json:"repos,omitempty"`
- ProjectID string `json:"project_id,omitempty"` // issue's project, when present
+ ProjectID string `json:"project_id,omitempty"` // active project for this task, when present
ProjectTitle string `json:"project_title,omitempty"` // human-readable project title for context injection
ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the brief
ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // project-scoped resources to expose to the agent
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 26458a6122..0a5ce898df 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -31,8 +31,9 @@ const chatSessionTitleMaxLen = 200
// ---------------------------------------------------------------------------
type CreateChatSessionRequest struct {
- AgentID string `json:"agent_id"`
- Title string `json:"title"`
+ AgentID string `json:"agent_id"`
+ Title string `json:"title"`
+ ProjectID *string `json:"project_id"`
}
func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
@@ -59,6 +60,13 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ projectID := pgtype.UUID{Valid: false}
+ if req.ProjectID != nil && strings.TrimSpace(*req.ProjectID) != "" {
+ projectID, ok = parseUUIDOrBadRequest(w, strings.TrimSpace(*req.ProjectID), "project_id")
+ if !ok {
+ return
+ }
+ }
// Verify agent exists in workspace.
agent, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{
@@ -103,12 +111,26 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to lock workspace")
return
}
+ if projectID.Valid {
+ if _, err := qtx.LockProjectForChatSessionCreate(r.Context(), db.LockProjectForChatSessionCreateParams{
+ ID: projectID,
+ WorkspaceID: workspaceUUID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock project")
+ return
+ }
+ }
session, err := qtx.CreateChatSession(r.Context(), db.CreateChatSessionParams{
WorkspaceID: workspaceUUID,
AgentID: agentID,
CreatorID: parseUUID(userID),
Title: req.Title,
+ ProjectID: projectID,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create chat session")
@@ -171,6 +193,7 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
WorkspaceID: uuidToString(s.WorkspaceID),
AgentID: uuidToString(s.AgentID),
CreatorID: uuidToString(s.CreatorID),
+ ProjectID: uuidToPtr(s.ProjectID),
Title: s.Title,
Status: s.Status,
HasUnread: s.UnreadCount > 0,
@@ -200,6 +223,7 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
WorkspaceID: uuidToString(s.WorkspaceID),
AgentID: uuidToString(s.AgentID),
CreatorID: uuidToString(s.CreatorID),
+ ProjectID: uuidToPtr(s.ProjectID),
Title: s.Title,
Status: s.Status,
HasUnread: s.UnreadCount > 0,
@@ -278,15 +302,15 @@ func (h *Handler) GetChatSession(w http.ResponseWriter, r *http.Request) {
}
type UpdateChatSessionRequest struct {
- Title *string `json:"title"`
+ Title *string `json:"title"`
+ ProjectID json.RawMessage `json:"project_id"`
}
-// UpdateChatSession updates user-editable fields on a chat session — today
-// just `title`, surfaced by the inline rename affordance in the session
-// dropdown. Title is the only field accepted here: `status` has its own
-// archive/unarchive endpoint (SetChatSessionArchived), `pinned` its own pin
-// endpoint, agent/creator/workspace are immutable, the resume pointers
-// (session_id / work_dir / runtime_id) are daemon-owned.
+// UpdateChatSession updates one user-editable field on a chat session. Title
+// is surfaced by inline rename; project_id controls the project context used
+// by subsequent turns. Status and pinned keep their dedicated endpoints,
+// agent/creator/workspace are immutable, and the resume pointers
+// (session_id / work_dir / runtime_id) remain daemon-owned.
func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -300,17 +324,10 @@ func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
- if req.Title == nil {
- writeError(w, http.StatusBadRequest, "title is required")
- return
- }
- title := strings.TrimSpace(*req.Title)
- if title == "" {
- writeError(w, http.StatusBadRequest, "title is required")
- return
- }
- if len([]rune(title)) > chatSessionTitleMaxLen {
- writeError(w, http.StatusBadRequest, "title is too long")
+ hasTitle := req.Title != nil
+ hasProjectID := req.ProjectID != nil
+ if hasTitle == hasProjectID {
+ writeError(w, http.StatusBadRequest, "exactly one of title or project_id is required")
return
}
@@ -319,21 +336,92 @@ func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {
return
}
- updated, err := h.Queries.UpdateChatSessionTitle(r.Context(), db.UpdateChatSessionTitleParams{
- ID: session.ID,
- Title: title,
- })
+ var (
+ updated db.ChatSession
+ err error
+ )
+ var projectIDChanged bool
+ if hasTitle {
+ title := strings.TrimSpace(*req.Title)
+ if title == "" {
+ writeError(w, http.StatusBadRequest, "title is required")
+ return
+ }
+ if len([]rune(title)) > chatSessionTitleMaxLen {
+ writeError(w, http.StatusBadRequest, "title is too long")
+ return
+ }
+ updated, err = h.Queries.UpdateChatSessionTitle(r.Context(), db.UpdateChatSessionTitleParams{
+ ID: session.ID,
+ Title: title,
+ })
+ } else {
+ projectID := pgtype.UUID{Valid: false}
+ if string(req.ProjectID) != "null" {
+ var rawProjectID string
+ if err := json.Unmarshal(req.ProjectID, &rawProjectID); err != nil {
+ writeError(w, http.StatusBadRequest, "project_id must be a UUID or null")
+ return
+ }
+ rawProjectID = strings.TrimSpace(rawProjectID)
+ if rawProjectID == "" {
+ writeError(w, http.StatusBadRequest, "project_id must be a UUID or null")
+ return
+ }
+ projectID, ok = parseUUIDOrBadRequest(w, rawProjectID, "project_id")
+ if !ok {
+ return
+ }
+ }
+
+ tx, txErr := h.TxStarter.Begin(r.Context())
+ if txErr != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if projectID.Valid {
+ if _, lockErr := qtx.LockProjectForChatSessionCreate(r.Context(), db.LockProjectForChatSessionCreateParams{
+ ID: projectID,
+ WorkspaceID: session.WorkspaceID,
+ }); lockErr != nil {
+ if errors.Is(lockErr, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock project")
+ return
+ }
+ }
+
+ updated, err = qtx.UpdateChatSessionProject(r.Context(), db.UpdateChatSessionProjectParams{
+ ID: session.ID,
+ WorkspaceID: session.WorkspaceID,
+ ProjectID: projectID,
+ })
+ if err == nil {
+ err = tx.Commit(r.Context())
+ }
+ projectIDChanged = true
+ }
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update chat session")
return
}
resolvedSessionID := uuidToString(updated.ID)
- h.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionUpdatedPayload{
+ payload := protocol.ChatSessionUpdatedPayload{
ChatSessionID: resolvedSessionID,
Title: updated.Title,
UpdatedAt: timestampToString(updated.UpdatedAt),
- })
+ }
+ if projectIDChanged {
+ projectID := uuidToPtr(updated.ProjectID)
+ payload.ProjectID = &projectID
+ }
+ h.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, payload)
writeJSON(w, http.StatusOK, chatSessionToResponse(updated))
}
@@ -1378,12 +1466,13 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
// ---------------------------------------------------------------------------
type ChatSessionResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- AgentID string `json:"agent_id"`
- CreatorID string `json:"creator_id"`
- Title string `json:"title"`
- Status string `json:"status"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ CreatorID string `json:"creator_id"`
+ ProjectID *string `json:"project_id"`
+ Title string `json:"title"`
+ Status string `json:"status"`
// Only populated by list endpoints — single-session fetches return 0/false/nil.
// HasUnread is kept as a convenience (== UnreadCount > 0) for existing consumers.
HasUnread bool `json:"has_unread"`
@@ -1456,6 +1545,7 @@ func chatSessionToResponse(s db.ChatSession) ChatSessionResponse {
WorkspaceID: uuidToString(s.WorkspaceID),
AgentID: uuidToString(s.AgentID),
CreatorID: uuidToString(s.CreatorID),
+ ProjectID: uuidToPtr(s.ProjectID),
Title: s.Title,
Status: s.Status,
Pinned: s.PinnedAt.Valid,
diff --git a/server/internal/handler/chat_project_context_test.go b/server/internal/handler/chat_project_context_test.go
new file mode 100644
index 0000000000..19f4ef3653
--- /dev/null
+++ b/server/internal/handler/chat_project_context_test.go
@@ -0,0 +1,372 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func createChatProjectTestProject(t *testing.T, workspaceID, title, description string) string {
+ t.Helper()
+
+ var projectID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO project (workspace_id, title, description)
+ VALUES ($1, $2, NULLIF($3, ''))
+ RETURNING id
+ `, workspaceID, title, description).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+ return projectID
+}
+
+func createChatSessionWithProjectForTest(t *testing.T, agentID, projectID string) string {
+ t.Helper()
+
+ var sessionID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status, project_id)
+ VALUES ($1, $2, $3, 'Project context chat', 'active', $4)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, projectID).Scan(&sessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, sessionID)
+ })
+ return sessionID
+}
+
+func TestCreateChatSession_ProjectContext(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "ChatProjectContextAgent", []byte("[]"))
+ projectID := createChatProjectTestProject(t, testWorkspaceID, "Chat project", "Durable context")
+
+ t.Run("persists a workspace project", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "title": "with project",
+ "project_id": projectID,
+ }))
+ testHandler.CreateChatSession(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateChatSession: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var response ChatSessionResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, response.ID)
+ })
+ if response.ProjectID == nil || *response.ProjectID != projectID {
+ t.Fatalf("project_id = %v, want %s", response.ProjectID, projectID)
+ }
+
+ var storedProjectID *string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT project_id::text FROM chat_session WHERE id = $1
+ `, response.ID).Scan(&storedProjectID); err != nil {
+ t.Fatalf("load persisted project_id: %v", err)
+ }
+ if storedProjectID == nil || *storedProjectID != projectID {
+ t.Fatalf("stored project_id = %v, want %s", storedProjectID, projectID)
+ }
+
+ listW := httptest.NewRecorder()
+ listReq := withChatTestWorkspaceCtx(t, newRequest(http.MethodGet, "/api/chat/sessions", nil))
+ testHandler.ListChatSessions(listW, listReq)
+ if listW.Code != http.StatusOK {
+ t.Fatalf("ListChatSessions: expected 200, got %d: %s", listW.Code, listW.Body.String())
+ }
+ var sessions []ChatSessionResponse
+ if err := json.NewDecoder(listW.Body).Decode(&sessions); err != nil {
+ t.Fatalf("decode session list: %v", err)
+ }
+ found := false
+ for _, session := range sessions {
+ if session.ID != response.ID {
+ continue
+ }
+ found = true
+ if session.ProjectID == nil || *session.ProjectID != projectID {
+ t.Fatalf("listed project_id = %v, want %s", session.ProjectID, projectID)
+ }
+ }
+ if !found {
+ t.Fatalf("created session %s missing from list", response.ID)
+ }
+ })
+
+ t.Run("rejects malformed project id", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "project_id": "not-a-uuid",
+ }))
+ testHandler.CreateChatSession(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("rejects a project from another workspace", func(t *testing.T) {
+ var foreignWorkspaceID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO workspace (name, slug) VALUES ('Foreign chat context', $1) RETURNING id
+ `, "chat-context-"+uuid.NewString()).Scan(&foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
+ })
+ foreignProjectID := createChatProjectTestProject(t, foreignWorkspaceID, "Foreign project", "")
+
+ w := httptest.NewRecorder()
+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "project_id": foreignProjectID,
+ }))
+ testHandler.CreateChatSession(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+
+ t.Run("keeps project optional", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "title": "workspace context only",
+ }))
+ testHandler.CreateChatSession(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateChatSession: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var response ChatSessionResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, response.ID)
+ })
+ if response.ProjectID != nil {
+ t.Fatalf("project_id = %v, want null", response.ProjectID)
+ }
+ })
+}
+
+func TestUpdateChatSession_UpdatesProjectContext(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ projectID := createChatProjectTestProject(t, testWorkspaceID, "Removable chat project", "")
+ replacementProjectID := createChatProjectTestProject(t, testWorkspaceID, "Replacement chat project", "")
+ agentID := createHandlerTestAgent(t, "RemoveChatProjectAgent", []byte("[]"))
+ sessionID := createChatSessionWithProjectForTest(t, agentID, projectID)
+
+ updateProject := func(projectID any) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := withURLParam(
+ withChatTestWorkspaceCtx(t, newRequest(http.MethodPatch, "/api/chat/sessions/"+sessionID, map[string]any{
+ "project_id": projectID,
+ })),
+ "sessionId",
+ sessionID,
+ )
+ testHandler.UpdateChatSession(w, req)
+ return w
+ }
+
+ w := updateProject(replacementProjectID)
+ if w.Code != http.StatusOK {
+ t.Fatalf("replace project: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response ChatSessionResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.ID != sessionID {
+ t.Fatalf("session id = %q, want %q", response.ID, sessionID)
+ }
+ if response.ProjectID == nil || *response.ProjectID != replacementProjectID {
+ t.Fatalf("response project_id = %v, want %s", response.ProjectID, replacementProjectID)
+ }
+
+ var foreignWorkspaceID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO workspace (name, slug) VALUES ('Foreign chat update', $1) RETURNING id
+ `, "chat-update-"+uuid.NewString()).Scan(&foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
+ })
+ foreignProjectID := createChatProjectTestProject(t, foreignWorkspaceID, "Foreign replacement", "")
+ foreignW := updateProject(foreignProjectID)
+ if foreignW.Code != http.StatusNotFound {
+ t.Fatalf("foreign project: expected 404, got %d: %s", foreignW.Code, foreignW.Body.String())
+ }
+
+ w = updateProject(nil)
+ if w.Code != http.StatusOK {
+ t.Fatalf("remove project: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ response = ChatSessionResponse{}
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode remove response: %v", err)
+ }
+ if response.ProjectID != nil {
+ t.Fatalf("response project_id = %v, want null", response.ProjectID)
+ }
+
+ var storedProjectID *string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT project_id::text FROM chat_session WHERE id = $1
+ `, sessionID).Scan(&storedProjectID); err != nil {
+ t.Fatalf("load updated chat session: %v", err)
+ }
+ if storedProjectID != nil {
+ t.Fatalf("stored project_id = %v, want null", storedProjectID)
+ }
+}
+
+func TestDeleteProject_ClearsChatSessionContext(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ projectID := createChatProjectTestProject(t, testWorkspaceID, "Deleted chat project", "")
+ agentID := createHandlerTestAgent(t, "DeletedChatProjectAgent", []byte("[]"))
+ sessionID := createChatSessionWithProjectForTest(t, agentID, projectID)
+
+ w := httptest.NewRecorder()
+ req := withURLParam(
+ newRequest(http.MethodDelete, "/api/projects/"+projectID, nil),
+ "id",
+ projectID,
+ )
+ testHandler.DeleteProject(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteProject: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var storedProjectID *string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT project_id::text FROM chat_session WHERE id = $1
+ `, sessionID).Scan(&storedProjectID); err != nil {
+ t.Fatalf("load chat session after project delete: %v", err)
+ }
+ if storedProjectID != nil {
+ t.Fatalf("project_id = %v after project delete, want null", storedProjectID)
+ }
+}
+
+func TestClaimTaskByRuntime_ChatProjectContext(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ setHandlerTestWorkspaceRepos(t, []map[string]string{
+ {"url": "https://github.com/example/workspace-fallback"},
+ })
+ projectID := createChatProjectTestProject(
+ t,
+ testWorkspaceID,
+ "Chat claim project",
+ "Use the project design system and release branch.",
+ )
+ const projectRepoURL = "https://github.com/example/chat-project-repo"
+ const projectRepoRef = "release/chat-context"
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO project_resource (
+ project_id, workspace_id, resource_type, resource_ref, label, position
+ ) VALUES ($1, $2, 'github_repo', $3::jsonb, 'Chat repository', 0)
+ `, projectID, testWorkspaceID, `{"url":"`+projectRepoURL+`","ref":"`+projectRepoRef+`"}`); err != nil {
+ t.Fatalf("create project resource: %v", err)
+ }
+
+ agentID := createHandlerTestAgent(t, "ChatProjectClaimAgent", []byte("[]"))
+ runtimeID := handlerTestRuntimeID(t)
+ sessionID := createChatSessionWithProjectForTest(t, agentID, projectID)
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'user', 'Plan the project release')
+ `, sessionID); err != nil {
+ t.Fatalf("create chat message: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, status, priority, chat_session_id
+ ) VALUES ($1, $2, 'queued', 1000, $3)
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("create chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest(
+ http.MethodPost,
+ "/api/daemon/runtimes/"+runtimeID+"/claim",
+ nil,
+ testWorkspaceID,
+ "chat-project-context-test",
+ )
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var response struct {
+ Task *struct {
+ ID string `json:"id"`
+ ProjectID string `json:"project_id"`
+ ProjectTitle string `json:"project_title"`
+ ProjectDescription string `json:"project_description"`
+ ProjectResources []ProjectResourceData `json:"project_resources"`
+ Repos []RepoData `json:"repos"`
+ } `json:"task"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.Task == nil || response.Task.ID != taskID {
+ t.Fatalf("claimed task = %+v, want %s", response.Task, taskID)
+ }
+ if response.Task.ProjectID != projectID {
+ t.Fatalf("project_id = %q, want %q", response.Task.ProjectID, projectID)
+ }
+ if response.Task.ProjectTitle != "Chat claim project" {
+ t.Fatalf("project_title = %q", response.Task.ProjectTitle)
+ }
+ if response.Task.ProjectDescription != "Use the project design system and release branch." {
+ t.Fatalf("project_description = %q", response.Task.ProjectDescription)
+ }
+ if len(response.Task.ProjectResources) != 1 || response.Task.ProjectResources[0].Label != "Chat repository" {
+ t.Fatalf("project_resources = %+v", response.Task.ProjectResources)
+ }
+ if len(response.Task.Repos) != 1 || response.Task.Repos[0].URL != projectRepoURL || response.Task.Repos[0].Ref != projectRepoRef {
+ t.Fatalf("repos = %+v, want project repo only", response.Task.Repos)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index da83f2c43f..528b2e46ef 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2089,7 +2089,53 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
break
}
- if ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {
+ // A web chat can opt into the same durable project context as an
+ // issue-bound task. Revalidate the soft reference in this workspace at
+ // claim time: a deleted/stale project degrades to workspace context and
+ // can never leak a project from another tenant.
+ var projectRepos []RepoData
+ if cs.ProjectID.Valid {
+ if project, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{
+ ID: cs.ProjectID,
+ WorkspaceID: cs.WorkspaceID,
+ }); err == nil {
+ resp.ProjectID = uuidToString(project.ID)
+ resp.ProjectTitle = project.Title
+ resp.ProjectDescription = project.Description.String
+ if rows := h.listProjectResourcesForProject(r.Context(), project.ID); len(rows) > 0 {
+ resources := make([]ProjectResourceData, 0, len(rows))
+ for _, row := range rows {
+ label := ""
+ if row.Label.Valid {
+ label = row.Label.String
+ }
+ ref := json.RawMessage(row.ResourceRef)
+ if len(ref) == 0 {
+ ref = json.RawMessage("{}")
+ }
+ resources = append(resources, ProjectResourceData{
+ ID: uuidToString(row.ID),
+ ResourceType: row.ResourceType,
+ ResourceRef: ref,
+ Label: label,
+ })
+ if row.ResourceType == "github_repo" {
+ var payload struct {
+ URL string `json:"url"`
+ Ref string `json:"ref,omitempty"`
+ }
+ if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {
+ projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})
+ }
+ }
+ }
+ resp.ProjectResources = resources
+ }
+ }
+ }
+ if len(projectRepos) > 0 {
+ resp.Repos = projectRepos
+ } else if ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {
var repos []RepoData
if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {
resp.Repos = repos
diff --git a/server/internal/handler/project.go b/server/internal/handler/project.go
index 58b58d152f..e27da79a5f 100644
--- a/server/internal/handler/project.go
+++ b/server/internal/handler/project.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -586,13 +587,43 @@ func (h *Handler) DeleteProject(w http.ResponseWriter, r *http.Request) {
return
}
userID := uuidToString(requester.UserID)
- if err := h.Queries.DeleteProject(r.Context(), db.DeleteProjectParams{
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if _, err := qtx.LockProjectForDelete(r.Context(), db.LockProjectForDeleteParams{
+ ID: project.ID,
+ WorkspaceID: project.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock project")
+ return
+ }
+ if err := qtx.ClearChatSessionProjectByProject(r.Context(), db.ClearChatSessionProjectByProjectParams{
+ ProjectID: project.ID,
+ WorkspaceID: project.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clear project chat context")
+ return
+ }
+ if err := qtx.DeleteProject(r.Context(), db.DeleteProjectParams{
ID: project.ID,
WorkspaceID: project.WorkspaceID,
}); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete project")
return
}
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit project delete")
+ return
+ }
h.publish(protocol.EventProjectDeleted, workspaceID, "member", userID, map[string]any{"project_id": uuidToString(project.ID)})
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/migrations/213_chat_session_project.down.sql b/server/migrations/213_chat_session_project.down.sql
new file mode 100644
index 0000000000..ae0ce92275
--- /dev/null
+++ b/server/migrations/213_chat_session_project.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_session
+ DROP COLUMN IF EXISTS project_id;
diff --git a/server/migrations/213_chat_session_project.up.sql b/server/migrations/213_chat_session_project.up.sql
new file mode 100644
index 0000000000..880d4f67db
--- /dev/null
+++ b/server/migrations/213_chat_session_project.up.sql
@@ -0,0 +1,8 @@
+-- Chat sessions may opt into one project's durable context. Keep this as a
+-- soft reference: adding a foreign key would validate the established,
+-- write-active chat_session table and take a cross-table lock during deploy.
+-- Create/delete handlers serialize on the project row, project deletion clears
+-- existing references, and daemon claim revalidates workspace ownership before
+-- injecting any context.
+ALTER TABLE chat_session
+ ADD COLUMN project_id UUID;
diff --git a/server/migrations/214_chat_session_project_index.down.sql b/server/migrations/214_chat_session_project_index.down.sql
new file mode 100644
index 0000000000..1a77a84cc3
--- /dev/null
+++ b/server/migrations/214_chat_session_project_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_session_project;
diff --git a/server/migrations/214_chat_session_project_index.up.sql b/server/migrations/214_chat_session_project_index.up.sql
new file mode 100644
index 0000000000..f3a7ddfe15
--- /dev/null
+++ b/server/migrations/214_chat_session_project_index.up.sql
@@ -0,0 +1,7 @@
+-- Project deletion clears chat-session references by project_id. Build this
+-- partial index concurrently so the established chat_session write path stays
+-- available throughout rollout. A single statement is required because
+-- CREATE INDEX CONCURRENTLY cannot run inside a transaction.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_session_project
+ ON chat_session (project_id)
+ WHERE project_id IS NOT NULL;
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index d682e63f17..a1ff29a067 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -31,6 +31,25 @@ func (q *Queries) ChatSessionHasUserMessage(ctx context.Context, chatSessionID p
return has_user_message, err
}
+const clearChatSessionProjectByProject = `-- name: ClearChatSessionProjectByProject :exec
+UPDATE chat_session
+SET project_id = NULL
+WHERE project_id = $1 AND workspace_id = $2
+`
+
+type ClearChatSessionProjectByProjectParams struct {
+ ProjectID pgtype.UUID `json:"project_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Project references are intentionally soft (no database FK). Keep chat
+// history while removing the context selection when a project is deleted.
+// Do not touch updated_at: context cleanup is not chat activity.
+func (q *Queries) ClearChatSessionProjectByProject(ctx context.Context, arg ClearChatSessionProjectByProjectParams) error {
+ _, err := q.db.Exec(ctx, clearChatSessionProjectByProject, arg.ProjectID, arg.WorkspaceID)
+ return err
+}
+
const createChatDraftRestore = `-- name: CreateChatDraftRestore :one
INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
VALUES ($1, $2, $3, $4, $5)
@@ -114,9 +133,9 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
}
const createChatSession = `-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5)
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, $6)
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
type CreateChatSessionParams struct {
@@ -125,6 +144,7 @@ type CreateChatSessionParams struct {
CreatorID pgtype.UUID `json:"creator_id"`
Title string `json:"title"`
IsAgentIntro bool `json:"is_agent_intro"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionParams) (ChatSession, error) {
@@ -134,6 +154,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
arg.CreatorID,
arg.Title,
arg.IsAgentIntro,
+ arg.ProjectID,
)
var i ChatSession
err := row.Scan(
@@ -152,6 +173,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
@@ -400,7 +422,7 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
}
const getChatSession = `-- name: GetChatSession :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
WHERE id = $1
`
@@ -423,12 +445,13 @@ func (q *Queries) GetChatSession(ctx context.Context, id pgtype.UUID) (ChatSessi
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
const getChatSessionInWorkspace = `-- name: GetChatSessionInWorkspace :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
WHERE id = $1 AND workspace_id = $2
`
@@ -456,6 +479,7 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
@@ -603,7 +627,7 @@ func (q *Queries) LinkChatMessageToTask(ctx context.Context, arg LinkChatMessage
}
const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many
-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at,
+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
CASE WHEN cs.status = 'archived' THEN 0
ELSE (SELECT count(*) FROM chat_message m
WHERE m.chat_session_id = cs.id
@@ -648,6 +672,7 @@ type ListAllChatSessionsByCreatorRow struct {
LastReadAt pgtype.Timestamptz `json:"last_read_at"`
IsAgentIntro bool `json:"is_agent_intro"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ ProjectID pgtype.UUID `json:"project_id"`
UnreadCount int32 `json:"unread_count"`
LastMessageContent string `json:"last_message_content"`
LastMessageRole string `json:"last_message_role"`
@@ -688,6 +713,7 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
&i.UnreadCount,
&i.LastMessageContent,
&i.LastMessageRole,
@@ -871,7 +897,7 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
}
const listChatSessionsByCreator = `-- name: ListChatSessionsByCreator :many
-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at,
+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
(SELECT count(*) FROM chat_message m
WHERE m.chat_session_id = cs.id
AND m.role = 'assistant'
@@ -914,6 +940,7 @@ type ListChatSessionsByCreatorRow struct {
LastReadAt pgtype.Timestamptz `json:"last_read_at"`
IsAgentIntro bool `json:"is_agent_intro"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ ProjectID pgtype.UUID `json:"project_id"`
UnreadCount int32 `json:"unread_count"`
LastMessageContent string `json:"last_message_content"`
LastMessageRole string `json:"last_message_role"`
@@ -950,6 +977,7 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
&i.UnreadCount,
&i.LastMessageContent,
&i.LastMessageRole,
@@ -1218,7 +1246,7 @@ UPDATE chat_session
SET status = CASE WHEN $2::bool THEN 'archived' ELSE 'active' END,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
type SetChatSessionArchivedParams struct {
@@ -1249,6 +1277,7 @@ func (q *Queries) SetChatSessionArchived(ctx context.Context, arg SetChatSession
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
@@ -1257,7 +1286,7 @@ const setChatSessionPinned = `-- name: SetChatSessionPinned :one
UPDATE chat_session
SET pinned_at = CASE WHEN $2::bool THEN COALESCE(pinned_at, now()) ELSE NULL END
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
type SetChatSessionPinnedParams struct {
@@ -1289,6 +1318,7 @@ func (q *Queries) SetChatSessionPinned(ctx context.Context, arg SetChatSessionPi
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
@@ -1371,6 +1401,45 @@ func (q *Queries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
return err
}
+const updateChatSessionProject = `-- name: UpdateChatSessionProject :one
+UPDATE chat_session
+SET project_id = $1
+WHERE id = $2 AND workspace_id = $3
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+`
+
+type UpdateChatSessionProjectParams struct {
+ ProjectID pgtype.UUID `json:"project_id"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Project context is user-editable session metadata. Do not touch updated_at:
+// changing context is not conversation activity and must not reorder history.
+func (q *Queries) UpdateChatSessionProject(ctx context.Context, arg UpdateChatSessionProjectParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, updateChatSessionProject, arg.ProjectID, arg.ID, arg.WorkspaceID)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ )
+ return i, err
+}
+
const updateChatSessionSession = `-- name: UpdateChatSessionSession :exec
UPDATE chat_session
SET session_id = COALESCE($1, session_id),
@@ -1405,7 +1474,7 @@ func (q *Queries) UpdateChatSessionSession(ctx context.Context, arg UpdateChatSe
const updateChatSessionTitle = `-- name: UpdateChatSessionTitle :one
UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
type UpdateChatSessionTitleParams struct {
@@ -1432,6 +1501,7 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
@@ -1439,7 +1509,7 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess
const updateChatSessionTitleIfCurrent = `-- name: UpdateChatSessionTitleIfCurrent :one
UPDATE chat_session SET title = $1, updated_at = now()
WHERE id = $2 AND title = $3
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
type UpdateChatSessionTitleIfCurrentParams struct {
@@ -1475,6 +1545,7 @@ func (q *Queries) UpdateChatSessionTitleIfCurrent(ctx context.Context, arg Updat
&i.LastReadAt,
&i.IsAgentIntro,
&i.PinnedAt,
+ &i.ProjectID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 4223f57eb6..ce4fd0f4cd 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -388,6 +388,7 @@ type ChatSession struct {
LastReadAt pgtype.Timestamptz `json:"last_read_at"`
IsAgentIntro bool `json:"is_agent_intro"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
type ClientUsageDaily struct {
diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.go
index 2d86726f90..656a631309 100644
--- a/server/pkg/db/generated/project.sql.go
+++ b/server/pkg/db/generated/project.sql.go
@@ -232,6 +232,46 @@ func (q *Queries) ListProjects(ctx context.Context, arg ListProjectsParams) ([]P
return items, nil
}
+const lockProjectForChatSessionCreate = `-- name: LockProjectForChatSessionCreate :one
+SELECT id FROM project
+WHERE id = $1 AND workspace_id = $2
+FOR KEY SHARE
+`
+
+type LockProjectForChatSessionCreateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Conflicts with project deletion so a chat session cannot commit a soft
+// project reference after the delete transaction has swept existing sessions.
+func (q *Queries) LockProjectForChatSessionCreate(ctx context.Context, arg LockProjectForChatSessionCreateParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockProjectForChatSessionCreate, arg.ID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
+const lockProjectForDelete = `-- name: LockProjectForDelete :one
+SELECT id FROM project
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockProjectForDeleteParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Serializes project deletion with chat-session creation. The handler locks,
+// clears every soft chat reference, and deletes the project in one transaction.
+func (q *Queries) LockProjectForDelete(ctx context.Context, arg LockProjectForDeleteParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockProjectForDelete, arg.ID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
const updateProject = `-- name: UpdateProject :one
UPDATE project SET
title = COALESCE($2, title),
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index b72f9036f9..1a90d64ecd 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -1,8 +1,16 @@
-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5)
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, sqlc.narg('project_id'))
RETURNING *;
+-- name: ClearChatSessionProjectByProject :exec
+-- Project references are intentionally soft (no database FK). Keep chat
+-- history while removing the context selection when a project is deleted.
+-- Do not touch updated_at: context cleanup is not chat activity.
+UPDATE chat_session
+SET project_id = NULL
+WHERE project_id = $1 AND workspace_id = $2;
+
-- name: GetChatSession :one
SELECT * FROM chat_session
WHERE id = $1;
@@ -72,6 +80,14 @@ UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
RETURNING *;
+-- name: UpdateChatSessionProject :one
+-- Project context is user-editable session metadata. Do not touch updated_at:
+-- changing context is not conversation activity and must not reorder history.
+UPDATE chat_session
+SET project_id = sqlc.narg('project_id')
+WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')
+RETURNING *;
+
-- name: UpdateChatSessionTitleIfCurrent :one
-- Compare-and-swap the title: only overwrite it when it still equals the
-- value the caller observed (@expected_title). This is the idempotency /
diff --git a/server/pkg/db/queries/project.sql b/server/pkg/db/queries/project.sql
index 3a887139cd..bc67883b81 100644
--- a/server/pkg/db/queries/project.sql
+++ b/server/pkg/db/queries/project.sql
@@ -13,6 +13,20 @@ WHERE id = $1;
SELECT * FROM project
WHERE id = $1 AND workspace_id = $2;
+-- name: LockProjectForChatSessionCreate :one
+-- Conflicts with project deletion so a chat session cannot commit a soft
+-- project reference after the delete transaction has swept existing sessions.
+SELECT id FROM project
+WHERE id = $1 AND workspace_id = $2
+FOR KEY SHARE;
+
+-- name: LockProjectForDelete :one
+-- Serializes project deletion with chat-session creation. The handler locks,
+-- clears every soft chat reference, and deletes the project in one transaction.
+SELECT id FROM project
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: CreateProject :one
INSERT INTO project (
workspace_id, title, description, icon, status,
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 8378ecc88f..e9c67177fd 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -229,6 +229,9 @@ type ChatSessionDeletedPayload struct {
type ChatSessionUpdatedPayload struct {
ChatSessionID string `json:"chat_session_id"`
Title string `json:"title"`
+ // ProjectID is set only by the project-context update path. The double
+ // pointer distinguishes an omitted field from an explicit JSON null.
+ ProjectID **string `json:"project_id,omitempty"`
// Pinned is set only by the pin/unpin path; nil on a plain rename so a
// receiver leaves the existing pin state untouched.
Pinned *bool `json:"pinned,omitempty"`