Skip to content

Studio: share attached files across a project, remember params per model - #8751

Closed
shimmyshimmer wants to merge 3 commits into
mainfrom
studio-project-files-and-per-model-params
Closed

shimmyshimmer wants to merge 3 commits into
mainfrom
studio-project-files-and-per-model-params

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

Fixes two pieces of feedback about Studio chat.

1. Files are not shared across a project

I thought that if I added a new chat to an existing project, I'd be able to access the same files since they share the project, but it turns out I can't.

This is real. A file attached inside a chat that belongs to a project is indexed at thread scope, so no other chat in the project can see it:

thread_A docs: ['repro_notes.txt']
thread_B docs: []          # same project
project docs : []

The composer's Docs bar only ever had two scopes, thread and kb, so there was no way to attach a file to the project from a chat and no sign that the file you just dropped was chat-private. Project sources did exist, but only through the separate Sources tab on the project page.

What changed: in a project chat the Docs bar now files new attachments against the project by default, with a Project / This chat menu on the composer for per-chat overrides. It also lists the project's existing sources inline (folder glyph) beside the chat's own documents, so inherited context is visible instead of merely in effect.

Retrieval already combined project and thread scopes server side (core/rag/tool.py), so the mechanism works end to end once the upload lands in the right place:

chat-scope only (old behaviour):      []
project+chat scope (project chat):    ['shared_brief.txt']

There is also a related race in resolveProjectId. initialize() starts the thread row write without awaiting it, so the first message in a new project chat could read ahead of its own row, conclude the chat had no project, and silently drop the project's sources, instructions and sandbox from exactly the message the project was opened to ask. It now falls back to the composer's project, and never for incognito threads, which are deliberately unpersisted.

2. Chat parameters are global rather than per model

The way chat parameters are handled is awkward; instead of being tied to specific models, there's basically just a single global setting that applies to the chat itself. There is a preset function, but that's designed for switching settings for the same model based on the use case, not for switching between different models.

Also real. inferenceParams is one flat blob and setCheckpoint carried every sampling value across a model switch, clamping only maxTokens. Presets were the only workaround and, as the report says, they are built for switching use case within one model.

What changed: sampling params are now remembered per checkpoint and replayed on switch, with a Settings toggle (on by default). A model with nothing remembered keeps whatever is on screen rather than snapping to defaults. Storage is a per-model map that the server deep merges per key, so tuning one model never clobbers another's:

{
  "rememberParamsPerModel": true,
  "inferenceParamsByModel": {
    "unsloth/Qwen3.5-9B-GGUF": { "temperature": 0.2, "systemPrompt": "Be terse." },
    "unsloth/Llama-4-8B": { "temperature": 0.9 }
  }
}

The rules live in a new pure module, features/chat/lib/per-model-params.ts, free of store and network imports so they stay unit testable.

Settings

Two new rows under Settings, both searchable:

  • Remember settings per model, on by default
  • Share files across a project, on by default, the same choice as the composer menu

Testing

  • Frontend: 2287 pass, including 10 new tests for the per-model rules
  • Backend: new tests for the per-model settings merge and the payload schema
  • Typecheck and the backend sweep match main exactly. The 5 pre-existing typecheck errors (speech dictation DOM types) and 16 pre-existing backend failures (macOS sandbox/env) are byte identical before and after
  • Lint is at parity with main
  • Locale parity passes; new strings are English only, which the parity check allows outside the picker. and studio. prefixes

One gap worth a reviewer's eyes: I verified the mechanism over HTTP and against the RAG scope resolver directly, but did not click through the new composer menu and chip rendering in a browser.

Two things people keep hitting in Studio chat.

Files attached inside a chat that belongs to a project were indexed at
thread scope only, so a new chat in the same project could not see them.
The composer had no way to attach to the project at all: project sources
lived behind the Sources tab on the project page. Project chats now file
attachments against the project by default, with a Project / This chat
switch on the composer, and the bar lists the project's existing sources
next to the chat's own.

Also fixes a race where a fresh chat's first message could miss its
project. initialize() does not await the thread row write, so the send
could read ahead of its own row and drop the project's sources,
instructions and sandbox.

