@aomi-labs/react 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { AomiClient, Session, WalletRequest } from '@aomi-labs/client';
2
- export { AomiChatResponse, AomiClient, AomiClientOptions, AomiCreateThreadResponse, AomiInterruptResponse, AomiMessage, AomiSSEEvent, AomiStateResponse, AomiSystemEvent, AomiSystemResponse, AomiThread, WalletEip712Payload, WalletRequest, WalletTxPayload, toViemSignTypedDataArgs } from '@aomi-labs/client';
1
+ import { AomiClient, Session, WalletRequest, UserState } from '@aomi-labs/client';
2
+ export { AomiChatResponse, AomiClient, AomiClientOptions, AomiCreateThreadResponse, AomiInterruptResponse, AomiMessage, AomiSSEEvent, AomiStateResponse, AomiSystemEvent, AomiSystemResponse, AomiThread, UserState, WalletEip712Payload, WalletRequest, WalletTxPayload, toViemSignTypedDataArgs } from '@aomi-labs/client';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import { ReactNode, SetStateAction } from 'react';
5
5
  import { ThreadMessageLike } from '@assistant-ui/react';
@@ -11,25 +11,6 @@ type AomiRuntimeProviderProps = {
11
11
  };
12
12
  declare function AomiRuntimeProvider({ children, backendUrl, }: Readonly<AomiRuntimeProviderProps>): react_jsx_runtime.JSX.Element;
13
13
 
