fix(sdk-js): avoid stale client when fetching history

This commit is contained in:
Tat Dat Duong
2025-06-27 19:51:49 +02:00
parent 80d6bddd1b
commit 9b7cc1c82e
2 changed files with 38 additions and 2 deletions
+30
View File
@@ -1658,7 +1658,30 @@ export class Client<
*/
public "~ui": UiClient;
/**
* @internal Used to obtain a stable key representing the client.
*/
private "~configHash": string | undefined;
constructor(config?: ClientConfig) {
this["~configHash"] = (() =>
JSON.stringify({
apiUrl: config?.apiUrl,
apiKey: config?.apiKey,
timeoutMs: config?.timeoutMs,
defaultHeaders: config?.defaultHeaders,
maxConcurrency: config?.callerOptions?.maxConcurrency,
maxRetries: config?.callerOptions?.maxRetries,
callbacks: {
onFailedResponseHook:
config?.callerOptions?.onFailedResponseHook != null,
onRequest: config?.onRequest != null,
fetch: config?.callerOptions?.fetch != null,
},
}))();
this.assistants = new AssistantsClient(config);
this.threads = new ThreadsClient(config);
this.runs = new RunsClient(config);
@@ -1667,3 +1690,10 @@ export class Client<
this["~ui"] = new UiClient(config);
}
}
/**
* @internal Used to obtain a stable key representing the client.
*/
export function getClientConfigHash(client: Client): string | undefined {
return client["~configHash"];
}
+8 -2
View File
@@ -1,7 +1,7 @@
/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */
"use client";
import { Client, type ClientConfig } from "../client.js";
import { Client, getClientConfigHash, type ClientConfig } from "../client.js";
import type {
Command,
DisconnectMode,
@@ -321,11 +321,17 @@ function useThreadHistory<StateType extends Record<string, unknown>>(
) {
const [history, setHistory] = useState<ThreadState<StateType>[]>([]);
const clientRef = useRef(client);
clientRef.current = client;
const clientHash = getClientConfigHash(client);
const fetcher = useCallback(
(
threadId: string | undefined | null,
): Promise<ThreadState<StateType>[]> => {
if (threadId != null) {
const client = clientRef.current;
return fetchHistory<StateType>(client, threadId).then((history) => {
setHistory(history);
return history;
@@ -336,7 +342,7 @@ function useThreadHistory<StateType extends Record<string, unknown>>(
clearCallbackRef.current?.();
return Promise.resolve([]);
},
[],
[clientHash],
);
useEffect(() => {