Sampling params were a single global set, so switching models handed the
next model the previous one's temperature and prompt. Presets were the
only way back, and they exist to switch use case within one model. Params
are now remembered per checkpoint and replayed on switch, with a Settings
toggle. A model with nothing remembered keeps the current settings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bf134b3694

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1813 to +1815
if (thread) {
return thread.projectId ?? null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve thread-read errors instead of using the active project

When a persisted thread lookup fails transiently, the .catch(() => null) makes it indistinguishable from the intentional fresh-thread race and execution falls through to activeProjectId. Because chat-page.tsx updates that value only after its own asynchronous thread lookup, sending immediately after navigating from a project chat to an unrelated thread can apply the previous project's sources, instructions, and sandbox to the new request, potentially forwarding unrelated project context to the selected model. Only a confirmed not-yet-persisted thread should use this fallback; transport failures should not.

Useful? React with 👍 / 👎.

Comment on lines +71 to +75
return {
...paramsByModel,
// Merge, not replace: an edit reports only the params it moved.
[modelId]: { ...paramsByModel[modelId], ...changedParams },
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Snapshot all settings when first remembering a model

For a model with no existing entry, this stores only the fields changed by the current edit. For example, editing only model A's temperature, switching to model B and changing its system prompt, then switching back to A overlays A's remembered temperature onto B's current prompt, so A does not regain the settings last used with it and experiments can silently run under the wrong prompt. The first entry for a model needs a complete persisted snapshot, or the outgoing model must be snapshotted before switching.

Useful? React with 👍 / 👎.

Comment on lines +351 to +354
if (sharesWithProject && projectId) {
invalidateProjectSources(projectId);
void uploadToProject(items).finally(() =>
invalidateProjectSources(projectId),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass an explicit project scope when a drop enables RAG

On a project chat where RAG is initially off—the store's default each session—a native desktop drop enters the effect that enables RAG and immediately calls attach, but this render's project useRagDocuments scope is still null because it is gated by ragEnabled. The project branch then calls uploadToProject(items) without an override scope, so the upload consumes the dropped intent and fails with “Could not start a chat” instead of attaching it. Pass { type: "project", projectId } as the upload override, as the thread branch already does for its lazily acquired scope.

Useful? React with 👍 / 👎.

Comment on lines +282 to +284
} = useRagDocuments(
projectId && ragEnabled ? { type: "project", projectId } : null,
projectLister,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Show automatically active project sources with RAG toggled off

Project retrieval is enabled independently of the manual RAG toggle: chat-adapter.ts sets ragOn when projectHasSources(projectId) is true. However, this new project-document hook is disabled when ragEnabled is false, and the bar subsequently returns null, so after every session startup the model can consume project files while the promised inline source chips remain invisible. Load and display the project's inherited sources whenever the project has them, even if thread-level RAG is toggled off.

Useful? React with 👍 / 👎.

Comment on lines +1852 to +1858
const paramsByModel = trackParamsByModel(
getRememberedParamsPatch(
state.rememberParamsPerModel,
state.paramsByModel,
params.checkpoint,
changedParams,
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Replay remembered params when setParams changes checkpoints

The ordinary interactive local-model load completes by calling setParams(mergeBackendRecommendedInference(...)) with the destination checkpoint rather than calling setCheckpoint first. This branch only records the incoming changes under that destination; it never reads the destination's existing paramsByModel entry. The later status refresh calls setCheckpoint after params.checkpoint already equals the new model, so checkpointChanged is false and replay is skipped. Consequently, switching between local models—the main model-switch path—does not restore even a complete remembered parameter set.

Useful? React with 👍 / 👎.

Comment on lines +234 to +237
// A KB-scoped chat uploads through the KB dialog, so neither scope applies there.
const projectId = ragSource.type === "kb" ? null : activeProjectId;
const sharesWithProject =
projectId !== null && projectAttachmentTarget === "project";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve attachment scope from the displayed thread

This uses the global activeProjectId, but when navigating from a project chat to a thread URL, chat-page.tsx does not update that value until an asynchronous getStoredChatThread finishes. During that normal transition the new thread's document bar can therefore list the previous project's files and the default attach action can upload a dropped or quickly selected file into that previous project. Derive the scope from the displayed thread's resolved record, or suppress project actions while its project is unresolved.

Useful? React with 👍 / 👎.

Six issues from review, all confirmed against the code.

Per-model params were never restored on the main switch. An interactive
local load calls setParams with the destination checkpoint and the
backend's recommended params, and only reaches setCheckpoint later, once
params.checkpoint already matches, so checkpointChanged was false and
replay was skipped. setParams now replays too.

A model's entry recorded only the params an edit moved, so replay left
the gaps filled by whatever model was on screen last. Entries are now a
full snapshot.

resolveProjectId treated a failed thread lookup like a not-yet-written
row and fell through to activeProjectId, which could name a project the
user had just left. A failed read now returns no project.

The docs bar read the global activeProjectId, which the chat page
updates only after its own async lookup. It now resolves the project
from the displayed chat's own row and suppresses project actions while
that is unresolved.

A desktop drop with the Docs pill off enables RAG and attaches in the
same tick, so the project hook's scope was still null and the upload
failed. It passes an explicit project scope, as the thread branch does.

Project sources retrieve whenever the project has them, pill or not, but
the bar returned null with the pill off, so the model could answer from
files the user could not see. Those sources are now listed read-only.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Went through all six and they were all real. Fixed in b7c163f.

Replay never ran on the main model switch (P1). Confirmed: use-chat-model-runtime.ts has only two setCheckpoint calls, and neither is on the fresh-load branch. The interactive local load ends at setParams(mergeBackendRecommendedInference({ ..., checkpoint: modelId })), and the only later setCheckpoint is the post-load status refresh, by which point params.checkpoint already equals the new model. So checkpointChanged was false and replay was skipped for exactly the switch people use most. setParams now replays on a checkpoint change, which also puts the memory ahead of the backend recommendation, which is the point of the setting. Pinned by a test that walks the load, edit, switch away, switch back sequence.

Partial entries (P1). Right, and it is worse than the example suggests because replay overlays the entry onto the outgoing model's params, so every unrecorded key silently kept the other model's value. Entries are now a complete snapshot rather than the delta. Added a test for your exact case: A tuned only on temperature, B's prompt changed, back to A, A gets its own prompt.

Transient read failure adopting activeProjectId (P1). Correct, and it was a regression against the old thread?.projectId ?? null, which failed safe. .catch(() => null) conflated a transport failure with the not-yet-written row. Now the error path returns no project and only a confirmed-absent row uses the fallback.

Stale activeProjectId during navigation (P2). Confirmed in chat-page.tsx: the search.thread branch awaits getStoredChatThread before calling setActiveProjectId, so the previous project stays live across that window. The bar no longer reads the global. It resolves the project from the displayed chat's own row and returns null while unresolved, so the project affordances are suppressed rather than aimed at the wrong project. It keeps the composer's project only when there is no thread id yet, or when the row is genuinely absent, which is the same rule the adapter uses.

Drop with the Docs pill off (P2). Confirmed: ragEnabled defaults to false each session, and the native-drop effect enables it and calls attach in the same tick, so the project hook's scope was still null on that render and upload resolved activeScope to null. It now passes { type: "project", projectId } explicitly, matching what the thread branch already does.

Project sources invisible with the pill off (P2). Confirmed against chat-adapter.ts, which gates on ragEnabled || projectRagEnabled, so project retrieval is on whenever the project has sources. The project document hook is no longer gated on ragEnabled, and with the pill off the bar renders those sources read-only instead of returning null. The attach controls stay behind the pill, since thread scope is inert there. I also aligned the KB gate with the adapter: an active KB replaces the project scope, but a KB preference left over while the pill is off does not.

Checks: 2289 frontend tests pass, backend suites pass, typecheck and lint still match main.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7c163f22a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

): Record<string, PersistedInferenceParams> | undefined {
if (!isRecord(value)) return undefined;
const byModel: Record<string, PersistedInferenceParams> = {};
const entries = Object.entries(value).slice(-MAX_REMEMBERED_MODELS);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Evict persisted models instead of slicing only on load

When more than 100 checkpoints have been remembered, this slice drops the oldest entries only from the hydrated client object, while the server retains every key. If the user revisits and edits one of those dropped checkpoints, the server's recursive merge updates that key in its original insertion position rather than moving it to the end, so the next reload slices it out again and loses the newly remembered settings. Persist an actual bounded/recency-ordered map, or otherwise reorder updated entries server-side.

Useful? React with 👍 / 👎.

return () => {
cancelled = true;
};
}, [threadId]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh project scope after moving the active chat

When the currently displayed chat is moved through the sidebar's “Move to project” action, moveStoredChatItemToProject updates the thread row without changing its id, so this effect never reruns. The document bar therefore continues listing the old project's sources and can upload new files into that old project, while chat-adapter.ts rereads the row and retrieves from the new project. Subscribe to thread-record changes or explicitly refresh this scope after a move.

Useful? React with 👍 / 👎.

Comment on lines +1867 to +1875
const paramsByModel = trackParamsByModel(
getRememberedParamsPatch(
state.rememberParamsPerModel,
state.paramsByModel,
nextParams.checkpoint,
changedParams,
pickPersistedInferenceParams(nextParams),
),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve saved model maps during startup status refresh

When Studio starts with a resident local model and the inference-status request finishes before chat-settings hydration, applyActiveModelStatusToStore calls setParams with backend-recommended values and this path marks paramsByModel as mutated from its initial empty map. The concurrent hydration then rejects the entire persisted inferenceParamsByModel map at lines 1582-1586, so switching models during that session silently uses recommendations or another model's settings instead of the saved prompt and sampling parameters. Await hydration before the mount-time status refresh, or avoid treating pre-hydration status reconciliation as a local map edit.

Useful? React with 👍 / 👎.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

Split into two so each fix can be reviewed on its own:

Both branch from current main and carry the review fixes from b7c163f. I checked that merging the two reproduces this PR's content exactly, differing only in the order of the two settings rows. They add adjacent lines at the same anchor in four shared files, so whichever lands second needs a trivial keep-both rebase.

Closing this one in favour of those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant