Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8663 fix(chat): bind collection requests to their workspace (#10007)
Frezc7c75b34a23fd
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 3b9693d267..31094de4ce 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -754,10 +754,16 @@ function subscriberTarget(* explicitly, or a concurrent writer of that singleton silently redirects the* write to the wrong workspace.*/+type WorkspaceScope = string | { workspaceId: string };+function workspaceHeader(- slug?: string,+ scope?: WorkspaceScope,): Record<string, string> | undefined {- return slug ? { "X-Workspace-Slug": slug } : undefined;+ if (typeof scope === "object") {+ // The server resolves slugs first, so suppress the ambient route slug.+ return { "X-Workspace-Slug": "", "X-Workspace-ID": scope.workspaceId };+ }+ return scope ? { "X-Workspace-Slug": scope } : undefined;}function dingTalkGroupSearch(params: ListDingTalkGroupsParams): string {@@ -3833,11 +3839,11 @@ export class ApiClient {// Chat Sessionsasync listChatSessions(params?: { status?: string },- workspaceSlug?: string,+ workspace?: WorkspaceScope,): Promise<ChatSession[]> {const query = params?.status ? `?status=${params.status}` : "";const raw: unknown = await this.fetch(`/api/chat/sessions${query}`, {- headers: workspaceHeader(workspaceSlug),+ headers: workspaceHeader(workspace),});return parseWithFallback(raw, ChatSessionListSchema, EMPTY_CHAT_SESSION_LIST, {endpoint: "GET /api/chat/sessions",@@ -3915,8 +3921,8 @@ export class ApiClient {}// Quick-agent bar: per-user pinned agents.- async listChatPinnedAgents(): Promise<ChatPinnedAgent[]> {- return this.fetch("/api/chat/pinned-agents");+ async listChatPinnedAgents(workspace?: WorkspaceScope): Promise<ChatPinnedAgent[]> {+ return this.fetch("/api/chat/pinned-agents", { headers: workspaceHeader(workspace) });}async pinChatAgent(agentId: string): Promise<ChatPinnedAgent> {@@ -4078,12 +4084,12 @@ export class ApiClient {});}- async listPendingChatTasks(): Promise<PendingChatTasksResponse> {- return this.fetch(`/api/chat/pending-tasks`);+ async listPendingChatTasks(workspace?: WorkspaceScope): Promise<PendingChatTasksResponse> {+ return this.fetch(`/api/chat/pending-tasks`, { headers: workspaceHeader(workspace) });}- async hasAnyPendingChatTasks(): Promise<HasPendingChatTasksResponse> {- return this.fetch(`/api/chat/pending-tasks/has-any`);+ async hasAnyPendingChatTasks(workspace?: WorkspaceScope): Promise<HasPendingChatTasksResponse> {+ return this.fetch(`/api/chat/pending-tasks/has-any`, { headers: workspaceHeader(workspace) });}async markChatSessionRead(sessionId: string): Promise<void> {diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex 58eaf211c4..9bb58f5337 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -23,12 +23,10 @@ import type {*/export const QUICK_ACTIONS_PENDING_TIMEOUT_MS = 12_000;-// NOTE on workspace scoping:-// `wsId` is used only as part of queryKey for cache isolation per workspace.-// The actual workspace context comes from ApiClient's X-Workspace-Slug header,-// which is set by the URL-driven [workspaceSlug] layout. Callers must ensure-// the header is in sync with the wsId they pass here — otherwise cache writes-// will be misattributed during a workspace switch race window.+// Sessions, pinned agents, pending tasks, and the running indicator explicitly+// bind requests to the workspace UUID in their query key. Other session/task+// queries still use ApiClient's current workspace header, which callers must+// keep aligned with the resource's workspace and any wsId in the query key.export const chatKeys = {all: (wsId: string) => ["chat", wsId] as const,@@ -77,7 +75,7 @@ export function isTaskMessageTaskId(taskId: string | null | undefined): taskId iexport function chatSessionsOptions(wsId: string) {return queryOptions({queryKey: chatKeys.sessions(wsId),- queryFn: () => api.listChatSessions({ status: "all" }),+ queryFn: () => api.listChatSessions({ status: "all" }, { workspaceId: wsId }),staleTime: Infinity,});}@@ -125,7 +123,7 @@ export function countUnreadChatSessions(sessions: ChatSession[]): number {export function chatPinnedAgentsOptions(wsId: string) {return queryOptions({queryKey: chatKeys.pinnedAgents(wsId),- queryFn: () => api.listChatPinnedAgents(),+ queryFn: () => api.listChatPinnedAgents({ workspaceId: wsId }),staleTime: Infinity,});}@@ -339,7 +337,7 @@ export function isTaskMessageTimelineHeld(export function pendingChatTasksOptions(wsId: string) {return queryOptions({queryKey: chatKeys.pendingTasks(wsId),- queryFn: () => api.listPendingChatTasks(),+ queryFn: () => api.listPendingChatTasks({ workspaceId: wsId }),staleTime: Infinity,});}@@ -354,7 +352,7 @@ export function pendingChatTasksOptions(wsId: string) {export function hasPendingChatTasksOptions(wsId: string) {return queryOptions({queryKey: chatKeys.pendingTasksHasAny(wsId),- queryFn: () => api.hasAnyPendingChatTasks(),+ queryFn: () => api.hasAnyPendingChatTasks({ workspaceId: wsId }),staleTime: Infinity,});}diff --git a/packages/core/chat/workspace-scope.test.ts b/packages/core/chat/workspace-scope.test.tsnew file mode 100644index 0000000000..2c73116e1e--- /dev/null+++ b/packages/core/chat/workspace-scope.test.ts@@ -0,0 +1,156 @@+// @vitest-environment node+import { QueryClient, QueryObserver } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { api, ApiClient, setApiInstance } from "../api";+import { setCurrentWorkspace } from "../platform/workspace-storage";+import type { ChatSession } from "../types/chat";+import {+ chatKeys,+ chatPinnedAgentsOptions,+ chatSessionsOptions,+ hasPendingChatTasksOptions,+ pendingChatTasksOptions,+} from "./queries";++const workspaceA = "11111111-1111-4111-8111-111111111111";+const workspaceB = "22222222-2222-4222-8222-222222222222";+const workspacesBySlug: Record<string, string> = {+ "workspace-a": workspaceA,+ "workspace-b": workspaceB,+};++const session = (workspaceId: string): ChatSession => ({+ id: `session-${workspaceId}`,+ workspace_id: workspaceId,+ agent_id: `agent-${workspaceId}`,+ creator_id: "member-1",+ title: `Chat in ${workspaceId}`,+ status: "active",+ has_unread: false,+ created_at: "2026-11-05T00:00:00Z",+ updated_at: "2026-11-05T00:00:00Z",+});++function responseBody(path: string, workspaceId: string): unknown {+ switch (path) {+ case "/api/chat/sessions":+ return [session(workspaceId)];+ case "/api/chat/pinned-agents":+ return [{ agent_id: `agent-${workspaceId}`, position: 1 }];+ case "/api/chat/pending-tasks":+ return { tasks: [{+ task_id: `task-${workspaceId}`,+ chat_session_id: `session-${workspaceId}`,+ status: "running",+ }] };+ case "/api/chat/pending-tasks/has-any":+ return { has_pending: workspaceId === workspaceA };+ default:+ throw new Error(`Unexpected request: ${path}`);+ }+}++function stubWorkspaceServer(failFirst = false) {+ const requestedWorkspaces: string[] = [];+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ const slug = headers.get("X-Workspace-Slug");+ // Match server resolution: a nonempty slug takes precedence over the UUID.+ const workspaceId = slug+ ? workspacesBySlug[slug]+ : headers.get("X-Workspace-ID");+ if (!workspaceId) throw new Error("Request has no valid workspace");+ requestedWorkspaces.push(workspaceId);+ if (failFirst && requestedWorkspaces.length === 1) {+ setCurrentWorkspace("workspace-b", workspaceB);+ return new Response(JSON.stringify({ error: "temporarily unavailable" }), { status: 503 });+ }+ const url = new URL(input instanceof Request ? input.url : String(input));+ return new Response(JSON.stringify(responseBody(url.pathname, workspaceId)), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }));+ return requestedWorkspaces;+}++let queryClient: QueryClient;++beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },+ });+ setApiInstance(new ApiClient("https://api.example.test"));+ setCurrentWorkspace("workspace-a", workspaceA);+});++afterEach(() => {+ queryClient.clear();+ setCurrentWorkspace(null, null);+ vi.unstubAllGlobals();+});++describe("chat collection workspace ownership", () => {+ it("keeps a sessions retry in its original workspace after navigation", async () => {+ const requestedWorkspaces = stubWorkspaceServer(true);++ await queryClient.fetchQuery({+ ...chatSessionsOptions(workspaceA),+ retry: 1,+ retryDelay: 0,+ });++ expect(requestedWorkspaces).toEqual([workspaceA, workspaceA]);+ expect(queryClient.getQueryData(chatKeys.sessions(workspaceA))).toEqual([session(workspaceA)]);+ expect(queryClient.getQueryData(chatKeys.sessions(workspaceB))).toBeUndefined();+ });++ it("refetches a retained workspace observer without using the newly active workspace", async () => {+ const requestedWorkspaces = stubWorkspaceServer();+ const options = chatSessionsOptions(workspaceA);+ const observer = new QueryObserver(queryClient, options);+ const unsubscribe = observer.subscribe(() => undefined);+ try {+ await queryClient.fetchQuery(options);+ setCurrentWorkspace("workspace-b", workspaceB);++ await queryClient.invalidateQueries({ queryKey: chatKeys.sessions(workspaceA) });++ expect(requestedWorkspaces).toEqual([workspaceA, workspaceA]);+ expect(observer.getCurrentResult().data).toEqual([session(workspaceA)]);+ expect(queryClient.getQueryData(chatKeys.sessions(workspaceA))).toEqual([session(workspaceA)]);+ } finally {+ unsubscribe();+ }+ });++ const collections: Array<{+ name: string;+ path: string;+ fetch: () => Promise<unknown>;+ }> = [+ { name: "sessions", path: "/api/chat/sessions", fetch: () => queryClient.fetchQuery(chatSessionsOptions(workspaceA)) },+ { name: "pinned agents", path: "/api/chat/pinned-agents", fetch: () => queryClient.fetchQuery(chatPinnedAgentsOptions(workspaceA)) },+ { name: "pending tasks", path: "/api/chat/pending-tasks", fetch: () => queryClient.fetchQuery(pendingChatTasksOptions(workspaceA)) },+ { name: "pending indicator", path: "/api/chat/pending-tasks/has-any", fetch: () => queryClient.fetchQuery(hasPendingChatTasksOptions(workspaceA)) },+ ];++ it.each(collections)("fetches $name for the key workspace when options are created after navigation", async ({ path, fetch }) => {+ const requestedWorkspaces = stubWorkspaceServer();+ setCurrentWorkspace("workspace-b", workspaceB);++ expect(await fetch()).toEqual(responseBody(path, workspaceA));+ expect(requestedWorkspaces).toEqual([workspaceA]);+ });++ it.each([+ { name: "an explicit slug", scope: "workspace-a", expected: workspaceA },+ { name: "the current workspace by default", scope: undefined, expected: workspaceB },+ ])("preserves listChatSessions routing with $name", async ({ scope, expected }) => {+ const requestedWorkspaces = stubWorkspaceServer();+ setCurrentWorkspace("workspace-b", workspaceB);++ expect(await api.listChatSessions({ status: "all" }, scope)).toEqual([session(expected)]);+ expect(requestedWorkspaces).toEqual([expected]);+ });+});