Skip to content

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.

Studio: fix per-chat settings and fork counts for app-created chats (#9639)

Nilayf3c2437c6abf
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 9676139a876..6987831730a 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -2172,17 +2172,18 @@ function ThreadScopedSettingsSync({
enabled,
}: { enabled: boolean }): ReactElement | null {
const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);
+ const pendingNewThreadId = useAuiState(({ threads }) => threads.newThreadId);
const settingsHydrated = useChatRuntimeStore(
(state) => state.settingsHydrated,
);
useEffect(() => {
const { applyThreadScopedSettings } = useChatRuntimeStore.getState();
- // An unsaved chat carries a runtime-made id that no row can exist for, so its read
- // can only 404. Opening a pairing window for it holds every edit behind a round
- // trip that is certain to say "no snapshot", which is how an edit made on a fresh
- // /chat stopped reaching the installation defaults straight away.
- if (isAssistantLocalThreadId(activeThreadId)) {
+ // A chat not yet sent to has no row, so pairing it holds every edit behind a read certain
+ // to 404 -- which is how an edit on a fresh /chat stopped reaching the installation
+ // defaults. The `__LOCALID_` prefix stays on the id for good, so only the runtime's
+ // pending-new-thread id tells the two apart.
+ if (activeThreadId !== null && activeThreadId === pendingNewThreadId) {
applyThreadScopedSettings(null, null);
return;
}
@@ -2253,27 +2254,36 @@ function ThreadScopedSettingsSync({
// over the values the user set and is written out again by the next edit.
const read = new AbortController();
reads.add(read);
- void awaitThreadScopedSettingsWrite(activeThreadId)
- .then(() =>
- // Bounded, because this read is what holds sends back: an unbounded GET that
- // never settles would park every send in the chat behind "Loading this chat's
- // settings" with nothing to release it, and leave the request open besides.
- // The fetch carries THIS attempt's deadline and its controller, so a stall ends
- // the request rather than leaving it running while the retry opens the next one;
- // the race is the backstop for the rest of the read.
- Promise.race([
- getStoredChatThreadReadResult(activeThreadId, {
- timeoutMs: THREAD_READ_TIMEOUT_MS,
- signal: read.signal,
- }),
- new Promise<never>((_, reject) =>
- setTimeout(
- () => reject(new Error("thread settings read timed out")),
- THREAD_READ_TIMEOUT_MS,
- ),
- ),
- ]),
- )
+ // The deadline covers the WAITS as well as the read: neither is bounded on its own (the
+ // settings chain is a PATCH, and awaitStoredChatThreadWrites settles a row write opening
+ // with an unbounded getStoredChatThread). In front of it their time went uncounted, so
+ // the chain could outlast THREAD_PAIRING_WAIT_MS with the gate shut and the send refused.
+ // Inside it, a stall is one failed attempt, which retryThreadRead handles.
+ void Promise.race([
+ Promise.all([
+ // This chat's own PATCH first: a read that overtakes it returns the pre-edit
+ // snapshot, which then goes back over the values the user just set.
+ awaitThreadScopedSettingsWrite(activeThreadId),
+ // And its row, which may not exist yet: initialize() resolves as soon as the id is
+ // minted and leaves the POST tracked, so on a first send a read can overtake it, find
+ // no row, and release this chat's held edits into the installation defaults. Settles
+ // at once when nothing is tracked, so an existing chat waits for nothing.
+ awaitStoredChatThreadWrites(activeThreadId),
+ ]).then(() =>
+ getStoredChatThreadReadResult(activeThreadId, {
+ timeoutMs: THREAD_READ_TIMEOUT_MS,
+ signal: read.signal,
+ }),
+ ),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => {
+ // The waits can expire before the fetch is issued; the controller is the only
+ // thing stopping one issued a moment later from outliving them.
+ read.abort();
+ reject(new Error("thread settings read timed out"));
+ }, THREAD_READ_TIMEOUT_MS),
+ ),
+ ])
.finally(() => {
reads.delete(read);
})
@@ -2360,7 +2370,7 @@ function ThreadScopedSettingsSync({
commitHeldThreadScopedEditsToTheirThread();
window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, sync);
};
- }, [activeThreadId, enabled, settingsHydrated]);
+ }, [activeThreadId, enabled, pendingNewThreadId, settingsHydrated]);
return null;
}
diff --git a/studio/frontend/src/features/chat/utils/fork-count-store.ts b/studio/frontend/src/features/chat/utils/fork-count-store.ts
index 1f0dd98da1e..02a9167b19c 100644
--- a/studio/frontend/src/features/chat/utils/fork-count-store.ts
+++ b/studio/frontend/src/features/chat/utils/fork-count-store.ts
@@ -12,7 +12,7 @@ import {
CHAT_HISTORY_UPDATED_EVENT,
getThreadForkCounts,
} from "../api/chat-api";
-import { isAssistantLocalThreadId } from "./thread-ids";
+import { isThreadIncognito } from "./chat-history-storage";
// Same reasoning as the sidebar's refresh: each quiet window costs one fetch.
export const FORK_COUNT_REFRESH_DEBOUNCE_MS = 300;
@@ -52,16 +52,14 @@ let listening = false;
async function refresh(threadId: string): Promise<void> {
const entry = entries.get(threadId);
if (!entry) return;
- // A thread the server has never seen cannot have forks, so this request can only
- // ever 404 -- and getThreadForkCounts already maps that to an empty map, which is
- // what the entry starts as. It is a round trip whose answer is known.
+ // A temporary chat is the one thread whose forks cannot exist: ensureThreadRecord marks it
+ // and returns without a row. The row decides that, not the id -- a `__LOCALID_` prefix
+ // belongs to every chat the app creates, saved ones included.
//
- // Not a rounding error: a new chat is in exactly this state, and this store
- // refreshes on CHAT_HISTORY_UPDATED_EVENT, which fires once per streaming chunk.
- // So the first reply in a new chat pays one guaranteed-useless request per debounce
- // window for as long as it streams. The heavy-thread smoke is what noticed --
- // it counts requests issued inside a measured interaction, and these landed there.
- if (isAssistantLocalThreadId(threadId)) return;
+ // Skipped because the answer is already the empty map the entry holds, not to dodge a
+ // failure: fork_counts_for_thread GROUPs chat_threads without looking the source up, so an
+ // unknown thread gets 200 and an empty map. Only GET /threads/{id} 404s.
+ if (isThreadIncognito(threadId)) return;
const seq = ++entry.seq;
let counts: Counts;
try {
diff --git a/studio/frontend/tests/assistant-ui-new-thread-contract.test.ts b/studio/frontend/tests/assistant-ui-new-thread-contract.test.ts
new file mode 100644
index 00000000000..55ff8b0823e
--- /dev/null
+++ b/studio/frontend/tests/assistant-ui-new-thread-contract.test.ts
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// ThreadScopedSettingsSync reads "this chat has no row yet" off `threads.newThreadId`, which
+// only discriminates while assistant-ui clears that field on new -> regular. Upstream has
+// shipped versions where it never was (assistant-ui issue #2292, 0.10.35 / 0.10.36), and such
+// a bump would make the guard permanently true and silently restore the bug this PR fixes.
+// The sibling tests are source-text regexes and would stay green through it, so this drives
+// the shipped reducer instead.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// Deep relative path, not the package specifier: @assistant-ui/core's exports map does
+// not publish this module, and the point is to test the shipped artifact.
+import { createThreadMappingId, updateStatusReducer } from "../node_modules/@assistant-ui/core/dist/runtimes/remote-thread-list/remote-thread-state.js";
+
+const LOCAL_ID = "__LOCALID_contract0001";
+
+/** The state shape a pending new thread is in, as switchToNewThread leaves it. */
+function pendingNewThread() {
+ return {
+ isLoading: false,
+ newThreadId: LOCAL_ID,
+ threadIds: [] as string[],
+ archivedThreadIds: [] as string[],
+ threadIdMap: { [LOCAL_ID]: createThreadMappingId(LOCAL_ID) },
+ // RemoteThreadData's "new" variant: the id is the minted __LOCALID_ one and remoteId
+ // is still undefined -- initialize()'s response is what supplies it, and Studio's
+ // adapter answers with the same string it was handed.
+ threadData: {
+ [LOCAL_ID]: {
+ id: LOCAL_ID,
+ remoteId: undefined,
+ externalId: undefined,
+ status: "new" as const,
+ title: undefined,
+ custom: undefined,
+ },
+ },
+ };
+}
+
+test("a pending new thread is the one thread newThreadId names", () => {
+ const state = pendingNewThread();
+ assert.equal(state.newThreadId, LOCAL_ID);
+ assert.ok(
+ LOCAL_ID.startsWith("__LOCALID_"),
+ "the id assistant-ui mints is what Studio stores as the row's primary key",
+ );
+});
+
+test("newThreadId is cleared on new -> regular, which is what initialize() drives", () => {
+ // The substitution in runtime-provider.tsx is only sound because of this line.
+ const after = updateStatusReducer(pendingNewThread(), LOCAL_ID, "regular");
+
+ assert.equal(
+ after.newThreadId,
+ undefined,
+ "assistant-ui no longer clears newThreadId on new -> regular. The pairing guard in " +
+ "ThreadScopedSettingsSync (activeThreadId === pendingNewThreadId) would then be " +
+ "permanently true for every app-created chat, silently restoring the bug #9639 " +
+ "fixed. See assistant-ui issue #2292 for the precedent.",
+ );
+});
+
+test("the id keeps its __LOCALID_ prefix after the transition", () => {
+ // The other half of the premise: the prefix is NOT dropped when the thread is saved,
+ // which is why the prefix cannot be read as "no row yet".
+ const after = updateStatusReducer(pendingNewThread(), LOCAL_ID, "regular");
+
+ assert.ok(
+ after.threadIds.includes(LOCAL_ID),
+ "a saved thread should be listed under the very id it was minted with",
+ );
+});
+
+test("archived and deleted also clear it, so no transition can strand the guard", () => {
+ for (const status of ["archived", "deleted"] as const) {
+ const after = updateStatusReducer(pendingNewThread(), LOCAL_ID, status);
+ assert.equal(
+ after.newThreadId,
+ undefined,
+ `newThreadId survived new -> ${status}, which would strand the pairing guard`,
+ );
+ }
+});
+
+test("a no-op transition leaves the pending new thread pending", () => {
+ // The converse: while the chat really has not been sent to, the guard must stay true.
+ const after = updateStatusReducer(pendingNewThread(), LOCAL_ID, "new" as never);
+ assert.equal(after.newThreadId, LOCAL_ID);
+});
diff --git a/studio/frontend/tests/fork-count-batching.test.ts b/studio/frontend/tests/fork-count-batching.test.ts
index 0d3eae6aed7..26b1629d529 100644
--- a/studio/frontend/tests/fork-count-batching.test.ts
+++ b/studio/frontend/tests/fork-count-batching.test.ts
@@ -10,9 +10,6 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test, { mock } from "node:test";
-// The real one, not a stub: what counts as a local thread is the rule under test,
-// and a hand-written copy of the prefix here could drift from the app's.
-import { isAssistantLocalThreadId } from "../src/features/chat/utils/thread-ids.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
@@ -47,7 +44,10 @@ function fireHistoryUpdated(): void {
}
/** A fresh module instance plus the request log its fetches write to. */
-function freshStore(counts: Record<string, number> = {}): {
+function freshStore(
+ counts: Record<string, number> = {},
+ incognito: readonly string[] = [],
+): {
store: Store;
requests: string[];
} {
@@ -62,7 +62,9 @@ function freshStore(counts: Record<string, number> = {}): {
return new Map(Object.entries(counts));
},
},
- "./thread-ids": { isAssistantLocalThreadId },
+ "./chat-history-storage": {
+ isThreadIncognito: (threadId: string) => incognito.includes(threadId),
+ },
},
);
return { store, requests };
@@ -358,41 +360,50 @@ test("unsubscribing cancels the ceiling as well as the trailing edge", async (t)
second();
});
-test("a local thread never asks the server for forks it cannot have", async (t) => {
- // #8992 added this store; it did not exclude threads the server has never seen.
- // A `__LOCALID_` thread has no server record, so the request can only 404, and
- // getThreadForkCounts maps 404 to the empty map the entry already holds.
- //
- // It is not a rounding error. A new chat is in exactly this state, and this store
- // refreshes on CHAT_HISTORY_UPDATED_EVENT, which fires once per streaming chunk --
- // so the first reply in a new chat paid one useless request per debounce window
- // for as long as it streamed. The heavy-thread smoke, which counts requests issued
- // inside a measured interaction, is what caught it.
+test("a chat created in the app asks for its fork counts", async (t) => {
+ // A `__LOCALID_` id is the permanent primary key of every chat Studio creates, so skipping
+ // the fetch on that prefix left their badges reading 0 for good.
mock.timers.enable({ apis: ["setTimeout"] });
t.after(() => mock.timers.reset());
const { store, requests } = freshStore({ m1: 2 });
const unsubscribe = store.subscribeForkCounts("__LOCALID_abc123", () => {});
await flush();
- assert.deepEqual(
- requests,
- [],
- "subscribing to a local thread must not fetch",
- );
+ assert.deepEqual(requests, ["__LOCALID_abc123"]);
+ assert.equal(store.forkCountFor("__LOCALID_abc123", "m1"), 2);
+
+ unsubscribe();
+});
+
+test("a temporary chat is the one thread that never asks", async (t) => {
+ // An incognito thread has no row, so its forks cannot exist. The saved chat beside it still
+ // asks: the guard is the row, not the `__LOCALID_` prefix both of them carry.
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore({ m1: 2 }, ["__LOCALID_temp"]);
+
+ const stop = [
+ store.subscribeForkCounts("__LOCALID_temp", () => {}),
+ store.subscribeForkCounts("__LOCALID_saved", () => {}),
+ ];
+ await flush();
+ assert.deepEqual(requests, ["__LOCALID_saved"]);
for (let i = 0; i < 20; i++) fireHistoryUpdated();
mock.timers.tick(store.FORK_COUNT_REFRESH_MAX_WAIT_MS);
await flush();
- assert.deepEqual(requests, [], "nor must a burst of history events");
+ assert.equal(
+ requests.filter((id) => id === "__LOCALID_temp").length,
+ 0,
+ "nor must a burst of history events reach a temporary chat",
+ );
+ assert.equal(store.forkCountFor("__LOCALID_temp", "m1"), 0);
+ assert.equal(store.forkCountFor("__LOCALID_saved", "m1"), 2);
- // The badge still reads, it just reads the empty answer without asking.
- assert.equal(store.forkCountFor("__LOCALID_abc123", "m1"), 0);
- unsubscribe();
+ for (const unsubscribe of stop) unsubscribe();
});
-test("a saved thread alongside a local one still refreshes", async (t) => {
- // The guard must be per thread, not a global off switch: the local thread is the
- // one being composed, and a saved thread is on screen next to it.
+test("every subscribed thread refreshes, whatever its id looks like", async (t) => {
mock.timers.enable({ apis: ["setTimeout"] });
t.after(() => mock.timers.reset());
const { store, requests } = freshStore({ m1: 2 });
@@ -402,13 +413,21 @@ test("a saved thread alongside a local one still refreshes", async (t) => {
store.subscribeForkCounts("thread-saved", () => {}),
];
await flush();
- assert.deepEqual(requests, ["thread-saved"]);
+ assert.deepEqual(requests.slice().sort(), [
+ "__LOCALID_abc123",
+ "thread-saved",
+ ]);
+ requests.length = 0;
fireHistoryUpdated();
mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
await flush();
- assert.deepEqual(requests, ["thread-saved", "thread-saved"]);
+ assert.deepEqual(requests.slice().sort(), [
+ "__LOCALID_abc123",
+ "thread-saved",
+ ]);
assert.equal(store.forkCountFor("thread-saved", "m1"), 2);
+ assert.equal(store.forkCountFor("__LOCALID_abc123", "m1"), 2);
for (const unsubscribe of stop) unsubscribe();
});
diff --git a/studio/frontend/tests/thread-scoped-pairing-composition.test.ts b/studio/frontend/tests/thread-scoped-pairing-composition.test.ts
new file mode 100644
index 00000000000..2aeba6d43f4
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-pairing-composition.test.ts
@@ -0,0 +1,163 @@
+// 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 sibling invariants file asserts on source TEXT, which pins which calls are present and
+// in what order but not how they COMBINE -- and here the combinator is the invariant. Turning
+// the inner `Promise.all` into `Promise.race` is one token, leaves every call present and
+// every index unmoved, and reinstates the race the gate closed: the GET then fires as soon as
+// EITHER prerequisite settles, so a first send can still overtake the row write, find no row,
+// and release the chat's held edits into the installation defaults. Measured on the parent
+// commit, that edit passes the whole suite, 4045 of 4045.
+//
+// So these walk the syntax tree. Kept out of the text-based file like tsx-ast.ts and
+// module-stubs.ts: only tests that need the TypeScript compiler should pay to load it.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import ts from "typescript";
+
+const source = ts.createSourceFile(
+ "runtime-provider.tsx",
+ readFileSync(
+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),
+ "utf8",
+ ),
+ ts.ScriptTarget.ES2022,
+ true,
+ ts.ScriptKind.TSX,
+);
+
+/** Every node under `root` satisfying `match`, outermost first. */
+function collect(root: ts.Node, match: (node: ts.Node) => boolean): ts.Node[] {
+ const found: ts.Node[] = [];
+ const walk = (node: ts.Node): void => {
+ if (match(node)) found.push(node);
+ ts.forEachChild(node, walk);
+ };
+ walk(root);
+ return found;
+}
+
+/** `Promise.<name>(...)` as a call. */
+function isCombinator(node: ts.Node, name: string): node is ts.CallExpression {
+ if (!ts.isCallExpression(node)) return false;
+ const callee = node.expression;
+ return (
+ ts.isPropertyAccessExpression(callee) &&
+ ts.isIdentifier(callee.expression) &&
+ callee.expression.text === "Promise" &&
+ callee.name.text === name
+ );
+}
+
+/** Calls to the free function `name` anywhere under `root`. */
+function calls(root: ts.Node, name: string): ts.Node[] {
+ return collect(
+ root,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === name,
+ );
+}
+
+/** The `sync` closure inside ThreadScopedSettingsSync, which is the whole subject here. */
+function syncBody(): ts.Node {
+ const declarations = collect(
+ source,
+ (node) =>
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.name.text === "sync" &&
+ node.initializer !== undefined &&
+ ts.isArrowFunction(node.initializer),
+ ) as ts.VariableDeclaration[];
+ assert.equal(
+ declarations.length,
+ 1,
+ "expected exactly one `const sync = () => ...` in runtime-provider",
+ );
+ return declarations[0].initializer as ts.ArrowFunction;
+}
+
+/** The Promise.all whose settling is what lets the read start. */
+function prerequisites(): ts.CallExpression {
+ const gates = collect(syncBody(), (node) => isCombinator(node, "all"));
+ assert.equal(
+ gates.length,
+ 1,
+ "expected exactly one Promise.all inside sync(): the read's prerequisites",
+ );
+ return gates[0] as ts.CallExpression;
+}
+
+test("the read waits for ALL of its prerequisites, not whichever answers first", () => {
+ // Promise.race here would let the GET start while the row POST is still in flight. Both
+ // waits would still be present, and still textually ahead of the read, so nothing that
+ // reads this file as a string can tell the difference.
+ const gate = prerequisites();
+ assert.equal(gate.arguments.length, 1, "Promise.all takes one array");
+ const [waits] = gate.arguments;
+ assert.ok(ts.isArrayLiteralExpression(waits), "Promise.all argument is an array literal");
+
+ for (const wait of [
+ "awaitThreadScopedSettingsWrite",
+ "awaitStoredChatThreadWrites",
+ ]) {
+ assert.ok(
+ waits.elements.some((element) => calls(element, wait).length > 0),
+ `${wait}() is not one of the gated prerequisites`,
+ );
+ }
+});
+
+test("the read hangs off the prerequisites rather than running beside them", () => {
+ // Two independent promises would issue the GET immediately, however the waits combine.
+ const gate = prerequisites();
+ const parent = gate.parent;
+ assert.ok(
+ ts.isPropertyAccessExpression(parent) && parent.name.text === "then",
+ "the prerequisites are not immediately followed by .then",
+ );
+ const then = parent.parent;
+ assert.ok(ts.isCallExpression(then), "the .then is not called");
+ assert.ok(
+ calls(then.arguments[0], "getStoredChatThreadReadResult").length > 0,
+ "the thread read does not happen inside the prerequisites' .then",
+ );
+ assert.equal(
+ calls(syncBody(), "getStoredChatThreadReadResult").length,
+ 1,
+ "more than one thread read in sync(); only the gated one may exist",
+ );
+});
+
+test("the whole attempt, waits included, sits inside one deadline", () => {
+ // The structural form of the sibling file's index check: the deadline must CONTAIN the
+ // prerequisites, not just precede them in the text. Neither wait is bounded on its own, so
+ // outside it a stalled write ends in a refused send.
+ const gate = prerequisites();
+ const races = collect(syncBody(), (node) => isCombinator(node, "race"));
+ assert.ok(races.length >= 1, "the per-attempt deadline is gone");
+
+ const enclosing = races.find(
+ (race) => race.getStart() <= gate.getStart() && race.getEnd() >= gate.getEnd(),
+ );
+ assert.ok(enclosing, "the prerequisites are not inside a Promise.race deadline");
+
+ const [candidates] = (enclosing as ts.CallExpression).arguments;
+ assert.ok(ts.isArrayLiteralExpression(candidates));
+ assert.ok(
+ candidates.elements.some(
+ (element) =>
+ element !== gate &&
+ element.getText().includes("THREAD_READ_TIMEOUT_MS") &&
+ /reject\(/.test(element.getText()),
+ ),
+ "the deadline does not reject on THREAD_READ_TIMEOUT_MS; a deadline that RESOLVES " +
+ "would fall through to the read, find no row, and release this chat's held edits " +
+ "into the installation defaults",
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
index f0581284b38..671a33572fa 100644
--- a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
@@ -36,6 +36,10 @@ test("the read waits for this chat's own write before it can be believed", () =>
// returns the pre-edit snapshot, which is then applied over what the user set.
const sync = slice(provider, "const sync = () => {", "// The read did not answer");
assert.match(sync, /awaitThreadScopedSettingsWrite\(activeThreadId\)/);
+ // And the row's own creation: initialize() resolves as soon as the id is minted and leaves
+ // the POST tracked, so a first send's read can overtake it, see no row, and release this
+ // chat's held edits into the installation defaults.
+ assert.match(sync, /awaitStoredChatThreadWrites\(activeThreadId\)/);
// and the read only happens after it, not alongside
assert.ok(
sync.indexOf("awaitThreadScopedSettingsWrite") <
@@ -44,6 +48,52 @@ test("the read waits for this chat's own write before it can be believed", () =>
);
});
+/** sync()'s body with comments removed, for the two order assertions below. These call
+ * sites are heavily commented, and a prose mention of a call ahead of the call itself
+ * would otherwise read as the call being in the wrong place. */
+function syncCode(): string {
+ return slice(provider, "const sync = () => {", "// The read did not answer")
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ .replace(/^[ \t]*\/\/.*$/gm, "");
+}
+
+test("both waits sit inside the attempt's deadline, not in front of it", () => {
+ // Neither wait is bounded on its own, so in front of the deadline their time goes
+ // uncounted and a stalled write ends in a refused send. The reasoning is at the call site.
+ const sync = syncCode();
+ const race = sync.indexOf("Promise.race");
+ assert.ok(race !== -1, "the per-attempt deadline is gone");
+
+ for (const wait of ["awaitThreadScopedSettingsWrite", "awaitStoredChatThreadWrites"]) {
+ assert.ok(
+ sync.indexOf(wait) > race,
+ `${wait}() is awaited before the deadline opens, so its time is unbounded`,
+ );
+ }
+});
+
+test("the pairing wait still outlasts the worst case read chain", () => {
+ // The arithmetic THREAD_PAIRING_WAIT_MS's own comment claims. Read from source so the
+ // two cannot drift apart: whichever constant moves, this is what catches it.
+ const constant = (source: string, name: string): number => {
+ const match = source.match(new RegExp(`${name}\\s*=\\s*([0-9_]+)`));
+ assert.ok(match, `${name} not found`);
+ return Number(match[1].replace(/_/g, ""));
+ };
+ const store = read("../src/features/chat/stores/chat-runtime-store.ts");
+
+ const attempts = constant(provider, "THREAD_READ_RETRIES") + 1;
+ const worstCase =
+ attempts * constant(provider, "THREAD_READ_TIMEOUT_MS") +
+ (attempts - 1) * constant(provider, "THREAD_READ_RETRY_MS");
+
+ assert.ok(
+ worstCase < constant(store, "THREAD_PAIRING_WAIT_MS"),
+ `the read chain can take ${worstCase}ms, at or past the gate's give-up, so a slow ` +
+ "read refuses the user's send instead of falling back to the installation defaults",
+ );
+});
+
test("running out of read retries ends the pairing rather than parking sends forever", () => {
// threadScopedSettingsPending gates the composer, so a pairing left open with no retry
// left holds every send behind a wait that nothing can resolve.
@@ -462,19 +512,30 @@ test("a fork stops when the chat's settings could not be saved", () => {
});
test("an unsaved chat's edit reaches the installation defaults without a round trip", () => {
- // assistant-ui gives an unsaved thread a `__LOCALID_` id (RemoteThreadListThreadList
- // RuntimeCore), which no row can exist for, so its read can only 404. Holding edits
- // behind that certain-to-fail read is what stopped a pill clicked on a fresh /chat
- // from reaching localStorage straight away, which playwright_chat_ui asserts.
+ // Holding edits behind a read certain to 404 is what stopped a pill clicked on a fresh
+ // /chat from reaching localStorage at once, which playwright_chat_ui asserts. A chat is
+ // unsaved only until its first send, so the test is the runtime's pending-new-thread id:
+ // the `__LOCALID_` prefix stays for good and gated every app-created chat out of its own
+ // settings (#8686).
const effect = slice(
provider,
"const { applyThreadScopedSettings } = useChatRuntimeStore.getState();",
"if (!enabled) {",
);
- assert.match(effect, /isAssistantLocalThreadId\(activeThreadId\)/);
+ assert.match(effect, /activeThreadId === pendingNewThreadId/);
+ assert.doesNotMatch(effect, /isAssistantLocalThreadId/);
assert.match(effect, /applyThreadScopedSettings\(null, null\)/);
});
+test("the pairing effect tracks the runtime's pending new thread", () => {
+ assert.match(
+ provider,
+ /const pendingNewThreadId = useAuiState\(\(\{ threads \}\) => threads\.newThreadId\)/,
+ );
+ const deps = slice(provider, "}, [activeThreadId, enabled,", ");");
+ assert.match(deps, /pendingNewThreadId/);
+});
+
test("a run whose pairing never settled is refused, not run on another chat's settings", () => {
// The wait only runs out for a chat left mid-read, whose gate is held shut on purpose;
// by then the store describes whatever chat the user moved to.
diff --git a/tests/studio/playwright_thread_scoped_settings.py b/tests/studio/playwright_thread_scoped_settings.py
index 05e702e6514..2236f3f0bed 100644
--- a/tests/studio/playwright_thread_scoped_settings.py
+++ b/tests/studio/playwright_thread_scoped_settings.py
@@ -119,9 +119,24 @@ def sign_in(page):
return page.evaluate("() => localStorage.getItem('unsloth_auth_token')")
-def seed_thread(page, token, title):
+def app_created_thread_id():
+ """The id a chat started in the app really carries.
+
+ assistant-ui mints `__LOCALID_<id>` for a thread before its first send, the thread list
+ adapter hands that same string back as the remoteId, and the row keeps it as its primary
+ key. The prefix therefore says nothing about whether a row exists.
+ """
+ return f"__LOCALID_{uuid.uuid4().hex}"
+
+
+def seed_thread(
+ page,
+ token,
+ title,
+ thread_id = None,
+):
"""Create a saved chat with one message, the state the sidebar and the loader expect."""
- thread_id = str(uuid.uuid4())
+ thread_id = thread_id or str(uuid.uuid4())
now = int(time.time() * 1000)
api(
page,
@@ -330,7 +345,10 @@ def main():
)
step("seed two saved chats")
- thread_a = seed_thread(page, token, "Chat A")
+ # Both id shapes are real: chats started in the app keep their `__LOCALID_` id as the
+ # row's primary key, imported and older rows do not. Seeding only uuids is what let
+ # this run miss the prefix being read as "no row yet".
+ thread_a = seed_thread(page, token, "Chat A", app_created_thread_id())
thread_b = seed_thread(page, token, "Chat B")
print(f"[thread-settings] A={thread_a} B={thread_b}", flush = True)