14
- type UserState = {
15
- address?: string;
16
- chainId?: number;
17
- isConnected: boolean;
18
- ensName?: string;
19
- ext?: Record<string, unknown>;
20
- };
21
- declare function useUser(): {
22
- user: UserState;
23
- setUser: (data: Partial<UserState>) => void;
24
- addExtValue: (key: string, value: unknown) => void;
25
- removeExtValue: (key: string) => void;
26
- getUserState: () => UserState;
27
- onUserStateChange: (callback: (user: UserState) => void) => () => void;
28
- };
29
- declare function UserContextProvider({ children }: {
30
- children: ReactNode;
31
- }): react_jsx_runtime.JSX.Element;
32
-
33
14
  type ThreadContext = {
34
15
  currentThreadId: string;
35
16
  setCurrentThreadId: (id: string) => void;
@@ -152,12 +133,14 @@ type WalletHandlerConfig = {
152
133
  type WalletHandlerApi = {
153
134
  /** All queued wallet requests (tx + eip712) */
154
135
  pendingRequests: WalletRequest[];
155
- /** Enqueue a wallet request (called by orchestrator on ClientSession events) */
156
- enqueueRequest: (request: WalletRequest) => void;
136
+ /** Replace pending requests with the session's authoritative snapshot. */
137
+ setRequests: (requests: WalletRequest[]) => void;
138
+ /** Mark a request as in-flight so it is not replayed while awaiting backend ack. */
139
+ startRequest: (id: string) => void;
157
140
  /** Complete a request successfully — sends response to backend via ClientSession */
158
- resolveRequest: (id: string, result: WalletRequestResult) => void;
141
+ resolveRequest: (id: string, result: WalletRequestResult) => Promise<void>;
159
142
  /** Fail a request — sends error to backend via ClientSession */
160
- rejectRequest: (id: string, error?: string) => void;
143
+ rejectRequest: (id: string, error?: string) => Promise<void>;
161
144
  };
162
145
  declare function useWalletHandler({ getSession, }: WalletHandlerConfig): WalletHandlerApi;
163
146
 
@@ -212,10 +195,10 @@ type AomiRuntimeApi = {
212
195
  pendingWalletRequests: WalletRequest[];
213
196
  /** Mark a wallet request as being processed */
214
197
  startWalletRequest: (id: string) => void;
215
- /** Complete a wallet request dequeues + sends response to backend */
216
- resolveWalletRequest: (id: string, result: WalletRequestResult) => void;
217
- /** Fail a wallet request dequeues + sends error to backend */
218
- rejectWalletRequest: (id: string, error?: string) => void;
198
+ /** Complete a wallet request after the backend acknowledges the response */
199
+ resolveWalletRequest: (id: string, result: WalletRequestResult) => Promise<void>;
200
+ /** Fail a wallet request after the backend acknowledges the error */
201
+ rejectWalletRequest: (id: string, error?: string) => Promise<void>;
219
202
  /** Subscribe to inbound events by type. Returns unsubscribe function. */
220
203
  subscribe: (type: string, callback: EventSubscriber) => () => void;
221
204
  /** Send a system command to the backend */
@@ -280,6 +263,18 @@ type NotificationApi = {
280
263
  };
281
264
  declare function useNotificationHandler({ onNotification, }?: NotificationHandlerConfig): NotificationApi;
282
265
 
266
+ declare function useUser(): {
267
+ user: UserState;
268
+ setUser: (data: Partial<UserState>) => void;
269
+ addExtValue: (key: string, value: unknown) => void;
270
+ removeExtValue: (key: string) => void;
271
+ getUserState: () => UserState;
272
+ onUserStateChange: (callback: (user: UserState) => void) => () => void;
273
+ };
274
+ declare function UserContextProvider({ children }: {
275
+ children: ReactNode;
276
+ }): react_jsx_runtime.JSX.Element;
277
+
283
278
  /**
284
279
  * Utility function to merge Tailwind CSS classes with conflict resolution.
285
280
  * Combines clsx for conditional classes and tailwind-merge for deduplication.
@@ -385,4 +380,4 @@ type ControlContextProviderProps = {
385
380
  };
386
381
  declare function ControlContextProvider({ children, aomiClient, sessionId, publicKey, getThreadMetadata, updateThreadMetadata, }: ControlContextProviderProps): react_jsx_runtime.JSX.Element;
387
382
 
388
- export { type AomiRuntimeApi, AomiRuntimeProvider, type AomiRuntimeProviderProps, type ChainInfo, type ControlContextApi, ControlContextProvider, type ControlContextProviderProps, type ControlState, type EventContext, EventContextProvider, type EventContextProviderProps, type EventSubscriber, type InboundEvent, type Notification$1 as Notification, type NotificationApi, NotificationContextProvider, type NotificationContextProviderProps, type NotificationContextApi as NotificationContextValue, type NotificationHandlerConfig, type NotificationType, type SSEStatus, SUPPORTED_CHAINS, type NotificationData as ShowNotificationParams, type StoredProviderKey, type ThreadContext, ThreadContextProvider, type ThreadControlState, type ThreadMetadata, type UserConfig, UserContextProvider, type UserState, type WalletHandlerApi, type WalletHandlerConfig, type WalletRequestKind, type WalletRequestResult, type WalletRequestStatus, cn, formatAddress, getChainInfo, getNetworkName, initThreadControl, useAomiRuntime, useControl, useCurrentThreadMessages, useCurrentThreadMetadata, useEventContext, useNotification, useNotificationHandler, useThreadContext, useUser, useWalletHandler };
383
+ export { type AomiRuntimeApi, AomiRuntimeProvider, type AomiRuntimeProviderProps, type ChainInfo, type ControlContextApi, ControlContextProvider, type ControlContextProviderProps, type ControlState, type EventContext, EventContextProvider, type EventContextProviderProps, type EventSubscriber, type InboundEvent, type Notification$1 as Notification, type NotificationApi, NotificationContextProvider, type NotificationContextProviderProps, type NotificationContextApi as NotificationContextValue, type NotificationHandlerConfig, type NotificationType, type SSEStatus, SUPPORTED_CHAINS, type NotificationData as ShowNotificationParams, type StoredProviderKey, type ThreadContext, ThreadContextProvider, type ThreadControlState, type ThreadMetadata, type UserConfig, UserContextProvider, type WalletHandlerApi, type WalletHandlerConfig, type WalletRequestKind, type WalletRequestResult, type WalletRequestStatus, cn, formatAddress, getChainInfo, getNetworkName, initThreadControl, useAomiRuntime, useControl, useCurrentThreadMessages, useCurrentThreadMetadata, useEventContext, useNotification, useNotificationHandler, useThreadContext, useUser, useWalletHandler };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { AomiClient, Session, WalletRequest } from '@aomi-labs/client';
2
- export { AomiChatResponse, AomiClient, AomiClientOptions, AomiCreateThreadResponse, AomiInterruptResponse, AomiMessage, AomiSSEEvent, AomiStateResponse, AomiSystemEvent, AomiSystemResponse, AomiThread, WalletEip712Payload, WalletRequest, WalletTxPayload, toViemSignTypedDataArgs } from '@aomi-labs/client';
1
+ import { AomiClient, Session, WalletRequest, UserState } from '@aomi-labs/client';
2
+ export { AomiChatResponse, AomiClient, AomiClientOptions, AomiCreateThreadResponse, AomiInterruptResponse, AomiMessage, AomiSSEEvent, AomiStateResponse, AomiSystemEvent, AomiSystemResponse, AomiThread, UserState, WalletEip712Payload, WalletRequest, WalletTxPayload, toViemSignTypedDataArgs } from '@aomi-labs/client';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import { ReactNode, SetStateAction } from 'react';
5
5
  import { ThreadMessageLike } from '@assistant-ui/react';
@@ -11,25 +11,6 @@ type AomiRuntimeProviderProps = {
11
11
  };
12
12
  declare function AomiRuntimeProvider({ children, backendUrl, }: Readonly<AomiRuntimeProviderProps>): react_jsx_runtime.JSX.Element;
13
13
 
14
- type UserState = {
15
- address?: string;
16
- chainId?: number;
17
- isConnected: boolean;
18
- ensName?: string;
19
- ext?: Record<string, unknown>;
20
- };
21
- declare function useUser(): {
22
- user: UserState;
23
- setUser: (data: Partial<UserState>) => void;
24
- addExtValue: (key: string, value: unknown) => void;
25
- removeExtValue: (key: string) => void;
26
- getUserState: () => UserState;
27
- onUserStateChange: (callback: (user: UserState) => void) => () => void;
28
- };
29
- declare function UserContextProvider({ children }: {
30
- children: ReactNode;
31
- }): react_jsx_runtime.JSX.Element;
32
-
33
14
  type ThreadContext = {
34
15
  currentThreadId: string;
35
16
  setCurrentThreadId: (id: string) => void;
@@ -152,12 +133,14 @@ type WalletHandlerConfig = {
152
133
  type WalletHandlerApi = {
153
134
  /** All queued wallet requests (tx + eip712) */
154
135
  pendingRequests: WalletRequest[];
155
- /** Enqueue a wallet request (called by orchestrator on ClientSession events) */
156
- enqueueRequest: (request: WalletRequest) => void;
136
+ /** Replace pending requests with the session's authoritative snapshot. */
137
+ setRequests: (requests: WalletRequest[]) => void;
138
+ /** Mark a request as in-flight so it is not replayed while awaiting backend ack. */
139
+ startRequest: (id: string) => void;
157
140
  /** Complete a request successfully — sends response to backend via ClientSession */
158
- resolveRequest: (id: string, result: WalletRequestResult) => void;
141
+ resolveRequest: (id: string, result: WalletRequestResult) => Promise<void>;
159
142
  /** Fail a request — sends error to backend via ClientSession */
160
- rejectRequest: (id: string, error?: string) => void;
143
+ rejectRequest: (id: string, error?: string) => Promise<void>;
161
144
  };
162
145
  declare function useWalletHandler({ getSession, }: WalletHandlerConfig): WalletHandlerApi;
163
146
 
@@ -212,10 +195,10 @@ type AomiRuntimeApi = {
212
195
  pendingWalletRequests: WalletRequest[];
213
196
  /** Mark a wallet request as being processed */
214
197
  startWalletRequest: (id: string) => void;
215
- /** Complete a wallet request dequeues + sends response to backend */
216
- resolveWalletRequest: (id: string, result: WalletRequestResult) => void;
217
- /** Fail a wallet request dequeues + sends error to backend */
218
- rejectWalletRequest: (id: string, error?: string) => void;
198
+ /** Complete a wallet request after the backend acknowledges the response */
199
+ resolveWalletRequest: (id: string, result: WalletRequestResult) => Promise<void>;
200
+ /** Fail a wallet request after the backend acknowledges the error */
201
+ rejectWalletRequest: (id: string, error?: string) => Promise<void>;
219
202
  /** Subscribe to inbound events by type. Returns unsubscribe function. */
220
203
  subscribe: (type: string, callback: EventSubscriber) => () => void;
221
204
  /** Send a system command to the backend */
@@ -280,6 +263,18 @@ type NotificationApi = {
280
263
  };
281
264
  declare function useNotificationHandler({ onNotification, }?: NotificationHandlerConfig): NotificationApi;
282
265
 
266
+ declare function useUser(): {
267
+ user: UserState;
268
+ setUser: (data: Partial<UserState>) => void;
269
+ addExtValue: (key: string, value: unknown) => void;
270
+ removeExtValue: (key: string) => void;
271
+ getUserState: () => UserState;
272
+ onUserStateChange: (callback: (user: UserState) => void) => () => void;
273
+ };
274
+ declare function UserContextProvider({ children }: {
275
+ children: ReactNode;
276
+ }): react_jsx_runtime.JSX.Element;
277
+
283
278
  /**
284
279
  * Utility function to merge Tailwind CSS classes with conflict resolution.
285
280
  * Combines clsx for conditional classes and tailwind-merge for deduplication.
@@ -385,4 +380,4 @@ type ControlContextProviderProps = {
385
380
  };
386
381
  declare function ControlContextProvider({ children, aomiClient, sessionId, publicKey, getThreadMetadata, updateThreadMetadata, }: ControlContextProviderProps): react_jsx_runtime.JSX.Element;
387
382
 
388
- export { type AomiRuntimeApi, AomiRuntimeProvider, type AomiRuntimeProviderProps, type ChainInfo, type ControlContextApi, ControlContextProvider, type ControlContextProviderProps, type ControlState, type EventContext, EventContextProvider, type EventContextProviderProps, type EventSubscriber, type InboundEvent, type Notification$1 as Notification, type NotificationApi, NotificationContextProvider, type NotificationContextProviderProps, type NotificationContextApi as NotificationContextValue, type NotificationHandlerConfig, type NotificationType, type SSEStatus, SUPPORTED_CHAINS, type NotificationData as ShowNotificationParams, type StoredProviderKey, type ThreadContext, ThreadContextProvider, type ThreadControlState, type ThreadMetadata, type UserConfig, UserContextProvider, type UserState, type WalletHandlerApi, type WalletHandlerConfig, type WalletRequestKind, type WalletRequestResult, type WalletRequestStatus, cn, formatAddress, getChainInfo, getNetworkName, initThreadControl, useAomiRuntime, useControl, useCurrentThreadMessages, useCurrentThreadMetadata, useEventContext, useNotification, useNotificationHandler, useThreadContext, useUser, useWalletHandler };
383
+ export { type AomiRuntimeApi, AomiRuntimeProvider, type AomiRuntimeProviderProps, type ChainInfo, type ControlContextApi, ControlContextProvider, type ControlContextProviderProps, type ControlState, type EventContext, EventContextProvider, type EventContextProviderProps, type EventSubscriber, type InboundEvent, type Notification$1 as Notification, type NotificationApi, NotificationContextProvider, type NotificationContextProviderProps, type NotificationContextApi as NotificationContextValue, type NotificationHandlerConfig, type NotificationType, type SSEStatus, SUPPORTED_CHAINS, type NotificationData as ShowNotificationParams, type StoredProviderKey, type ThreadContext, ThreadContextProvider, type ThreadControlState, type ThreadMetadata, type UserConfig, UserContextProvider, type WalletHandlerApi, type WalletHandlerConfig, type WalletRequestKind, type WalletRequestResult, type WalletRequestStatus, cn, formatAddress, getChainInfo, getNetworkName, initThreadControl, useAomiRuntime, useControl, useCurrentThreadMessages, useCurrentThreadMetadata, useEventContext, useNotification, useNotificationHandler, useThreadContext, useUser, useWalletHandler };
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ import { toViemSignTypedDataArgs } from "@aomi-labs/client";
37
37
 
38
38
  // packages/react/src/runtime/aomi-runtime.tsx
39
39
  import { useMemo as useMemo3 } from "react";
40
- import { AomiClient } from "@aomi-labs/client";
40
+ import { AomiClient, UserState as UserState4 } from "@aomi-labs/client";
41
41
 
42
42
  // packages/react/src/contexts/control-context.tsx
43
43
  import {
@@ -880,18 +880,10 @@ import {
880
880
  useRef as useRef4,
881
881
  useState as useState3
882
882
  } from "react";
883
+ import { UserState } from "@aomi-labs/client";
884
+ import { UserState as UserState2 } from "@aomi-labs/client";
883
885
  import { jsx as jsx5 } from "react/jsx-runtime";
884
886
  var UserContext = createContext5(void 0);
885
- function normalizeUserState(next, data) {
886
- if (data.isConnected === false) {
887
- return __spreadProps(__spreadValues({}, next), {
888
- address: void 0,
889
- chainId: void 0,
890
- ensName: void 0
891
- });
892
- }
893
- return next;
894
- }
895
887
  function useUser() {
896
888
  const context = useContext5(UserContext);
897
889
  if (!context) {
@@ -908,10 +900,10 @@ function useUser() {
908
900
  }
909
901
  function UserContextProvider({ children }) {
910
902
  const [user, setUserState] = useState3({
911
- isConnected: false,
912
903
  address: void 0,
913
- chainId: void 0,
914
- ensName: void 0,
904
+ chain_id: void 0,
905
+ is_connected: false,
906
+ ens_name: void 0,
915
907
  ext: void 0
916
908
  });
917
909
  const userRef = useRef4(user);
@@ -921,7 +913,13 @@ function UserContextProvider({ children }) {
921
913
  );
922
914
  const setUser = useCallback4((data) => {
923
915
  setUserState((prev) => {
924
- const next = normalizeUserState(__spreadValues(__spreadValues({}, prev), data), data);
916
+ var _a, _b, _c;
917
+ const normalizedData = (_a = UserState.normalize(data)) != null ? _a : {};
918
+ const next = normalizedData.is_connected === false ? __spreadProps(__spreadValues({}, (_b = UserState.normalize(__spreadValues(__spreadValues({}, prev), normalizedData))) != null ? _b : prev), {
919
+ address: void 0,
920
+ chain_id: void 0,
921
+ ens_name: void 0
922
+ }) : (_c = UserState.normalize(__spreadValues(__spreadValues({}, prev), normalizedData))) != null ? _c : prev;
925
923
  StateChangeCallbacks.current.forEach((callback) => {
926
924
  callback(next);
927
925
  });
@@ -930,12 +928,7 @@ function UserContextProvider({ children }) {
930
928
  }, []);
931
929
  const addExtValue = useCallback4((key, value) => {
932
930
  setUserState((prev) => {
933
- var _a;
934
- const next = __spreadProps(__spreadValues({}, prev), {
935
- ext: __spreadProps(__spreadValues({}, (_a = prev.ext) != null ? _a : {}), {
936
- [key]: value
937
- })
938
- });
931
+ const next = UserState.withExt(prev, key, value);
939
932
  StateChangeCallbacks.current.forEach((callback) => {
940
933
  callback(next);
941
934
  });
@@ -944,10 +937,11 @@ function UserContextProvider({ children }) {
944
937
  }, []);
945
938
  const removeExtValue = useCallback4((key) => {
946
939
  setUserState((prev) => {
947
- if (!prev.ext || !(key in prev.ext)) {
940
+ const ext = prev.ext;
941
+ if (typeof ext !== "object" || ext === null || Array.isArray(ext) || !(key in ext)) {
948
942
  return prev;
949
943
  }
950
- const nextExt = __spreadValues({}, prev.ext);
944
+ const nextExt = __spreadValues({}, ext);
951
945
  delete nextExt[key];
952
946
  const next = __spreadProps(__spreadValues({}, prev), {
953
947
  ext: Object.keys(nextExt).length > 0 ? nextExt : void 0
@@ -990,6 +984,7 @@ import {
990
984
  AssistantRuntimeProvider,
991
985
  useExternalStoreRuntime
992
986
  } from "@assistant-ui/react";
987
+ import { UserState as UserState3 } from "@aomi-labs/client";
993
988
 
994
989
  // packages/react/src/runtime/orchestrator.ts
995
990
  import { useCallback as useCallback5, useEffect as useEffect2, useRef as useRef5, useState as useState4 } from "react";
@@ -1183,16 +1178,13 @@ function useRuntimeOrchestrator(aomiClient, options) {
1183
1178
  })
1184
1179
  );
1185
1180
  cleanups.push(
1186
- session.on("wallet_tx_request", (req) => {
1187
- var _a2;
1188
- return (_a2 = options.onWalletRequest) == null ? void 0 : _a2.call(options, req);
1189
- })
1190
- );
1191
- cleanups.push(
1192
- session.on("wallet_eip712_request", (req) => {
1193
- var _a2;
1194
- return (_a2 = options.onWalletRequest) == null ? void 0 : _a2.call(options, req);
1195
- })
1181
+ session.on(
1182
+ "wallet_requests_changed",
1183
+ (requests) => {
1184
+ var _a2;
1185
+ return (_a2 = options.onPendingRequestsChange) == null ? void 0 : _a2.call(options, requests);
1186
+ }
1187
+ )
1196
1188
  );
1197
1189
  cleanups.push(
1198
1190
  session.on("title_changed", ({ title }) => {
@@ -1218,7 +1210,7 @@ function useRuntimeOrchestrator(aomiClient, options) {
1218
1210
  );
1219
1211
  const ensureInitialState = useCallback5(
1220
1212
  async (threadId) => {
1221
- var _a;
1213
+ var _a, _b;
1222
1214
  if (pendingFetches.current.has(threadId)) return;
1223
1215
  pendingFetches.current.add(threadId);
1224
1216
  try {
@@ -1226,6 +1218,7 @@ function useRuntimeOrchestrator(aomiClient, options) {
1226
1218
  const userState = (_a = options.getUserState) == null ? void 0 : _a.call(options);
1227
1219
  if (userState) session.resolveUserState(userState);
1228
1220
  await session.fetchCurrentState();
1221
+ (_b = options.onPendingRequestsChange) == null ? void 0 : _b.call(options, session.getPendingRequests());
1229
1222
  if (threadContextRef.current.currentThreadId === threadId) {
1230
1223
  setIsRunning(session.getIsProcessing());
1231
1224
  }
@@ -1242,7 +1235,7 @@ function useRuntimeOrchestrator(aomiClient, options) {
1242
1235
  );
1243
1236
  const sendMessage = useCallback5(
1244
1237
  async (text, threadId) => {
1245
- var _a;
1238
+ var _a, _b;
1246
1239
  const session = getSession(threadId);
1247
1240
  const userState = (_a = options.getUserState) == null ? void 0 : _a.call(options);
1248
1241
  if (userState) session.resolveUserState(userState);
@@ -1260,6 +1253,7 @@ function useRuntimeOrchestrator(aomiClient, options) {
1260
1253
  lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1261
1254
  });
1262
1255
  await session.sendAsync(text);
1256
+ (_b = options.onPendingRequestsChange) == null ? void 0 : _b.call(options, session.getPendingRequests());
1263
1257
  },
1264
1258
  [getSession]
1265
1259
  );
@@ -1447,44 +1441,85 @@ function useWalletHandler({
1447
1441
  getSession
1448
1442
  }) {
1449
1443
  const [pendingRequests, setPendingRequests] = useState5([]);
1450
- const requestsRef = useRef6([]);
1451
- const enqueueRequest = useCallback6((request) => {
1452
- requestsRef.current = [...requestsRef.current, request];
1453
- setPendingRequests(requestsRef.current);
1444
+ const requestsRef = useRef6(pendingRequests);
1445
+ const inFlightRequestSetRef = useRef6(/* @__PURE__ */ new Set());
1446
+ const suppressedRequestSetRef = useRef6(/* @__PURE__ */ new Set());
1447
+ const syncVisibleRequests = useCallback6(() => {
1448
+ setPendingRequests(
1449
+ requestsRef.current.filter(
1450
+ (request) => !suppressedRequestSetRef.current.has(request.id)
1451
+ )
1452
+ );
1454
1453
  }, []);
1454
+ const setRequests = useCallback6((requests) => {
1455
+ const incomingIds = new Set(requests.map((request) => request.id));
1456
+ for (const id of suppressedRequestSetRef.current) {
1457
+ if (!incomingIds.has(id) && !inFlightRequestSetRef.current.has(id)) {
1458
+ suppressedRequestSetRef.current.delete(id);
1459
+ }
1460
+ }
1461
+ const preservedInFlight = requestsRef.current.filter(
1462
+ (request) => inFlightRequestSetRef.current.has(request.id) && !incomingIds.has(request.id)
1463
+ );
1464
+ requestsRef.current = [...requests, ...preservedInFlight];
1465
+ syncVisibleRequests();
1466
+ }, [syncVisibleRequests]);
1467
+ const startRequest = useCallback6((id) => {
1468
+ if (!requestsRef.current.some((request) => request.id === id)) {
1469
+ return;
1470
+ }
1471
+ inFlightRequestSetRef.current.add(id);
1472
+ suppressedRequestSetRef.current.add(id);
1473
+ syncVisibleRequests();
1474
+ }, [syncVisibleRequests]);
1455
1475
  const resolveRequest = useCallback6(
1456
- (id, result) => {
1476
+ async (id, result) => {
1457
1477
  const session = getSession();
1458
1478
  if (!session) {
1459
1479
  console.error("[wallet-handler] No session available to resolve request");
1460
1480
  return;
1461
1481
  }
1462
- requestsRef.current = requestsRef.current.filter((r) => r.id !== id);
1463
- setPendingRequests(requestsRef.current);
1464
- void session.resolve(id, result).catch((err) => {
1482
+ startRequest(id);
1483
+ try {
1484
+ await session.resolve(id, result);
1485
+ } catch (err) {
1465
1486
  console.error("[wallet-handler] Failed to resolve request:", err);
1466
- });
1487
+ } finally {
1488
+ requestsRef.current = requestsRef.current.filter(
1489
+ (request) => request.id !== id
1490
+ );
1491
+ inFlightRequestSetRef.current.delete(id);
1492
+ syncVisibleRequests();
1493
+ }
1467
1494
  },
1468
- [getSession]
1495
+ [getSession, startRequest, syncVisibleRequests]
1469
1496
  );
1470
1497
  const rejectRequest = useCallback6(
1471
- (id, error) => {
1498
+ async (id, error) => {
1472
1499
  const session = getSession();
1473
1500
  if (!session) {
1474
1501
  console.error("[wallet-handler] No session available to reject request");
1475
1502
  return;
1476
1503
  }
1477
- requestsRef.current = requestsRef.current.filter((r) => r.id !== id);
1478
- setPendingRequests(requestsRef.current);
1479
- void session.reject(id, error).catch((err) => {
1504
+ startRequest(id);
1505
+ try {
1506
+ await session.reject(id, error);
1507
+ } catch (err) {
1480
1508
  console.error("[wallet-handler] Failed to reject request:", err);
1481
- });
1509
+ } finally {
1510
+ requestsRef.current = requestsRef.current.filter(
1511
+ (request) => request.id !== id
1512
+ );
1513
+ inFlightRequestSetRef.current.delete(id);
1514
+ syncVisibleRequests();
1515
+ }
1482
1516
  },
1483
- [getSession]
1517
+ [getSession, startRequest, syncVisibleRequests]
1484
1518
  );
1485
1519
  return {
1486
1520
  pendingRequests,
1487
- enqueueRequest,
1521
+ setRequests,
1522
+ startRequest,
1488
1523
  resolveRequest,
1489
1524
  rejectRequest
1490
1525
  };
@@ -1518,11 +1553,7 @@ function AomiRuntimeCore({
1518
1553
  cancelGeneration: orchestratorCancel,
1519
1554
  aomiClientRef
1520
1555
  } = useRuntimeOrchestrator(aomiClient, {
1521
- getPublicKey: () => {
1522
- var _a;
1523
- const userState = getUserState();
1524
- return userState.isConnected ? (_a = userState.address) != null ? _a : void 0 : void 0;
1525
- },
1556
+ getPublicKey: () => UserState3.isConnected(getUserState()) ? UserState3.address(getUserState()) : void 0,
1526
1557
  getUserState,
1527
1558
  getApp: getCurrentThreadApp,
1528
1559
  getApiKey: () => getControlState().apiKey,
@@ -1530,17 +1561,20 @@ function AomiRuntimeCore({
1530
1561
  var _a;
1531
1562
  return (_a = getControlState().clientId) != null ? _a : void 0;
1532
1563
  },
1533
- onWalletRequest: (request) => walletHandler.enqueueRequest(request),
1564
+ onPendingRequestsChange: walletHandler.setRequests,
1534
1565
  onEvent: (event) => eventContext.dispatch(event)
1535
1566
  });
1536
1567
  sessionManagerRef.current = sessionManager;
1537
1568
  const walletSnapshot = useCallback7(
1538
- (nextUser) => ({
1539
- address: nextUser.address,
1540
- chainId: nextUser.chainId,
1541
- isConnected: nextUser.isConnected,
1542
- ensName: nextUser.ensName
1543
- }),
1569
+ (nextUser) => {
1570
+ var _a;
1571
+ return {
1572
+ address: UserState3.address(nextUser),
1573
+ chain_id: UserState3.chainId(nextUser),
1574
+ is_connected: (_a = UserState3.isConnected(nextUser)) != null ? _a : false,
1575
+ ens_name: typeof nextUser.ens_name === "string" ? nextUser.ens_name : void 0
1576
+ };
1577
+ },
1544
1578
  [getUserState]
1545
1579
  );
1546
1580
  const lastWalletStateRef = useRef7(walletSnapshot(getUserState()));
@@ -1549,7 +1583,7 @@ function AomiRuntimeCore({
1549
1583
  const unsubscribe = onUserStateChange(async (newUser) => {
1550
1584
  const nextWalletState = walletSnapshot(newUser);
1551
1585
  const prevWalletState = lastWalletStateRef.current;
1552
- if (prevWalletState.address === nextWalletState.address && prevWalletState.chainId === nextWalletState.chainId && prevWalletState.isConnected === nextWalletState.isConnected && prevWalletState.ensName === nextWalletState.ensName) {
1586
+ if (prevWalletState.address === nextWalletState.address && prevWalletState.chain_id === nextWalletState.chain_id && prevWalletState.is_connected === nextWalletState.is_connected && prevWalletState.ens_name === nextWalletState.ens_name) {
1553
1587
  return;
1554
1588
  }
1555
1589
  lastWalletStateRef.current = nextWalletState;
@@ -1570,26 +1604,50 @@ function AomiRuntimeCore({
1570
1604
  ]);
1571
1605
  const threadContextRef = useRef7(threadContext);
1572
1606
  threadContextRef.current = threadContext;
1573
- const currentThreadIdRef = useRef7(threadContext.currentThreadId);
1574
- useEffect3(() => {
1575
- currentThreadIdRef.current = threadContext.currentThreadId;
1576
- }, [threadContext.currentThreadId]);
1607
+ const remoteThreadIdsRef = useRef7(/* @__PURE__ */ new Set());
1608
+ const warmedThreadIdsRef = useRef7(/* @__PURE__ */ new Set());
1609
+ const warmThread = useCallback7(
1610
+ async (threadId) => {
1611
+ if (!remoteThreadIdsRef.current.has(threadId) || warmedThreadIdsRef.current.has(threadId)) {
1612
+ return;
1613
+ }
1614
+ const userState = getUserState();
1615
+ await aomiClientRef.current.createThread(
1616
+ threadId,
1617
+ UserState3.isConnected(userState) ? UserState3.address(userState) : void 0
1618
+ );
1619
+ warmedThreadIdsRef.current.add(threadId);
1620
+ },
1621
+ [aomiClientRef, getUserState]
1622
+ );
1577
1623
  useEffect3(() => {
1578
1624
  const unsubscribe = eventContext.subscribe(
1579
1625
  "user_state_request",
1580
1626
  () => {
1627
+ var _a, _b, _c;
1628
+ const session = (_b = (_a = sessionManagerRef.current) == null ? void 0 : _a.get(threadContext.currentThreadId)) != null ? _b : getSession(threadContext.currentThreadId);
1581
1629
  eventContext.sendOutboundSystem({
1582
1630
  type: "user_state_response",
1583
1631
  sessionId: threadContext.currentThreadId,
1584
- payload: getUserState()
1632
+ payload: (_c = session.getUserState()) != null ? _c : getUserState()
1585
1633
  });
1586
1634
  }
1587
1635
  );
1588
1636
  return unsubscribe;
1589
- }, [eventContext, threadContext.currentThreadId, getUserState]);
1637
+ }, [eventContext, threadContext.currentThreadId, getSession, getUserState]);
1590
1638
  useEffect3(() => {
1591
- void ensureInitialState(threadContext.currentThreadId);
1592
- }, [ensureInitialState, threadContext.currentThreadId]);
1639
+ const threadId = threadContext.currentThreadId;
1640
+ let cancelled = false;
1641
+ void (async () => {
1642
+ await warmThread(threadId);
1643
+ if (!cancelled) {
1644
+ await ensureInitialState(threadId);
1645
+ }
1646
+ })();
1647
+ return () => {
1648
+ cancelled = true;
1649
+ };
1650
+ }, [ensureInitialState, threadContext.currentThreadId, warmThread]);
1593
1651
  useEffect3(() => {
1594
1652
  const threadId = threadContext.currentThreadId;
1595
1653
  const currentMeta = threadContext.getThreadMetadata(threadId);
@@ -1605,16 +1663,22 @@ function AomiRuntimeCore({
1605
1663
  threadContext.currentThreadId
1606
1664
  );
1607
1665
  useEffect3(() => {
1608
- const userAddress = user.isConnected ? user.address : void 0;
1609
- if (!userAddress) return;
1666
+ const userAddress = UserState3.isConnected(user) ? UserState3.address(user) : void 0;
1667
+ if (!userAddress) {
1668
+ remoteThreadIdsRef.current.clear();
1669
+ warmedThreadIdsRef.current.clear();
1670
+ return;
1671
+ }
1610
1672
  const fetchThreadList = async () => {
1611
1673
  var _a, _b, _c;
1612
1674
  try {
1613
1675
  const threadList = await aomiClientRef.current.listThreads(userAddress);
1614
1676
  const currentContext = threadContextRef.current;
1677
+ const remoteThreadIds = /* @__PURE__ */ new Set();
1615
1678
  const newMetadata = new Map(currentContext.allThreadsMetadata);
1616
1679
  let maxChatNum = currentContext.threadCnt;
1617
1680
  for (const thread of threadList) {
1681
+ remoteThreadIds.add(thread.session_id);
1618
1682
  const rawTitle = (_a = thread.title) != null ? _a : "";
1619
1683
  const title = isPlaceholderTitle(rawTitle) ? "" : rawTitle;
1620
1684
  const lastActive = ((_b = newMetadata.get(thread.session_id)) == null ? void 0 : _b.lastActiveAt) || (/* @__PURE__ */ new Date()).toISOString();
@@ -1633,16 +1697,26 @@ function AomiRuntimeCore({
1633
1697
  }
1634
1698
  }
1635
1699
  }
1700
+ remoteThreadIdsRef.current = remoteThreadIds;
1701
+ warmedThreadIdsRef.current = new Set(
1702
+ Array.from(warmedThreadIdsRef.current).filter(
1703
+ (threadId) => remoteThreadIds.has(threadId)
1704
+ )
1705
+ );
1636
1706
  currentContext.setThreadMetadata(newMetadata);
1637
1707
  if (maxChatNum > currentContext.threadCnt) {
1638
1708
  currentContext.setThreadCnt(maxChatNum);
1639
1709
  }
1710
+ if (remoteThreadIds.has(currentContext.currentThreadId)) {
1711
+ await warmThread(currentContext.currentThreadId);
1712
+ await ensureInitialState(currentContext.currentThreadId);
1713
+ }
1640
1714
  } catch (error) {
1641
1715
  console.error("Failed to fetch thread list:", error);
1642
1716
  }
1643
1717
  };
1644
1718
  void fetchThreadList();
1645
- }, [user.address, user.isConnected, aomiClientRef]);
1719
+ }, [user, aomiClientRef, ensureInitialState, warmThread]);
1646
1720
  const threadListAdapter = useMemo2(
1647
1721
  () => buildThreadListAdapter({
1648
1722
  aomiClientRef,
@@ -1791,9 +1865,7 @@ function AomiRuntimeCore({
1791
1865
  clearAllNotifications: notificationContext.clearAll,
1792
1866
  // Wallet API
1793
1867
  pendingWalletRequests: walletHandler.pendingRequests,
1794
- startWalletRequest: () => {
1795
- },
1796
- // No-op: ClientSession manages processing state
1868
+ startWalletRequest: walletHandler.startRequest,
1797
1869
  resolveWalletRequest: walletHandler.resolveRequest,
1798
1870
  rejectWalletRequest: walletHandler.rejectRequest,
1799
1871
  // Event API
@@ -1845,7 +1917,7 @@ function AomiRuntimeInner({
1845
1917
  {
1846
1918
  aomiClient,
1847
1919
  sessionId: threadContext.currentThreadId,
1848
- publicKey: user.isConnected ? (_a = user.address) != null ? _a : void 0 : void 0,
1920
+ publicKey: UserState4.isConnected(user) ? (_a = UserState4.address(user)) != null ? _a : void 0 : void 0,
1849
1921
  getThreadMetadata: threadContext.getThreadMetadata,
1850
1922
  updateThreadMetadata: threadContext.updateThreadMetadata,
1851
1923
  children: /* @__PURE__ */ jsx7(