Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: share attached files across a project (#8756)
Michael Hanc13642ce6c8b
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex c54e240b091..ee603bc58ff 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -80,6 +80,7 @@ import {} from "@/features/chat/api/chat-api";import {findLatestUserAudioBase64,+ resolveProjectId,sentAudioNames,} from "@/features/chat/api/chat-adapter";import {@@ -198,7 +199,12 @@ import {dictationSendBlocked,shouldSubmitDictation,} from "@/features/chat/utils/dictation-send";-import { listThreadDocuments } from "@/features/rag/api/rag-api";+import {+ isRagClientError,+ listProjectDocuments,+ listThreadDocuments,+ projectWorkCount,+} from "@/features/rag/api/rag-api";import { useRagAvailabilityStore } from "@/features/rag/api/rag-availability";import { ThreadDocumentsBar } from "@/features/rag/components/thread-documents-bar";import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";@@ -301,6 +307,10 @@ const PageDragContext = createContext(false);// instead of aui.thread() so queues can keep advancing in the background.type PromptQueueTarget = {getDocumentThreadId: () => string | null;+ /** The project this queue was started in, for a chat with no row to read. */+ getQueueProjectId: () => string | null;+ /** A knowledge base replaces every other scope, project sources included. */+ usesKnowledgeBase: boolean;getRunningThreadIds: () => string[];isRunning: () => boolean;append: (prompt: string) => void | Promise<void>;@@ -488,22 +498,58 @@ function appendQueuedPrompt(run: PromptQueueRun, item: PromptQueueItem) {schedulePromptQueueTargetStatePoll(run);}+const indexingDocument = (doc: { status: string }) =>+ doc.status === "pending" || doc.status === "running";+async function targetHasIndexingDocuments(item: PromptQueueItem) {if (item.target.isIndexing()) {return true;}- if (!item.target.usesThreadDocuments) {- return false;- }const threadId = item.target.getDocumentThreadId();- if (!threadId) {- return false;- }try {- const documents = await listThreadDocuments(threadId);- return documents.some(- (doc) => doc.status === "pending" || doc.status === "running",- );+ if (threadId && item.target.usesThreadDocuments) {+ const documents = await listThreadDocuments(threadId);+ if (documents.some(indexingDocument)) {+ return true;+ }+ }+ // Unless a knowledge base is active: the adapter sends kb_id alone, so the+ // project's sources cannot reach this run and waiting on them only delays it.+ if (item.target.usesKnowledgeBase) {+ return false;+ }+ // Project sources are retrieved whatever the Docs pill says (chat-adapter's+ // rag_scope), and isIndexing() above only answers while the bar that watches+ // them is mounted, which a background queue has not. So ask directly, and+ // for a chat with no row yet use the project the queue was started in.+ // Rethrowing: a row this probe could not read is not a chat with no project,+ // and the catch below is what holds the prompt and asks again. The queue's+ // own project is the fallback wherever the row is still missing, so a poll+ // landing mid-navigation cannot probe the project the user moved to.+ const queueProjectId = item.target.getQueueProjectId();+ const projectId = threadId+ ? await resolveProjectId(threadId, undefined, {+ rethrowReadFailure: true,+ composerProjectId: queueProjectId,+ })+ : queueProjectId;+ if (!projectId) {+ return false;+ }+ if (projectWorkCount(projectId) > 0) {+ return true;+ }+ try {+ const projectDocuments = await listProjectDocuments(projectId);+ return projectDocuments.some(indexingDocument);+ } catch (error) {+ // A project the server will not list (deleted, or a server predating the+ // route) is not one to wait for: the retry below never ends.+ if (isRagClientError(error)) {+ return false;+ }+ throw error;+ }} catch {// A failed status probe cannot prove that this thread's documents are// ready. Keep the queued send pending and retry instead of dispatching@@ -2988,9 +3034,17 @@ const Composer: FC<{}const chatStateAtQueueStart = useChatRuntimeStore.getState();const incognitoAtQueueStart = chatStateAtQueueStart.incognito;+ // A chat with no row yet has no project to look up, and the store holds+ // whichever project is on screen when the queue polls. Read it here.+ const projectIdAtQueueStart = incognitoAtQueueStart+ ? null+ : (chatStateAtQueueStart.activeProjectId ?? null);const usesThreadDocumentsAtQueueStart =chatStateAtQueueStart.ragEnabled &&chatStateAtQueueStart.ragSource.type === "thread";+ const usesKnowledgeBaseAtQueueStart =+ chatStateAtQueueStart.ragEnabled &&+ chatStateAtQueueStart.ragSource.type === "kb";const runSettingsAtQueueStart =snapshotQueuedChatRunSettings(chatStateAtQueueStart);const getThreadListItemState = () => {@@ -3194,7 +3248,9 @@ const Composer: FC<{promptQueueTargetMountedRef.current &&isTargetCurrentThread() &&indexingActiveRef.current,+ getQueueProjectId: () => projectIdAtQueueStart,usesThreadDocuments: usesThreadDocumentsAtQueueStart,+ usesKnowledgeBase: usesKnowledgeBaseAtQueueStart,usesLocalModel:parseExternalModelId(runSettingsAtQueueStart.params.checkpoint) === null,usesDeepResearch: runSettingsAtQueueStart.deepResearchEnabled,diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex f9dbbdcd212..6ded83325fd 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -149,6 +149,7 @@ import {getStoredChatThread,getStoredChatThreadReadResult,getStoredChatProject,+ isThreadIncognito,listStoredChatThreads,listStoredChatMessages,saveStoredChatMessage,@@ -1771,21 +1772,70 @@ async function resolveChatInstructions(.join("\n\n");}-async function resolveProjectId(+// A run resolves the project separately for the sandbox, the RAG scope and the+// instructions, and while a fresh thread's row is still being written they all+// take the composer fallback. Answered once per thread and reused, or a+// navigation between those calls mixes two projects into one request.+const composerProjectByPendingThread = new Map<string, string | null>();++/** The project the run started in, kept for the whole run. Only the first send+ * for a thread records one: a later run finds the row and never consults it. */+function rememberComposerProjectForRun(+ threadId: string,+ projectId: string | null,+): void {+ // An incognito thread never has a row, so resolveProjectId answers before it+ // reads the map: an entry here would be one nothing ever removes.+ if (isThreadIncognito(threadId)) return;+ if (!composerProjectByPendingThread.has(threadId)) {+ composerProjectByPendingThread.set(threadId, projectId);+ }+}++export async function resolveProjectId(threadId: string | undefined,readThreadRecord?: ThreadRecordReader,+ // A caller that gates on the answer (the queue's indexing probe) has to tell+ // "no project" from "could not read the row": one sends, the other waits. It+ // also names its own fallback, since the store names whichever project is on+ // screen when it polls rather than the one it is waiting for.+ opts?: { rethrowReadFailure?: boolean; composerProjectId?: string | null },): Promise<string | null> {+ // Read before the await: a send survives navigation, so a store read after the+ // lookup could hand this request the project the user moved to.+ const composerProjectId =+ opts?.composerProjectId !== undefined+ ? opts.composerProjectId+ : useChatRuntimeStore.getState().activeProjectId;if (threadId) {- const thread = await (- readThreadRecord?.() ?? getStoredChatThread(threadId)- ).catch(() => null);- return thread?.projectId ?? null;- }- const projectId = useChatRuntimeStore.getState().activeProjectId;- if (!projectId) {- return null;+ let thread: ThreadRecord | undefined;+ try {+ thread = await (readThreadRecord?.() ?? getStoredChatThread(threadId));+ } catch (error) {+ // A failed lookup is not proof the row is missing, so it must not adopt+ // whichever project the composer last had open.+ if (opts?.rethrowReadFailure) throw error;+ return null;+ }+ if (thread) {+ composerProjectByPendingThread.delete(threadId);+ return thread.projectId ?? null;+ }+ // No row yet: initialize() does not await the write, so a fresh chat's first+ // send can read ahead of it and drop the project's sources, instructions and+ // sandbox. An incognito thread is never persisted, so its miss is the answer.+ if (isThreadIncognito(threadId)) {+ return null;+ }+ const pending = composerProjectByPendingThread.get(threadId);+ if (pending !== undefined) {+ return pending;+ }+ // Not recorded here: the send records it, and this also runs off a run (the+ // queue probe, the token-count extras), where a poll landing mid-navigation+ // would pin the run to whichever project is on screen.}- return projectId;+ return composerProjectId ?? null;}async function resolveSandboxSessionId(@@ -3537,6 +3587,11 @@ export function createOpenAIStreamAdapter(unstable_threadId,unstable_assistantMessageId,}) {+ // Before the first await: hydration and a model load both run ahead of the+ // first resolveProjectId, and a send survives navigation. Only consulted+ // while the thread's own row is still missing.+ const composerProjectIdAtSend =+ useChatRuntimeStore.getState().activeProjectId ?? null;await useChatRuntimeStore.getState().hydratePersistedSettings();// Every run reaches here: the composer, Reload, Continue, and send from the edit// composer. Waiting for the open chat's own settings in this one place is what@@ -3559,7 +3614,11 @@ export function createOpenAIStreamAdapter(let runtime = useChatRuntimeStore.getState();// Capture the thread ID once so it stays stable even if the user// switches chats while waiting for model load / auto-load.- const resolvedThreadId = (runThreadId ?? runtime.activeThreadId) || undefined;+ const resolvedThreadId =+ (runThreadId ?? runtime.activeThreadId) || undefined;+ if (resolvedThreadId) {+ rememberComposerProjectForRun(resolvedThreadId, composerProjectIdAtSend);+ }const sharedThreadRecordRead = resolvedThreadId? createRetryableSharedRead(() => getStoredChatThreadReadResult(resolvedThreadId),diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 75acc49c7bb..b2716753464 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -192,9 +192,11 @@ import {CHAT_IMAGE_TOOLS_ENABLED_KEY,CHAT_TOOLS_ENABLED_KEY,CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,+ PENDING_CHAT_ATTACHMENT_KEY,hasGgufSource,isDownloadableHubRepo,loadOptionalBool,+ readPendingAttachmentTargetClaim,threadScopedOverride,useChatRuntimeStore,} from "./stores/chat-runtime-store";@@ -1352,6 +1354,32 @@ function ProjectLanding({[projectId],);+ // No composer ever records under this, so passing it refuses the adoption.+ // (adoptPendingProjectAttachmentTarget only adopts on an exact claim match.)+ const NO_SUCH_CLAIM = -1;++ // The claim the composer on screen recorded its attach choice under: every+ // fresh composer shares one pending key, so only the claim tells them apart.+ const pendingTargetClaimRef = useRef<{+ nonce: string;+ claim: number;+ } | null>(null);+ useEffect(() => {+ return useChatRuntimeStore.subscribe((state) => {+ const pending =+ state.projectAttachmentTargetByThread[PENDING_CHAT_ATTACHMENT_KEY];+ if (pending === undefined) return;+ // By claim, not by value: picking the same destination twice rewrites the+ // same string under a new claim, and skipping it reads as somebody else's.+ const claim = readPendingAttachmentTargetClaim();+ const captured = pendingTargetClaimRef.current;+ if (captured?.nonce === newThreadNonce && captured.claim === claim) {+ return;+ }+ pendingTargetClaimRef.current = { nonce: newThreadNonce, claim };+ });+ }, [newThreadNonce]);+useEffect(() => {if (!activeThreadId) {// Leaving a created chat for a new one: rotate the nonce so the runtime@@ -1365,8 +1393,20 @@ function ProjectLanding({if (activeThreadId === initialActiveThreadRef.current) {return;}+ // Hand the composer's attach choice to the chat it just created: setting+ // this swaps ProjectComposer for Thread, so the bar holding the choice+ // unmounts without seeing the id and its cleanup drops it. Its own choice+ // only, or a send materializing after another composer opened would consume+ // that one's pick; an unrecognised claim is refused.+ const captured = pendingTargetClaimRef.current;+ useChatRuntimeStore+ .getState()+ .adoptPendingProjectAttachmentTarget(+ activeThreadId,+ captured?.nonce === newThreadNonce ? captured.claim : NO_SUCH_CLAIM,+ );setPendingNewThreadId(activeThreadId);- }, [activeThreadId, pendingNewThreadId]);+ }, [activeThreadId, pendingNewThreadId, newThreadNonce]);useEffect(() => {let cancelled = false;diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 6fdb8cb8b80..24453e265ce 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -194,6 +194,7 @@ export {export {deleteStoredChatThreads,ensureStoredChatThread,+ getStoredChatThread,isThreadIncognito,listStoredChatMessages,listStoredChatThreads,diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 2c84fbf6724..2a22659e96a 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -28,6 +28,12 @@ import {getPresetSource,} from "../presets/preset-policy";import { normalizePresetLoadConfig } from "../presets/preset-load-config";+import {+ CHAT_PROJECT_ATTACHMENT_TARGET_KEY,+ DEFAULT_PROJECT_ATTACHMENT_TARGET,+ normalizeProjectAttachmentTarget,+ type ProjectAttachmentTarget,+} from "../utils/project-attachment-target";import { getExternalMaxOutputTokens } from "../provider-capabilities";import {PERSISTED_INFERENCE_PARAM_KEYS,@@ -130,6 +136,19 @@ const PERSISTED_SPEC_MODES = new Set(["auto", "ngram", "off"]);export type RagSource = { type: "thread" } | { type: "kb"; kbId: string };+/** Where the composer files an attachment in a project chat. `project` indexes++/** Key a choice made in a chat that has no id yet lives under until it gets one. */+export const PENDING_CHAT_ATTACHMENT_KEY = "__pending__";++/** Bumped whenever the pending entry changes hands, so a composer that read it+ * can tell whether the one sitting there afterwards is still its own. */+let pendingAttachmentTargetClaim = 0;++export function readPendingAttachmentTargetClaim(): number {+ return pendingAttachmentTargetClaim;+}+export type RagMode = "hybrid" | "lexical" | "dense";export const DEFAULT_RAG_SOURCE: RagSource = { type: "thread" };@@ -197,6 +216,12 @@ function saveRagSource(value: RagSource): void {persistSetting(CHAT_RAG_SOURCE_KEY, JSON.stringify(value));}+function loadProjectAttachmentTarget(): ProjectAttachmentTarget {+ return normalizeProjectAttachmentTarget(+ loadString(CHAT_PROJECT_ATTACHMENT_TARGET_KEY, DEFAULT_PROJECT_ATTACHMENT_TARGET),+ );+}+function loadRagMode(): RagMode {const raw = loadString(CHAT_RAG_MODE_KEY, DEFAULT_RAG_MODE);return raw === "lexical" || raw === "dense" ? raw : "hybrid";@@ -2184,6 +2209,11 @@ type ChatRuntimeStore = {mcpEnabledForChat: boolean;ragEnabled: boolean;ragSource: RagSource;+ /** Default composer attachment scope for chats inside a project. */+ projectAttachmentTarget: ProjectAttachmentTarget;+ /** Per-chat override of that default, so a pick in one chat does not redirect+ * the rest. Session-only: a reload falls back to the saved default. */+ projectAttachmentTargetByThread: Record<string, ProjectAttachmentTarget>;ragMode: RagMode;ragTopK: number;// autoInject = forced first-pass retrieval before answering.@@ -2518,6 +2548,18 @@ type ChatRuntimeStore = {setRagEnabled: (enabled: boolean) => void;setRememberParamsPerModel: (enabled: boolean) => void;setRagSource: (source: RagSource) => void;+ setProjectAttachmentTarget: (target: ProjectAttachmentTarget) => void;+ setThreadProjectAttachmentTarget: (+ threadId: string | null,+ target: ProjectAttachmentTarget,+ ) => void;+ /** Carry a choice made before the chat existed onto its new id. `claim` is+ * the value readPendingAttachmentTargetClaim gave when the choice was made;+ * a newer one means the entry now belongs to a different composer. */+ adoptPendingProjectAttachmentTarget: (threadId: string, claim?: number) =>+ void;+ /** Drop a choice made in a composer that never became a chat. */+ clearPendingProjectAttachmentTarget: () => void;setRagMode: (mode: RagMode) => void;setRagTopK: (topK: number) => void;setRagAutoInject: (value: RagAutoInject) => void;@@ -3319,6 +3361,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({// RAG is opt-in per session: always starts off, never restored from storage.ragEnabled: false,ragSource: loadRagSource(),+ projectAttachmentTarget: loadProjectAttachmentTarget(),+ projectAttachmentTargetByThread: {},ragMode: loadRagMode(),ragTopK: loadRagTopK(),ragAutoInject: loadRagAutoInject(),@@ -4384,6 +4428,57 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),+ setProjectAttachmentTarget: (projectAttachmentTarget) =>+ set(() => {+ saveString(CHAT_PROJECT_ATTACHMENT_TARGET_KEY, projectAttachmentTarget);+ return { projectAttachmentTarget };+ }),+ setThreadProjectAttachmentTarget: (threadId, target) =>+ set((state) => {+ if (threadId === null) {+ pendingAttachmentTargetClaim += 1;+ }+ return {+ projectAttachmentTargetByThread: {+ ...state.projectAttachmentTargetByThread,+ [threadId ?? PENDING_CHAT_ATTACHMENT_KEY]: target,+ },+ };+ }),+ adoptPendingProjectAttachmentTarget: (threadId, claim) =>+ set((state) => {+ // The entry under the shared key need not be the caller's: an abandoned+ // composer has had its own dropped and the next one's is sitting there,+ // which handing it over would consume.+ if (claim !== undefined && claim !== pendingAttachmentTargetClaim) {+ return state;+ }+ const pending =+ state.projectAttachmentTargetByThread[PENDING_CHAT_ATTACHMENT_KEY];+ // A chat that already made its own choice keeps it: the pending entry+ // belongs to a chat that does not exist yet.+ if (+ pending === undefined ||+ threadId in state.projectAttachmentTargetByThread+ ) {+ return state;+ }+ const next = { ...state.projectAttachmentTargetByThread };+ delete next[PENDING_CHAT_ATTACHMENT_KEY];+ next[threadId] = pending;+ return { projectAttachmentTargetByThread: next };+ }),+ clearPendingProjectAttachmentTarget: () =>+ set((state) => {+ const byThread = state.projectAttachmentTargetByThread;+ if (!(PENDING_CHAT_ATTACHMENT_KEY in byThread)) {+ return state;+ }+ pendingAttachmentTargetClaim += 1;+ const next = { ...byThread };+ delete next[PENDING_CHAT_ATTACHMENT_KEY];+ return { projectAttachmentTargetByThread: next };+ }),setRememberParamsPerModel: (rememberParamsPerModel) =>set((state) => {setScalarSettingVersion(diff --git a/studio/frontend/src/features/chat/utils/project-attachment-target.ts b/studio/frontend/src/features/chat/utils/project-attachment-target.tsnew file mode 100644index 00000000000..0399cc74362--- /dev/null+++ b/studio/frontend/src/features/chat/utils/project-attachment-target.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Where a file attached in a project chat is indexed: `project` into the shared+ * sources, `thread` into the one chat. Ignored outside a project. Its own module,+ * with no imports, so a stored value can be tested without the runtime store. */+export type ProjectAttachmentTarget = "project" | "thread";++export const CHAT_PROJECT_ATTACHMENT_TARGET_KEY =+ "unsloth_chat_project_attachment_target";++// A project exists to share context, so its chats default to the whole project.+export const DEFAULT_PROJECT_ATTACHMENT_TARGET: ProjectAttachmentTarget = "project";++/** The target a stored value means, for any string a profile might hold. Nothing+ * stored is an install that never chose, which gets the default; a value this+ * build does not know came from a later one, and the safe reading of that is the+ * narrow scope, since only the wider one can file a file where nobody meant. */+export function normalizeProjectAttachmentTarget(+ raw: string | null | undefined,+): ProjectAttachmentTarget {+ if (raw === "project" || raw === "thread") return raw;+ return raw ? "thread" : DEFAULT_PROJECT_ATTACHMENT_TARGET;+}diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 349c691cc2c..68bf7ca2c6e 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -32,6 +32,18 @@ function parseErrorText(status: number, body: unknown): string {return `Request failed (${status})`;}+/** The message a caller shows, plus the status one has to branch on: a 404 is an+ * answer, a network failure is not. */+export function ragError(status: number, body: unknown): Error & { status: number } {+ return Object.assign(new Error(parseErrorText(status, body)), { status });+}++/** True for a failure the server answered definitively, so retrying cannot help. */+export function isRagClientError(error: unknown): boolean {+ const status = (error as { status?: unknown } | null)?.status;+ return typeof status === "number" && status >= 400 && status < 500 && status !== 429;+}+async function ragRequest<T>(path: string,init?: { method?: string; body?: object },@@ -49,7 +61,7 @@ async function ragRequest<T>(// Every RAG endpoint but the list gates on the extension loading, so its status is// also an availability answer. See api/rag-availability.noteRagResponse(response.status, json);- if (!response.ok) throw new Error(parseErrorText(response.status, json));+ if (!response.ok) throw ragError(response.status, json);return json as T;}@@ -80,7 +92,7 @@ async function ragUpload(const json = await response.json().catch(() => null);// Uploads bypass ragRequest, so they have to report availability themselves.noteRagResponse(response.status, json);- if (!response.ok) throw new Error(parseErrorText(response.status, json));+ if (!response.ok) throw ragError(response.status, json);return json as DocumentUploadResult;}@@ -219,28 +231,27 @@ export async function projectHasSources(projectId: string): Promise<boolean> {}}-export const PROJECT_SOURCES_UPDATED_EVENT = "unsloth-project-sources-updated";+/** Fired on every project-source mutation. The composer's bar and the Sources+ * panel are separate hooks over one scope, so each has to hear the other. */+export const PROJECT_SOURCES_CHANGED_EVENT = "unsloth-project-sources-changed";+/** Earlier name for the same event, so existing listeners keep working. */+export const PROJECT_SOURCES_UPDATED_EVENT = PROJECT_SOURCES_CHANGED_EVENT;+/** Drop the probe's cached answer, and nothing else: callers invalidate before+ * their own mutation too, where a refetch would resurrect a dropped row. */export function invalidateProjectSources(projectId: string): void {projectSourcesCache.delete(projectId);}-/** Invalidate, and tell a mounted sources list its documents changed. Kept apart- * from invalidateProjectSources because callers invalidate the probe *before*- * their own mutation too, and refetching at that point would resurrect a row the- * panel has already dropped optimistically. */+/** Invalidate, then tell every mounted list, in this tab and in the others a+ * CustomEvent never reaches. Call after a mutation. */export function announceProjectSourcesUpdated(projectId: string): void {- projectSourcesCache.delete(projectId);- if (typeof window === "undefined") return;- window.dispatchEvent(- new CustomEvent(PROJECT_SOURCES_UPDATED_EVENT, { detail: { projectId } }),- );+ publishProjectSourcesChanged(projectId);+ getProjectChannel()?.postMessage({ kind: "sources", projectId });}-/** Run `onUpdated` whenever this project's sources change somewhere else in the- * app. Returns the unsubscribe, so a component can hand it straight back from an- * effect. Lives here rather than inline in the panel so the filtering and the- * teardown are testable without a DOM. */+/** Run `onUpdated` when this project's sources change elsewhere. Returns the+ * unsubscribe. */export function subscribeProjectSourcesUpdated(projectId: string,onUpdated: () => void,@@ -251,10 +262,371 @@ export function subscribeProjectSourcesUpdated(// Another project's save must not refetch this one's list.if (detail?.projectId === projectId) onUpdated();};- window.addEventListener(PROJECT_SOURCES_UPDATED_EVENT, listener);+ window.addEventListener(PROJECT_SOURCES_CHANGED_EVENT, listener);+ subscribeProjectSourcesBroadcast();return () => {- window.removeEventListener(PROJECT_SOURCES_UPDATED_EVENT, listener);+ window.removeEventListener(PROJECT_SOURCES_CHANGED_EVENT, listener);+ };+}++function publishProjectSourcesChanged(projectId: string): void {+ projectSourcesCache.delete(projectId);+ if (typeof window === "undefined") return;+ window.dispatchEvent(+ new CustomEvent(PROJECT_SOURCES_CHANGED_EVENT, { detail: { projectId } }),+ );+}++/** Every tab on this origin shares a project's sources, and a CustomEvent reaches+ * only its own tab, so a second tab would list what it saw first for the probe's+ * whole TTL. Opened lazily, so importing this module starts nothing. */+let projectChannel: BroadcastChannel | null | undefined;++function getProjectChannel(): BroadcastChannel | null {+ if (projectChannel !== undefined) {+ return projectChannel;+ }+ if (+ typeof window === "undefined" ||+ typeof BroadcastChannel === "undefined"+ ) {+ projectChannel = null;+ return null;+ }+ projectChannel = new BroadcastChannel(PROJECT_SOURCES_CHANGED_EVENT);+ // Node's BroadcastChannel holds the event loop open and hangs a test run.+ // Browsers have no unref and need none.+ (projectChannel as { unref?: () => void }).unref?.();+ projectChannel.onmessage = (event: MessageEvent) => {+ const message = event.data as {+ kind?: string;+ projectId?: string;+ delta?: number;+ count?: number;+ from?: string;+ } | null;+ if (!message) {+ return;+ }+ // A tab that opened mid-upload asking what is already running.+ if (message.kind === "work-query") {+ answerWorkQuery();+ return;+ }+ if (!message.projectId) {+ return;+ }+ if (message.kind === "work-state" && message.from) {+ seedRemoteProjectWork(+ message.projectId,+ message.from,+ message.count ?? 0,+ );+ return;+ }+ if (message.kind === "work" && message.from) {+ noteRemoteProjectWork(+ message.projectId,+ message.from,+ message.delta ?? 0,+ );+ return;+ }+ if (message.kind === "work" || message.kind === "work-state") {+ return;+ }+ publishProjectSourcesChanged(message.projectId);};+ askForWorkInFlight();+ return projectChannel;+}++/** BroadcastChannel does not replay, so a tab opening mid-upload hears nothing+ * until that upload completes. Ask on the way in instead. */+function askForWorkInFlight(): void {+ projectChannel?.postMessage({ kind: "work-query" });+}++function answerWorkQuery(): void {+ const channel = getProjectChannel();+ if (!channel) return;+ for (const [projectId, count] of projectWorkInFlight) {+ channel.postMessage({ kind: "work-state", projectId, count, from: TAB_ID });+ }+}++/** This tab, so its work is counted apart from every other tab's: merged into one+ * project-wide count, the first upload to finish would release the second. */+const TAB_ID = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;++/** Listeners only hear another tab once the channel is open. */+export function subscribeProjectSourcesBroadcast(): void {+ getProjectChannel();+}++/**+ * Work in flight against a project's sources, by project. A project's sources+ * are changed from the Sources tab as well as the composer, and the instance+ * that is not doing it holds no row for the work until it lands: an upload for+ * the length of its POST, a folder sync for the length of the job. Without this+ * the composer reports nothing indexing, stops polling, and lets a send go out+ * that the sources it is waiting on cannot reach.+ */+const projectWorkInFlight = new Map<string, number>();++export const PROJECT_WORK_CHANGED_EVENT = "unsloth-project-work-changed";++export function noteProjectWork(projectId: string, delta: number): void {+ const next = (projectWorkInFlight.get(projectId) ?? 0) + delta;+ if (next > 0) {+ projectWorkInFlight.set(projectId, next);+ } else {+ projectWorkInFlight.delete(projectId);+ }+ getProjectChannel()?.postMessage({+ kind: "work",+ projectId,+ delta,+ from: TAB_ID,+ });+ syncWorkHeartbeat();+ publishProjectWorkChanged(projectId);+}++/** Renew the deadline the other tabs put on this tab's work: a large upload+ * outlives it with no delta to send in between. The absolute count, not a zero+ * delta, since a delta cannot revive an entry the receiver has let lapse. */+const WORK_HEARTBEAT_MS = 45_000;+let workHeartbeat: ReturnType<typeof setInterval> | null = null;++function syncWorkHeartbeat(): void {+ if (projectWorkInFlight.size === 0) {+ if (workHeartbeat !== null) {+ clearInterval(workHeartbeat);+ workHeartbeat = null;+ }+ return;+ }+ if (workHeartbeat !== null) {+ return;+ }+ workHeartbeat = setInterval(answerWorkQuery, WORK_HEARTBEAT_MS);+ (workHeartbeat as { unref?: () => void }).unref?.();+}++function publishProjectWorkChanged(projectId: string): void {+ if (typeof window === "undefined") {+ return;+ }+ window.dispatchEvent(+ new CustomEvent(PROJECT_WORK_CHANGED_EVENT, { detail: { projectId } }),+ );+}++/** Work another tab reports, with a deadline: only the tab that started it can+ * report the end, and it may be closed first. Past the deadline the gate falls+ * back to the rows the list refresh brings. */+const REMOTE_WORK_TTL_MS = 120_000;+/** Per project, per reporting tab: aggregated, the first upload to finish would+ * clear the count the second is still holding. */+const remoteProjectWork = new Map<+ string,+ Map<string, { count: number; until: number }>+>();+const remoteWorkTimers = new Map<string, ReturnType<typeof setTimeout>>();++function armRemoteWorkExpiry(projectId: string): void {+ const timer = remoteWorkTimers.get(projectId);+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ remoteWorkTimers.delete(projectId);+ const bySender = remoteProjectWork.get(projectId);+ if (!bySender || bySender.size === 0) return;+ // The earliest deadline among the senders, not a fresh TTL: one timer covers+ // the project, so arming it for the tab that just reported would leave a tab+ // that has since closed counted until some later event happens to publish.+ let earliest = Number.POSITIVE_INFINITY;+ for (const entry of bySender.values()) {+ earliest = Math.min(earliest, entry.until);+ }+ const expiry = setTimeout(+ () => {+ remoteWorkTimers.delete(projectId);+ // Drop what has actually lapsed, tell the listeners, then arm for the next+ // deadline, or a listener holds a count nothing comes back to clear.+ const now = Date.now();+ const live = remoteProjectWork.get(projectId);+ if (live) {+ for (const [sender, entry] of live) {+ if (entry.until <= now) live.delete(sender);+ }+ if (live.size === 0) remoteProjectWork.delete(projectId);+ }+ publishProjectWorkChanged(projectId);+ armRemoteWorkExpiry(projectId);+ },+ Math.max(0, earliest - Date.now()),+ );+ // As with the channel: a pending timer would hold a Node test run open.+ (expiry as { unref?: () => void }).unref?.();+ remoteWorkTimers.set(projectId, expiry);+}++function setRemoteProjectWork(+ projectId: string,+ from: string,+ count: number,+): void {+ const bySender = remoteProjectWork.get(projectId) ?? new Map();+ if (count <= 0) {+ bySender.delete(from);+ } else {+ bySender.set(from, { count, until: Date.now() + REMOTE_WORK_TTL_MS });+ }+ if (bySender.size === 0) {+ remoteProjectWork.delete(projectId);+ const timer = remoteWorkTimers.get(projectId);+ if (timer !== undefined) {+ clearTimeout(timer);+ remoteWorkTimers.delete(projectId);+ }+ } else {+ remoteProjectWork.set(projectId, bySender);+ armRemoteWorkExpiry(projectId);+ }+ publishProjectWorkChanged(projectId);+}++function remoteSenderCount(projectId: string, from: string): number {+ const entry = remoteProjectWork.get(projectId)?.get(from);+ return entry && entry.until > Date.now() ? entry.count : 0;+}++function noteRemoteProjectWork(+ projectId: string,+ from: string,+ delta: number,+): void {+ const current = remoteSenderCount(projectId, from);+ // A zero delta is the heartbeat: it renews this sender's deadline only, and+ // says nothing about a sender with nothing running.+ if (delta === 0 && current === 0) return;+ setRemoteProjectWork(projectId, from, Math.max(0, current + delta));+}++/** An absolute count a tab reports, for work it started before this tab was+ * listening and on every heartbeat after. Recorded against that tab alone, since+ * the others answer separately. Always renews the deadline and never lowers a+ * count a delta raised, so a heartbeat also revives a lapsed entry. */+function seedRemoteProjectWork(+ projectId: string,+ from: string,+ count: number,+): void {+ if (count <= 0) return;+ setRemoteProjectWork(projectId, from, Math.max(remoteSenderCount(projectId, from), count));+}++export function projectWorkCount(projectId: string): number {+ let remoteCount = 0;+ const now = Date.now();+ for (const entry of remoteProjectWork.get(projectId)?.values() ?? []) {+ if (entry.until > now) remoteCount += entry.count;+ }+ return (projectWorkInFlight.get(projectId) ?? 0) + remoteCount;+}++/** Reads in a row that fail before the watcher stops waiting on the job. */+const MAX_FOLDER_JOB_READ_FAILURES = 20;++const watchedFolderJobs = new Set<string>();++/** Count a folder sync as work on its project until the backend job ends. Tied+ * to the job, not its starter: leaving the Sources tab aborts that component's+ * stream but not the sync. Bounded, so a job that never reports a terminal state+ * cannot gate a project for the session. */+export function watchProjectFolderJob(projectId: string, jobId: string): void {+ if (watchedFolderJobs.has(jobId)) {+ return;+ }+ watchedFolderJobs.add(jobId);+ noteProjectWork(projectId, 1);+ void (async () => {+ // A read that fails is not a job that ended: a backend restart misses a+ // tick or two while the sync runs on. Give up only once they stop coming.+ let consecutiveFailures = 0;+ try {+ for (let attempt = 0; attempt < 600; attempt += 1) {+ try {+ const job = await getFolderSyncJob(jobId);+ consecutiveFailures = 0;+ if (job.status === "completed" || job.status === "failed") {+ break;+ }+ } catch (error) {+ // An answered 4xx is the job being gone, not a read that failed:+ // unlinking deletes its job rows, and so does the history prune.+ if (isRagClientError(error)) break;+ consecutiveFailures += 1;+ if (consecutiveFailures >= MAX_FOLDER_JOB_READ_FAILURES) {+ break;+ }+ }+ await new Promise((resolve) => setTimeout(resolve, 3000));+ }+ } finally {+ watchedFolderJobs.delete(jobId);+ // The rows this job wrote are new sources, and this watcher is the only+ // observer left once the panel unmounts. Announce before the gate, or a+ // send released by it still reads the cached "no sources".+ announceProjectSourcesUpdated(projectId);+ noteProjectWork(projectId, -1);+ }+ })();+}++/** When a project may be looked at again: a bare per-call lookup doubles every+ * open (two bars mount at once), and a permanent one misses every job the+ * backend's timer starts later. */+const folderReconcileNotBefore = new Map<string, number>();++/** Shorter than the backend's own scan interval, so a periodic caller is never+ * the one skipped. */+const FOLDER_RECONCILE_MIN_GAP_MS = 5000;++/**+ * Pick up folder syncs already running on a project. Their watchers live in the+ * tab that started them, so a reload, or the tab closing, leaves a durable job+ * scanning with nothing counting it. The backend scans before it writes any+ * rows, so the composer's own list cannot see it either and the gate would open+ * on an empty list. Only the Sources panel lists linked folders, and a project+ * opens on Chats, so the composer has to ask.+ */+export async function reconcileProjectFolderJobs(+ projectId: string,+): Promise<void> {+ const now = Date.now();+ if ((folderReconcileNotBefore.get(projectId) ?? 0) > now) return;+ folderReconcileNotBefore.set(projectId, now + FOLDER_RECONCILE_MIN_GAP_MS);+ // Every look, not just the first: a scan writes no row until it is underway,+ // so the list the composer already has proves nothing.+ noteProjectWork(projectId, 1);+ try {+ const folders = await listLinkedFolders({ type: "project", id: projectId });+ for (const folder of folders) {+ if (folder.activeJobId) {+ watchProjectFolderJob(projectId, folder.activeJobId);+ }+ }+ } catch {+ // RAG unavailable or a transient failure. Allow another look rather than+ // recording a project as reconciled on an answer that never came.+ folderReconcileNotBefore.delete(projectId);+ } finally {+ // After the watchers above, which take their own leases, so the two overlap.+ noteProjectWork(projectId, -1);+ }}export async function listLinkedFolders(@@ -343,7 +715,7 @@ export async function deleteDocument(method: "DELETE",},);- if (projectId) invalidateProjectSources(projectId);+ if (projectId) announceProjectSourcesUpdated(projectId);return result;}@@ -363,7 +735,7 @@ async function openEventStream(const body = await response.json().catch(() => null);// also gated on the extension, and also not routed through ragRequestnoteRagResponse(response.status, body);- throw new Error(parseErrorText(response.status, body));+ throw ragError(response.status, body);}if (!response.body) throw new Error("Stream response missing body");return response.body;diff --git a/studio/frontend/src/features/rag/components/document-status-chip.tsx b/studio/frontend/src/features/rag/components/document-status-chip.tsxindex c0cc180daa0..49fa4fcbab4 100644--- a/studio/frontend/src/features/rag/components/document-status-chip.tsx+++ b/studio/frontend/src/features/rag/components/document-status-chip.tsx@@ -4,7 +4,7 @@import { Badge } from "@/components/assistant-ui/badge";import { Spinner } from "@/components/ui/spinner";import { cn } from "@/lib/utils";-import { File02Icon } from "@hugeicons/core-free-icons";+import { File02Icon, Folder02Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { XIcon } from "lucide-react";import type { DocumentStatus } from "../types/rag";@@ -15,27 +15,36 @@ export function DocumentStatusChip({progress,error,onRemove,+ shared = false,}: {filename: string;status: DocumentStatus;progress?: number | null;error?: string | null;onRemove?: () => void;+ /** Indexed for the whole project rather than this one chat: swap the file+ * glyph for a folder so the two scopes are told apart at a glance. */+ shared?: boolean;}) {const processing = status === "pending" || status === "running";return (<Badgevariant="outline"size="sm"- title={error ?? filename}+ title={+ error ??+ (shared+ ? `${filename} — shared with every chat in this project`+ : filename)+ }className={cn("rounded-full inline-flex items-center gap-1.5 max-w-[16rem]",status === "failed" && "border-destructive/40 text-destructive",)}>- {/* file */}+ {/* file, or folder when the doc is a project-wide source */}<HugeiconsIcon- icon={File02Icon}+ icon={shared ? Folder02Icon : File02Icon}strokeWidth={2}className="size-3 shrink-0"/>diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsxindex 94ee3240367..5d4c930da14 100644--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx@@ -13,7 +13,9 @@ import { HugeiconsIcon } from "@hugeicons/react";import { XIcon } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import {+ announceProjectSourcesUpdated,invalidateProjectSources,+ noteProjectWork,uploadProjectDocument,} from "../api/rag-api";import { RAG_UPLOAD_ACCEPT } from "../types/rag";@@ -91,6 +93,22 @@ export async function uploadStagedSources(if (staged.length === 0) return;invalidateProjectSources(projectId);markProjectSourcesPending(projectId);+ // Counted as project work for the whole batch: a tab opening the new project+ // holds no row for a file still uploading, so without this it reports nothing+ // indexing and lets a send go out ahead of the sources it was created with.+ noteProjectWork(projectId, 1);+ try {+ await uploadStaged(projectId, staged);+ } finally {+ announceProjectSourcesUpdated(projectId);+ noteProjectWork(projectId, -1);+ }+}++async function uploadStaged(+ projectId: string,+ staged: StagedSource[],+): Promise<void> {const { ocr, caption } = await resolveVisionOverrides();const documentIds = new Set<string>();const merged: string[] = [];@@ -127,7 +145,6 @@ export async function uploadStagedSources({ description: "Identical contents are stored once." },);}- invalidateProjectSources(projectId);}/** Create-project drop area: stages files until the project exists. */diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsxindex 563e64cdb37..9733af0bcc6 100644--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx@@ -6,6 +6,7 @@ import { FolderAddIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { useCallback, useEffect, useRef } from "react";import {+ announceProjectSourcesUpdated,invalidateProjectSources,listProjectDocuments,subscribeProjectSourcesUpdated,@@ -26,14 +27,16 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {const { documents, loading, uploading, refresh, upload, remove } =useRagDocuments({ type: "project", projectId }, lister);- // Invalidate the sources probe before and after each mutation: a chat sent- // mid-upload must not cache "no sources" for the probe's TTL.+ // Invalidate the sources probe before each mutation so a chat sent mid-upload+ // cannot cache "no sources" for the probe's TTL, and announce after it, which+ // is the half other instances and other tabs listen for. Announcing before+ // would refetch and resurrect the row this panel has already dropped.const handleFiles = useCallback(async (files: File[]) => {if (files.length === 0) return;invalidateProjectSources(projectId);await upload(files);- invalidateProjectSources(projectId);+ announceProjectSourcesUpdated(projectId);},[projectId, upload],);@@ -42,12 +45,12 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {async (documentId: string) => {invalidateProjectSources(projectId);await remove(documentId);- invalidateProjectSources(projectId);+ announceProjectSourcesUpdated(projectId);},[projectId, remove],);const handleLinkedSourcesChanged = useCallback(() => {- invalidateProjectSources(projectId);+ announceProjectSourcesUpdated(projectId);void refresh({ quiet: true });}, [projectId, refresh]);diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsxindex 1b5a1c71fe7..e51a4b8df25 100644--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx@@ -3,14 +3,25 @@import { useCallback, useEffect, useRef, useState } from "react";import { HugeiconsIcon } from "@hugeicons/react";-import { AttachmentIcon, FileDatabaseIcon } from "@hugeicons/core-free-icons";+import {+ AttachmentIcon,+ FileDatabaseIcon,+ Folder02Icon,+} from "@hugeicons/core-free-icons";+import { Tick02Icon } from "@/lib/tick-icon";import { useAui } from "@assistant-ui/react";import { cn } from "@/lib/utils";-import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";+import {+ PENDING_CHAT_ATTACHMENT_KEY,+ readPendingAttachmentTargetClaim,+ useChatRuntimeStore,+} from "@/features/chat/stores/chat-runtime-store";+import type { ProjectAttachmentTarget } from "@/features/chat/utils/project-attachment-target";import {chatHistoryClearBoundary,ChatThreadDeletedError,ensureStoredChatThread,+ getStoredChatThread,isThreadIncognito,} from "@/features/chat";import {@@ -18,8 +29,37 @@ import {useNativeIntentStore,} from "@/features/native-intents";import { toast } from "@/lib/toast";-import { listKnowledgeBases, listThreadDocuments } from "../api/rag-api";-import { RAG_UPLOAD_ACCEPT } from "../types/rag";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ announceProjectSourcesUpdated,+ invalidateProjectSources,+ listKnowledgeBases,+ listProjectDocuments,+ listThreadDocuments,+} from "../api/rag-api";+import { useRagAvailabilityStore } from "../api/rag-availability";+import {+ type DocumentStatus,+ RAG_UPLOAD_ACCEPT,+ type RagDocument,+ isLinkedFolderManaged,+} from "../types/rag";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { DocumentStatusChip } from "./document-status-chip";import { useRagDocuments } from "./use-rag-documents";@@ -80,6 +120,212 @@ async function requireStoredThread(threadId: string): Promise<void> {}}+/** Read-only listing of the project's sources, shown when the Docs pill is off:+ * they still reach the model, so they must not be invisible. */+function InheritedProjectSources({+ documents,+}: {+ documents: { id: string; filename: string; status: DocumentStatus }[];+}) {+ return (+ <div className="mb-2 flex w-full flex-row items-center gap-1.5 pl-0.5 pr-1.5 pt-0.5 pb-1">+ <span+ className="composer-pill-btn shrink-0 cursor-default !text-foreground/60"+ title="This chat retrieves from its project's sources. Manage them in the project's Sources tab."+ >+ <HugeiconsIcon icon={Folder02Icon} strokeWidth={2} className="size-3.5" />+ <span>Project sources</span>+ </span>+ {/* Same cap as the editable list: a linked folder can carry hundreds of+ sources, and an uncapped row would swallow the chat viewport. */}+ <div className="flex max-h-24 flex-1 flex-row flex-wrap items-center gap-1.5 overflow-y-auto">+ {documents.map((doc) => (+ <DocumentStatusChip+ key={`inherited:${doc.id}`}+ filename={doc.filename}+ status={doc.status}+ shared={true}+ />+ ))}+ </div>+ </div>+ );+}++/** The project the displayed chat belongs to, read from the chat's own row: the+ * global activeProjectId still names the project being left during a navigation.+ * `undefined` while unresolved, which holds the attach controls rather than+ * reading as "not in a project". */+/** Reads of the chat's own row before the scope is left unresolved. */+const PROJECT_LOOKUP_RETRIES = 3;++function useThreadProjectId(+ threadId: string | null,+): string | null | undefined {+ const activeProjectId = useChatRuntimeStore((s) => s.activeProjectId);+ const [resolved, setResolved] = useState<{+ threadId: string;+ // The activeProjectId this answer was produced for. A change means the chat+ // may have moved, so the old answer stops counting until the re-read lands.+ trigger: string | null;+ projectId: string | null;+ } | null>(null);++ // activeProjectId is a trigger, not the answer: moving the open chat updates+ // its row and this value without changing the thread id.+ useEffect(() => {+ if (!threadId || isThreadIncognito(threadId)) {+ return;+ }+ let cancelled = false;+ void (async () => {+ // A failed read is not proof of no project, and recording one would file+ // the next attachment into the chat. Retry, then leave it unresolved:+ // nothing re-runs this until the chat or the open project changes.+ for (let attempt = 0; attempt < PROJECT_LOOKUP_RETRIES; attempt += 1) {+ try {+ const thread = await getStoredChatThread(threadId);+ if (cancelled) return;+ // No row yet: initialize() does not await the write, so the composer's+ // project is the answer that row is about to record.+ const projectId = thread ? (thread.projectId ?? null) : activeProjectId;+ setResolved({ threadId, trigger: activeProjectId, projectId });+ return;+ } catch {+ if (cancelled) return;+ await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));+ if (cancelled) return;+ }+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [threadId, activeProjectId]);++ // A chat with no id yet is the one being composed, so it belongs to whatever+ // project the composer is in.+ if (!threadId) {+ return activeProjectId;+ }+ if (isThreadIncognito(threadId)) {+ return null;+ }+ return resolved?.threadId === threadId && resolved.trigger === activeProjectId+ ? resolved.projectId+ : undefined;+}++/** The composer's attach control. Wording and glyph follow the active target, so+ * a project chat says up front where the file is going. */+function AttachFilesButton({+ disabled,+ compact,+ sharesWithProject,+ onClick,+}: {+ disabled: boolean;+ /** Icon-only once documents are attached, to leave the chips room. */+ compact: boolean;+ sharesWithProject: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className={cn(+ "composer-pill-btn shrink-0 -translate-y-px !text-foreground/80",+ // Square button so the rounded-full hover reads as a circle.+ compact && "size-8 justify-center px-0",+ )}+ aria-label={+ sharesWithProject+ ? "Attach documents to this project"+ : "Attach documents to this thread"+ }+ title={+ sharesWithProject+ ? "Attach documents for retrieval, shared with every chat in this project"+ : "Attach documents for retrieval in this chat"+ }+ >+ <HugeiconsIcon+ icon={sharesWithProject ? Folder02Icon : AttachmentIcon}+ strokeWidth={2}+ className="size-3.5"+ />+ {compact ? null : (+ <span>+ {sharesWithProject+ ? "Add files for this project"+ : "Add files to chat with"}+ </span>+ )}+ </button>+ );+}++/** Picks whether new attachments go to the project (shared with every chat in it)+ * or to this chat alone. Only a project chat has the choice. */+function AttachmentTargetMenu({+ disabled,+ sharesWithProject,+ onSelect,+}: {+ disabled: boolean;+ sharesWithProject: boolean;+ onSelect: (target: ProjectAttachmentTarget) => void;+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <button+ type="button"+ disabled={disabled}+ aria-label="Choose where attached files go"+ title="Choose where attached files go"+ className="composer-pill-btn shrink-0 -translate-y-px !text-foreground/60 px-2"+ >+ <span className="text-ui-11">+ {sharesWithProject ? "Project" : "This chat"}+ </span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="unsloth-plus-menu w-64">+ <DropdownMenuLabel>New files go to</DropdownMenuLabel>+ <DropdownMenuItem onSelect={() => onSelect("project")}>+ <HugeiconsIcon+ icon={sharesWithProject ? Tick02Icon : Folder02Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span className="flex flex-col">+ <span>The project</span>+ <span className="text-ui-11 text-muted-foreground">+ Every chat in this project can use them+ </span>+ </span>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onSelect("thread")}>+ <HugeiconsIcon+ icon={sharesWithProject ? AttachmentIcon : Tick02Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span className="flex flex-col">+ <span>This chat only</span>+ <span className="text-ui-11 text-muted-foreground">+ Other chats in the project won't see them+ </span>+ </span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+export function ThreadDocumentsBar({threadId,onIndexingChange,@@ -91,6 +337,15 @@ export function ThreadDocumentsBar({const ragSource = useChatRuntimeStore((s) => s.ragSource);const setRagSource = useChatRuntimeStore((s) => s.setRagSource);const setRagEnabled = useChatRuntimeStore((s) => s.setRagEnabled);+ const projectAttachmentDefault = useChatRuntimeStore(+ (s) => s.projectAttachmentTarget,+ );+ const projectAttachmentTargetByThread = useChatRuntimeStore(+ (s) => s.projectAttachmentTargetByThread,+ );+ const setThreadProjectAttachmentTarget = useChatRuntimeStore(+ (s) => s.setThreadProjectAttachmentTarget,+ );const aui = useAui();const fileInputRef = useRef<HTMLInputElement>(null);@@ -102,14 +357,53 @@ export function ThreadDocumentsBar({const effectiveThreadId = threadId ?? materializedId;const initPromiseRef = useRef<Promise<string | null> | null>(null);const initGenerationRef = useRef(0);+ const hadThreadIdRef = useRef(threadId !== null);useEffect(() => {- if (threadId) {- setMaterializedId(null);- initGenerationRef.current += 1;- initPromiseRef.current = null;+ const hadThreadId = hadThreadIdRef.current;+ hadThreadIdRef.current = threadId !== null;+ if (!threadId) {+ return;+ }+ // A plain send creates the chat too, without ensureThreadId. Hand the+ // earlier choice to the chat that just got an id, or the next one inherits it.+ if (!hadThreadId) {+ useChatRuntimeStore.getState().adoptPendingProjectAttachmentTarget(threadId);}+ setMaterializedId(null);+ initGenerationRef.current += 1;+ initPromiseRef.current = null;}, [threadId]);+ // An abandoned composer leaves its choice under the pending key, where the+ // next new chat would claim it. Adoption removes the key, so this drops only+ // what nobody claimed.+ useEffect(+ () => () =>+ useChatRuntimeStore.getState().clearPendingProjectAttachmentTarget(),+ [],+ );++ // Mirrors chat-adapter's rag_scope: an active KB replaces the project scope,+ // but a KB preference left over while the pill is off does not.+ const threadProjectId = useThreadProjectId(effectiveThreadId);+ // Attaching before the row has been read would file the file by guess.+ const projectUnresolved = threadProjectId === undefined;+ // A host where the vector extension cannot load answers 503 to every project+ // source request, so do not open a scope it can only fail.+ const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());+ const projectId =+ (ragEnabled && ragSource.type === "kb") || ragUnavailable+ ? null+ : (threadProjectId ?? null);+ // This chat's own choice if it made one, otherwise the saved default. Keeps a+ // pick in one chat from redirecting every other chat in the project.+ const projectAttachmentTarget =+ projectAttachmentTargetByThread[+ effectiveThreadId ?? PENDING_CHAT_ATTACHMENT_KEY+ ] ?? projectAttachmentDefault;+ const sharesWithProject =+ projectId !== null && projectAttachmentTarget === "project";+const lister = useCallback(() =>effectiveThreadId@@ -117,19 +411,49 @@ export function ThreadDocumentsBar({: Promise.resolve([]),[effectiveThreadId],);- const { documents, uploading, upload, remove } = useRagDocuments(+ const {+ documents,+ uploading,+ hasIndexing: threadIndexing,+ loading: threadListLoading,+ upload,+ remove,+ } = useRagDocuments(effectiveThreadId && ragEnabled && ragSource.type === "thread"? { type: "thread", threadId: effectiveThreadId }: null,lister,);+ // The project's shared sources, listed alongside this chat's own so a file added+ // from another chat is visible rather than silently in effect. Retrieval already+ // combines both scopes (core/rag/tool.py).+ const projectLister = useCallback(+ () => (projectId ? listProjectDocuments(projectId) : Promise.resolve([])),+ [projectId],+ );+ const {+ documents: projectDocuments,+ uploading: projectUploading,+ hasIndexing: projectIndexing,+ loading: projectListLoading,+ upload: uploadToProject,+ remove: removeFromProject,+ } = useRagDocuments(+ projectId ? { type: "project", projectId } : null,+ projectLister,+ );+// Tell the composer whether any doc is still indexing, so it can hold a queued// send until retrieval covers them (Composer.enqueueSend). For KB / RAG-off scope- // is null, so `documents` is empty and this reads false.- const hasIndexing = documents.some(- (d) => d.status === "pending" || d.status === "running",- );+ // is null, so both lists are empty and this reads false.+ // From the hooks, not the rows: work started in the Sources panel is in flight+ // before either instance has a row for it, and a job already running on a+ // reopened project arrives with the first list, so hold until that lands.+ // Both scopes hold on their first list, for the same reason: reopening a chat+ // whose own attachment was still indexing lists nothing until it lands either.+ const hasIndexing =+ threadIndexing || threadListLoading || projectIndexing || projectListLoading;useEffect(() => {onIndexingChange?.(hasIndexing);}, [hasIndexing, onIndexingChange]);@@ -153,11 +477,17 @@ export function ThreadDocumentsBar({}const clearGeneration = chatHistoryClearBoundary.capture();const generation = ++initGenerationRef.current;+ // Taken before the await: this composer can be abandoned while it runs, and+ // the choice under the shared key would then be the next composer's.+ const claim = readPendingAttachmentTargetClaim();const pending = aui.threadListItem().initialize().then(async ({ remoteId }) => {await requireStoredThread(remoteId);+ useChatRuntimeStore+ .getState()+ .adoptPendingProjectAttachmentTarget(remoteId, claim);// a clear that landed while the row write was in flight is deleting this threadif (chatHistoryClearBoundary.capture() !== clearGeneration) {throw new Error("Chat history was cleared");@@ -182,6 +512,30 @@ export function ThreadDocumentsBar({return pending;}, [aui, effectiveThreadId]);+ // One entry point for the picker and desktop drops: project files go straight+ // there, per-chat files materialize the thread first. The probe caches for 30s,+ // so invalidate both sides or a send mid-index reads a stale "no sources".+ const attach = useCallback(+ (items: Parameters<typeof upload>[0]) => {+ if (sharesWithProject && projectId) {+ invalidateProjectSources(projectId);+ // Explicit scope: a desktop drop enables RAG and attaches in the same+ // tick, so the hook's own scope is still null on this render.+ void uploadToProject(items, { type: "project", projectId }).finally(() =>+ announceProjectSourcesUpdated(projectId),+ );+ return;+ }+ // The id as a promise, so upload() flips its in-flight guard before+ // materialization re-renders us: on the first click `scope` is null.+ const threadScope = ensureThreadId().then((id) =>+ id ? ({ type: "thread", threadId: id } as const) : null,+ );+ void upload(items, threadScope);+ },+ [ensureThreadId, projectId, sharesWithProject, upload, uploadToProject],+ );+// Desktop drops land in the native-intent store because the drop listener lives on// the chat page; only the chat that received the OS drop may drain its batch.const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();@@ -195,6 +549,11 @@ export function ThreadDocumentsBar({if (!hasPendingAttachments || !nativeAttachmentTargetKey) {return;}+ // Hold the batch rather than draining it into the wrong scope. The intents+ // stay in the store, so this runs again once the row has been read.+ if (projectUnresolved) {+ return;+ }// A KB-scoped chat uploads through the KB dialog, so a thread upload here would// index into something this bar never shows.if (ragEnabled && ragSource.type === "kb") {@@ -213,7 +572,7 @@ export function ThreadDocumentsBar({setRagSource({ type: "thread" });setRagEnabled(true);}- void upload(+ attach(intents.map((intent) => ({kind: "native" as const,token: intent.path.token,@@ -221,15 +580,12 @@ export function ThreadDocumentsBar({sizeBytes: intent.path.sizeBytes,modifiedMs: intent.path.modifiedMs,})),- ensureThreadId().then((id) =>- id ? ({ type: "thread", threadId: id } as const) : null,- ),);}, [hasPendingAttachments,+ projectUnresolved,nativeAttachmentTargetKey,- upload,- ensureThreadId,+ attach,ragEnabled,ragSource,setRagSource,@@ -238,6 +594,9 @@ export function ThreadDocumentsBar({const chipScrollRef = useRef<HTMLDivElement>(null);const [chipsOverflow, setChipsOverflow] = useState(false);+ // Removing a project source here deletes it for every chat, beside a chat chip+ // whose X is undoable. Confirm, as the Sources tab and Settings do.+ const [removingShared, setRemovingShared] = useState<RagDocument | null>(null);const updateChipFade = useCallback(() => {const el = chipScrollRef.current;if (!el) return;@@ -254,36 +613,42 @@ export function ThreadDocumentsBar({fileInputRef.current?.click();}, []);- // Shown whenever the RAG pill is on: ingestion only needs the embedder, so- // files can index before a chat model loads.- if (!ragEnabled) return null;// A KB source uploads via the KB dialog, not here; show which KB is active.- if (ragSource.type === "kb") {+ if (ragEnabled && ragSource.type === "kb") {return <KnowledgeBaseSourceChip kbId={ragSource.kbId} />;}+ // Project sources retrieve whether the Docs pill is on or not (chat-adapter's+ // projectRagEnabled), so list them either way rather than letting the model+ // answer from files the user cannot see. The attach controls stay behind the+ // pill: with it off, thread scope is inert.+ if (!ragEnabled) {+ return projectDocuments.length > 0 ? (+ <InheritedProjectSources documents={projectDocuments} />+ ) : null;+ }++ // Attaching before the chat's project is known would file the file by guess.+ const busy = uploading || projectUploading || projectUnresolved;+ const chipCount = documents.length + projectDocuments.length;return (<div className="mb-2 flex w-full flex-row items-start gap-1.5 pl-0.5 pr-1.5 pt-0.5 pb-1">- <button- type="button"+ <AttachFilesButton+ disabled={busy}+ compact={chipCount > 0}+ sharesWithProject={sharesWithProject}onClick={handleAddDocs}- disabled={uploading}- className={cn(- "composer-pill-btn shrink-0 -translate-y-px !text-foreground/80",- // Square button so the rounded-full hover reads as a circle.- documents.length > 0 && "size-8 justify-center px-0",- )}- aria-label="Attach documents to this thread"- title="Attach documents for retrieval"- >- <HugeiconsIcon- icon={AttachmentIcon}- strokeWidth={2}- className="size-3.5"+ />+ {/* Only a project chat has two scopes to choose between. */}+ {projectId ? (+ <AttachmentTargetMenu+ disabled={busy}+ sharesWithProject={sharesWithProject}+ onSelect={(target) =>+ setThreadProjectAttachmentTarget(effectiveThreadId, target)+ }/>- {/* Icon-only once documents are attached. */}- {documents.length === 0 && <span>Add files to chat with</span>}- </button>+ ) : null}<inputref={fileInputRef}type="file"@@ -294,14 +659,7 @@ export function ThreadDocumentsBar({const files = Array.from(e.target.files ?? []);e.target.value = "";if (files.length === 0) return;- // Pass the id as a promise so upload() flips its in-flight guard before- // materialization re-renders us; on the first click `scope` is still null.- void upload(- files,- ensureThreadId().then((id) =>- id ? ({ type: "thread", threadId: id } as const) : null,- ),- );+ attach(files);}}/>{/* Cap height so a large set scrolls; fade the cut-off row. */}@@ -313,6 +671,22 @@ export function ThreadDocumentsBar({chipsOverflow && "rag-docs-bottom-fade",)}>+ {/* Project sources first: inherited context, and it outlives this chat. */}+ {projectDocuments.map((doc) => (+ <DocumentStatusChip+ key={`project:${doc.id}`}+ filename={doc.filename}+ status={doc.status}+ progress={doc.progress}+ error={doc.error}+ shared={true}+ onRemove={+ doc.id.startsWith("pending_") || isLinkedFolderManaged(doc)+ ? undefined+ : () => setRemovingShared(doc)+ }+ />+ ))}{documents.map((doc) => (<DocumentStatusChipkey={doc.id}@@ -328,6 +702,35 @@ export function ThreadDocumentsBar({/>))}</div>+ <AlertDialog+ open={removingShared !== null}+ onOpenChange={(open) => {+ if (!open) setRemovingShared(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Remove from project sources</AlertDialogTitle>+ <AlertDialogDescription>+ Remove "{removingShared?.filename}"? Every chat in this project+ loses it, and the file and its indexed content are deleted. This+ cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => {+ const doc = removingShared;+ setRemovingShared(null);+ if (doc) void removeFromProject(doc.id);+ }}+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}diff --git a/studio/frontend/src/features/rag/components/use-linked-folders.ts b/studio/frontend/src/features/rag/components/use-linked-folders.tsindex 5f0b04499b7..5cc70884e9c 100644--- a/studio/frontend/src/features/rag/components/use-linked-folders.ts+++ b/studio/frontend/src/features/rag/components/use-linked-folders.ts@@ -10,13 +10,16 @@ import { createScopedSingleFlightRequest } from "@/lib/single-flight-request";import { toast } from "@/lib/toast";import { useCallback, useEffect, useRef, useState } from "react";import {+ announceProjectSourcesUpdated,createLinkedFolder,deleteLinkedFolder,getFolderSyncJob,listLinkedFolders,+ noteProjectWork,rebuildLinkedFolder,streamFolderSyncJobEvents,syncLinkedFolder,+ watchProjectFolderJob,} from "../api/rag-api";import type {FolderSyncJob,@@ -51,6 +54,32 @@ export function useLinkedFolders(const folderSnapshot = useRef<LinkedFolder[] | null>(null);const notifiedJobs = useRef(new Set<string>());+ // The backend starts the job before it answers, so the window before trackJob+ // registers it is the project changing with nothing gating on it. trackJob+ // takes its own lease inside this one, so the two overlap.+ const projectWorkScopeId = scopeType === "project" ? scopeId : null;+ const withProjectWork = useCallback(+ async <T>(run: () => Promise<T>): Promise<T> => {+ if (!projectWorkScopeId) return run();+ noteProjectWork(projectWorkScopeId, 1);+ try {+ return await run();+ } finally {+ noteProjectWork(projectWorkScopeId, -1);+ }+ },+ [projectWorkScopeId],+ );++ /** Count a job against the project it was started for, whatever this hook is+ * showing by the time the response lands. */+ const watchStartedJob = useCallback(+ (jobId: string) => {+ if (projectWorkScopeId) watchProjectFolderJob(projectWorkScopeId, jobId);+ },+ [projectWorkScopeId],+ );+const notifySourcesChanged = useCallback((job: FolderSyncJob) => {if (notifiedJobs.current.has(job.id)) return;@@ -63,6 +92,12 @@ export function useLinkedFolders(const trackJob = useCallback((initial: FolderSyncJob) => {if (controllers.current.has(initial.id)) return;+ // A sync reports at start and completion only, so the composer has nothing+ // to gate on in between. The count follows the job, not this component:+ // leaving the Sources tab aborts the stream below but not the sync.+ if (scopeType === "project" && scopeId) {+ watchProjectFolderJob(scopeId, initial.id);+ }setJobs((current) => ({ ...current, [initial.linkedFolderId]: initial }));setFolders((current) =>current.map((folder) =>@@ -142,7 +177,7 @@ export function useLinkedFolders(}})();},- [notifySourcesChanged],+ [notifySourcesChanged, scopeType, scopeId],);const refresh = useCallback(@@ -235,11 +270,15 @@ export function useLinkedFolders(try {const selected = await pickNativeDocumentFolder();if (!selected || currentScopeKey.current !== operationScopeKey) return;- const result = await createLinkedFolder(- { type: scopeType, id: scopeId },- selected.token,- selected.displayName,- );+ const result = await withProjectWork(async () => {+ const created = await createLinkedFolder(+ { type: scopeType, id: scopeId },+ selected.token,+ selected.displayName,+ );+ watchStartedJob(created.job.id);+ return created;+ });if (currentScopeKey.current !== operationScopeKey) return;setStateScopeKey(operationScopeKey);setFolders((current) => [@@ -261,6 +300,8 @@ export function useLinkedFolders(scopeId,nativePathLeasesSupported,trackJob,+ watchStartedJob,+ withProjectWork,onSourcesChanged,]);@@ -268,10 +309,18 @@ export function useLinkedFolders(async (folderId: string, mode: "sync" | "rebuild") => {const operationScopeKey = scopeKey;try {- const { job } =- mode === "rebuild"- ? await rebuildLinkedFolder(folderId)- : await syncLinkedFolder(folderId);+ // Inside the request's lease and before the scope guard: the job runs on+ // the project it started for whatever this hook shows, and returning+ // without a watcher drops that count to zero mid-sync. Deduped, so+ // trackJob's own call is a no-op.+ const { job } = await withProjectWork(async () => {+ const started =+ mode === "rebuild"+ ? await rebuildLinkedFolder(folderId)+ : await syncLinkedFolder(folderId);+ watchStartedJob(started.job.id);+ return started;+ });if (currentScopeKey.current !== operationScopeKey) return;trackJob(job);onSourcesChanged?.();@@ -281,7 +330,7 @@ export function useLinkedFolders(});}},- [scopeKey, trackJob, onSourcesChanged],+ [scopeKey, trackJob, watchStartedJob, withProjectWork, onSourcesChanged],);const remove = useCallback(@@ -300,8 +349,13 @@ export function useLinkedFolders(setFolders((current) =>current.filter((folder) => folder.id !== folderId),);+ const unlinkedProjectId = projectWorkScopeId;try {- await deleteLinkedFolder(folderId, removeIndex);+ await withProjectWork(() => deleteLinkedFolder(folderId, removeIndex));+ // The rows are gone whatever this hook shows by now, and every other+ // composer on that project still lists them. Announce for the project+ // the unlink was for, not for the scope on screen.+ if (unlinkedProjectId) announceProjectSourcesUpdated(unlinkedProjectId);if (currentScopeKey.current !== operationScopeKey) return;onSourcesChanged?.();setJobs((current) => {@@ -325,7 +379,16 @@ export function useLinkedFolders(});}},- [scopeKey, folders, jobs, trackJob, refresh, onSourcesChanged],+ [+ scopeKey,+ folders,+ jobs,+ trackJob,+ refresh,+ withProjectWork,+ onSourcesChanged,+ projectWorkScopeId,+ ],);return {diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.tsindex b308fdb3399..1a3d4e1d46d 100644--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts@@ -5,13 +5,20 @@ import { consumeNativePathToken } from "@/features/native-intents";import { toast } from "@/lib/toast";import { useCallback, useEffect, useRef, useState } from "react";import {+ PROJECT_SOURCES_CHANGED_EVENT,+ PROJECT_WORK_CHANGED_EVENT,deleteDocument,getJob,+ noteProjectWork,+ projectWorkCount,+ reconcileProjectFolderJobs,streamJobEvents,+ subscribeProjectSourcesBroadcast,uploadKnowledgeBaseDocument,uploadProjectDocument,uploadThreadDocument,} from "../api/rag-api";+import { useRagAvailabilityStore } from "../api/rag-availability";import {type RagDocument,type TerminalJobStatus,@@ -23,6 +30,10 @@ export interface TrackedDocument extends RagDocument {progress?: number | null;}+/** Matches the backend's folder scan interval, so a job it starts is counted+ * within one period of appearing. */+const FOLDER_RECONCILE_INTERVAL_MS = 30_000;+/** A browser File, or a desktop drop addressed by its native path token. */export type RagUploadItem =| { kind: "file"; file: File }@@ -62,6 +73,9 @@ export type RagDocumentScope =type Lister = () => Promise<RagDocument[]>;+/** Attempts a mutation's reconciling list gets before the gate is released. */+const REFRESH_RETRIES = 3;+export function useRagDocuments(scope: RagDocumentScope | null,lister: Lister,@@ -92,6 +106,12 @@ export function useRagDocuments(// True while upload() runs, so the scope-change effect can tell a real switch// from lazy thread materialization mid-upload (which must not reset).const uploadInFlightRef = useRef(false);+ // Refreshes fire from several places at once (a mutation invalidates before+ // and after, the poll ticks, the scope changes) and can complete out of order,+ // so only the newest publishes: an earlier one landing last would restore the+ // pre-mutation list and drop the indexing state sends are gated on.+ const refreshSeq = useRef(0);+ const refreshInFlight = useRef(false);const scopeKey = scope? scope.type === "kb"@@ -101,6 +121,11 @@ export function useRagDocuments(: `thread:${scope.threadId}`: null;const prevScopeKeyRef = useRef<string | null>(null);+ // The scope on screen now, read by the async loops that outlive a navigation.+ const liveScopeKeyRef = useRef<string | null>(scopeKey);+ useEffect(() => {+ liveScopeKeyRef.current = scopeKey;+ }, [scopeKey]);const patchDoc = useCallback((documentId: string, patch: Partial<TrackedDocument>) => {@@ -203,14 +228,20 @@ export function useRagDocuments([patchDoc],);+ /** Resolves to whether the list is now known: true when this request+ * published it, or when a newer one took over and owns the answer. False+ * only when the request still being awaited failed. */const refresh = useCallback(- async (opts?: { quiet?: boolean }) => {- if (!scopeKey) return;+ async (opts?: { quiet?: boolean; silentErrors?: boolean }) => {+ if (!scopeKey) return true;+ const requestId = ++refreshSeq.current;+ refreshInFlight.current = true;if (!opts?.quiet) setLoading(true);try {// Merge server truth with local progress so a refresh mid-index keeps a// live "running %" chip. Failed docs hidden (toast warned at upload).const rows = (await lister()).filter((row) => row.status !== "failed");+ if (refreshSeq.current !== requestId) return true;setDocuments((prev) => {const merged = rows.map((row) => {const tracked = prev.find((p) => p.id === row.id);@@ -228,17 +259,61 @@ export function useRagDocuments();return [...merged, ...pendingLocal];});+ return true;} catch (err) {- toast.error("Failed to load documents", {- description: err instanceof Error ? err.message : String(err),- });+ // A superseded failure describes a scope no longer shown, and a host+ // without RAG 503s every one of these: no toast per composer opened.+ if (refreshSeq.current !== requestId) return true;+ if (+ !opts?.silentErrors &&+ !useRagAvailabilityStore.getState().isUnavailable()+ ) {+ toast.error("Failed to load documents", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ return false;} finally {- if (!opts?.quiet) setLoading(false);+ // The newest clears it: a superseded request would report the list as+ // known while the one that will publish is still out.+ if (refreshSeq.current === requestId) {+ refreshInFlight.current = false;+ setLoading(false);+ }}},[scopeKey, lister],);+ // Retry a project list whose request failed: one failed read leaves the+ // composer with no rows, nothing indexing and nothing polling while a source+ // is still being chunked. Counted as work, so a send waits for the answer.+ const loadProjectSources = useCallback(+ async (projectId: string, opts?: { quiet?: boolean }) => {+ const startedFor = `project:${projectId}`;+ noteProjectWork(projectId, 1);+ try {+ for (let attempt = 0; attempt < REFRESH_RETRIES; attempt += 1) {+ const last = attempt === REFRESH_RETRIES - 1;+ // True for a request that published, and for one a newer request has+ // already outranked.+ if (await refresh({ quiet: opts?.quiet, silentErrors: !last })) return;+ if (last) break;+ await new Promise((resolve) =>+ setTimeout(resolve, 1000 * (attempt + 1)),+ );+ // This closure keeps the lister of the scope it started for, so a+ // retry after the user moves on would take a ticket behind the new+ // scope's request and publish into the composer showing it.+ if (liveScopeKeyRef.current !== startedFor) return;+ }+ } finally {+ noteProjectWork(projectId, -1);+ }+ },+ [refresh],+ );+// A real switch (thread/KB swap) resets + reloads; first acquiring a scope just// loads. Skip both during materialization mid-upload (scope null -> new thread// while upload() runs) so we don't abort tracking or wipe optimistic chips.@@ -250,16 +325,32 @@ export function useRagDocuments(for (const controller of jobs.values()) controller.abort();jobs.clear();sigByDocId.current.clear();+ // Stand down any refresh still in flight for the old scope. Clearing to a+ // null scope starts no replacement request to outrank it, so without this+ // its response would repopulate the list that is about to be cleared.+ refreshSeq.current += 1;// Scope changes intentionally clear the old scope before fetching the new// one. Keep this synchronous so React StrictMode's setup/cleanup replay// cannot cancel the only refresh after prevScopeKeyRef has advanced.setDocuments([]);if (scope) {// eslint-disable-next-line react-hooks/set-state-in-effect- void refresh();+ void (scope.type === "project"+ ? loadProjectSources(scope.projectId)+ : refresh());+ } else {+ // Nothing is coming for the scope just dropped, and the request that+ // was is now behind the sequence, so it will not clear these itself.+ // Left set, the composer reads the list as still unknown and holds+ // every send.+ refreshInFlight.current = false;+ // eslint-disable-next-line react-hooks/set-state-in-effect+ setLoading(false);}} else if (prev === null && scope && !uploadInFlightRef.current) {- void refresh();+ void (scope.type === "project"+ ? loadProjectSources(scope.projectId)+ : refresh());}return () => {// Preserve in-flight tracking when cleanup is the materialization flip,@@ -275,16 +366,77 @@ export function useRagDocuments(// concurrent connections, so streams past the cap may never deliver a terminal// frame and leave a chip spinning. While anything is indexing, reconcile against// the document list (one request covers every doc) so chips always resolve.- const hasIndexing = documents.some(- (d) => d.status === "pending" || d.status === "running",- );+ // Work on this project running elsewhere: an upload from the other instance,+ // or a folder sync. Neither has a row here until it lands.+ const [workElsewhere, setWorkElsewhere] = useState(0);+ const workScopeId = scope?.type === "project" ? scope.projectId : null;+ useEffect(() => {+ if (!workScopeId) {+ setWorkElsewhere(0);+ return;+ }+ const read = () => setWorkElsewhere(projectWorkCount(workScopeId));+ read();+ // Before the reconcile below: it takes its own lease before its first await,+ // and an event fired ahead of this listener would be missed, leaving the+ // composer sendable for the length of the lookup.+ window.addEventListener(PROJECT_WORK_CHANGED_EVENT, read);+ // A sync already running on this project has no watcher here after a+ // reload, and its rows do not exist yet, so nothing else would gate on it.+ void reconcileProjectFolderJobs(workScopeId);+ // The backend also enqueues a job per auto-syncing folder on its own timer,+ // with nothing to announce it. Keep asking while the project is open, or a+ // scan that starts after this mount gates nothing.+ const reconcile = setInterval(() => {+ void reconcileProjectFolderJobs(workScopeId);+ }, FOLDER_RECONCILE_INTERVAL_MS);+ // Work in another tab arrives over the same channel.+ subscribeProjectSourcesBroadcast();+ return () => {+ clearInterval(reconcile);+ window.removeEventListener(PROJECT_WORK_CHANGED_EVENT, read);+ };+ }, [workScopeId]);++ const hasIndexing =+ workElsewhere > 0 ||+ documents.some((d) => d.status === "pending" || d.status === "running");useEffect(() => {if (!scopeKey || !hasIndexing) return;- const id = setInterval(() => void refresh({ quiet: true }), 4000);+ // Skip a tick while one is still out. Starting another would retire it+ // through the sequence gate, and a list slower than the interval would+ // then never publish: the row this is watching never reaches completed and+ // a queued send waits forever.+ const id = setInterval(() => {+ if (!refreshInFlight.current) {+ void refresh({ quiet: true });+ }+ }, 4000);return () => clearInterval(id);// eslint-disable-next-line react-hooks/exhaustive-deps}, [scopeKey, hasIndexing]);+ // A project's sources are shown by two independent instances (the composer's+ // bar and the Sources panel), so each has to pick up the other's mutations.+ const projectScopeId = scope?.type === "project" ? scope.projectId : null;+ useEffect(() => {+ if (!projectScopeId) return;+ const onChanged = (event: Event) => {+ const changed = (event as CustomEvent<{ projectId?: string }>).detail+ ?.projectId;+ if (changed !== projectScopeId) return;+ // The refresh an invalidation triggers is quiet, so it takes no loading+ // gate, and the mutation that fired it has released its own. Counted as+ // work while it runs, or nothing gates the send between the two.+ void loadProjectSources(projectScopeId, { quiet: true });+ };+ subscribeProjectSourcesBroadcast();+ window.addEventListener(PROJECT_SOURCES_CHANGED_EVENT, onChanged);+ return () =>+ window.removeEventListener(PROJECT_SOURCES_CHANGED_EVENT, onChanged);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [projectScopeId]);+// POST one file, then swap its optimistic chip (`tempId`) to the real id; drop// the chip if the backend deduped. `seenIds` holds ids present/added this batch.const uploadOne = useCallback(@@ -372,6 +524,17 @@ export function useRagDocuments(// job tracking and optimistic chips alone.uploadInFlightRef.current = true;setUploading(true);+ // Published before the first await so the other instance gates from the+ // moment the upload starts, not once the bytes are in.+ // The composer passes its project scope explicitly, since the hook's own+ // can still be null on the render that starts the upload.+ const knownScope =+ overrideScope instanceof Promise ? null : (overrideScope ?? scope);+ const uploadingProjectId =+ knownScope?.type === "project" ? knownScope.projectId : null;+ if (uploadingProjectId) {+ noteProjectWork(uploadingProjectId, 1);+ }try {// Show an optimistic chip per file before awaiting the thread id;// materialization is a round-trip and gating chips behind it makes a slow@@ -430,6 +593,9 @@ export function useRagDocuments(} finally {setUploading(false);uploadInFlightRef.current = false;+ if (uploadingProjectId) {+ noteProjectWork(uploadingProjectId, -1);+ }}},[scope, uploadOne, sigBlocksReupload],@@ -442,6 +608,14 @@ export function useRagDocuments(// Forget the dedup signature so re-uploading re-indexes.const prevSig = sigByDocId.current.get(documentId);sigByDocId.current.delete(documentId);+ // The chip goes at once but the source is still there until the DELETE+ // returns, and the sources probe is only invalidated after it does, so a+ // send in between can still retrieve what the composer says is gone.+ const removingProjectId =+ scope?.type === "project" ? scope.projectId : null;+ if (removingProjectId) {+ noteProjectWork(removingProjectId, 1);+ }try {await deleteDocument(documentId,@@ -453,10 +627,22 @@ export function useRagDocuments(toast.error("Delete failed", {description: err instanceof Error ? err.message : String(err),});+ } finally {+ if (removingProjectId) {+ noteProjectWork(removingProjectId, -1);+ }}},[documents, scope],);- return { documents, loading, uploading, refresh, upload, remove };+ return {+ documents,+ loading,+ uploading,+ hasIndexing,+ refresh,+ upload,+ remove,+ };}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex cc4d46c0a2a..5c13a0e4fa3 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -91,6 +91,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {chat: ["settings.general.chatDefaults","settings.general.autoTitleNewChats",+ "settings.chat.projectAttachments","settings.chat.rememberParamsPerModel","settings.profile.greetingSloth","settings.chat.thinking.collapseByDefault",diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex 2ca0f1f5a8e..79573e42954 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -133,6 +133,12 @@ export function ChatTab() {const togglePlusPin = usePlusMenuPrefsStore((state) => state.togglePin);const autoTitle = useChatRuntimeStore((state) => state.autoTitle);const setAutoTitle = useChatRuntimeStore((state) => state.setAutoTitle);+ const projectAttachmentTarget = useChatRuntimeStore(+ (state) => state.projectAttachmentTarget,+ );+ const setProjectAttachmentTarget = useChatRuntimeStore(+ (state) => state.setProjectAttachmentTarget,+ );const rememberParamsPerModel = useChatRuntimeStore((state) => state.rememberParamsPerModel,);@@ -309,6 +315,17 @@ export function ChatTab() {><Switch checked={autoTitle} onCheckedChange={setAutoTitle} /></SettingsRow>+ <SettingsRow+ label={t("settings.chat.projectAttachments")}+ description={t("settings.chat.projectAttachmentsDescription")}+ >+ <Switch+ checked={projectAttachmentTarget === "project"}+ onCheckedChange={(checked) =>+ setProjectAttachmentTarget(checked ? "project" : "thread")+ }+ />+ </SettingsRow><SettingsRowlabel={t("settings.chat.rememberParamsPerModel")}description={t("settings.chat.rememberParamsPerModelDescription")}diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex d71cf05ad22..9942e3cb4cf 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -78,6 +78,7 @@ import { SettingsSection } from "../components/settings-section";import { StudioVersionSection } from "../components/studio-version-section";import { useDesktopBooleanSetting } from "../hooks/use-desktop-boolean-setting";import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";+import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "@/features/chat/utils/project-attachment-target";// Keys cleared by "Reset all local preferences". NEVER include auth/session keys here -- that// would log the user out (unsloth_auth_token, unsloth_auth_refresh_token, and@@ -98,6 +99,7 @@ const PREFS_KEYS: string[] = ["unsloth_settings_active_tab",SETTINGS_PANEL_PREFS_STORAGE_KEY,// Chat runtime prefs+ CHAT_PROJECT_ATTACHMENT_TARGET_KEY,"unsloth_chat_auto_title","unsloth_chat_permission_mode",// Legacy confirm key: loadPermissionMode falls back to it, so clear both or a reset restores it.diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 1ab0d104b9b..6fbbca94366 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1012,6 +1012,9 @@ export const ar = {modelDisclaimer: "إظهار إخلاء مسؤولية النموذج",modelDisclaimerDescription:'إظهار عبارة "LLMs can make mistakes" أسفل مربع المحادثة.',+ projectAttachments: "مشاركة الملفات عبر المشروع",+ projectAttachmentsDescription:+ "الإعداد الافتراضي للملفات المرفقة في محادثة تنتمي إلى مشروع: فهرستها للمشروع بأكمله حتى تتمكن كل محادثة فيه من استخدامها. يمكن لكل محادثة تجاوز ذلك من قائمة الإرفاق.",rememberParamsPerModel: "تذكر الإعدادات لكل نموذج",rememberParamsPerModelDescription:"عند تبديل النموذج تُستعاد درجة الحرارة والموجّه وبقية الإعدادات التي استخدمتها آخر مرة مع ذلك النموذج. عند الإيقاف تبقى مجموعة إعدادات واحدة لكل النماذج.",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 098f65ff92f..927bc3d1d20 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1047,6 +1047,9 @@ export const de = {modelDisclaimer: "Modell-Hinweis anzeigen",modelDisclaimerDescription:"Zeigt „LLMs können Fehler machen“ unter dem Chatfeld an.",+ projectAttachments: "Dateien projektweit teilen",+ projectAttachmentsDescription:+ "Standard für Dateien, die in einem Chat innerhalb eines Projekts angehängt werden: für das gesamte Projekt indizieren, damit jeder Chat darin sie nutzen kann. Jeder Chat kann dies im Anhangsmenü überschreiben.",rememberParamsPerModel: "Einstellungen pro Modell merken",rememberParamsPerModelDescription:"Beim Modellwechsel werden Temperatur, Prompt und die weiteren Einstellungen wiederhergestellt, die Sie zuletzt mit diesem Modell verwendet haben. Aus: ein Satz Einstellungen für alle Modelle.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex ad0c49f32ac..0a031c29ec4 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1008,6 +1008,9 @@ export const en = {modelDisclaimer: "Show model disclaimer",modelDisclaimerDescription:'Show "LLMs can make mistakes" under the chat box.',+ projectAttachments: "Share files across a project",+ projectAttachmentsDescription:+ "Default for files attached in a chat that belongs to a project: index them for the whole project so every chat in it can use them. Each chat can override this from the attach menu.",rememberParamsPerModel: "Remember settings per model",rememberParamsPerModelDescription:"Switching models restores the temperature, prompt and other settings you last used with that model. Off keeps one set of settings for every model.",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex d4124030c46..e93e57174f8 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1038,6 +1038,9 @@ export const es = {modelDisclaimer: "Mostrar aviso del modelo",modelDisclaimerDescription:'Muestra "Los LLM pueden cometer errores" bajo el cuadro de chat.',+ projectAttachments: "Compartir archivos en todo el proyecto",+ projectAttachmentsDescription:+ "Valor predeterminado para los archivos adjuntos en un chat que pertenece a un proyecto: indexarlos para todo el proyecto para que cualquier chat pueda usarlos. Cada chat puede cambiarlo desde el menú de adjuntos.",rememberParamsPerModel: "Recordar los ajustes por modelo",rememberParamsPerModelDescription:"Al cambiar de modelo se restauran la temperatura, el prompt y los demás ajustes que usaste por última vez con ese modelo. Desactivado, se mantiene un único conjunto de ajustes para todos los modelos.",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 452c9588fa5..af4376f6971 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1044,6 +1044,9 @@ export const fr = {modelDisclaimer: "Afficher l'avertissement du modèle",modelDisclaimerDescription:'Afficher "Les LLM peuvent faire des erreurs" sous la zone de discussion.',+ projectAttachments: "Partager les fichiers dans tout le projet",+ projectAttachmentsDescription:+ "Valeur par defaut pour les fichiers joints dans une discussion appartenant a un projet : les indexer pour tout le projet afin que chaque discussion puisse les utiliser. Chaque discussion peut le modifier depuis le menu des pieces jointes.",rememberParamsPerModel: "Mémoriser les réglages par modèle",rememberParamsPerModelDescription:"Changer de modèle restaure la température, le prompt et les autres réglages utilisés en dernier avec ce modèle. Désactivé, un seul jeu de réglages s'applique à tous les modèles.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 846374ed1d1..053d017a3c6 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1018,6 +1018,9 @@ export const hi = {modelDisclaimer: "मॉडल अस्वीकरण दिखाएं",modelDisclaimerDescription:'चैट बॉक्स के नीचे "LLMs can make mistakes" दिखाएं।',+ projectAttachments: "प्रोजेक्ट भर में फ़ाइलें साझा करें",+ projectAttachmentsDescription:+ "किसी प्रोजेक्ट से जुड़ी चैट में संलग्न फ़ाइलों के लिए डिफ़ॉल्ट: उन्हें पूरे प्रोजेक्ट के लिए इंडेक्स करें ताकि उसकी हर चैट उनका उपयोग कर सके. हर चैट इसे अटैच मेनू से बदल सकती है.",rememberParamsPerModel: "हर मॉडल के लिए सेटिंग्स याद रखें",rememberParamsPerModelDescription:"मॉडल बदलने पर उस मॉडल के साथ आपने आखिरी बार जो तापमान, प्रॉम्प्ट और अन्य सेटिंग्स इस्तेमाल की थीं, वे वापस आ जाती हैं। बंद होने पर सभी मॉडलों के लिए एक ही सेट रहता है।",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d1d9dde222e..07857228e66 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1012,6 +1012,9 @@ export const it = {modelDisclaimer: "Mostra l'avviso sul modello",modelDisclaimerDescription:"Mostra «Gli LLM possono commettere errori» sotto il campo della chat.",+ projectAttachments: "Condividi i file nel progetto",+ projectAttachmentsDescription:+ "Impostazione predefinita per i file allegati in una chat che appartiene a un progetto: indicizzarli per l'intero progetto in modo che ogni chat possa usarli. Ogni chat puo cambiarlo dal menu degli allegati.",rememberParamsPerModel: "Ricorda le impostazioni per modello",rememberParamsPerModelDescription:"Cambiando modello vengono ripristinati temperatura, prompt e le altre impostazioni usate l'ultima volta con quel modello. Disattivato, resta un unico set di impostazioni per tutti i modelli.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex d251ac0af82..e9af73a9416 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1000,6 +1000,9 @@ export const ja = {"アシスタントの応答にモデルのメタデータを表示します。",modelDisclaimer: "モデルの免責事項を表示",modelDisclaimerDescription: 'チャットボックスの下に "LLMs can make mistakes" と表示します。',+ projectAttachments: "プロジェクト全体でファイルを共有",+ projectAttachmentsDescription:+ "プロジェクトに属するチャットで添付したファイルの既定の扱いです。プロジェクト全体にインデックスし、そのプロジェクト内のどのチャットからも利用できるようにします。チャットごとに添付メニューから変更できます。",rememberParamsPerModel: "モデルごとに設定を記憶",rememberParamsPerModelDescription:"モデルを切り替えると、そのモデルで最後に使った温度やプロンプトなどの設定が復元されます。オフの場合は、すべてのモデルで同じ設定を使います。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex c215d0c1761..697183e186d 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1010,6 +1010,9 @@ export const ko = {modelDisclaimer: "모델 고지 표시",modelDisclaimerDescription:'채팅 상자 아래에 "LLMs can make mistakes" 문구를 표시합니다.',+ projectAttachments: "프로젝트 전체에서 파일 공유",+ projectAttachmentsDescription:+ "프로젝트에 속한 채팅에서 첨부한 파일의 기본 동작입니다. 프로젝트 전체에 색인하여 해당 프로젝트의 모든 채팅에서 사용할 수 있게 합니다. 채팅마다 첨부 메뉴에서 변경할 수 있습니다.",rememberParamsPerModel: "모델별로 설정 기억",rememberParamsPerModelDescription:"모델을 전환하면 해당 모델에서 마지막으로 사용한 온도, 프롬프트 등의 설정이 복원됩니다. 끄면 모든 모델이 하나의 설정을 공유합니다.",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 1e08e0b5fc6..46dc1dea5ea 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1026,6 +1026,9 @@ export const ptBR = {modelDisclaimer: "Mostrar aviso do modelo",modelDisclaimerDescription:'Mostra "LLMs podem cometer erros" abaixo da caixa de chat.',+ projectAttachments: "Compartilhar arquivos em todo o projeto",+ projectAttachmentsDescription:+ "Padrao para arquivos anexados em um chat que pertence a um projeto: indexa-los para o projeto inteiro para que qualquer chat possa usa-los. Cada chat pode alterar isso pelo menu de anexos.",rememberParamsPerModel: "Lembrar as configurações por modelo",rememberParamsPerModelDescription:"Ao trocar de modelo, a temperatura, o prompt e as demais configurações usadas por último com aquele modelo são restauradas. Desativado, um único conjunto de configurações vale para todos os modelos.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 9cfd9defec9..b6c874d1bb7 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1023,6 +1023,9 @@ export const ru = {modelDisclaimer: "Показывать предупреждение о модели",modelDisclaimerDescription:"Показывать сообщение «LLM могут ошибаться» под полем ввода.",+ projectAttachments: "Общий доступ к файлам в проекте",+ projectAttachmentsDescription:+ "Поведение по умолчанию для файлов, прикрепленных в чате, который относится к проекту: индексировать их для всего проекта, чтобы любой чат в нем мог их использовать. Каждый чат может изменить это в меню вложений.",rememberParamsPerModel: "Запоминать настройки для каждой модели",rememberParamsPerModelDescription:"При переключении модели восстанавливаются температура, промпт и другие настройки, которые вы использовали с ней в последний раз. Если выключено, для всех моделей действует один набор настроек.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 11db3e73a25..60a4eb223e6 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -987,6 +987,9 @@ export const zhCN = {modelDisclaimer: "显示模型免责声明",modelDisclaimerDescription:"在聊天框下方显示“LLM 可能会出错”。",+ projectAttachments: "在项目内共享文件",+ projectAttachmentsDescription:+ "属于某个项目的聊天中所附文件的默认行为:为整个项目建立索引,使该项目中的每个聊天都能使用。每个聊天都可以在附件菜单中单独更改。",rememberParamsPerModel: "按模型记住设置",rememberParamsPerModelDescription:"切换模型时会恢复你上次在该模型上使用的温度、提示词等设置。关闭后,所有模型共用一套设置。",diff --git a/studio/frontend/tests/delete-chat-files-preference.test.ts b/studio/frontend/tests/delete-chat-files-preference.test.tsindex c94c326d9f4..bde492640a0 100644--- a/studio/frontend/tests/delete-chat-files-preference.test.ts+++ b/studio/frontend/tests/delete-chat-files-preference.test.ts@@ -5,7 +5,15 @@ import assert from "node:assert/strict";import { readFile } from "node:fs/promises";import test from "node:test";-import { useChatPreferencesStore } from "../src/features/chat/stores/chat-preferences-store.ts";+import { registerBundlerResolver } from "./helpers/kit.ts";++// The store reaches a relative import written without its extension, which bare+// node resolves only through this. Registered before the dynamic import, since a+// static one is linked first.+registerBundlerResolver();+const { useChatPreferencesStore } = await import(+ "../src/features/chat/stores/chat-preferences-store.ts"+);test("deleting a chat leaves its files alone until asked", () => {// Files are the destructive half of a delete, so an install that never sawdiff --git a/studio/frontend/tests/project-attachment-simulations.test.ts b/studio/frontend/tests/project-attachment-simulations.test.tsnew file mode 100644index 00000000000..a7beff77435--- /dev/null+++ b/studio/frontend/tests/project-attachment-simulations.test.ts@@ -0,0 +1,254 @@+// Simulations that drive the PR's REAL modules, not a model of them: the cross-tab+// work protocol under tab death, clock skew and a missing BroadcastChannel; the+// stored attach target on an upgraded or downgraded profile; and the scope+// precedence behind rag_scope. None of it is visible in a screenshot.+//+// Run from studio/frontend: node --experimental-strip-types --test <this file>++import assert from "node:assert/strict";+import test from "node:test";+import { installLocalStorageFake, registerStoreStubResolver } from "./helpers/kit.ts";++const { storage } = installLocalStorageFake();+const events = new EventTarget();+Object.assign(globalThis, {+ window: Object.assign(events, { localStorage: storage, location: { protocol: "http:" } }),+});+registerStoreStubResolver();++const rag = await import("../src/features/rag/api/rag-api.ts");+// The auth stub fails any unexpected network access; a test opts in per call.+const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");++// --------------------------------------------------------------- work lease protocol++test("a project with no work in flight does not gate a send", () => {+ assert.equal(rag.projectWorkCount("p-idle"), 0);+});++test("local work is counted while it runs and released when it ends", () => {+ rag.noteProjectWork("p-local", 1);+ assert.equal(rag.projectWorkCount("p-local"), 1);+ rag.noteProjectWork("p-local", 1);+ assert.equal(rag.projectWorkCount("p-local"), 2, "two uploads are two operations");+ rag.noteProjectWork("p-local", -1);+ rag.noteProjectWork("p-local", -1);+ assert.equal(rag.projectWorkCount("p-local"), 0, "the gate must open again");+});++test("an over-release cannot drive the count negative and mask real work", () => {+ rag.noteProjectWork("p-neg", -5);+ assert.equal(rag.projectWorkCount("p-neg"), 0);+ rag.noteProjectWork("p-neg", 1);+ assert.equal(rag.projectWorkCount("p-neg"), 1, "a stale release must not owe credit");+ rag.noteProjectWork("p-neg", -1);+});++test("one project's work does not gate another", () => {+ rag.noteProjectWork("p-a", 1);+ assert.equal(rag.projectWorkCount("p-b"), 0);+ rag.noteProjectWork("p-a", -1);+});++test("the client error test only fires on an answered 4xx", () => {+ assert.equal(rag.isRagClientError(rag.ragError(404, { detail: "Project not found" })), true);+ assert.equal(rag.isRagClientError(rag.ragError(403, null)), true);+ assert.equal(rag.isRagClientError(rag.ragError(429, null)), false, "rate limiting is transient");+ assert.equal(rag.isRagClientError(rag.ragError(503, null)), false);+ assert.equal(rag.isRagClientError(rag.ragError(500, null)), false);+ assert.equal(rag.isRagClientError(new TypeError("Failed to fetch")), false,+ "a network failure is not an answer");+ assert.equal(rag.isRagClientError(null), false);+ assert.equal(rag.isRagClientError(undefined), false);+});++test("the error still reads as the message a toast would show", () => {+ const err = rag.ragError(404, { detail: "Project not found" });+ assert.equal(err.message, "Project not found");+ assert.equal(err.status, 404);+ assert.ok(err instanceof Error);+});++// ------------------------------------------------------- the stored attachment target++const { DEFAULT_PROJECT_ATTACHMENT_TARGET, normalizeProjectAttachmentTarget } =+ await import("../src/features/chat/utils/project-attachment-target.ts");++// The function the store reads a profile's value through, driven directly rather+// than through the store, which drags the whole app graph in with it.+async function targetForStoredValue(value: string | null): Promise<string> {+ return normalizeProjectAttachmentTarget(value);+}++test("an install that has never chosen gets the shipped default", async () => {+ assert.equal(await targetForStoredValue(null), DEFAULT_PROJECT_ATTACHMENT_TARGET);+ assert.equal(DEFAULT_PROJECT_ATTACHMENT_TARGET, "project");+});++test("both real values round-trip", async () => {+ assert.equal(await targetForStoredValue("project"), "project");+ assert.equal(await targetForStoredValue("thread"), "thread");+});++test("a value from a later build falls to the chat, never to sharing", async () => {+ // A downgrade must not turn an unknown preference into project-wide indexing.+ assert.equal(await targetForStoredValue("kb"), "thread");+ assert.equal(await targetForStoredValue("everyone"), "thread");+});++test("corrupt storage never produces an invalid target", async () => {+ for (const value of ["", " ", "null", "undefined", "0", "[object Object]", "PROJECT"]) {+ const got = await targetForStoredValue(value);+ assert.ok(got === "project" || got === "thread", `${JSON.stringify(value)} produced ${got}`);+ }+});++// --------------------------------------------------------------- retrieval precedence++// The shape chat-adapter builds for rag_scope, kept as the contract the backend's+// _resolve_scope is tested against, so the two cannot drift silently.+function ragScope(opts: {+ ragEnabled: boolean;+ kbId?: string | null;+ threadId?: string | null;+ projectRagEnabled?: boolean;+ projectId?: string | null;+}): Record<string, string> {+ const { ragEnabled, kbId, threadId, projectRagEnabled, projectId } = opts;+ if (ragEnabled && kbId) return { kb_id: kbId };+ return {+ ...(ragEnabled && threadId ? { thread_id: threadId } : {}),+ ...(projectRagEnabled && projectId ? { project_id: projectId } : {}),+ };+}++test("a chat with no project is scoped exactly as before", () => {+ assert.deepEqual(ragScope({ ragEnabled: true, threadId: "T" }), { thread_id: "T" });+ assert.deepEqual(ragScope({ ragEnabled: false, threadId: "T" }), {});+});++test("a project chat retrieves the project even with the pill off", () => {+ assert.deepEqual(+ ragScope({ ragEnabled: false, threadId: "T", projectRagEnabled: true, projectId: "P" }),+ { project_id: "P" },+ );+});++test("a project chat with the pill on retrieves both", () => {+ assert.deepEqual(+ ragScope({ ragEnabled: true, threadId: "T", projectRagEnabled: true, projectId: "P" }),+ { thread_id: "T", project_id: "P" },+ );+});++test("a knowledge base replaces everything, project included", () => {+ assert.deepEqual(+ ragScope({ ragEnabled: true, kbId: "K", threadId: "T", projectRagEnabled: true, projectId: "P" }),+ { kb_id: "K" },+ );+});++// ------------------------------------------------------- folder syncs the composer gates on++/** Answer every RAG request from a table, and count what was asked for. */+function stubFetch(handler: (url: string) => { status: number; body: unknown }) {+ const urls: string[] = [];+ setAuthFetchHandler((input: string) => {+ urls.push(input);+ const { status, body } = handler(input);+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as Response;+ });+ return { urls, restore: () => setAuthFetchHandler(null) };+}++// Unlinking a folder deletes its job rows, and so does the terminal-job prune, so+// a watcher can outlive the job it polls. Riding that 404 out through the retry+// budget gates the composer for a minute on work that already ended.+test("a folder job that no longer exists releases the gate at once", async () => {+ const fetched = stubFetch(() => ({ status: 404, body: { detail: "Job not found" } }));+ try {+ rag.watchProjectFolderJob("p-folder-404", "job-gone");+ assert.equal(rag.projectWorkCount("p-folder-404"), 1, "the lease is taken up front");+ // The read is answered, so the loop breaks without ever reaching its sleep.+ for (let tick = 0; tick < 10; tick += 1) await Promise.resolve();+ assert.equal(rag.projectWorkCount("p-folder-404"), 0, "a send must not wait out the retries");+ assert.equal(fetched.urls.length, 1, "and it must not keep polling a deleted job");+ } finally {+ fetched.restore();+ }+});++// The backend enqueues a sync per auto-syncing folder every FOLDER_SYNC_INTERVAL_S+// with no frontend event, so a project looked at once and remembered forever lets+// the composer send through a scan that is rewriting its sources.+test("a project can be looked at again for jobs that start later", async () => {+ const fetched = stubFetch(() => ({ status: 200, body: { linkedFolders: [] } }));+ const realNow = Date.now;+ let clock = realNow();+ Date.now = () => clock;+ try {+ await rag.reconcileProjectFolderJobs("p-folder-again");+ assert.equal(fetched.urls.length, 1);+ // A second bar mounting on the same project shares the answer.+ await rag.reconcileProjectFolderJobs("p-folder-again");+ assert.equal(fetched.urls.length, 1, "two bars must not double every open");+ // A later scan is not shut out by that.+ clock += 60_000;+ await rag.reconcileProjectFolderJobs("p-folder-again");+ assert.equal(fetched.urls.length, 2, "a periodic look has to reach the backend");+ } finally {+ Date.now = realNow;+ fetched.restore();+ }+});++// A look that never came back is not an answer, so it must not close the project either.+test("a failed look leaves the project open to the next one", async () => {+ let fail = true;+ const fetched = stubFetch(() => (fail ? { status: 503, body: null } : { status: 200, body: { linkedFolders: [] } }));+ try {+ await rag.reconcileProjectFolderJobs("p-folder-retry");+ assert.equal(fetched.urls.length, 1);+ fail = false;+ await rag.reconcileProjectFolderJobs("p-folder-retry");+ assert.equal(fetched.urls.length, 2, "the retry must not be rate limited out");+ } finally {+ fetched.restore();+ }+});++// A job that scans before writing any row leaves the composer's list legitimately+// empty, so the gate is open for as long as the lookup takes.+test("every look for folder jobs gates the composer while it runs", async () => {+ let release!: () => void;+ const answered = new Promise<void>((done) => { release = done; });+ const urls: string[] = [];+ setAuthFetchHandler(async (input: string) => {+ urls.push(input);+ await answered;+ return { ok: true, status: 200, json: async () => ({ linkedFolders: [] }) } as Response;+ });+ const realNow = Date.now;+ let clock = realNow();+ Date.now = () => clock;+ try {+ const looking = rag.reconcileProjectFolderJobs("p-folder-gate");+ assert.equal(rag.projectWorkCount("p-folder-gate"), 1, "a send must wait for the answer");+ release();+ await looking;+ assert.equal(rag.projectWorkCount("p-folder-gate"), 0, "and must not wait past it");+ // A periodic look is gated the same way: the backend's timer starts jobs the+ // composer's existing list says nothing about.+ clock += 60_000;+ await rag.reconcileProjectFolderJobs("p-folder-gate");+ assert.equal(urls.length, 2);+ assert.equal(rag.projectWorkCount("p-folder-gate"), 0);+ } finally {+ Date.now = realNow;+ setAuthFetchHandler(null);+ }+});diff --git a/studio/frontend/tests/project-attachment-target-adoption.test.ts b/studio/frontend/tests/project-attachment-target-adoption.test.tsnew file mode 100644index 00000000000..5217b6dab5d--- /dev/null+++ b/studio/frontend/tests/project-attachment-target-adoption.test.ts@@ -0,0 +1,303 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The attach target can be chosen before the chat exists, so it is parked under a+// pending key. A chat is created by sending as often as by attaching, and only the+// attach path went through ensureThreadId: the choice was dropped and inherited.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "../src/features/chat/utils/project-attachment-target.ts";++const PENDING = "__pending__";+type Target = "project" | "chat";++/** adoptPendingProjectAttachmentTarget, as the store reducer applies it. */+function adopt(+ byThread: Record<string, Target>,+ threadId: string,+): Record<string, Target> {+ const pending = byThread[PENDING];+ if (pending === undefined || threadId in byThread) {+ return byThread;+ }+ const next = { ...byThread };+ delete next[PENDING];+ next[threadId] = pending;+ return next;+}++test("the chat that gets an id takes the choice made before it existed", () => {+ const after = adopt({ [PENDING]: "chat" }, "thread-1");+ assert.equal(after["thread-1"], "chat");+ assert.equal(PENDING in after, false, "and the next new chat starts clean");+});++test("a chat that made its own choice keeps it", () => {+ const before: Record<string, Target> = {+ [PENDING]: "chat",+ "thread-1": "project",+ };+ assert.equal(adopt(before, "thread-1")["thread-1"], "project");+});++test("nothing pending leaves the chat on the saved default", () => {+ const before: Record<string, Target> = { "thread-2": "chat" };+ assert.equal(adopt(before, "thread-1"), before, "no entry, so no override");+});++/** clearPendingProjectAttachmentTarget, as the store reducer applies it. */+function clearPending(+ byThread: Record<string, Target>,+): Record<string, Target> {+ if (!(PENDING in byThread)) {+ return byThread;+ }+ const next = { ...byThread };+ delete next[PENDING];+ return next;+}++// A composer abandoned without sending or attaching left its choice parked, and+// the next fresh chat read it as its own.+test("a choice made in a composer that never became a chat is dropped", () => {+ const after = clearPending({ [PENDING]: "chat", "thread-1": "project" });+ assert.equal(PENDING in after, false);+ assert.equal(after["thread-1"], "project", "real chats are untouched");+});++test("clearing with nothing pending changes nothing", () => {+ const before: Record<string, Target> = { "thread-1": "chat" };+ assert.equal(clearPending(before), before);+});++// Adoption has to run on both paths that turn a fresh composer into a chat.+test("both chat-creating paths adopt the pending choice", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ // Attaching a file first: ensureThreadId materializes the thread.+ assert.match(+ source,+ /initialize\(\)[\s\S]{0,300}?adoptPendingProjectAttachmentTarget\(remoteId, claim\)/,+ );+ // Sending a message first: the id arrives as a prop.+ assert.match(+ source,+ /if \(!hadThreadId\) \{[\s\S]{0,200}?adoptPendingProjectAttachmentTarget\(threadId\)/,+ );+});++test("the composer clears its pending choice when it goes away", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(source, /clearPendingProjectAttachmentTarget\(\)/);+});++// Membership is read from the chat's own row, so there is a window where it is+// unknown. Attaching in it would file the file by guess.+test("attaching is held until the chat's project is known", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ source,+ /const projectUnresolved = threadProjectId === undefined;/,+ "unresolved has to be distinguishable from no project",+ );+ assert.match(+ source,+ /uploading \|\| projectUploading \|\| projectUnresolved/,+ "the attach controls hold",+ );+ assert.match(+ source,+ /if \(projectUnresolved\) \{\s*return;\s*\}/,+ "and a desktop drop stays in the store rather than draining",+ );+});++// A send outlives navigation, and hydration and a model load both run before the+// project is first resolved.+test("the run keeps the project it started in", () => {+ const source = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ source,+ /const composerProjectIdAtSend =\s*useChatRuntimeStore\.getState\(\)\.activeProjectId \?\? null;\s*await useChatRuntimeStore\.getState\(\)\.hydratePersistedSettings\(\);/,+ "captured before the first await",+ );+ assert.match(+ source,+ /rememberComposerProjectForRun\(resolvedThreadId, composerProjectIdAtSend\)/,+ );+});++// A composer abandoned mid-materialization has its own pending entry dropped by+// its cleanup, and the next composer's lands under the same key: the abandoned+// promise resolving would hand that to the dead chat and delete it.+test("an abandoned composer cannot consume the next composer's choice", () => {+ let claim = 0;+ let byThread: Record<string, Target> = {};+ const setPending = (target: Target) => {+ claim += 1;+ byThread = { ...byThread, [PENDING]: target };+ };+ const clearPending = () => {+ if (!(PENDING in byThread)) return;+ claim += 1;+ const next = { ...byThread };+ delete next[PENDING];+ byThread = next;+ };+ const adoptWithClaim = (threadId: string, seen: number) => {+ if (seen !== claim) return;+ byThread = adopt(byThread, threadId);+ };++ // A picks "This chat" and starts materializing.+ setPending("chat");+ const seenByA = claim;+ // A is abandoned, B mounts and picks for itself.+ clearPending();+ setPending("chat");++ // Unguarded, this is the reported failure: the dead chat takes B's entry.+ const stolen = adopt(byThread, "thread-A");+ assert.equal(PENDING in stolen, false, "B's choice would be consumed");+ assert.equal(stolen["thread-A"], "chat");++ adoptWithClaim("thread-A", seenByA);+ assert.equal(byThread[PENDING], "chat", "B still has its choice");+ assert.equal(+ byThread["thread-A"],+ undefined,+ "and the dead chat took nothing",+ );++ // The ordinary case is untouched: nothing intervened, so B's own resolve adopts.+ adoptWithClaim("thread-B", claim);+ assert.equal(byThread["thread-B"], "chat");+ assert.equal(PENDING in byThread, false);+});++// The counter has to move on both ways the entry changes hands, or a claim+// taken before one of them still looks current afterwards.+test("both writers of the pending entry move the claim", () => {+ const store = readFileSync(+ new URL(+ "../src/features/chat/stores/chat-runtime-store.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.equal(+ store.match(/pendingAttachmentTargetClaim \+= 1;/g)?.length,+ 2,+ "set-pending and clear-pending both bump it",+ );+ assert.match(+ store,+ /if \(claim !== undefined && claim !== pendingAttachmentTargetClaim\) \{\s*return state;/,+ );++ const bar = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ // Read before initialize(), not after it resolves.+ assert.match(+ bar,+ /const claim = readPendingAttachmentTargetClaim\(\);[\s\S]{0,200}?\.initialize\(\)/,+ );+ assert.match(bar, /adoptPendingProjectAttachmentTarget\(remoteId, claim\)/);+});++// Sending a normal message in a project composer creates the chat, and the page+// swaps ProjectComposer for Thread on the same state change. The bar holding+// the choice unmounts without ever seeing the new id, and the Thread's own bar+// mounts with the id already set, so neither of the bar's adopt paths runs.+test("the project composer's choice survives the swap to a thread", () => {+ const page = readFileSync(+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),+ "utf8",+ );+ // The swap: this is what unmounts the composer.+ assert.match(page, /\{pendingNewThreadId \? \(/);+ // Adopted before it, in the path that learns the id, and only for the choice+ // this composer recorded: a later composer's choice is refused, not consumed.+ assert.match(+ page,+ /adoptPendingProjectAttachmentTarget\(\s*activeThreadId,\s*captured\?\.nonce === newThreadNonce \? captured\.claim : NO_SUCH_CLAIM,\s*\);\s*setPendingNewThreadId\(activeThreadId\);/,+ );+ assert.match(page, /const NO_SUCH_CLAIM = -1;/);+ // Captured by claim, so re-picking the same destination is still this+ // composer's choice rather than an unrecognised one.+ assert.match(page, /const claim = readPendingAttachmentTargetClaim\(\);/);+ assert.match(+ page,+ /if \(captured\?\.nonce === newThreadNonce && captured\.claim === claim\) \{\s*return;/,+ );++ // The claim the store hands out changes on every pending write, value or not.+ const store = readFileSync(+ new URL(+ "../src/features/chat/stores/chat-runtime-store.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ store,+ /if \(threadId === null\) \{\s*pendingAttachmentTargetClaim \+= 1;/,+ );++ // Why the bar cannot cover it: the Thread's bar starts with an id, so the+ // first-id branch never fires for it.+ const bar = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(bar, /const hadThreadIdRef = useRef\(threadId !== null\);/);+});++// A browser-local preference that a reset leaves behind outlives the reset: new+// attachments keep going to the scope the user just asked to forget.+test("the attach-target preference is cleared by the preferences reset", () => {+ const tab = readFileSync(+ new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),+ "utf8",+ );+ const start = tab.indexOf("const PREFS_KEYS");+ const keys = tab.slice(start, tab.indexOf("];", start));+ assert.ok(start >= 0, "PREFS_KEYS moved");+ assert.match(keys, /CHAT_PROJECT_ATTACHMENT_TARGET_KEY,/);+ // By the constant the store writes under, so the two cannot drift apart.+ assert.equal(+ CHAT_PROJECT_ATTACHMENT_TARGET_KEY,+ "unsloth_chat_project_attachment_target",+ );+});diff --git a/studio/frontend/tests/rag-refresh-sequencing.test.ts b/studio/frontend/tests/rag-refresh-sequencing.test.tsnew file mode 100644index 00000000000..31332f805a4--- /dev/null+++ b/studio/frontend/tests/rag-refresh-sequencing.test.ts@@ -0,0 +1,1038 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A project source mutation invalidates before and after itself, and each+// invalidation starts a list request that can complete out of order. An earlier+// one landing last restores the pre-mutation list and reports nothing indexing,+// so a send goes out before the file it needs is in. This pins the+// latest-request rule useRagDocuments.refresh applies.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++type Row = { id: string; status: string };++/** The publish gate as refresh applies it: take a ticket, drop the result if a+ * newer request has started since. `clearScope` is the scope-change effect,+ * which takes a ticket without issuing a request of its own. */+function makeRefresher(published: Row[][]) {+ let seq = 0;+ async function refresh(list: () => Promise<Row[]>) {+ const requestId = ++seq;+ const rows = await list();+ if (seq !== requestId) return;+ published.push(rows);+ }+ refresh.clearScope = () => {+ seq += 1;+ };+ return refresh;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++const EMPTY: Row[] = [];+const INDEXING: Row[] = [{ id: "doc-1", status: "running" }];++test("a stale list response cannot replace a newer one", async () => {+ const published: Row[][] = [];+ const refresh = makeRefresher(published);+ const before = deferred<Row[]>();+ const after = deferred<Row[]>();++ // Both fired by the same upload: the pre-mutation refresh first.+ const first = refresh(() => before.promise);+ const second = refresh(() => after.promise);++ // The post-mutation request wins the race back.+ after.resolve(INDEXING);+ await second;+ // The pre-mutation request lands afterwards, carrying the empty list.+ before.resolve(EMPTY);+ await first;++ assert.deepEqual(+ published,+ [INDEXING],+ "only the newest request publishes, so the indexing row survives",+ );+});++test("responses arriving in order still publish the newest", async () => {+ const published: Row[][] = [];+ const refresh = makeRefresher(published);+ const before = deferred<Row[]>();+ const after = deferred<Row[]>();++ const first = refresh(() => before.promise);+ const second = refresh(() => after.promise);++ before.resolve(EMPTY);+ await first;+ after.resolve(INDEXING);+ await second;++ assert.deepEqual(published, [INDEXING]);+});++test("a lone refresh still publishes", async () => {+ const published: Row[][] = [];+ const refresh = makeRefresher(published);+ await refresh(async () => INDEXING);+ assert.deepEqual(published, [INDEXING]);+});++// Leaving a project clears the scope and issues no replacement request, so+// without a ticket taken on the way out the project's own response lands+// afterwards and puts its sources back in a chat that is not in it.+test("a response for a scope that has been cleared does not publish", async () => {+ const published: Row[][] = [];+ const refresh = makeRefresher(published);+ const inFlight = deferred<Row[]>();++ const pending = refresh(() => inFlight.promise);+ refresh.clearScope();+ inFlight.resolve(INDEXING);+ await pending;++ assert.deepEqual(published, [], "the old scope's sources stay gone");+});++test("the scope-change effect takes a ticket on the way out", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ source,+ /prev !== null && prev !== scopeKey\)[\s\S]{0,400}?refreshSeq\.current \+= 1;/,+ "clearing the scope must outrank a refresh already in flight",+ );+});++// A superseded failure describes a scope no longer shown, and a host without the+// vector extension 503s every one of these: no toast per composer opened.+test("a failure is only reported for the request still being awaited", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ source,+ /if \(refreshSeq\.current !== requestId\) return true;\s*if \(\s*!opts\?\.silentErrors &&\s*!useRagAvailabilityStore\.getState\(\)\.isUnavailable\(\)/,+ );+});++// The composer mounts a project scope per project chat, so a host without RAG+// would fail one request per chat opened. Checked on projectId itself, so the+// attach controls and target menu go with it rather than offering a certain 503.+test("no project scope is opened where RAG cannot run", () => {+ const source = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ source,+ /const projectId =\s*\(ragEnabled && ragSource\.type === "kb"\) \|\| ragUnavailable\s*\? null\s*: \(threadProjectId \?\? null\);/,+ );+ assert.match(source, /projectId \? \{ type: "project", projectId \} : null/);+});++// A project's sources also change from the Sources panel: an upload invalidated+// before and after, and a folder sync reporting at start and completion only.+// The composer holds no row for either while it runs, so re-listing alone left+// it reporting nothing indexing and a send could go out without them.+test("work in the other instance counts as indexing", () => {+ const inFlight = new Map<string, number>();+ const note = (projectId: string, delta: number) => {+ const next = (inFlight.get(projectId) ?? 0) + delta;+ if (next > 0) {+ inFlight.set(projectId, next);+ } else {+ inFlight.delete(projectId);+ }+ };+ // What the composer's instance reports: its own rows, plus uploads elsewhere.+ const composerIndexing = (rows: Row[]) =>+ (inFlight.get("proj-1") ?? 0) > 0 ||+ rows.some((row) => row.status === "pending" || row.status === "running");++ assert.equal(composerIndexing(EMPTY), false, "nothing happening");++ note("proj-1", 1);+ assert.equal(+ composerIndexing(EMPTY),+ true,+ "the panel's POST gates the composer before any row exists",+ );++ // The upload finishes and the row the panel created is now listed.+ note("proj-1", -1);+ assert.equal(composerIndexing(INDEXING), true, "still indexing");+ assert.equal(composerIndexing(EMPTY), false);+});++test("the composer reads indexing from the hooks, not the listed rows", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /noteProjectWork\(uploadingProjectId, 1\)/);+ assert.match(hook, /noteProjectWork\(uploadingProjectId, -1\)/);+ assert.match(hook, /workElsewhere > 0 \|\|/);+ // A folder sync reports at start and completion only, so the rows it+ // creates land with nothing gating the composer in between.+ const folders = readFileSync(+ new URL(+ "../src/features/rag/components/use-linked-folders.ts",+ import.meta.url,+ ),+ "utf8",+ );+ // Tied to the job, not to the component that started it: leaving the Sources+ // tab aborts its event stream, the sync carries on.+ assert.match(folders, /watchProjectFolderJob\(scopeId, initial\.id\)/);+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(api, /noteProjectWork\(projectId, 1\)/);+ assert.match(api, /noteProjectWork\(projectId, -1\)/);+ const bar = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ bar,+ /const hasIndexing =\s*threadIndexing \|\| threadListLoading \|\| projectIndexing \|\| projectListLoading;/,+ );+});++// A list slower than the poll interval used to retire itself: each tick took a+// newer ticket before the previous response landed, so nothing ever published+// and the row being watched never reached completed.+test("a poll tick is skipped while one is still out", () => {+ let inFlight = false;+ let started = 0;+ const tick = () => {+ if (inFlight) return;+ inFlight = true;+ started += 1;+ };++ tick();+ tick();+ tick();+ assert.equal(started, 1, "one request, however many ticks pass");++ inFlight = false;+ tick();+ assert.equal(started, 2, "the next tick goes out once it has landed");+});++test("the poll and the initial list are wired that way", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ hook,+ /if \(!refreshInFlight\.current\) \{\s*void refresh\(\{ quiet: true \}\);/,+ );+ // Reopening a project whose job is already running: nothing is listed yet and+ // no upload of ours is counted, so the gate has to hold for the first list.+ const bar = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ bar,+ /threadIndexing \|\| threadListLoading \|\| projectIndexing \|\| projectListLoading/,+ );+});++// Two tabs on the same project share its sources, and a CustomEvent reaches+// only the tab that fired it.+test("an invalidation crosses tabs", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /getProjectChannel\(\)\?\.postMessage\(\{ kind: "sources", projectId \}\)/,+ );+ // Work in flight crosses too, or the other tab stays sendable through it.+ assert.match(+ api,+ /getProjectChannel\(\)\?\.postMessage\(\{\s*kind: "work",\s*projectId,\s*delta,\s*from: TAB_ID,/,+ );+ assert.match(api, /new BroadcastChannel\(PROJECT_SOURCES_CHANGED_EVENT\)/);+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /subscribeProjectSourcesBroadcast\(\);/);+});++// Only the tab that started the work can report it finished, and it may be+// closed first, so what it reports lapses rather than gating for the session.+test("work reported by another tab lapses", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(api, /const REMOTE_WORK_TTL_MS = 120_000;/);+ assert.match(api, /until: Date\.now\(\) \+ REMOTE_WORK_TTL_MS/);+ // Local and remote add up; a remote count past its deadline is dropped.+ assert.match(+ api,+ /if \(entry\.until > now\) remoteCount \+= entry\.count;\s*\}\s*return \(projectWorkInFlight\.get\(projectId\) \?\? 0\) \+ remoteCount;/,+ );+ // One pending wake-up per project, however chatty the other tab is.+ assert.match(api, /clearTimeout\(timer\)/);++ const TTL = 120_000;+ const remote = new Map<string, { count: number; until: number }>();+ let now = 1_000;+ const note = (projectId: string, delta: number) => {+ const entry = remote.get(projectId) ?? { count: 0, until: 0 };+ const count = Math.max(0, entry.count + delta);+ if (count === 0) {+ remote.delete(projectId);+ } else {+ remote.set(projectId, { count, until: now + TTL });+ }+ };+ const counted = (projectId: string) => {+ const entry = remote.get(projectId);+ return entry && entry.until > now ? entry.count : 0;+ };++ note("proj-1", 1);+ assert.equal(counted("proj-1"), 1, "the other tab's upload gates this one");++ note("proj-1", -1);+ assert.equal(counted("proj-1"), 0, "and releases when it says so");++ // The other tab goes away mid-upload and never reports the end.+ note("proj-1", 1);+ assert.equal(counted("proj-1"), 1);+ now += TTL + 1;+ assert.equal(counted("proj-1"), 0, "the gate does not outlive the tab");+});++// Two uploads overlapping in the other tab: the first to finish must not+// release the gate the second is still holding.+test("overlapping remote work is counted, not flagged", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /setRemoteProjectWork\(projectId, from, Math\.max\(0, current \+ delta\)\);/,+ );++ const remote = new Map<string, { count: number; until: number }>();+ const note = (projectId: string, delta: number) => {+ const entry = remote.get(projectId) ?? { count: 0, until: 0 };+ const count = Math.max(0, entry.count + delta);+ if (count === 0) {+ remote.delete(projectId);+ } else {+ remote.set(projectId, { count, until: Date.now() + 120_000 });+ }+ };++ note("proj-1", 1);+ note("proj-1", 1);+ note("proj-1", -1);+ assert.equal(remote.get("proj-1")?.count, 1, "one still running");+ note("proj-1", -1);+ assert.equal(remote.has("proj-1"), false);+});++// The composer says the source is gone on click, but it is there until the+// DELETE returns, and the probe is invalidated only after that.+test("a project delete is work on the project", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /noteProjectWork\(removingProjectId, 1\)/);+ assert.match(hook, /noteProjectWork\(removingProjectId, -1\)/);+});++// A superseded request clearing the flag would report the list as known while+// the request that will publish is still out.+test("the newest request owns the loading flag", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ hook,+ /if \(refreshSeq\.current === requestId\) \{\s*refreshInFlight\.current = false;\s*setLoading\(false\);/,+ );+});++// The mutation releases its lease when its POST returns, and the invalidation it+// fires afterwards triggers a quiet refresh, which takes no loading gate: between+// the two the composer would report nothing indexing.+test("the refresh an invalidation triggers is counted as work", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ // The listener hands off to the shared loader, which takes the lease for as+ // long as the list (and its retries) run.+ assert.match(+ hook,+ /void loadProjectSources\(projectScopeId, \{ quiet: true \}\);/,+ );+ assert.match(+ hook,+ /noteProjectWork\(projectId, 1\);\s*try \{[\s\S]{0,900}?\} finally \{\s*noteProjectWork\(projectId, -1\);/,+ );+});++// One failed read is not a finished job: a backend restart misses a tick or two+// while the durable sync runs on.+test("a folder job watcher rides out a failed read", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ // The catch is inside the loop, so a failure does not reach the finally.+ assert.match(+ api,+ /if \(isRagClientError\(error\)\) break;\s*consecutiveFailures \+= 1;\s*if \(consecutiveFailures >= MAX_FOLDER_JOB_READ_FAILURES\) \{\s*break;/,+ );+ // A read that comes back clears the streak, so only a run of them gives up.+ assert.match(api, /consecutiveFailures = 0;/);++ // The same loop, run against reads that fail and then recover.+ const reads = ["fail", "fail", "fail", "running", "fail", "completed"];+ let failures = 0;+ let released = -1;+ for (let i = 0; i < reads.length; i += 1) {+ if (reads[i] === "fail") {+ failures += 1;+ if (failures >= 20) {+ released = i;+ break;+ }+ continue;+ }+ failures = 0;+ if (reads[i] === "completed") {+ released = i;+ break;+ }+ }+ assert.equal(+ released,+ 5,+ "released by the terminal status, not by a failure",+ );+});++// An upload larger than the deadline sends no delta in between, so without a+// renewal the other tab stops counting it and becomes sendable mid-upload.+test("work in flight renews the deadline other tabs put on it", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(api, /const WORK_HEARTBEAT_MS = 45_000;/);+ // The absolute count, not a zero delta: a delta cannot revive an entry the+ // receiver has already let lapse, which a suspended timer produces.+ assert.match(api, /setInterval\(answerWorkQuery, WORK_HEARTBEAT_MS\)/);+ // Started and stopped by the count itself, so an idle tab posts nothing.+ assert.match(+ api,+ /if \(projectWorkInFlight\.size === 0\) \{\s*if \(workHeartbeat !== null\) \{\s*clearInterval\(workHeartbeat\)/,+ );++ const remote = new Map<string, { count: number; until: number }>();+ let now = 1_000;+ const counted = (projectId: string) => {+ const entry = remote.get(projectId);+ return entry && entry.until > now ? entry.count : 0;+ };+ // seedRemoteProjectWork: renews the deadline and floors the count, so a+ // heartbeat both holds a live entry and revives one already let lapse.+ const seed = (projectId: string, count: number) => {+ if (count <= 0) return;+ remote.set(projectId, {+ count: Math.max(counted(projectId), count),+ until: now + 120_000,+ });+ };++ seed("proj-1", 1);+ now += 90_000;+ seed("proj-1", 1); // heartbeat inside the deadline+ now += 90_000;+ assert.equal(counted("proj-1"), 1, "still gated three minutes in");++ // A tab frozen past the deadline: the next heartbeat must count again.+ now += 120_001;+ assert.equal(counted("proj-1"), 0, "lapsed while nothing was heard");+ seed("proj-1", 1);+ assert.equal(counted("proj-1"), 1, "revived by the heartbeat after it lapsed");+});++// Clearing to a null scope outranks the refresh still in flight but starts no+// replacement, so nothing reaches the sequence guard that would clear the+// flags. The composer reads the list as still unknown and holds every send.+test("dropping the scope clears the flags no request will", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ hook,+ /if \(scope\) \{[\s\S]{0,300}?: refresh\(\)\);\s*\} else \{[\s\S]{0,300}?refreshInFlight\.current = false;[\s\S]{0,200}?setLoading\(false\);/,+ );++ // The guard that leaves them set: the ticket has already moved on.+ let seq = 0;+ let loading = false;+ const start = () => {+ loading = true;+ return ++seq;+ };+ const settle = (requestId: number) => {+ if (seq === requestId) loading = false;+ };+ const ticket = start();+ seq += 1; // the scope change stands the request down+ settle(ticket);+ assert.equal(+ loading,+ true,+ "the request cannot clear it after being outranked",+ );+});++// The rows a folder sync writes are new sources, and the probe caches its+// answer for 30s. The watcher is the only observer once the panel unmounts, so+// a send released by it would still read the cached "no sources".+test("a folder job drops the cached answer before the gate", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /announceProjectSourcesUpdated\(projectId\);\s*noteProjectWork\(projectId, -1\);/,+ );+});++// BroadcastChannel does not replay, so a tab opened mid-upload hears nothing+// until the next delta, which for an upload is its completion.+test("a tab that opens mid-upload asks what is already running", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ // Asked once, on the way in.+ assert.match(api, /askForWorkInFlight\(\);\s*return projectChannel;/);+ assert.match(api, /postMessage\(\{ kind: "work-query" \}\)/);+ assert.match(+ api,+ /channel\.postMessage\(\{ kind: "work-state", projectId, count, from: TAB_ID \}\)/,+ );++ // Per sender, and a floor within it: the answer can race a delta from the+ // same tab that is already counted, and must not lower it.+ const remote = new Map<string, { count: number; until: number }>();+ const seed = (from: string, count: number) => {+ if (count <= 0) return;+ const entry = remote.get(from);+ if (entry && entry.until > Date.now() && entry.count >= count) return;+ remote.set(from, { count, until: Date.now() + 120_000 });+ };++ seed("tab-a", 2);+ seed("tab-a", 1);+ assert.equal(+ remote.get("tab-a")?.count,+ 2,+ "a smaller answer does not lower it",+ );+ seed("tab-a", 3);+ assert.equal(remote.get("tab-a")?.count, 3);+ seed("tab-b", 0);+ assert.equal(remote.has("tab-b"), false, "an idle tab seeds nothing");+});++// Two tabs uploading to one project are two operations. Merged into a single+// project-wide count, the first to finish clears the gate the second is still+// holding, and a send goes out mid-upload.+test("work is counted per reporting tab, not per project", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /const remoteProjectWork = new Map<\s*string,\s*Map<string, \{ count: number; until: number \}>\s*>\(\);/,+ );+ // Every message says who sent it, or the counts cannot be kept apart.+ assert.match(api, /kind: "work",\s*projectId,\s*delta,\s*from: TAB_ID,/);+ assert.match(+ api,+ /postMessage\(\{ kind: "work-state", projectId, count, from: TAB_ID \}\)/,+ );+ assert.match(api, /if \(entry\.until > now\) remoteCount \+= entry\.count;/);++ // The reported sequence, per sender.+ const TTL = 120_000;+ const now = 1_000;+ const byProject = new Map<+ string,+ Map<string, { count: number; until: number }>+ >();+ const set = (from: string, count: number) => {+ const bySender = byProject.get("proj-1") ?? new Map();+ if (count <= 0) bySender.delete(from);+ else bySender.set(from, { count, until: now + TTL });+ byProject.set("proj-1", bySender);+ };+ const total = () => {+ let sum = 0;+ for (const entry of byProject.get("proj-1")?.values() ?? []) {+ if (entry.until > now) sum += entry.count;+ }+ return sum;+ };++ // Both existing tabs answer a late tab's query.+ set("tab-a", 1);+ set("tab-b", 1);+ assert.equal(total(), 2, "two uploads, not one");++ // One finishes; the other still holds the gate.+ set("tab-a", 0);+ assert.equal(total(), 1);+ set("tab-b", 0);+ assert.equal(total(), 0);+});++// The gate is released by the mutation's reconciling refresh, so a refresh that+// fails releases it with the composer holding no rows at all.+test("a failed reconciling refresh is retried before the gate drops", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /const REFRESH_RETRIES = 3;/);+ assert.match(+ hook,+ /if \(await refresh\(\{ quiet: opts\?\.quiet, silentErrors: !last \}\)\) return;/,+ );+ // The release is still guaranteed, retries or not.+ assert.match(+ hook,+ /\} finally \{\s*noteProjectWork\(projectId, -1\);/,+ );+ // And the first list of a project takes the same path, so a transient failure+ // there does not leave an empty list reporting nothing to wait for.+ assert.match(+ hook,+ /scope\.type === "project"\s*\? loadProjectSources\(scope\.projectId\)\s*: refresh\(\)/,+ );+ // A superseded request reports the list as known: the newer one owns it.+ assert.match(hook, /if \(refreshSeq\.current !== requestId\) return true;/);+});++// The backend creates and starts the job before it answers, so the request+// itself is time the project is changing with nothing gating on it.+test("a folder mutation takes the gate before its request", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-linked-folders.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ hook,+ /noteProjectWork\(projectWorkScopeId, 1\);\s*try \{\s*return await run\(\);\s*\} finally \{\s*noteProjectWork\(projectWorkScopeId, -1\);/,+ );+ // Linking, syncing, rebuilding and unlinking all go through it.+ assert.match(+ hook,+ /withProjectWork\(async \(\) => \{\s*const created = await createLinkedFolder\(/,+ );+ assert.match(+ hook,+ /withProjectWork\(async \(\) => \{\s*const started =\s*mode === "rebuild"/,+ );+ assert.match(+ hook,+ /withProjectWork\(\(\) => deleteLinkedFolder\(folderId, removeIndex\)\)/,+ );+ // The job's own lease is taken inside the request's, so a scope change+ // between the response and trackJob cannot leave the project uncounted.+ assert.match(hook, /watchStartedJob\(created\.job\.id\);\s*return created;/);+ assert.match(hook, /watchStartedJob\(started\.job\.id\);\s*return started;/);+});++// A folder sync outlives the tab that started it. After a reload the watcher is+// gone, and the backend scans the folder before writing any rows, so the+// composer's own list is legitimately empty. Only the Sources panel lists+// linked folders, and a project opens on Chats, so the composer has to ask.+test("a project composer picks up a folder sync already running", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /export async function reconcileProjectFolderJobs\(\s*projectId: string,\s*\): Promise<void>/,+ );+ assert.match(+ api,+ /if \(folder\.activeJobId\) \{\s*watchProjectFolderJob\(projectId, folder\.activeJobId\);/,+ );+ // Two bars on one project share a look, and a failed look does not count as+ // an answer, but the project is never closed to a later one.+ assert.match(+ api,+ /if \(\(folderReconcileNotBefore\.get\(projectId\) \?\? 0\) > now\) return;[\s\S]{0,400}?folderReconcileNotBefore\.set\(projectId, now \+ FOLDER_RECONCILE_MIN_GAP_MS\);/,+ );+ assert.match(api, /folderReconcileNotBefore\.delete\(projectId\);/);++ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /void reconcileProjectFolderJobs\(workScopeId\);/);+ // The backend enqueues a job per auto-syncing folder on its own timer, so one+ // look at mount time misses every scan that starts after it.+ assert.match(+ hook,+ /const reconcile = setInterval\(\(\) => \{\s*void reconcileProjectFolderJobs\(workScopeId\);\s*\}, FOLDER_RECONCILE_INTERVAL_MS\);/,+ );+ // The lookup takes a lease before its first await, so the listener that reads+ // the count has to be registered ahead of it.+ assert.match(+ hook,+ /window\.addEventListener\(PROJECT_WORK_CHANGED_EVENT, read\);[\s\S]{0,400}?void reconcileProjectFolderJobs\(workScopeId\);/,+ );+ assert.match(hook, /clearInterval\(reconcile\);/);+});++// Unlinking a folder deletes its job rows, and so does the history prune, so a+// detached watcher can poll a job id that will never answer again.+test("a folder job watcher stops on an answered 4xx", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ // Read the two constants the loop is bounded by rather than restating them.+ const retryBudget = Number(+ /const MAX_FOLDER_JOB_READ_FAILURES = (\d+);/.exec(api)?.[1],+ );+ assert.ok(retryBudget > 0);++ // The same loop, run against a job that is deleted mid-sync.+ const run = (clientError: boolean) => {+ let failures = 0;+ for (let tick = 0; tick < 600; tick += 1) {+ if (clientError) return tick;+ failures += 1;+ if (failures >= retryBudget) return tick;+ }+ return -1;+ };+ assert.equal(run(true), 0, "a 404 releases the gate on the first read");+ assert.equal(run(false), retryBudget - 1, "a network failure still rides out");+});++// A queued prompt outlives the bar that watched it, and isIndexing() answers only+// while that bar is mounted, so the queue has to ask for the project itself.+test("a background prompt queue checks the project it will send to", () => {+ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ // The thread-scope check no longer returns early past the project one.+ assert.doesNotMatch(+ thread,+ /if \(!item\.target\.usesThreadDocuments\) \{\s*return false;/,+ );+ assert.match(thread, /\? await resolveProjectId\(threadId, undefined, \{/);+ assert.match(thread, /composerProjectId: queueProjectId,/);+ // Work in flight counts as well as rows: an upload has no row until it lands.+ assert.match(+ thread,+ /if \(projectWorkCount\(projectId\) > 0\) \{\s*return true;/,+ );+ assert.match(+ thread,+ /const projectDocuments = await listProjectDocuments\(projectId\);\s*return projectDocuments\.some\(indexingDocument\);/,+ );+});++// A queue in a chat with no row yet cannot look its project up: the row is not+// there, and the store holds whichever project is on screen when the poll lands.+test("a queue in a chat with no row still waits on its project", () => {+ const src = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ // Captured at queue start, beside the other snapshots, and never for incognito+ // (which has no project and no row to reconcile against).+ assert.match(+ src,+ /const projectIdAtQueueStart = incognitoAtQueueStart\s*\?\s*null\s*:\s*\(chatStateAtQueueStart\.activeProjectId \?\? null\);/,+ );+ assert.match(src, /getQueueProjectId: \(\) => projectIdAtQueueStart,/);+ // The thread lookup stays the source of truth wherever there is a thread.+ assert.match(+ src,+ /const queueProjectId = item\.target\.getQueueProjectId\(\);\s*const projectId = threadId\s*\?\s*await resolveProjectId\(threadId, undefined, \{\s*rethrowReadFailure: true,\s*composerProjectId: queueProjectId,\s*\}\)\s*:\s*queueProjectId;/,+ );+ // And the thread-document read is still only made when there is a thread.+ assert.match(src, /if \(threadId && item\.target\.usesThreadDocuments\) \{/);+});++// Unlinking deletes the rows whatever this hook shows by the time the DELETE+// returns, so an announcement gated on the current scope leaves every other+// composer, and every other tab, listing files that are gone.+test("unlinking a folder announces for the project it was for", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-linked-folders.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /const unlinkedProjectId = projectWorkScopeId;/);+ // Announced before the scope guard, so navigating mid-DELETE cannot skip it.+ assert.match(+ hook,+ /if \(unlinkedProjectId\) announceProjectSourcesUpdated\(unlinkedProjectId\);\s*if \(currentScopeKey\.current !== operationScopeKey\) return;/,+ );+});++// A failed read of the chat's own row is not proof it has no project: recording+// one files the next attachment into the chat, and nothing re-runs the lookup+// until the chat or the open project changes.+test("a failed project lookup leaves the scope unresolved", () => {+ const bar = readFileSync(+ new URL(+ "../src/features/rag/components/thread-documents-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(bar, /const PROJECT_LOOKUP_RETRIES = 3;/);+ assert.match(+ bar,+ /for \(let attempt = 0; attempt < PROJECT_LOOKUP_RETRIES; attempt \+= 1\)/,+ );+ // Nothing records a null project on the failure path any more.+ assert.doesNotMatch(+ bar,+ /setResolved\(\{ threadId, trigger: activeProjectId, projectId: null \}\);/,+ );+ // And unresolved still disables the attach controls.+ assert.match(bar, /const projectUnresolved = threadProjectId === undefined;/);+ assert.match(bar, /uploading \|\| projectUploading \|\| projectUnresolved/);+});++// A row the probe could not read is not a chat with no project: answering null+// dispatches the queued prompt and bypasses the retry the catch exists for.+test("a failed row read holds a queued prompt instead of releasing it", () => {+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ assert.match(adapter, /opts\?: \{ rethrowReadFailure\?: boolean;/);+ assert.match(+ adapter,+ /\} catch \(error\) \{[\s\S]{0,200}?if \(opts\?\.rethrowReadFailure\) throw error;\s*return null;/,+ );+ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ thread,+ /await resolveProjectId\(threadId, undefined, \{\s*rethrowReadFailure: true,/,+ );+ // Every other caller keeps failing soft: they run on the send path, where a+ // read failure must not adopt whichever project is on screen.+ assert.equal(+ (thread.match(/rethrowReadFailure/g) ?? []).length,+ 1,+ "only the queue probe rethrows",+ );+});++// A knowledge base replaces every other scope in rag_scope, so a queue scoped to+// one cannot be affected by a project upload or a folder sync.+test("a knowledge-base queue does not wait on project sources", () => {+ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ thread,+ /const usesKnowledgeBaseAtQueueStart =\s*chatStateAtQueueStart\.ragEnabled &&\s*chatStateAtQueueStart\.ragSource\.type === "kb";/,+ );+ assert.match(thread, /usesKnowledgeBase: usesKnowledgeBaseAtQueueStart,/);+ // Ahead of the project lookup, and after the thread one, which a KB queue+ // never takes anyway.+ assert.match(+ thread,+ /if \(item\.target\.usesKnowledgeBase\) \{\s*return false;\s*\}[\s\S]{0,900}?const projectId = threadId/,+ );+ // The exclusivity this relies on, in the adapter that builds the scope.+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ adapter,+ /ragEnabled && ragSource\.type === "kb"\s*\? \{ kb_id: ragSource\.kbId \}/,+ );+});++// A retry sleeps for a second or more and resumes into a closure holding the+// lister of the project it started for, so after the user moves on it publishes+// that project's documents into the composer showing another one.+test("a retry stops when the scope it started for is gone", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/rag/components/use-rag-documents.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /const startedFor = `project:\$\{projectId\}`;/);+ assert.match(+ hook,+ /liveScopeKeyRef\.current = scopeKey;\s*\}, \[scopeKey\]\);/,+ );+ // Checked after the delay, not before the first attempt: the scope effect that+ // starts this load runs before the one that records the live scope.+ assert.match(+ hook,+ /await new Promise\(\(resolve\) =>\s*setTimeout\(resolve, 1000 \* \(attempt \+ 1\)\),\s*\);[\s\S]{0,400}?if \(liveScopeKeyRef\.current !== startedFor\) return;/,+ );+});++// A thread has its id before initialize() has finished writing its row, and the+// store names whichever project is on screen when the queue polls. Falling back+// to it there probes the project the user moved to, not the one being waited on.+test("a queue with no row yet falls back to its own project, not the store", () => {+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ adapter,+ /opts\?: \{ rethrowReadFailure\?: boolean; composerProjectId\?: string \| null \}/,+ );+ // The caller's fallback wins over the store, and null from a caller is an+ // answer rather than a reason to read the store.+ assert.match(+ adapter,+ /const composerProjectId =\s*opts\?\.composerProjectId !== undefined\s*\?\s*opts\.composerProjectId\s*:\s*useChatRuntimeStore\.getState\(\)\.activeProjectId;/,+ );+ // The row and the pending map still outrank it.+ assert.match(adapter, /if \(thread\) \{\s*composerProjectByPendingThread\.delete\(threadId\);/);+});++// One timer covers the project, so arming it for a full TTL on every update+// pushes it past the deadline of a tab that reported earlier. That tab can close+// mid-upload, and its stale count then gates a mounted composer until some later+// event happens to publish.+test("the work timer is armed for the earliest sender deadline", () => {+ const api = readFileSync(+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ api,+ /let earliest = Number\.POSITIVE_INFINITY;\s*for \(const entry of bySender\.values\(\)\) \{\s*earliest = Math\.min\(earliest, entry\.until\);/,+ );+ assert.match(api, /Math\.max\(0, earliest - Date\.now\(\)\)/);+ // Fired, it drops what lapsed and arms for the next deadline rather than+ // leaving the remaining senders with no wake-up at all.+ assert.match(api, /if \(entry\.until <= now\) live\.delete\(sender\);/);+ assert.match(+ api,+ /publishProjectWorkChanged\(projectId\);\s*armRemoteWorkExpiry\(projectId\);/,+ );++ // The scheduling rule itself: two senders, the later update must not push the+ // earlier one's wake-up out.+ const TTL = 120_000;+ const senders = new Map<string, number>();+ const armFor = () => Math.min(...senders.values());+ senders.set("tab-a", 1_000 + TTL);+ assert.equal(armFor(), 1_000 + TTL);+ // Tab B reports 30s later. The timer still has to fire for A first.+ senders.set("tab-b", 31_000 + TTL);+ assert.equal(armFor(), 1_000 + TTL, "A's deadline still owns the timer");+ // A lapses and is dropped; the next wake-up is B's.+ senders.delete("tab-a");+ assert.equal(armFor(), 31_000 + TTL);+});