Repository navigation
Support independent multi-chat prompt queues (clean replacement) - #7406
Imagineer99 wants to merge 23 commits into
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d20b1af48f
ℹ️ 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".
| return; | ||
| } | ||
|
|
||
| if (!tryReservePreStreamRun()) { |
There was a problem hiding this comment.
Release the reservation for deep-research runs
When Deep Research is enabled, this reserves the sole pre-stream slot, but createOpenAIStreamAdapter takes its research branch, calls setThreadRunning(true), and returns without ever calling releasePreStreamRunForThread or notifyPreStreamRunFailed. After the research run finishes, the reservation count therefore remains one, so model changes stay blocked and subsequent chat prompts are queued indefinitely until the page reloads; release the reservation when the research branch transitions to its running state and on its pre-run failure paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. Deep Research now transfers its token-scoped pre-stream reservation immediately before registering run ownership, and its pre-run failure paths release only that reservation.
| if ( | ||
| !store.runningByThreadId[mainThreadId] && | ||
| !isPreStreamRunActive(mainThreadId) | ||
| ) { | ||
| store.clearThreadCancel(mainThreadId); |
There was a problem hiding this comment.
Clear retained cancel callbacks after background runs finish
When the user switches chats while the outgoing thread is running or pre-stream, this cleanup intentionally retains its cancelByThreadId callback, but after the background run finishes nothing re-runs this effect or clears that entry. Each such navigation leaves a closure and runtime reachable indefinitely, and clearAllChats now treats every stale key as active and invokes it; retain the callback while needed, but subscribe to run completion and remove it afterward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. A backgrounded registrar now watches both runtime state and pre-stream failure completion, removes its callback once the run settles, and exits safely if a newer callback replaced it.
| {hasActivityIndicator ? ( | ||
| <span | ||
| className={cn( | ||
| "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity", |
There was a problem hiding this comment.
Render only one spinner for an actively generating row
For every running chat, hasQueueActivity is true because it includes runningByThreadId, while isGenerating is also true. The row consequently renders both the existing chat-row-spinner inside the button and this new absolutely positioned spinner, producing two activity indicators for the same generation; restrict this indicator to queued-but-not-running activity or replace the existing spinner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. The additional activity indicator is now suppressed while the row's existing generating spinner is active.
| const existingRun = findPromptQueueRunByTarget(target); | ||
| if (existingRun) { | ||
| existingRun.items.push( | ||
| ...filtered.map((prompt) => createQueuedPrompt(prompt, target)), |
There was a problem hiding this comment.
Keep queued prompts from separate new chats isolated
If a prompt is queued from an unsaved New Chat while another generation owns capacity, the local thread remains uninitialized because the queued message has not been appended yet. Pressing New Chat again makes assistant-ui reuse that same newThreadId, so the next nominal chat resolves to the same target and this branch appends its prompt to the existing run; both prompts then execute in one conversation rather than independent chats. Assign or initialize a distinct thread identity before preserving an unsaved queue across New Chat actions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. Creating a queue target for an unsaved New Chat now initializes that thread immediately, giving the parked queue a durable identity before another New Chat can reuse the local slot.
| return; | ||
| } | ||
|
|
||
| if (!tryReservePreStreamRun()) { |
There was a problem hiding this comment.
Reserve capacity for generated-image edit submissions
When the generated-image overlay is active, the submit handler rewrites the prompt and returns before reaching this reservation, without preventing the ComposerPrimitive.Send submission. The image-edit request therefore enters history and attachment preparation with no pre-stream slot held, so a model change or another chat dispatch during that asynchronous gap can start concurrently and change the model/settings used for the edit; reserve before the overlay early return as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. Generated-image overlay submissions now reserve pre-stream capacity after validating the image/thread reference and before rewriting/submitting the composer.
| if (getPreStreamRunReservationCount() > 0) { | ||
| notifyPreStreamRunFailed(); |
There was a problem hiding this comment.
Scope attachment failure cleanup to its originating send
With multiple pending attachments, assistant-ui calls every adapter send concurrently via Promise.all, and the remaining conversions continue after the first one rejects. If one failure releases this send's reservation and the user starts another send before a slower attachment also fails, the later catch sees the new global reservation and releases that unrelated send's slot, allowing another queue or model change to overlap it. Associate cleanup with a per-send ownership token or ensure only the original reservation can be released.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. Each attachment conversion captures the originating reservation token; delayed failures can release only that token, so they cannot clear a later send's reservation.
| for (const threadId of activeThreadIds) { | ||
| cancelByThreadId[threadId]?.(); | ||
| } | ||
| requestPromptQueueStop(); |
There was a problem hiding this comment.
Stop compare run-list queues before clearing chat history
When Clear all is used while a saved-prompt Run list is active in Compare view, this event only stops the scheduler in thread.tsx; SharedComposer keeps its separate queue in queueRef and does not listen for the event. The preceding cancel callbacks stop the current pane runs, but that running-to-idle transition makes SharedComposer call advanceQueue() and send the next prompt after storage has been cleared, so generations continue and can recreate history immediately after the destructive action. Stop the compare queue explicitly or have it subscribe to the same boundary event before clearing storage.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e417897. SharedComposer now clears its run-list queue on a global prompt-queue stop, and Clear all dispatches that stop before cancelling active panes so their idle transition cannot advance the queue.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/frontend/src/components/assistant-ui/thread.tsx
Lines 399 to 400 in e417897
When a queued thread uses thread documents and its composer has unmounted after navigation, item.target.isIndexing() is deliberately always false. If this status request then fails transiently while documents are still pending, the catch therefore reports that indexing is finished and the scheduler dispatches the prompt immediately, so retrieval can omit the documents the queue was supposed to wait for. Treat an indeterminate background status as a retry (or fail the queue after bounded retries) rather than as confirmation that indexing completed.
ℹ️ 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".
| "webFetchToolsEnabled", | ||
| "ragEnabled", |
There was a problem hiding this comment.
Snapshot deep-research state for queued runs
When a prompt queued in chat A is waiting and the user enables Deep Research in chat B, consumeQueuedChatRunSettings overlays only these listed keys onto the live store, so createOpenAIStreamAdapter sees B's deepResearchEnabled value and unexpectedly runs A's normal prompt as server-managed research; the reverse can also turn a queued research prompt into a normal response, and the live researchWebsitePolicy can cross chat boundaries too. Include both deep-research fields in the queued snapshot so each background run retains the mode and website policy selected when it was queued.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f078157. Queued snapshots now include Deep Research mode and website policy, and a background queued research run no longer mutates the visible chat's Deep Research toggle.
| try { | ||
| thread.append(appendTextToThread(prompt)); | ||
| } catch (error) { |
There was a problem hiding this comment.
Observe asynchronous failures from queued thread appends
When initialization of a newly queued chat fails, ThreadRuntime.append() returns void while its underlying initialization and append work continues asynchronously, so this try/catch cannot observe the rejection. The scheduler has already marked the item dispatched and globally active, but the model adapter never starts to emit PROMPT_QUEUE_RUN_FAILED_EVENT; consequently the queue and its pending settings remain stuck and all later sends are blocked by global capacity. Await the explicit initialization result or expose another asynchronous failure callback before treating the item as dispatched.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f078157. Unsaved-thread initialization is captured as a settled promise and awaited by the queue target's async append; initialization rejection now reaches appendQueuedPrompt's existing failure/retry path before settings are registered or dispatch is considered successful.
| if (runSignal.aborted) return; | ||
| runtime.setGeneratingStatus("waiting"); | ||
| }, warmupDelayMs); | ||
| releasePreStreamRunForThread(threadKey); |
There was a problem hiding this comment.
Release only the reservation owned by this adapter run
When a queued run is stopped during an asynchronous pre-stream step, deleting its scheduler entry immediately permits a new interactive send to acquire the singleton reservation, while the canceled adapter can continue through preflight because those awaits do not honor its abort signal. This unconditional release then decrements the newer send's reservation, allowing another queue dispatch to overlap it; an unreserved classic compare adapter can cause the same cross-run release. Capture the reservation token belonging to this adapter invocation and pass it as expectedToken, as the research path already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f078157. The adapter captures its reservation token before its first await and passes it to every research, audio, normal-stream, and validation failure release, so stale or unreserved runs cannot release a later send.
|
Addressed the non-inline Codex finding about background document-status checks in f078157. A transient listThreadDocuments failure now keeps the queued item parked for retry instead of treating an unmounted composer's local indexing flag as proof that indexing finished. The same commit also adds a static contract for this behavior. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f078157915
ℹ️ 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".
| append: async (prompt) => { | ||
| const initialization = await queuedThreadInitialization; | ||
| if (initialization && !initialization.ok) { |
There was a problem hiding this comment.
Abort queued append after cancellation
When a new chat's initialization is still pending, stopping its queue, deleting/archiving the chat, or invoking Clear all calls target.cancel(), but that cancellation does not invalidate this async continuation. Once queuedThreadInitialization resolves, the code still registers settings and calls thread.append, so a prompt the user explicitly stopped can begin generating and can even recreate a conversation after its storage was cleared. Track cancellation on the target and check it after the await before appending.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 88053f3. Each queue target now records cancellation and checks it immediately after pending initialization resolves, before registering settings or appending, so a stopped/deleted queue cannot resume from the async continuation.
| if ( | ||
| failedThreadId && | ||
| getCompareThreadIds().includes(failedThreadId) |
There was a problem hiding this comment.
Reject unscoped compare pre-stream failures
For a fresh compare pane, unstable_threadId can still be absent when waitForRunStartHistoryAppend fails, so notifyPreStreamRunFailed dispatches this event with a null thread ID. This predicate ignores that event, while wasRunning remains false because streaming never started, leaving waitForRunEnd() unresolved and the compare workflow stuck indefinitely. The active compare reservation should associate failures with the pane or otherwise handle an unscoped failure while that pane is awaiting startup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 88053f3. A compare handle awaiting startup now rejects both pane-scoped failures and unscoped pre-stream failures; global pre-stream capacity ensures an unscoped startup failure belongs to the active compare attempt.
| if (detail?.threadIds?.length || !isQueueRunningRef.current) { | ||
| return; |
There was a problem hiding this comment.
Stop compare run lists on targeted deletion
When a compare chat is archived or deleted while its saved-prompt run list is active, those operations dispatch a targeted stop containing the pane thread IDs, so this early return leaves the separate compare run list enabled. Cancelling the active pane then produces the running/comparing transition that advances the list, allowing the next saved prompt to start against a conversation that is being archived or removed. Targeted stops matching either compare pane need to clear this run list before the pane runs are cancelled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 88053f3. Compare handles now expose their local/remote thread IDs, and the run-list stop listener clears on global stops or targeted stops intersecting either pane while ignoring unrelated chat deletions.
| runtime = queuedRunSettings | ||
| ? queuedRunSettings.params.checkpoint | ||
| ? { | ||
| ...liveRuntime, | ||
| ...queuedRunSettings, | ||
| params: queuedRunSettings.params, | ||
| } | ||
| : liveRuntime |
There was a problem hiding this comment.
Preserve queued settings after automatic model loading
When a saved-prompt queue starts with no checkpoint loaded, its snapshot necessarily has an empty params.checkpoint, so this branch replaces the entire snapshot with liveRuntime after auto-loading a model. Consequently, queued prompts use whatever reasoning, tool, RAG, permission, and timeout settings are live when each run starts rather than the settings captured when the queue was created; later prompts in the same queue are affected as well. Merge the queued fields back into the live runtime while retaining only the newly auto-loaded checkpoint and associated live model state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 88053f3. After auto-load, queued settings are merged back over live model state and only the newly loaded checkpoint is adopted into the queued params snapshot.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 88053f3689
ℹ️ 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".
| const queuedRunSettings = | ||
| consumeQueuedChatRunSettings(resolvedThreadId); | ||
| if (queuedRunSettings) { | ||
| runtime = { ...runtime, ...queuedRunSettings }; |
There was a problem hiding this comment.
Preserve queued settings through research preflight
When a queued prompt captured Deep Research and the user changes chat settings while it waits, this snapshot is discarded later in the research branch by the unconditional runtime = useChatRuntimeStore.getState() after model readiness. Consequently the research request uses live values for parameters, reasoning, RAG, and website policy rather than the settings captured when the prompt was queued, potentially changing experiment results; merge the queued snapshot back after the load, as the normal-chat path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 09dcc44. After research model readiness/auto-load, the adapter now merges the queued snapshot back over live model state and adopts only the live checkpoint when the snapshot began without one, matching the normal-chat path.
| const queuedThreadInitialization = initialState.remoteId | ||
| ? null | ||
| : aui | ||
| .threadListItem() | ||
| .initialize() |
There was a problem hiding this comment.
Clean up eagerly initialized chats when queues are canceled
When a prompt is queued from a fresh New Chat, this eager initialize() persists the thread immediately, before any queued item is dispatched. If the user removes that parked item or stops its queue while it is still waiting for capacity, the stop/removal paths delete the queue without calling the target's cancellation or deleting the initialized thread, leaving an empty “New Chat” in history; the same in-flight initialization can also recreate an empty thread after Clear All. Clean up an initialized-but-unused target when its queue is discarded, or defer persistence until dispatch while retaining a distinct local identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 09dcc44. Queue targets now expose idempotent disposal; run deletion/reset disposes every target, and an eagerly initialized but never-appended thread is deleted after initialization settles, including cancellation or Clear all races. Existing chats and targets that already appended are preserved.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 09dcc446aa
ℹ️ 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".
| if (promptQueueItems.length === 0) { | ||
| resetPromptQueue(); | ||
| const wasActive = itemIndex === Math.max(run.index, 0); | ||
| run.items.splice(itemIndex, 1); |
There was a problem hiding this comment.
Dispose targets removed from the prompt queue
When an undispatched item is removed, this splice can eliminate the only reference to its target before deletePromptQueueRun() collects targets to dispose. This is especially problematic for a fresh chat because createPromptQueueTarget() eagerly calls initialize(), while target.dispose() is what deletes that initialized thread when no append started; removing the sole queued prompt therefore leaves an orphaned empty thread and retained runtime resources. Dispose the removed target when no remaining item shares it, including when the run becomes empty.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5e5bdc7. Removing an undispatched item now disposes its target immediately when no remaining item shares it, before a now-empty run loses that reference; disposal remains idempotent.
| ? queuedRunSettings.params.checkpoint | ||
| ? { | ||
| ...liveRuntime, | ||
| ...queuedRunSettings, | ||
| params: queuedRunSettings.params, |
There was a problem hiding this comment.
Reload the snapshotted local model before queued dispatch
If a prompt is queued in another chat while a generalized compare is running, the snapshot can contain the model loaded for the first compare side (or the model from before compare), after which ensureModelLoaded() loads the second side and leaves that different model active on the server. Because a nonempty queued checkpoint skips the auto-load branch and is merely merged back here, the queued request is then labeled with the snapshotted model without actually reloading it, causing a backend rejection or, worse, a response from the wrong local model. Verify/load the snapshotted local checkpoint before transferring run ownership.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5e5bdc7. Queued snapshots now retain the active GGUF variant, and the adapter force-loads the exact snapshotted local checkpoint/variant (with queued max sequence length for safetensors) before research or normal preflight. Preferred reload failure does not fall back to another model.
| const toArchive = threads.filter((t) => !t.archived); | ||
| if (toArchive.length === 0) return 0; | ||
|
|
||
| requestPromptQueueStop(toArchive.map((thread) => thread.id)); |
There was a problem hiding this comment.
Stop pending new-chat queues when archiving all chats
Scoping the stop event only to IDs returned by listStoredChatThreads() misses a queue whose fresh-chat target is still completing the eager asynchronous initialize() call. That target is not yet in toArchive, and its captured local/remote IDs do not match any ID in this event, so it survives Archive All and later dispatches and persists a new unarchived chat; the early return when toArchive is empty has the same result. Stop all prompt queues for this bulk operation, or include pending target identities before archiving.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5e5bdc7. Archive all now dispatches a global prompt-queue stop before loading stored threads or taking the empty-list return, so pending fresh-chat targets are disposed even before they appear in history.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5e5bdc72d6
ℹ️ 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".
| if (initialization.ok && !appendStarted) { | ||
| return deleteStoredChatThreads([initialization.remoteId]); |
There was a problem hiding this comment.
Don't delete a chat initialized by its active first turn
When a user queues a follow-up on a new chat before the first message's initialize() call resolves, this target joins that same initialization because initialState.remoteId is still empty. If the user then removes or stops the queued follow-up, dispose() sees its target-local appendStarted as false and deletes the returned remote thread, even though the first message/run already owns it; on a slow history backend this can delete or disrupt persistence of the active conversation. Only delete an initialized thread that this queue created while it was genuinely empty and unowned.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c18aa7b. A queue target owns cleanup only when it observed an uninitialized thread with zero messages at target creation; a follow-up joining an active first turn can still share initialization but can never delete that conversation on disposal.
| if (!reserveInteractiveRun(event)) return; | ||
| aui.composer().send(); |
There was a problem hiding this comment.
Release the slot when an edit is empty
If a user deletes all text while editing a message and clicks Update while the thread is idle, this reserves the global pre-stream slot and then calls send(), but assistant-ui returns immediately for an empty composer without invoking the adapter. Nothing releases the reservation afterward, so every subsequent send and model change is treated as busy until the page is reloaded. Reject empty edits before reserving, or explicitly release the reservation when no run starts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c18aa7b. Edit submission now rejects trimmed-empty text before reserving, and the deferred resend-after-cancel path repeats the empty check before acquiring capacity.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c18aa7beec
ℹ️ 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".
| initialization.ok && | ||
| ownsEagerInitialization && | ||
| !appendStarted | ||
| ) { | ||
| return deleteStoredChatThreads([initialization.remoteId]); |
There was a problem hiding this comment.
Prevent sibling queue targets from deleting the active chat
When two prompts are queued from the same fresh chat before its shared initialize() promise resolves, both targets observe an empty, uninitialized thread and claim cleanup ownership. After the first target starts its run, removing the still-undispatched second prompt calls its dispose(); because that target's own appendStarted remains false, this block deletes the remote thread now used by the active first run. Fresh evidence in the final tree is that cleanup ownership and appendStarted remain target-local even when startPromptQueue merges targets sharing the same thread IDs, so ownership must be coordinated per initialized thread rather than per target.
Useful? React with 👍 / 👎.
Summary
Supersedes #6985 with the same intended feature on a clean, current-
mainhistory.Why this replacement exists
The original PR branch accumulated unrelated ancestry while review fixes were being applied. This replacement preserves the reviewed behavior while removing that ancestry and resolving the current-main draft and send-lifecycle changes together.
Validation
git diff --check