@assistant-ui/react-google-adk 0.0.27 → 0.0.28
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/useAdkMessages.d.ts.map +1 -1
- package/dist/useAdkMessages.js +10 -5
- package/dist/useAdkMessages.js.map +1 -1
- package/dist/useAdkRuntime.d.ts.map +1 -1
- package/dist/useAdkRuntime.js +23 -7
- package/dist/useAdkRuntime.js.map +1 -1
- package/package.json +6 -6
- package/src/useAdkMessages.ts +19 -5
- package/src/useAdkRuntime.toolOwnership.test.tsx +236 -0
- package/src/useAdkRuntime.ts +51 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAdkMessages.d.ts","names":[],"sources":["../src/useAdkMessages.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"useAdkMessages.d.ts","names":[],"sources":["../src/useAdkMessages.ts"],"mappings":";;KA2BY;EACV,QAAQ;EACR;IACE,UAAU;IACV,gBAAgB;IAChB,kBAAkB;;;cAcT,mBAAkB,QAAA,iBAG5B;;;;IAIQ;IACE;;;;;;;;EAkFW,cAAA,aAAA,cAAY,QAAU,yBAAoB;;EAnDhB,cAAA,MAAA;EA+BvC,kBAAA,MAAA;EAnBI,gBAAA,UAAA"}
|
package/dist/useAdkMessages.js
CHANGED
|
@@ -3,7 +3,7 @@ import { AdkEventAccumulator } from "./AdkEventAccumulator.js";
|
|
|
3
3
|
import { generateId } from "@assistant-ui/core";
|
|
4
4
|
import { invokeUserCallback } from "@assistant-ui/core/internal";
|
|
5
5
|
import { useAui } from "@assistant-ui/store";
|
|
6
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
6
|
+
import { useCallback, useEffect, useInsertionEffect, useMemo, useRef, useState } from "react";
|
|
7
7
|
//#region src/useAdkMessages.ts
|
|
8
8
|
const invokeAdkRuntimeCallback = (name, callback, ...args) => {
|
|
9
9
|
invokeUserCallback("react-google-adk", name, callback, ...args);
|
|
@@ -20,13 +20,18 @@ const useAdkMessages = ({ stream, eventHandlers }) => {
|
|
|
20
20
|
const [messageMetadata, setMessageMetadata] = useState(/* @__PURE__ */ new Map());
|
|
21
21
|
const lastTransferToAgentRef = useRef(void 0);
|
|
22
22
|
const messagesRef = useRef(messages);
|
|
23
|
-
messagesRef.current = messages;
|
|
24
23
|
const stateDeltaRef = useRef(stateDelta);
|
|
25
|
-
|
|
24
|
+
useInsertionEffect(() => {
|
|
25
|
+
stateDeltaRef.current = stateDelta;
|
|
26
|
+
}, [stateDelta]);
|
|
26
27
|
const artifactDeltaRef = useRef(artifactDelta);
|
|
27
|
-
|
|
28
|
+
useInsertionEffect(() => {
|
|
29
|
+
artifactDeltaRef.current = artifactDelta;
|
|
30
|
+
}, [artifactDelta]);
|
|
28
31
|
const messageMetadataRef = useRef(messageMetadata);
|
|
29
|
-
|
|
32
|
+
useInsertionEffect(() => {
|
|
33
|
+
messageMetadataRef.current = messageMetadata;
|
|
34
|
+
}, [messageMetadata]);
|
|
30
35
|
const setMessagesImmediate = useCallback((msgs) => {
|
|
31
36
|
messagesRef.current = msgs;
|
|
32
37
|
_setMessages(msgs);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAdkMessages.js","names":[],"sources":["../src/useAdkMessages.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { generateId } from \"@assistant-ui/core\";\nimport { useAui } from \"@assistant-ui/store\";\nimport { invokeUserCallback } from \"@assistant-ui/core/internal\";\nimport { AdkEventAccumulator } from \"./AdkEventAccumulator\";\nimport { contentToParts } from \"./contentToParts\";\nimport type {\n AdkEvent,\n AdkMessage,\n AdkMessageMetadata,\n AdkSendMessageConfig,\n AdkStreamCallback,\n AdkToolConfirmation,\n AdkAuthRequest,\n AdkThreadSnapshot,\n OnAdkErrorCallback,\n OnAdkCustomEventCallback,\n OnAdkAgentTransferCallback,\n} from \"./types\";\n\nexport type UseAdkMessagesOptions = {\n stream: AdkStreamCallback;\n eventHandlers?: {\n onError?: OnAdkErrorCallback;\n onCustomEvent?: OnAdkCustomEventCallback;\n onAgentTransfer?: OnAdkAgentTransferCallback;\n };\n};\n\ntype AdkRuntimeCallbackName = \"onError\" | \"onCustomEvent\" | \"onAgentTransfer\";\n\nconst invokeAdkRuntimeCallback = <TArgs extends readonly unknown[]>(\n name: AdkRuntimeCallbackName,\n callback: ((...args: TArgs) => unknown) | undefined,\n ...args: TArgs\n): void => {\n void invokeUserCallback(\"react-google-adk\", name, callback, ...args);\n};\n\nexport const useAdkMessages = ({\n stream,\n eventHandlers,\n}: UseAdkMessagesOptions) => {\n const [messages, _setMessages] = useState<AdkMessage[]>([]);\n const [stateDelta, setStateDelta] = useState<Record<string, unknown>>({});\n const [agentInfo, setAgentInfo] = useState<{\n name?: string | undefined;\n branch?: string | undefined;\n }>({});\n const [longRunningToolIds, setLongRunningToolIds] = useState<string[]>([]);\n const [artifactDelta, setArtifactDelta] = useState<Record<string, number>>(\n {},\n );\n const [toolConfirmations, setToolConfirmations] = useState<\n AdkToolConfirmation[]\n >([]);\n const [authRequests, setAuthRequests] = useState<AdkAuthRequest[]>([]);\n const [escalated, setEscalated] = useState(false);\n const [messageMetadata, setMessageMetadata] = useState<\n Map<string, AdkMessageMetadata>\n >(new Map());\n const lastTransferToAgentRef = useRef<string | undefined>(undefined);\n const messagesRef = useRef(messages);\n messagesRef.current = messages;\n const stateDeltaRef = useRef(stateDelta);\n stateDeltaRef.current = stateDelta;\n const artifactDeltaRef = useRef(artifactDelta);\n artifactDeltaRef.current = artifactDelta;\n const messageMetadataRef = useRef(messageMetadata);\n messageMetadataRef.current = messageMetadata;\n\n const setMessagesImmediate = useCallback((msgs: AdkMessage[]) => {\n messagesRef.current = msgs;\n _setMessages(msgs);\n }, []);\n\n /**\n * Swap the thread over to a loaded snapshot in one commit. Unlike\n * {@link replaceMessages} this never passes through a cleared state, so a\n * refetch that lands while a confirmation is on screen replaces it rather\n * than blanking it first.\n */\n const applySnapshot = useCallback(\n (snapshot: AdkThreadSnapshot) => {\n setMessagesImmediate(snapshot.messages);\n setLongRunningToolIds(snapshot.longRunningToolIds ?? []);\n setToolConfirmations(snapshot.toolConfirmations ?? []);\n setAuthRequests(snapshot.authRequests ?? []);\n setEscalated(snapshot.escalated ?? false);\n setMessageMetadata(snapshot.messageMetadata ?? new Map());\n setStateDelta(snapshot.stateDelta ?? {});\n setArtifactDelta(snapshot.artifactDelta ?? {});\n setAgentInfo(snapshot.agentInfo ?? {});\n },\n [setMessagesImmediate],\n );\n\n // Replace the message list AND reset derived per-turn HITL state.\n // Used by truncation paths (edit, reload) so that stale interrupt\n // markers and per-message metadata from the removed messages don't leak\n // into the next turn.\n const replaceMessages = useCallback(\n (msgs: AdkMessage[]) => {\n setMessagesImmediate(msgs);\n setLongRunningToolIds([]);\n setToolConfirmations([]);\n setAuthRequests([]);\n setEscalated(false);\n setMessageMetadata(new Map());\n },\n [setMessagesImmediate],\n );\n\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const { onError, onCustomEvent, onAgentTransfer } = useMemo(\n () => eventHandlers ?? {},\n [eventHandlers],\n );\n\n const aui = useAui();\n const sendMessage = useCallback(\n async (newMessages: AdkMessage[], config: AdkSendMessageConfig) => {\n const newMessagesWithId = newMessages.map((m) =>\n m.id ? m : { ...m, id: generateId() },\n ) as AdkMessage[];\n\n // A staged message is already in the thread under its own id, and the\n // merged event below re-emits the whole batch under the first one. Seeding\n // with the originals would leave every later staged id beside the merged\n // copy of itself.\n const resentIds = new Set(newMessagesWithId.map((m) => m.id));\n const accumulator = new AdkEventAccumulator(\n messagesRef.current.filter((m) => !resentIds.has(m.id)),\n );\n for (const event of messagesToEvents(newMessagesWithId)) {\n accumulator.processEvent(event);\n }\n setMessagesImmediate(accumulator.getMessages());\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n try {\n const response = await stream(newMessagesWithId, {\n ...config,\n abortSignal: abortController.signal,\n initialize: async () => {\n return await aui.threadListItem.initialize();\n },\n });\n\n for await (const event of response) {\n const updatedMessages = accumulator.processEvent(event);\n setMessagesImmediate(updatedMessages);\n setStateDelta({\n ...stateDeltaRef.current,\n ...accumulator.getStateDelta(),\n });\n setAgentInfo(accumulator.getAgentInfo());\n setLongRunningToolIds(accumulator.getLongRunningToolIds());\n setArtifactDelta({\n ...artifactDeltaRef.current,\n ...accumulator.getArtifactDelta(),\n });\n setToolConfirmations(accumulator.getToolConfirmations());\n setAuthRequests(accumulator.getAuthRequests());\n setEscalated(accumulator.isEscalated());\n {\n const newMeta = accumulator.getMessageMetadata();\n if (newMeta.size > 0) {\n setMessageMetadata(\n new Map([...messageMetadataRef.current, ...newMeta]),\n );\n }\n }\n\n const transfer = accumulator.getLastTransferToAgent();\n if (transfer && transfer !== lastTransferToAgentRef.current) {\n lastTransferToAgentRef.current = transfer;\n invokeAdkRuntimeCallback(\n \"onAgentTransfer\",\n onAgentTransfer,\n transfer,\n );\n }\n\n // Fire custom event callback for events with customMetadata\n if (event.customMetadata && onCustomEvent) {\n for (const [key, value] of Object.entries(event.customMetadata)) {\n invokeAdkRuntimeCallback(\n \"onCustomEvent\",\n onCustomEvent,\n key,\n value,\n );\n }\n }\n\n if (event.errorCode || event.errorMessage) {\n invokeAdkRuntimeCallback(\n \"onError\",\n onError,\n event.errorMessage ?? event.errorCode,\n );\n }\n }\n } catch (error) {\n if (\n !abortController.signal.aborted &&\n !(error instanceof Error && error.name === \"AbortError\")\n ) {\n throw error;\n }\n } finally {\n if (abortControllerRef.current === abortController) {\n abortControllerRef.current = null;\n }\n }\n },\n [\n aui,\n setMessagesImmediate,\n stream,\n onError,\n onCustomEvent,\n onAgentTransfer,\n ],\n );\n\n const cancel = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n }, []);\n\n useEffect(() => cancel, [cancel]);\n\n return {\n messages,\n stateDelta,\n agentInfo,\n longRunningToolIds,\n artifactDelta,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n sendMessage,\n cancel,\n setMessages: setMessagesImmediate,\n replaceMessages,\n applySnapshot,\n };\n};\n\n/**\n * Transport sends every human and tool message of one `send` call as a single\n * ADK `Content`, and ADK parses that event's function responses before running\n * any tool, so the batch runs whole or not at all. The optimistic projection\n * has to sit on the same boundary, so a run of those messages becomes one\n * synthetic event whose parts come from the same per-message conversion.\n *\n * The transport drops `ai` messages from that `Content`, so one interleaved\n * between two replies does not split the batch on the wire and must not split\n * it here either. It still becomes its own event, placed after the merged one,\n * so the optimistic projection keeps the assistant turn.\n *\n * @internal — exported for unit tests.\n */\nexport const messagesToEvents = (messages: AdkMessage[]): AdkEvent[] => {\n // A reload sends no messages at all, and the empty user content the transport\n // puts on the wire for it is not part of the optimistic view: projecting one\n // would put an empty user bubble above every regenerated turn.\n if (messages.length === 0) return [];\n\n const events: AdkEvent[] = [];\n const run: AdkMessage[] = [];\n let runIndex = 0;\n\n for (const msg of messages) {\n if (msg.type === \"ai\") {\n events.push(messageToEvent(msg));\n } else {\n if (run.length === 0) runIndex = events.length;\n run.push(msg);\n }\n }\n\n const parts = run.flatMap((m) => messageToEvent(m).content?.parts ?? []);\n const human = run.find((m) => m.type === \"human\");\n\n // A batch that contributes no part still reaches the wire: the transport\n // sends an empty user `Content`, which a reload replays as an empty human\n // message. Emitting it here keeps the optimistic view equal to that replay.\n if (parts.length === 0) parts.push({ text: \"\" });\n\n const event: AdkEvent = { id: (human ?? run[0])?.id ?? generateId() };\n if (human || run.length === 0) event.author = \"user\";\n event.content = { role: \"user\", parts };\n events.splice(run.length > 0 ? runIndex : events.length, 0, event);\n\n return events;\n};\n\n/** @internal — exported for unit tests. */\nexport const messageToEvent = (msg: AdkMessage): AdkEvent => {\n if (msg.type === \"human\") {\n return {\n id: msg.id ?? generateId(),\n author: \"user\",\n content: { role: \"user\", parts: contentToParts(msg.content) },\n };\n }\n\n if (msg.type === \"tool\") {\n let response: unknown;\n try {\n response = JSON.parse(msg.content);\n } catch {\n response = msg.content;\n }\n return {\n id: msg.id ?? generateId(),\n content: {\n role: \"user\",\n parts: [\n {\n functionResponse: {\n name: msg.name,\n id: msg.tool_call_id,\n response,\n },\n },\n ],\n },\n };\n }\n\n const result: AdkEvent = { id: msg.id ?? generateId() };\n if (msg.author != null) result.author = msg.author;\n result.content = {\n role: \"model\",\n parts: [\n ...contentToParts(msg.content),\n ...(msg.tool_calls?.map((tc) => ({\n functionCall: { name: tc.name, id: tc.id, args: { ...tc.args } },\n })) ?? []),\n ],\n };\n return result;\n};\n"],"mappings":";;;;;;;AA+BA,MAAM,4BACJ,MACA,UACA,GAAG,SACM;CACT,mBAAwB,oBAAoB,MAAM,UAAU,GAAG,IAAI;AACrE;AAEA,MAAa,kBAAkB,EAC7B,QACA,oBAC2B;CAC3B,MAAM,CAAC,UAAU,gBAAgB,SAAuB,CAAC,CAAC;CAC1D,MAAM,CAAC,YAAY,iBAAiB,SAAkC,CAAC,CAAC;CACxE,MAAM,CAAC,WAAW,gBAAgB,SAG/B,CAAC,CAAC;CACL,MAAM,CAAC,oBAAoB,yBAAyB,SAAmB,CAAC,CAAC;CACzE,MAAM,CAAC,eAAe,oBAAoB,SACxC,CAAC,CACH;CACA,MAAM,CAAC,mBAAmB,wBAAwB,SAEhD,CAAC,CAAC;CACJ,MAAM,CAAC,cAAc,mBAAmB,SAA2B,CAAC,CAAC;CACrE,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAChD,MAAM,CAAC,iBAAiB,sBAAsB,yBAE5C,IAAI,IAAI,CAAC;CACX,MAAM,yBAAyB,OAA2B,KAAA,CAAS;CACnE,MAAM,cAAc,OAAO,QAAQ;CACnC,YAAY,UAAU;CACtB,MAAM,gBAAgB,OAAO,UAAU;CACvC,cAAc,UAAU;CACxB,MAAM,mBAAmB,OAAO,aAAa;CAC7C,iBAAiB,UAAU;CAC3B,MAAM,qBAAqB,OAAO,eAAe;CACjD,mBAAmB,UAAU;CAE7B,MAAM,uBAAuB,aAAa,SAAuB;EAC/D,YAAY,UAAU;EAC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AI,OAAO;EAAE;CAC9D;CAGF,IAAI,IAAI,SAAS,QAAQ;EACvB,IAAI;EACJ,IAAI;GACF,WAAW,KAAK,MAAM,IAAI,OAAO;EACnC,QAAQ;GACN,WAAW,IAAI;EACjB;EACA,OAAO;GACL,IAAI,IAAI,MAAM,WAAW;GACzB,SAAS;IACP,MAAM;IACN,OAAO,CACL,EACE,kBAAkB;KAChB,MAAM,IAAI;KACV,IAAI,IAAI;KACR;IACF,EACF,CACF;GACF;EACF;CACF;CAEA,MAAM,SAAmB,EAAE,IAAI,IAAI,MAAM,WAAW,EAAE;CACtD,IAAI,IAAI,UAAU,MAAM,OAAO,SAAS,IAAI;CAC5C,OAAO,UAAU;EACf,MAAM;EACN,OAAO,CACL,GAAG,eAAe,IAAI,OAAO,GAC7B,GAAI,IAAI,YAAY,KAAK,QAAQ,EAC/B,cAAc;GAAE,MAAM,GAAG;GAAM,IAAI,GAAG;GAAI,MAAM,EAAE,GAAG,GAAG,KAAK;EAAE,EACjE,EAAE,KAAK,CAAC,CACV;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"useAdkMessages.js","names":[],"sources":["../src/useAdkMessages.ts"],"sourcesContent":["import {\n useState,\n useCallback,\n useEffect,\n useInsertionEffect,\n useRef,\n useMemo,\n} from \"react\";\nimport { generateId } from \"@assistant-ui/core\";\nimport { useAui } from \"@assistant-ui/store\";\nimport { invokeUserCallback } from \"@assistant-ui/core/internal\";\nimport { AdkEventAccumulator } from \"./AdkEventAccumulator\";\nimport { contentToParts } from \"./contentToParts\";\nimport type {\n AdkEvent,\n AdkMessage,\n AdkMessageMetadata,\n AdkSendMessageConfig,\n AdkStreamCallback,\n AdkToolConfirmation,\n AdkAuthRequest,\n AdkThreadSnapshot,\n OnAdkErrorCallback,\n OnAdkCustomEventCallback,\n OnAdkAgentTransferCallback,\n} from \"./types\";\n\nexport type UseAdkMessagesOptions = {\n stream: AdkStreamCallback;\n eventHandlers?: {\n onError?: OnAdkErrorCallback;\n onCustomEvent?: OnAdkCustomEventCallback;\n onAgentTransfer?: OnAdkAgentTransferCallback;\n };\n};\n\ntype AdkRuntimeCallbackName = \"onError\" | \"onCustomEvent\" | \"onAgentTransfer\";\n\nconst invokeAdkRuntimeCallback = <TArgs extends readonly unknown[]>(\n name: AdkRuntimeCallbackName,\n callback: ((...args: TArgs) => unknown) | undefined,\n ...args: TArgs\n): void => {\n void invokeUserCallback(\"react-google-adk\", name, callback, ...args);\n};\n\nexport const useAdkMessages = ({\n stream,\n eventHandlers,\n}: UseAdkMessagesOptions) => {\n const [messages, _setMessages] = useState<AdkMessage[]>([]);\n const [stateDelta, setStateDelta] = useState<Record<string, unknown>>({});\n const [agentInfo, setAgentInfo] = useState<{\n name?: string | undefined;\n branch?: string | undefined;\n }>({});\n const [longRunningToolIds, setLongRunningToolIds] = useState<string[]>([]);\n const [artifactDelta, setArtifactDelta] = useState<Record<string, number>>(\n {},\n );\n const [toolConfirmations, setToolConfirmations] = useState<\n AdkToolConfirmation[]\n >([]);\n const [authRequests, setAuthRequests] = useState<AdkAuthRequest[]>([]);\n const [escalated, setEscalated] = useState(false);\n const [messageMetadata, setMessageMetadata] = useState<\n Map<string, AdkMessageMetadata>\n >(new Map());\n const lastTransferToAgentRef = useRef<string | undefined>(undefined);\n // setMessagesImmediate is the only writer of the messages state and publishes\n // this ref with it, so the ref never trails a commit.\n const messagesRef = useRef(messages);\n const stateDeltaRef = useRef(stateDelta);\n useInsertionEffect(() => {\n stateDeltaRef.current = stateDelta;\n }, [stateDelta]);\n const artifactDeltaRef = useRef(artifactDelta);\n useInsertionEffect(() => {\n artifactDeltaRef.current = artifactDelta;\n }, [artifactDelta]);\n const messageMetadataRef = useRef(messageMetadata);\n useInsertionEffect(() => {\n messageMetadataRef.current = messageMetadata;\n }, [messageMetadata]);\n\n const setMessagesImmediate = useCallback((msgs: AdkMessage[]) => {\n messagesRef.current = msgs;\n _setMessages(msgs);\n }, []);\n\n /**\n * Swap the thread over to a loaded snapshot in one commit. Unlike\n * {@link replaceMessages} this never passes through a cleared state, so a\n * refetch that lands while a confirmation is on screen replaces it rather\n * than blanking it first.\n */\n const applySnapshot = useCallback(\n (snapshot: AdkThreadSnapshot) => {\n setMessagesImmediate(snapshot.messages);\n setLongRunningToolIds(snapshot.longRunningToolIds ?? []);\n setToolConfirmations(snapshot.toolConfirmations ?? []);\n setAuthRequests(snapshot.authRequests ?? []);\n setEscalated(snapshot.escalated ?? false);\n setMessageMetadata(snapshot.messageMetadata ?? new Map());\n setStateDelta(snapshot.stateDelta ?? {});\n setArtifactDelta(snapshot.artifactDelta ?? {});\n setAgentInfo(snapshot.agentInfo ?? {});\n },\n [setMessagesImmediate],\n );\n\n // Replace the message list AND reset derived per-turn HITL state.\n // Used by truncation paths (edit, reload) so that stale interrupt\n // markers and per-message metadata from the removed messages don't leak\n // into the next turn.\n const replaceMessages = useCallback(\n (msgs: AdkMessage[]) => {\n setMessagesImmediate(msgs);\n setLongRunningToolIds([]);\n setToolConfirmations([]);\n setAuthRequests([]);\n setEscalated(false);\n setMessageMetadata(new Map());\n },\n [setMessagesImmediate],\n );\n\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const { onError, onCustomEvent, onAgentTransfer } = useMemo(\n () => eventHandlers ?? {},\n [eventHandlers],\n );\n\n const aui = useAui();\n const sendMessage = useCallback(\n async (newMessages: AdkMessage[], config: AdkSendMessageConfig) => {\n const newMessagesWithId = newMessages.map((m) =>\n m.id ? m : { ...m, id: generateId() },\n ) as AdkMessage[];\n\n // A staged message is already in the thread under its own id, and the\n // merged event below re-emits the whole batch under the first one. Seeding\n // with the originals would leave every later staged id beside the merged\n // copy of itself.\n const resentIds = new Set(newMessagesWithId.map((m) => m.id));\n const accumulator = new AdkEventAccumulator(\n messagesRef.current.filter((m) => !resentIds.has(m.id)),\n );\n for (const event of messagesToEvents(newMessagesWithId)) {\n accumulator.processEvent(event);\n }\n setMessagesImmediate(accumulator.getMessages());\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n try {\n const response = await stream(newMessagesWithId, {\n ...config,\n abortSignal: abortController.signal,\n initialize: async () => {\n return await aui.threadListItem.initialize();\n },\n });\n\n for await (const event of response) {\n const updatedMessages = accumulator.processEvent(event);\n setMessagesImmediate(updatedMessages);\n setStateDelta({\n ...stateDeltaRef.current,\n ...accumulator.getStateDelta(),\n });\n setAgentInfo(accumulator.getAgentInfo());\n setLongRunningToolIds(accumulator.getLongRunningToolIds());\n setArtifactDelta({\n ...artifactDeltaRef.current,\n ...accumulator.getArtifactDelta(),\n });\n setToolConfirmations(accumulator.getToolConfirmations());\n setAuthRequests(accumulator.getAuthRequests());\n setEscalated(accumulator.isEscalated());\n {\n const newMeta = accumulator.getMessageMetadata();\n if (newMeta.size > 0) {\n setMessageMetadata(\n new Map([...messageMetadataRef.current, ...newMeta]),\n );\n }\n }\n\n const transfer = accumulator.getLastTransferToAgent();\n if (transfer && transfer !== lastTransferToAgentRef.current) {\n lastTransferToAgentRef.current = transfer;\n invokeAdkRuntimeCallback(\n \"onAgentTransfer\",\n onAgentTransfer,\n transfer,\n );\n }\n\n // Fire custom event callback for events with customMetadata\n if (event.customMetadata && onCustomEvent) {\n for (const [key, value] of Object.entries(event.customMetadata)) {\n invokeAdkRuntimeCallback(\n \"onCustomEvent\",\n onCustomEvent,\n key,\n value,\n );\n }\n }\n\n if (event.errorCode || event.errorMessage) {\n invokeAdkRuntimeCallback(\n \"onError\",\n onError,\n event.errorMessage ?? event.errorCode,\n );\n }\n }\n } catch (error) {\n if (\n !abortController.signal.aborted &&\n !(error instanceof Error && error.name === \"AbortError\")\n ) {\n throw error;\n }\n } finally {\n if (abortControllerRef.current === abortController) {\n abortControllerRef.current = null;\n }\n }\n },\n [\n aui,\n setMessagesImmediate,\n stream,\n onError,\n onCustomEvent,\n onAgentTransfer,\n ],\n );\n\n const cancel = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n }, []);\n\n useEffect(() => cancel, [cancel]);\n\n return {\n messages,\n stateDelta,\n agentInfo,\n longRunningToolIds,\n artifactDelta,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n sendMessage,\n cancel,\n setMessages: setMessagesImmediate,\n replaceMessages,\n applySnapshot,\n };\n};\n\n/**\n * Transport sends every human and tool message of one `send` call as a single\n * ADK `Content`, and ADK parses that event's function responses before running\n * any tool, so the batch runs whole or not at all. The optimistic projection\n * has to sit on the same boundary, so a run of those messages becomes one\n * synthetic event whose parts come from the same per-message conversion.\n *\n * The transport drops `ai` messages from that `Content`, so one interleaved\n * between two replies does not split the batch on the wire and must not split\n * it here either. It still becomes its own event, placed after the merged one,\n * so the optimistic projection keeps the assistant turn.\n *\n * @internal — exported for unit tests.\n */\nexport const messagesToEvents = (messages: AdkMessage[]): AdkEvent[] => {\n // A reload sends no messages at all, and the empty user content the transport\n // puts on the wire for it is not part of the optimistic view: projecting one\n // would put an empty user bubble above every regenerated turn.\n if (messages.length === 0) return [];\n\n const events: AdkEvent[] = [];\n const run: AdkMessage[] = [];\n let runIndex = 0;\n\n for (const msg of messages) {\n if (msg.type === \"ai\") {\n events.push(messageToEvent(msg));\n } else {\n if (run.length === 0) runIndex = events.length;\n run.push(msg);\n }\n }\n\n const parts = run.flatMap((m) => messageToEvent(m).content?.parts ?? []);\n const human = run.find((m) => m.type === \"human\");\n\n // A batch that contributes no part still reaches the wire: the transport\n // sends an empty user `Content`, which a reload replays as an empty human\n // message. Emitting it here keeps the optimistic view equal to that replay.\n if (parts.length === 0) parts.push({ text: \"\" });\n\n const event: AdkEvent = { id: (human ?? run[0])?.id ?? generateId() };\n if (human || run.length === 0) event.author = \"user\";\n event.content = { role: \"user\", parts };\n events.splice(run.length > 0 ? runIndex : events.length, 0, event);\n\n return events;\n};\n\n/** @internal — exported for unit tests. */\nexport const messageToEvent = (msg: AdkMessage): AdkEvent => {\n if (msg.type === \"human\") {\n return {\n id: msg.id ?? generateId(),\n author: \"user\",\n content: { role: \"user\", parts: contentToParts(msg.content) },\n };\n }\n\n if (msg.type === \"tool\") {\n let response: unknown;\n try {\n response = JSON.parse(msg.content);\n } catch {\n response = msg.content;\n }\n return {\n id: msg.id ?? generateId(),\n content: {\n role: \"user\",\n parts: [\n {\n functionResponse: {\n name: msg.name,\n id: msg.tool_call_id,\n response,\n },\n },\n ],\n },\n };\n }\n\n const result: AdkEvent = { id: msg.id ?? generateId() };\n if (msg.author != null) result.author = msg.author;\n result.content = {\n role: \"model\",\n parts: [\n ...contentToParts(msg.content),\n ...(msg.tool_calls?.map((tc) => ({\n functionCall: { name: tc.name, id: tc.id, args: { ...tc.args } },\n })) ?? []),\n ],\n };\n return result;\n};\n"],"mappings":";;;;;;;AAsCA,MAAM,4BACJ,MACA,UACA,GAAG,SACM;CACT,mBAAwB,oBAAoB,MAAM,UAAU,GAAG,IAAI;AACrE;AAEA,MAAa,kBAAkB,EAC7B,QACA,oBAC2B;CAC3B,MAAM,CAAC,UAAU,gBAAgB,SAAuB,CAAC,CAAC;CAC1D,MAAM,CAAC,YAAY,iBAAiB,SAAkC,CAAC,CAAC;CACxE,MAAM,CAAC,WAAW,gBAAgB,SAG/B,CAAC,CAAC;CACL,MAAM,CAAC,oBAAoB,yBAAyB,SAAmB,CAAC,CAAC;CACzE,MAAM,CAAC,eAAe,oBAAoB,SACxC,CAAC,CACH;CACA,MAAM,CAAC,mBAAmB,wBAAwB,SAEhD,CAAC,CAAC;CACJ,MAAM,CAAC,cAAc,mBAAmB,SAA2B,CAAC,CAAC;CACrE,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAChD,MAAM,CAAC,iBAAiB,sBAAsB,yBAE5C,IAAI,IAAI,CAAC;CACX,MAAM,yBAAyB,OAA2B,KAAA,CAAS;CAGnE,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,gBAAgB,OAAO,UAAU;CACvC,yBAAyB;EACvB,cAAc,UAAU;CAC1B,GAAG,CAAC,UAAU,CAAC;CACf,MAAM,mBAAmB,OAAO,aAAa;CAC7C,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I,SAAS,IAAI,WAAW,OAAO,QAAQ,GAAG,KAAK;CAEjE,OAAO;AACT;;AAGA,MAAa,kBAAkB,QAA8B;CAC3D,IAAI,IAAI,SAAS,SACf,OAAO;EACL,IAAI,IAAI,MAAM,WAAW;EACzB,QAAQ;EACR,SAAS;GAAE,MAAM;GAAQ,OAAO,eAAe,IAAI,OAAO;EAAE;CAC9D;CAGF,IAAI,IAAI,SAAS,QAAQ;EACvB,IAAI;EACJ,IAAI;GACF,WAAW,KAAK,MAAM,IAAI,OAAO;EACnC,QAAQ;GACN,WAAW,IAAI;EACjB;EACA,OAAO;GACL,IAAI,IAAI,MAAM,WAAW;GACzB,SAAS;IACP,MAAM;IACN,OAAO,CACL,EACE,kBAAkB;KAChB,MAAM,IAAI;KACV,IAAI,IAAI;KACR;IACF,EACF,CACF;GACF;EACF;CACF;CAEA,MAAM,SAAmB,EAAE,IAAI,IAAI,MAAM,WAAW,EAAE;CACtD,IAAI,IAAI,UAAU,MAAM,OAAO,SAAS,IAAI;CAC5C,OAAO,UAAU;EACf,MAAM;EACN,OAAO,CACL,GAAG,eAAe,IAAI,OAAO,GAC7B,GAAI,IAAI,YAAY,KAAK,QAAQ,EAC/B,cAAc;GAAE,MAAM,GAAG;GAAM,IAAI,GAAG;GAAI,MAAM,EAAE,GAAG,GAAG,KAAK;EAAE,EACjE,EAAE,KAAK,CAAC,CACV;CACF;CACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAdkRuntime.d.ts","names":[],"sources":["../src/useAdkRuntime.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"useAdkRuntime.d.ts","names":[],"sources":["../src/useAdkRuntime.ts"],"mappings":";;;;KA4DY,uBAAuB;EACjC,QAAQ;;;;;;;;;EASR,qBAAqB;EACrB;EACA;EACA,mBACE,kBACA,gBAAgB,iBACb;;;;;;;EAOL,QACE,kBACA;IAAY,SAAS;QAClB,QAAQ;EACb,eAAe;IAAU;;EACzB,UAAU,qBAAqB;EAC/B;IAEM,cAAc;IACd,SAAS;IACT,YAAY;IACZ,QAAQ;IACR,WAAW;;EAGjB;IAEM,UAAU;IACV,gBAAgB;IAChB,kBAAkB;;EAGxB,QAAQ;;;;;EAKR,iBAAiB;;cAgYN,kBAAiB,OAAA,gBAAA,QAAA,QAAA,UAAA,qBAAA,WAO3B,sDAAoB"}
|
package/dist/useAdkRuntime.js
CHANGED
|
@@ -7,7 +7,7 @@ import { generateId, pickExternalStoreSharedOptions } from "@assistant-ui/core";
|
|
|
7
7
|
import { useCloudThreadListAdapter, useExternalMessageConverter, useExternalStoreRuntime, useRemoteThreadListRuntime } from "@assistant-ui/core/react";
|
|
8
8
|
import { createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback } from "@assistant-ui/core/internal";
|
|
9
9
|
import { useAui } from "@assistant-ui/store";
|
|
10
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
10
|
+
import { useCallback, useEffect, useInsertionEffect, useMemo, useRef, useState } from "react";
|
|
11
11
|
//#region src/useAdkRuntime.ts
|
|
12
12
|
const useAdkRuntimeImpl = (options) => {
|
|
13
13
|
const { autoCancelPendingToolCalls, adapters: { attachments, dictation, feedback, speech, voice } = {}, unstable_allowCancellation, stream, load, getCheckpointId, eventHandlers } = options;
|
|
@@ -17,17 +17,23 @@ const useAdkRuntimeImpl = (options) => {
|
|
|
17
17
|
...eventHandlers && { eventHandlers }
|
|
18
18
|
});
|
|
19
19
|
const loadRef = useRef(load);
|
|
20
|
-
|
|
20
|
+
useInsertionEffect(() => {
|
|
21
|
+
loadRef.current = load;
|
|
22
|
+
}, [load]);
|
|
21
23
|
const loadController = useMemo(createAbortableThreadLoad, []);
|
|
22
24
|
const messagesRef = useRef(messages);
|
|
23
|
-
|
|
25
|
+
useInsertionEffect(() => {
|
|
26
|
+
messagesRef.current = messages;
|
|
27
|
+
}, [messages]);
|
|
24
28
|
const [isLoadingThread, setIsLoadingThread] = useState(() => load !== void 0 && aui.threadListItem.getState().externalId != null);
|
|
25
29
|
const [isRunning, setIsRunning] = useState(false);
|
|
26
30
|
const [toolStatuses, setToolStatuses] = useState({});
|
|
27
31
|
const hasExecutingTools = Object.values(toolStatuses).some((s) => s?.type === "executing");
|
|
28
32
|
const effectiveIsRunning = isRunning || hasExecutingTools;
|
|
29
33
|
const isRunningRef = useRef(effectiveIsRunning);
|
|
30
|
-
|
|
34
|
+
useInsertionEffect(() => {
|
|
35
|
+
isRunningRef.current = effectiveIsRunning;
|
|
36
|
+
}, [effectiveIsRunning]);
|
|
31
37
|
const handleSendMessage = async (msgs, config) => {
|
|
32
38
|
try {
|
|
33
39
|
setIsRunning(true);
|
|
@@ -39,6 +45,11 @@ const useAdkRuntimeImpl = (options) => {
|
|
|
39
45
|
const { approvals: toolApprovals, key: toolApprovalsKey } = projectAdkToolApprovals(messages);
|
|
40
46
|
const toolApprovalsRef = useRef(toolApprovals);
|
|
41
47
|
toolApprovalsRef.current = toolApprovals;
|
|
48
|
+
const longRunningToolIdsRef = useRef(longRunningToolIds);
|
|
49
|
+
useInsertionEffect(() => {
|
|
50
|
+
longRunningToolIdsRef.current = longRunningToolIds;
|
|
51
|
+
}, [longRunningToolIds]);
|
|
52
|
+
const isClientToolCall = useCallback((toolCall) => longRunningToolIdsRef.current.includes(toolCall.toolCallId), []);
|
|
42
53
|
const messageConverter = useMemo(() => toolApprovalsKey === "" ? convertAdkMessage : createAdkMessageConverter(toolApprovalsRef.current), [toolApprovalsKey]);
|
|
43
54
|
const threadMessages = useExternalMessageConverter({
|
|
44
55
|
callback: messageConverter,
|
|
@@ -46,9 +57,13 @@ const useAdkRuntimeImpl = (options) => {
|
|
|
46
57
|
isRunning: effectiveIsRunning
|
|
47
58
|
});
|
|
48
59
|
const threadMessagesRef = useRef(threadMessages);
|
|
49
|
-
|
|
60
|
+
useInsertionEffect(() => {
|
|
61
|
+
threadMessagesRef.current = threadMessages;
|
|
62
|
+
}, [threadMessages]);
|
|
50
63
|
const adkMessagesRef = useRef(messages);
|
|
51
|
-
|
|
64
|
+
useInsertionEffect(() => {
|
|
65
|
+
adkMessagesRef.current = messages;
|
|
66
|
+
}, [messages]);
|
|
52
67
|
const stagedMessagesRef = useRef(/* @__PURE__ */ new Map());
|
|
53
68
|
const [stagedMessageCount, setStagedMessageCount] = useState(0);
|
|
54
69
|
const hasStagedMessages = stagedMessageCount > 0;
|
|
@@ -116,6 +131,7 @@ const useAdkRuntimeImpl = (options) => {
|
|
|
116
131
|
isLoading: isLoadingThread,
|
|
117
132
|
messages: threadMessages,
|
|
118
133
|
unstable_enableToolInvocations: true,
|
|
134
|
+
unstable_isClientToolCall: isClientToolCall,
|
|
119
135
|
setToolStatuses,
|
|
120
136
|
adapters: {
|
|
121
137
|
attachments,
|
|
@@ -202,7 +218,7 @@ const useAdkRuntimeImpl = (options) => {
|
|
|
202
218
|
}], {});
|
|
203
219
|
},
|
|
204
220
|
onRespondToToolApproval: async (options) => {
|
|
205
|
-
await handleSendMessage([toAdkToolConfirmationReply(options,
|
|
221
|
+
await handleSendMessage([toAdkToolConfirmationReply(options, projectAdkToolApprovals(adkMessagesRef.current).approvals)], {});
|
|
206
222
|
},
|
|
207
223
|
onCancel: unstable_allowCancellation ? async () => {
|
|
208
224
|
cancel();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAdkRuntime.js","names":[],"sources":["../src/useAdkRuntime.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n pickExternalStoreSharedOptions,\n type AttachmentAdapter,\n type DictationAdapter,\n type ExternalStoreSharedOptions,\n type FeedbackAdapter,\n type RealtimeVoiceAdapter,\n type SpeechSynthesisAdapter,\n type AppendMessage,\n type ToolExecutionStatus,\n generateId,\n} from \"@assistant-ui/core\";\nimport {\n createAbortableThreadLoad,\n createCloudThreadListAdapterCreateFallback,\n} from \"@assistant-ui/core/internal\";\nimport {\n useCloudThreadListAdapter,\n useRemoteThreadListRuntime,\n useExternalMessageConverter,\n useExternalStoreRuntime,\n} from \"@assistant-ui/core/react\";\nimport { useAui } from \"@assistant-ui/store\";\nimport type { AssistantCloud } from \"assistant-cloud\";\nimport type { RemoteThreadListAdapter } from \"@assistant-ui/core\";\nimport type {\n AdkMessage,\n AdkThreadSnapshot,\n AdkSendMessageConfig,\n AdkStreamCallback,\n OnAdkErrorCallback,\n OnAdkCustomEventCallback,\n OnAdkAgentTransferCallback,\n} from \"./types\";\nimport { useAdkMessages } from \"./useAdkMessages\";\nimport {\n convertAdkMessage,\n createAdkMessageConverter,\n} from \"./convertAdkMessages\";\nimport {\n getMessageContent,\n getPendingCancellations,\n toAdkUserMessage,\n truncateAdkMessages,\n} from \"./convertToAdkMessages\";\nimport {\n projectAdkToolApprovals,\n toAdkToolConfirmationReply,\n} from \"./adkToolApproval\";\nimport { adkExtras } from \"./adkExtras\";\n\nexport type UseAdkRuntimeOptions = ExternalStoreSharedOptions & {\n stream: AdkStreamCallback;\n /**\n * Called whenever the active thread's canonical (remote) ID changes, so the\n * value can be treated as a managed/controlled variable (e.g. synced to a URL\n * query param). Only the settled remote ID is emitted: while a freshly created\n * thread is still optimistic the value is `undefined`, and the real ID is\n * emitted once the thread is initialized; the transient local ID is never\n * surfaced.\n */\n onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;\n autoCancelPendingToolCalls?: boolean | undefined;\n unstable_allowCancellation?: boolean | undefined;\n getCheckpointId?: (\n threadId: string,\n parentMessages: AdkMessage[],\n ) => Promise<string | null>;\n /**\n * Loads a thread's stored state. Called when the thread opens, and again for\n * `threads.reloadMainThread()`, which refetches in place rather than\n * remounting the runtime; the signal aborts a load the runtime no longer\n * needs.\n */\n load?: (\n threadId: string,\n options?: { signal?: AbortSignal | undefined },\n ) => Promise<AdkThreadSnapshot>;\n create?: () => Promise<{ externalId: string }>;\n delete?: (threadId: string) => Promise<void>;\n adapters?:\n | {\n attachments?: AttachmentAdapter;\n speech?: SpeechSynthesisAdapter;\n dictation?: DictationAdapter;\n voice?: RealtimeVoiceAdapter;\n feedback?: FeedbackAdapter;\n }\n | undefined;\n eventHandlers?:\n | {\n onError?: OnAdkErrorCallback;\n onCustomEvent?: OnAdkCustomEventCallback;\n onAgentTransfer?: OnAdkAgentTransferCallback;\n }\n | undefined;\n cloud?: AssistantCloud | undefined;\n /**\n * A `RemoteThreadListAdapter` to use instead of the cloud adapter.\n * Use with `createAdkSessionAdapter` for ADK session-backed persistence.\n */\n sessionAdapter?: RemoteThreadListAdapter | undefined;\n};\n\nconst useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {\n const {\n autoCancelPendingToolCalls,\n adapters: { attachments, dictation, feedback, speech, voice } = {},\n unstable_allowCancellation,\n stream,\n load,\n getCheckpointId,\n eventHandlers,\n } = options;\n const aui = useAui();\n const {\n messages,\n stateDelta,\n agentInfo,\n longRunningToolIds,\n artifactDelta,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n sendMessage,\n cancel,\n setMessages,\n replaceMessages,\n applySnapshot,\n } = useAdkMessages({\n stream,\n ...(eventHandlers && { eventHandlers }),\n });\n\n const loadRef = useRef(load);\n loadRef.current = load;\n const loadController = useMemo(createAbortableThreadLoad, []);\n const messagesRef = useRef(messages);\n messagesRef.current = messages;\n const [isLoadingThread, setIsLoadingThread] = useState(\n () =>\n load !== undefined && aui.threadListItem.getState().externalId != null,\n );\n\n const [isRunning, setIsRunning] = useState(false);\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const effectiveIsRunning = isRunning || hasExecutingTools;\n const isRunningRef = useRef(effectiveIsRunning);\n isRunningRef.current = effectiveIsRunning;\n\n const handleSendMessage = async (\n msgs: AdkMessage[],\n config: AdkSendMessageConfig,\n ) => {\n try {\n setIsRunning(true);\n await sendMessage(msgs, config);\n } finally {\n setIsRunning(false);\n }\n };\n\n const { approvals: toolApprovals, key: toolApprovalsKey } =\n projectAdkToolApprovals(messages);\n const toolApprovalsRef = useRef(toolApprovals);\n toolApprovalsRef.current = toolApprovals;\n\n const messageConverter = useMemo(\n () =>\n toolApprovalsKey === \"\"\n ? convertAdkMessage\n : createAdkMessageConverter(toolApprovalsRef.current),\n [toolApprovalsKey],\n );\n\n const threadMessages = useExternalMessageConverter({\n callback: messageConverter,\n messages,\n isRunning: effectiveIsRunning,\n });\n\n const threadMessagesRef = useRef(threadMessages);\n threadMessagesRef.current = threadMessages;\n\n const adkMessagesRef = useRef(messages);\n adkMessagesRef.current = messages;\n\n const stagedMessagesRef = useRef(\n new Map<\n string,\n {\n message: AdkMessage & { id: string };\n runConfig: AppendMessage[\"runConfig\"];\n }\n >(),\n );\n const [stagedMessageCount, setStagedMessageCount] = useState(0);\n const hasStagedMessages = stagedMessageCount > 0;\n\n const getStagedRun = (parentId: string | null) => {\n if (!parentId || !stagedMessagesRef.current.has(parentId)) return null;\n\n const staged: AdkMessage[] = [];\n for (const message of adkMessagesRef.current) {\n if (message.id && stagedMessagesRef.current.has(message.id)) {\n staged.push(stagedMessagesRef.current.get(message.id)!.message);\n }\n if (message.id === parentId) break;\n }\n\n return {\n messages: staged,\n runConfig: stagedMessagesRef.current.get(parentId)!.runConfig,\n };\n };\n\n const stageUserMessage = (msg: AppendMessage) => {\n const stagedMessage = toAdkUserMessage(msg);\n stagedMessagesRef.current.set(stagedMessage.id, {\n message: stagedMessage,\n runConfig: msg.runConfig,\n });\n setStagedMessageCount(stagedMessagesRef.current.size);\n const nextMessages = [...adkMessagesRef.current, stagedMessage];\n adkMessagesRef.current = nextMessages;\n setMessages(nextMessages);\n };\n\n // The scoped client, not `aui` itself: useAui returns a render-bound\n // instance, so depending on it would re-run the load on every render.\n const threadListItem =\n aui.threadListItem.source !== null ? aui.threadListItem : undefined;\n\n const runLoad = useCallback(\n (purpose: \"initial\" | \"reload\" = \"initial\") => {\n const loadFn = loadRef.current;\n if (!loadFn || !threadListItem) return Promise.resolve();\n\n const externalId = threadListItem.getState().externalId;\n if (externalId == null) return Promise.resolve();\n\n // The initial load is already fetching what a refetch would ask for, and\n // taking it over strands the thread's history if the refetch then fails.\n // Aborting a load the runtime no longer needs is not a failure.\n // A refetch reports the failure to whoever awaited it; the initial load\n // has no caller to tell.\n return loadController.run({\n purpose,\n load: async (signal) => {\n const messagesAtLoadStart = messagesRef.current;\n if (purpose === \"initial\") setIsLoadingThread(true);\n\n const snapshot = await loadFn(externalId, { signal });\n if (signal.aborted) return;\n // A snapshot the session assembled before a run cannot speak for what\n // that run has since produced, and an ADK id cannot correlate a\n // message sent optimistically with the one the session stored for it,\n // so there is nothing here that could merge the two. A refetch that\n // raced a run therefore defers to the run, whether the run started\n // during the load or was already streaming when it began.\n if (\n purpose === \"reload\" &&\n (isRunningRef.current ||\n messagesRef.current !== messagesAtLoadStart)\n )\n return;\n applySnapshot(snapshot);\n },\n onSettled: () => {\n setIsLoadingThread(false);\n },\n onInitialError: (error) => {\n console.warn(\"Failed to load ADK session:\", error);\n },\n });\n },\n [threadListItem, loadController, applySnapshot],\n );\n\n useEffect(() => {\n runLoad();\n return () => {\n // Whatever is current, not this effect's own controller: a refetch swaps\n // the ref, and one in flight at unmount must be aborted too.\n loadController.abort();\n setIsLoadingThread(false);\n };\n }, [loadController, runLoad]);\n\n const runtime = useExternalStoreRuntime({\n ...pickExternalStoreSharedOptions(options),\n isRunning,\n isLoading: isLoadingThread,\n messages: threadMessages,\n unstable_enableToolInvocations: true,\n setToolStatuses,\n adapters: { attachments, dictation, feedback, speech, voice },\n extras: adkExtras.provide({\n agentInfo,\n stateDelta,\n artifactDelta,\n longRunningToolIds,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n send: handleSendMessage,\n }),\n onNew: async (msg) => {\n if (!(msg.startRun ?? msg.role === \"user\")) {\n stageUserMessage(msg);\n return;\n }\n\n const cancellations =\n autoCancelPendingToolCalls !== false\n ? getPendingCancellations(messages, longRunningToolIds)\n : [];\n\n return handleSendMessage(\n [\n ...cancellations,\n {\n id: generateId(),\n type: \"human\",\n content: getMessageContent(msg),\n },\n ],\n { runConfig: msg.runConfig },\n );\n },\n onEdit: getCheckpointId\n ? async (msg) => {\n const truncated = truncateAdkMessages(\n threadMessagesRef.current,\n msg.parentId,\n );\n replaceMessages(truncated);\n if (!(msg.startRun ?? msg.role === \"user\")) {\n const stagedMessage = toAdkUserMessage(msg);\n stagedMessagesRef.current.set(stagedMessage.id, {\n message: stagedMessage,\n runConfig: msg.runConfig,\n });\n setStagedMessageCount(stagedMessagesRef.current.size);\n const nextMessages = [...truncated, stagedMessage];\n adkMessagesRef.current = nextMessages;\n setMessages(nextMessages);\n return;\n }\n const externalId = aui.threadListItem.getState().externalId;\n const checkpointId = externalId\n ? await getCheckpointId(externalId, truncated)\n : null;\n return handleSendMessage(\n [\n {\n id: generateId(),\n type: \"human\",\n content: getMessageContent(msg),\n },\n ],\n {\n runConfig: msg.runConfig,\n ...(checkpointId && { checkpointId }),\n },\n );\n }\n : undefined,\n ...(getCheckpointId || hasStagedMessages\n ? {\n onReload: async (parentId, config) => {\n const stagedRun = getStagedRun(parentId);\n if (stagedRun) {\n for (const message of stagedRun.messages) {\n stagedMessagesRef.current.delete(message.id);\n }\n setStagedMessageCount(stagedMessagesRef.current.size);\n return handleSendMessage(stagedRun.messages, {\n runConfig: config.runConfig ?? stagedRun.runConfig,\n });\n }\n\n if (!getCheckpointId)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n const truncated = truncateAdkMessages(\n threadMessagesRef.current,\n parentId,\n );\n replaceMessages(truncated);\n const externalId = aui.threadListItem.getState().externalId;\n const checkpointId = externalId\n ? await getCheckpointId(externalId, truncated)\n : null;\n return handleSendMessage([], {\n runConfig: config.runConfig,\n ...(checkpointId && { checkpointId }),\n });\n },\n }\n : {}),\n onAddToolResult: async ({\n toolCallId,\n toolName,\n result,\n isError,\n artifact,\n }) => {\n await handleSendMessage(\n [\n {\n id: generateId(),\n type: \"tool\",\n name: toolName,\n tool_call_id: toolCallId,\n content: JSON.stringify(result),\n artifact,\n status: isError ? \"error\" : \"success\",\n },\n ],\n {},\n );\n },\n onRespondToToolApproval: async (options) => {\n await handleSendMessage(\n [toAdkToolConfirmationReply(options, toolApprovalsRef.current)],\n {},\n );\n },\n onCancel: unstable_allowCancellation\n ? async () => {\n cancel();\n }\n : undefined,\n ...(load !== undefined && {\n onRefetchThread: () => runLoad(\"reload\"),\n }),\n });\n\n return runtime;\n};\n\nexport const useAdkRuntime = ({\n cloud,\n sessionAdapter,\n create,\n delete: deleteFn,\n onThreadIdChange,\n ...options\n}: UseAdkRuntimeOptions) => {\n const aui = useAui();\n const cloudAdapter = useCloudThreadListAdapter({\n cloud,\n create: createCloudThreadListAdapterCreateFallback(\n create,\n aui.threadListItem,\n ),\n delete: deleteFn,\n });\n\n const adapter = sessionAdapter ?? cloudAdapter;\n\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useAdkRuntimeImpl(options);\n },\n adapter,\n allowNesting: true,\n onThreadIdChange,\n });\n};\n"],"mappings":";;;;;;;;;;;AAyGA,MAAM,qBAAqB,YAAkC;CAC3D,MAAM,EACJ,4BACA,UAAU,EAAE,aAAa,WAAW,UAAU,QAAQ,UAAU,CAAC,GACjE,4BACA,QACA,MACA,iBACA,kBACE;CACJ,MAAM,MAAM,OAAO;CACnB,MAAM,EACJ,UACA,YACA,WACA,oBACA,eACA,mBACA,cACA,WACA,iBACA,aACA,QACA,aACA,iBACA,kBACE,eAAe;EACjB;EACA,GAAI,iBAAiB,EAAE,cAAc;CACvC,CAAC;CAED,MAAM,UAAU,OAAO,IAAI;CAC3B,QAAQ,UAAU;CAClB,MAAM,iBAAiB,QAAQ,2BAA2B,CAAC,CAAC;CAC5D,MAAM,cAAc,OAAO,QAAQ;CACnC,YAAY,UAAU;CACtB,MAAM,CAAC,iBAAiB,sBAAsB,eAE1C,SAAS,KAAA,KAAa,IAAI,eAAe,SAAS,CAAC,CAAC,cAAc,IACtE;CAEA,M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SAAS,cAAc;GAClC,OAAO,kBAAkB,OAAO;EAClC;EACA,SANc,kBAAkB;EAOhC,cAAc;EACd;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"useAdkRuntime.js","names":[],"sources":["../src/useAdkRuntime.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useInsertionEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n pickExternalStoreSharedOptions,\n type AttachmentAdapter,\n type DictationAdapter,\n type ExternalStoreSharedOptions,\n type FeedbackAdapter,\n type RealtimeVoiceAdapter,\n type SpeechSynthesisAdapter,\n type AppendMessage,\n type ToolCallMessagePart,\n type ToolExecutionStatus,\n generateId,\n} from \"@assistant-ui/core\";\nimport {\n createAbortableThreadLoad,\n createCloudThreadListAdapterCreateFallback,\n} from \"@assistant-ui/core/internal\";\nimport {\n useCloudThreadListAdapter,\n useRemoteThreadListRuntime,\n useExternalMessageConverter,\n useExternalStoreRuntime,\n} from \"@assistant-ui/core/react\";\nimport { useAui } from \"@assistant-ui/store\";\nimport type { AssistantCloud } from \"assistant-cloud\";\nimport type { RemoteThreadListAdapter } from \"@assistant-ui/core\";\nimport type {\n AdkMessage,\n AdkThreadSnapshot,\n AdkSendMessageConfig,\n AdkStreamCallback,\n OnAdkErrorCallback,\n OnAdkCustomEventCallback,\n OnAdkAgentTransferCallback,\n} from \"./types\";\nimport { useAdkMessages } from \"./useAdkMessages\";\nimport {\n convertAdkMessage,\n createAdkMessageConverter,\n} from \"./convertAdkMessages\";\nimport {\n getMessageContent,\n getPendingCancellations,\n toAdkUserMessage,\n truncateAdkMessages,\n} from \"./convertToAdkMessages\";\nimport {\n projectAdkToolApprovals,\n toAdkToolConfirmationReply,\n} from \"./adkToolApproval\";\nimport { adkExtras } from \"./adkExtras\";\n\nexport type UseAdkRuntimeOptions = ExternalStoreSharedOptions & {\n stream: AdkStreamCallback;\n /**\n * Called whenever the active thread's canonical (remote) ID changes, so the\n * value can be treated as a managed/controlled variable (e.g. synced to a URL\n * query param). Only the settled remote ID is emitted: while a freshly created\n * thread is still optimistic the value is `undefined`, and the real ID is\n * emitted once the thread is initialized; the transient local ID is never\n * surfaced.\n */\n onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;\n autoCancelPendingToolCalls?: boolean | undefined;\n unstable_allowCancellation?: boolean | undefined;\n getCheckpointId?: (\n threadId: string,\n parentMessages: AdkMessage[],\n ) => Promise<string | null>;\n /**\n * Loads a thread's stored state. Called when the thread opens, and again for\n * `threads.reloadMainThread()`, which refetches in place rather than\n * remounting the runtime; the signal aborts a load the runtime no longer\n * needs.\n */\n load?: (\n threadId: string,\n options?: { signal?: AbortSignal | undefined },\n ) => Promise<AdkThreadSnapshot>;\n create?: () => Promise<{ externalId: string }>;\n delete?: (threadId: string) => Promise<void>;\n adapters?:\n | {\n attachments?: AttachmentAdapter;\n speech?: SpeechSynthesisAdapter;\n dictation?: DictationAdapter;\n voice?: RealtimeVoiceAdapter;\n feedback?: FeedbackAdapter;\n }\n | undefined;\n eventHandlers?:\n | {\n onError?: OnAdkErrorCallback;\n onCustomEvent?: OnAdkCustomEventCallback;\n onAgentTransfer?: OnAdkAgentTransferCallback;\n }\n | undefined;\n cloud?: AssistantCloud | undefined;\n /**\n * A `RemoteThreadListAdapter` to use instead of the cloud adapter.\n * Use with `createAdkSessionAdapter` for ADK session-backed persistence.\n */\n sessionAdapter?: RemoteThreadListAdapter | undefined;\n};\n\nconst useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {\n const {\n autoCancelPendingToolCalls,\n adapters: { attachments, dictation, feedback, speech, voice } = {},\n unstable_allowCancellation,\n stream,\n load,\n getCheckpointId,\n eventHandlers,\n } = options;\n const aui = useAui();\n const {\n messages,\n stateDelta,\n agentInfo,\n longRunningToolIds,\n artifactDelta,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n sendMessage,\n cancel,\n setMessages,\n replaceMessages,\n applySnapshot,\n } = useAdkMessages({\n stream,\n ...(eventHandlers && { eventHandlers }),\n });\n\n const loadRef = useRef(load);\n useInsertionEffect(() => {\n loadRef.current = load;\n }, [load]);\n const loadController = useMemo(createAbortableThreadLoad, []);\n const messagesRef = useRef(messages);\n useInsertionEffect(() => {\n messagesRef.current = messages;\n }, [messages]);\n const [isLoadingThread, setIsLoadingThread] = useState(\n () =>\n load !== undefined && aui.threadListItem.getState().externalId != null,\n );\n\n const [isRunning, setIsRunning] = useState(false);\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const effectiveIsRunning = isRunning || hasExecutingTools;\n const isRunningRef = useRef(effectiveIsRunning);\n useInsertionEffect(() => {\n isRunningRef.current = effectiveIsRunning;\n }, [effectiveIsRunning]);\n\n const handleSendMessage = async (\n msgs: AdkMessage[],\n config: AdkSendMessageConfig,\n ) => {\n try {\n setIsRunning(true);\n await sendMessage(msgs, config);\n } finally {\n setIsRunning(false);\n }\n };\n\n const { approvals: toolApprovals, key: toolApprovalsKey } =\n projectAdkToolApprovals(messages);\n // The messageConverter memo below reads this during render, where the ref\n // must carry the same render's approvals; a commit-scoped write would feed\n // the memo the previous commit's approvals whenever the key changes. No\n // callback reads it — approval replies project from the committed messages.\n const toolApprovalsRef = useRef(toolApprovals);\n toolApprovalsRef.current = toolApprovals;\n\n const longRunningToolIdsRef = useRef(longRunningToolIds);\n useInsertionEffect(() => {\n longRunningToolIdsRef.current = longRunningToolIds;\n }, [longRunningToolIds]);\n // ADK resolves every call it did not mark long-running itself, and yields\n // that call to the client one or more events before its own response, so\n // only a long-running call is the client's to execute.\n const isClientToolCall = useCallback(\n (toolCall: ToolCallMessagePart) =>\n longRunningToolIdsRef.current.includes(toolCall.toolCallId),\n [],\n );\n\n const messageConverter = useMemo(\n () =>\n toolApprovalsKey === \"\"\n ? convertAdkMessage\n : createAdkMessageConverter(toolApprovalsRef.current),\n [toolApprovalsKey],\n );\n\n const threadMessages = useExternalMessageConverter({\n callback: messageConverter,\n messages,\n isRunning: effectiveIsRunning,\n });\n\n const threadMessagesRef = useRef(threadMessages);\n useInsertionEffect(() => {\n threadMessagesRef.current = threadMessages;\n }, [threadMessages]);\n\n // Staging assigns adkMessagesRef.current directly, so the effect must key on\n // the committed messages alone; a dep-less publication would clobber the\n // optimistic value on any unrelated commit.\n const adkMessagesRef = useRef(messages);\n useInsertionEffect(() => {\n adkMessagesRef.current = messages;\n }, [messages]);\n\n const stagedMessagesRef = useRef(\n new Map<\n string,\n {\n message: AdkMessage & { id: string };\n runConfig: AppendMessage[\"runConfig\"];\n }\n >(),\n );\n const [stagedMessageCount, setStagedMessageCount] = useState(0);\n const hasStagedMessages = stagedMessageCount > 0;\n\n const getStagedRun = (parentId: string | null) => {\n if (!parentId || !stagedMessagesRef.current.has(parentId)) return null;\n\n const staged: AdkMessage[] = [];\n for (const message of adkMessagesRef.current) {\n if (message.id && stagedMessagesRef.current.has(message.id)) {\n staged.push(stagedMessagesRef.current.get(message.id)!.message);\n }\n if (message.id === parentId) break;\n }\n\n return {\n messages: staged,\n runConfig: stagedMessagesRef.current.get(parentId)!.runConfig,\n };\n };\n\n const stageUserMessage = (msg: AppendMessage) => {\n const stagedMessage = toAdkUserMessage(msg);\n stagedMessagesRef.current.set(stagedMessage.id, {\n message: stagedMessage,\n runConfig: msg.runConfig,\n });\n setStagedMessageCount(stagedMessagesRef.current.size);\n const nextMessages = [...adkMessagesRef.current, stagedMessage];\n adkMessagesRef.current = nextMessages;\n setMessages(nextMessages);\n };\n\n // The scoped client, not `aui` itself: useAui returns a render-bound\n // instance, so depending on it would re-run the load on every render.\n const threadListItem =\n aui.threadListItem.source !== null ? aui.threadListItem : undefined;\n\n const runLoad = useCallback(\n (purpose: \"initial\" | \"reload\" = \"initial\") => {\n const loadFn = loadRef.current;\n if (!loadFn || !threadListItem) return Promise.resolve();\n\n const externalId = threadListItem.getState().externalId;\n if (externalId == null) return Promise.resolve();\n\n // The initial load is already fetching what a refetch would ask for, and\n // taking it over strands the thread's history if the refetch then fails.\n // Aborting a load the runtime no longer needs is not a failure.\n // A refetch reports the failure to whoever awaited it; the initial load\n // has no caller to tell.\n return loadController.run({\n purpose,\n load: async (signal) => {\n const messagesAtLoadStart = messagesRef.current;\n if (purpose === \"initial\") setIsLoadingThread(true);\n\n const snapshot = await loadFn(externalId, { signal });\n if (signal.aborted) return;\n // A snapshot the session assembled before a run cannot speak for what\n // that run has since produced, and an ADK id cannot correlate a\n // message sent optimistically with the one the session stored for it,\n // so there is nothing here that could merge the two. A refetch that\n // raced a run therefore defers to the run, whether the run started\n // during the load or was already streaming when it began.\n if (\n purpose === \"reload\" &&\n (isRunningRef.current ||\n messagesRef.current !== messagesAtLoadStart)\n )\n return;\n applySnapshot(snapshot);\n },\n onSettled: () => {\n setIsLoadingThread(false);\n },\n onInitialError: (error) => {\n console.warn(\"Failed to load ADK session:\", error);\n },\n });\n },\n [threadListItem, loadController, applySnapshot],\n );\n\n useEffect(() => {\n runLoad();\n return () => {\n // Whatever is current, not this effect's own controller: a refetch swaps\n // the ref, and one in flight at unmount must be aborted too.\n loadController.abort();\n setIsLoadingThread(false);\n };\n }, [loadController, runLoad]);\n\n const runtime = useExternalStoreRuntime({\n ...pickExternalStoreSharedOptions(options),\n isRunning,\n isLoading: isLoadingThread,\n messages: threadMessages,\n unstable_enableToolInvocations: true,\n unstable_isClientToolCall: isClientToolCall,\n setToolStatuses,\n adapters: { attachments, dictation, feedback, speech, voice },\n extras: adkExtras.provide({\n agentInfo,\n stateDelta,\n artifactDelta,\n longRunningToolIds,\n toolConfirmations,\n authRequests,\n escalated,\n messageMetadata,\n send: handleSendMessage,\n }),\n onNew: async (msg) => {\n if (!(msg.startRun ?? msg.role === \"user\")) {\n stageUserMessage(msg);\n return;\n }\n\n const cancellations =\n autoCancelPendingToolCalls !== false\n ? getPendingCancellations(messages, longRunningToolIds)\n : [];\n\n return handleSendMessage(\n [\n ...cancellations,\n {\n id: generateId(),\n type: \"human\",\n content: getMessageContent(msg),\n },\n ],\n { runConfig: msg.runConfig },\n );\n },\n onEdit: getCheckpointId\n ? async (msg) => {\n const truncated = truncateAdkMessages(\n threadMessagesRef.current,\n msg.parentId,\n );\n replaceMessages(truncated);\n if (!(msg.startRun ?? msg.role === \"user\")) {\n const stagedMessage = toAdkUserMessage(msg);\n stagedMessagesRef.current.set(stagedMessage.id, {\n message: stagedMessage,\n runConfig: msg.runConfig,\n });\n setStagedMessageCount(stagedMessagesRef.current.size);\n const nextMessages = [...truncated, stagedMessage];\n adkMessagesRef.current = nextMessages;\n setMessages(nextMessages);\n return;\n }\n const externalId = aui.threadListItem.getState().externalId;\n const checkpointId = externalId\n ? await getCheckpointId(externalId, truncated)\n : null;\n return handleSendMessage(\n [\n {\n id: generateId(),\n type: \"human\",\n content: getMessageContent(msg),\n },\n ],\n {\n runConfig: msg.runConfig,\n ...(checkpointId && { checkpointId }),\n },\n );\n }\n : undefined,\n ...(getCheckpointId || hasStagedMessages\n ? {\n onReload: async (parentId, config) => {\n const stagedRun = getStagedRun(parentId);\n if (stagedRun) {\n for (const message of stagedRun.messages) {\n stagedMessagesRef.current.delete(message.id);\n }\n setStagedMessageCount(stagedMessagesRef.current.size);\n return handleSendMessage(stagedRun.messages, {\n runConfig: config.runConfig ?? stagedRun.runConfig,\n });\n }\n\n if (!getCheckpointId)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n const truncated = truncateAdkMessages(\n threadMessagesRef.current,\n parentId,\n );\n replaceMessages(truncated);\n const externalId = aui.threadListItem.getState().externalId;\n const checkpointId = externalId\n ? await getCheckpointId(externalId, truncated)\n : null;\n return handleSendMessage([], {\n runConfig: config.runConfig,\n ...(checkpointId && { checkpointId }),\n });\n },\n }\n : {}),\n onAddToolResult: async ({\n toolCallId,\n toolName,\n result,\n isError,\n artifact,\n }) => {\n await handleSendMessage(\n [\n {\n id: generateId(),\n type: \"tool\",\n name: toolName,\n tool_call_id: toolCallId,\n content: JSON.stringify(result),\n artifact,\n status: isError ? \"error\" : \"success\",\n },\n ],\n {},\n );\n },\n onRespondToToolApproval: async (options) => {\n await handleSendMessage(\n [\n toAdkToolConfirmationReply(\n options,\n projectAdkToolApprovals(adkMessagesRef.current).approvals,\n ),\n ],\n {},\n );\n },\n onCancel: unstable_allowCancellation\n ? async () => {\n cancel();\n }\n : undefined,\n ...(load !== undefined && {\n onRefetchThread: () => runLoad(\"reload\"),\n }),\n });\n\n return runtime;\n};\n\nexport const useAdkRuntime = ({\n cloud,\n sessionAdapter,\n create,\n delete: deleteFn,\n onThreadIdChange,\n ...options\n}: UseAdkRuntimeOptions) => {\n const aui = useAui();\n const cloudAdapter = useCloudThreadListAdapter({\n cloud,\n create: createCloudThreadListAdapterCreateFallback(\n create,\n aui.threadListItem,\n ),\n delete: deleteFn,\n });\n\n const adapter = sessionAdapter ?? cloudAdapter;\n\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useAdkRuntimeImpl(options);\n },\n adapter,\n allowNesting: true,\n onThreadIdChange,\n });\n};\n"],"mappings":";;;;;;;;;;;AAiHA,MAAM,qBAAqB,YAAkC;CAC3D,MAAM,EACJ,4BACA,UAAU,EAAE,aAAa,WAAW,UAAU,QAAQ,UAAU,CAAC,GACjE,4BACA,QACA,MACA,iBACA,kBACE;CACJ,MAAM,MAAM,OAAO;CACnB,MAAM,EACJ,UACA,YACA,WACA,oBACA,eACA,mBACA,cACA,WACA,iBACA,aACA,QACA,aACA,iBACA,kBACE,eAAe;EACjB;EACA,GAAI,iBAAiB,EAAE,cAAc;CACvC,CAAC;CAED,MAAM,UAAU,OAAO,IAAI;CAC3B,yBAAyB;EACvB,QAAQ,UAAU;CACpB,GAAG,CAAC,IAAI,CAAC;CACT,MAAM,iBAAiB,QAAQ,2BAA2B,CAAC,CAAC;CAC5D,MAAM,cAAc,OAAO,QAAQ;CACnC,yBAAyB;EACvB,YAAY,UAAU;CACxB,GAAG,CAAC,QAAQ,CAAC;CACb,MAAM,CAAC,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C1C,MAAM,kBACJ,CACE,2BACE,SACA,wBAAwB,eAAe,OAAO,CAAC,CAAC,SAClD,CACF,GACA,CAAC,CACH;EACF;EACA,UAAU,6BACN,YAAY;GACV,OAAO;EACT,IACA,KAAA;EACJ,GAAI,SAAS,KAAA,KAAa,EACxB,uBAAuB,QAAQ,QAAQ,EACzC;CACF,CAEa;AACf;AAEA,MAAa,iBAAiB,EAC5B,OACA,gBACA,QACA,QAAQ,UACR,kBACA,GAAG,cACuB;CAC1B,MAAM,MAAM,OAAO;CACnB,MAAM,eAAe,0BAA0B;EAC7C;EACA,QAAQ,2CACN,QACA,IAAI,cACN;EACA,QAAQ;CACV,CAAC;CAID,OAAO,2BAA2B;EAChC,aAAa,SAAS,cAAc;GAClC,OAAO,kBAAkB,OAAO;EAClC;EACA,SANc,kBAAkB;EAOhC,cAAc;EACd;CACF,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-google-adk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.28",
|
|
4
4
|
"description": "Google ADK adapter for assistant-ui",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"google-adk",
|
|
@@ -34,10 +34,10 @@
|
|
|
34
34
|
],
|
|
35
35
|
"sideEffects": false,
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@assistant-ui/core": "^0.3.
|
|
38
|
-
"@assistant-ui/store": "^0.3.
|
|
37
|
+
"@assistant-ui/core": "^0.3.17",
|
|
38
|
+
"@assistant-ui/store": "^0.3.12",
|
|
39
39
|
"assistant-cloud": "*",
|
|
40
|
-
"assistant-stream": "^0.3.
|
|
40
|
+
"assistant-stream": "^0.3.41"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
43
|
"@google/adk": ">=0.5.0",
|
|
@@ -53,9 +53,9 @@
|
|
|
53
53
|
}
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
|
-
"@assistant-ui/x-buildutils": "0.0.
|
|
56
|
+
"@assistant-ui/x-buildutils": "0.0.25",
|
|
57
57
|
"@testing-library/dom": "^10.4.1",
|
|
58
|
-
"@testing-library/react": "^16.3.
|
|
58
|
+
"@testing-library/react": "^16.3.3",
|
|
59
59
|
"@types/react": "^19.2.18",
|
|
60
60
|
"jsdom": "^30.0.1",
|
|
61
61
|
"react": "^19.2.8",
|
package/src/useAdkMessages.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
useState,
|
|
3
|
+
useCallback,
|
|
4
|
+
useEffect,
|
|
5
|
+
useInsertionEffect,
|
|
6
|
+
useRef,
|
|
7
|
+
useMemo,
|
|
8
|
+
} from "react";
|
|
2
9
|
import { generateId } from "@assistant-ui/core";
|
|
3
10
|
import { useAui } from "@assistant-ui/store";
|
|
4
11
|
import { invokeUserCallback } from "@assistant-ui/core/internal";
|
|
@@ -60,14 +67,21 @@ export const useAdkMessages = ({
|
|
|
60
67
|
Map<string, AdkMessageMetadata>
|
|
61
68
|
>(new Map());
|
|
62
69
|
const lastTransferToAgentRef = useRef<string | undefined>(undefined);
|
|
70
|
+
// setMessagesImmediate is the only writer of the messages state and publishes
|
|
71
|
+
// this ref with it, so the ref never trails a commit.
|
|
63
72
|
const messagesRef = useRef(messages);
|
|
64
|
-
messagesRef.current = messages;
|
|
65
73
|
const stateDeltaRef = useRef(stateDelta);
|
|
66
|
-
|
|
74
|
+
useInsertionEffect(() => {
|
|
75
|
+
stateDeltaRef.current = stateDelta;
|
|
76
|
+
}, [stateDelta]);
|
|
67
77
|
const artifactDeltaRef = useRef(artifactDelta);
|
|
68
|
-
|
|
78
|
+
useInsertionEffect(() => {
|
|
79
|
+
artifactDeltaRef.current = artifactDelta;
|
|
80
|
+
}, [artifactDelta]);
|
|
69
81
|
const messageMetadataRef = useRef(messageMetadata);
|
|
70
|
-
|
|
82
|
+
useInsertionEffect(() => {
|
|
83
|
+
messageMetadataRef.current = messageMetadata;
|
|
84
|
+
}, [messageMetadata]);
|
|
71
85
|
|
|
72
86
|
const setMessagesImmediate = useCallback((msgs: AdkMessage[]) => {
|
|
73
87
|
messagesRef.current = msgs;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
import { act, render, waitFor } from "@testing-library/react";
|
|
4
|
+
import { type FC } from "react";
|
|
5
|
+
import { describe, expect, it, vi } from "vitest";
|
|
6
|
+
import {
|
|
7
|
+
AssistantRuntimeProvider,
|
|
8
|
+
useAssistantTool,
|
|
9
|
+
} from "@assistant-ui/core/react";
|
|
10
|
+
import type {
|
|
11
|
+
AssistantRuntime,
|
|
12
|
+
RemoteThreadListAdapter,
|
|
13
|
+
ToolCallMessagePart,
|
|
14
|
+
} from "@assistant-ui/core";
|
|
15
|
+
import { useAdkRuntime } from "./useAdkRuntime";
|
|
16
|
+
import type { AdkEvent } from "./types";
|
|
17
|
+
|
|
18
|
+
const makeThreadListAdapter = (): RemoteThreadListAdapter => ({
|
|
19
|
+
list: vi.fn(async () => ({
|
|
20
|
+
threads: [
|
|
21
|
+
{
|
|
22
|
+
status: "regular" as const,
|
|
23
|
+
remoteId: "adk-1",
|
|
24
|
+
externalId: "adk-1",
|
|
25
|
+
title: "Existing ADK session",
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
})),
|
|
29
|
+
initialize: vi.fn(async () => ({ remoteId: "adk-1", externalId: "adk-1" })),
|
|
30
|
+
rename: vi.fn(async () => {}),
|
|
31
|
+
archive: vi.fn(async () => {}),
|
|
32
|
+
unarchive: vi.fn(async () => {}),
|
|
33
|
+
delete: vi.fn(async () => {}),
|
|
34
|
+
generateTitle: vi.fn(async () => new ReadableStream() as never),
|
|
35
|
+
fetch: vi.fn(async () => ({
|
|
36
|
+
status: "regular" as const,
|
|
37
|
+
remoteId: "adk-1",
|
|
38
|
+
externalId: "adk-1",
|
|
39
|
+
title: "Existing ADK session",
|
|
40
|
+
})),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const toolCalls = (runtime: AssistantRuntime): ToolCallMessagePart[] =>
|
|
44
|
+
runtime.thread
|
|
45
|
+
.getState()
|
|
46
|
+
.messages.flatMap((message) => message.content as readonly unknown[])
|
|
47
|
+
.filter(
|
|
48
|
+
(part): part is ToolCallMessagePart =>
|
|
49
|
+
(part as ToolCallMessagePart).type === "tool-call",
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
const GATED_CALL = {
|
|
53
|
+
id: "adk-original-1",
|
|
54
|
+
name: "delete_file",
|
|
55
|
+
args: { path: "/tmp/a" },
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const callEvent = (longRunningToolIds?: string[]): AdkEvent => ({
|
|
59
|
+
id: "ev-1",
|
|
60
|
+
invocationId: "inv-1",
|
|
61
|
+
author: "agent",
|
|
62
|
+
content: { role: "model", parts: [{ functionCall: GATED_CALL }] },
|
|
63
|
+
...(longRunningToolIds && { longRunningToolIds }),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const confirmationEvent = (): AdkEvent => ({
|
|
67
|
+
id: "ev-2",
|
|
68
|
+
invocationId: "inv-1",
|
|
69
|
+
author: "agent",
|
|
70
|
+
content: {
|
|
71
|
+
role: "model",
|
|
72
|
+
parts: [
|
|
73
|
+
{
|
|
74
|
+
functionCall: {
|
|
75
|
+
id: "adk-confirmation-1",
|
|
76
|
+
name: "adk_request_confirmation",
|
|
77
|
+
args: {
|
|
78
|
+
originalFunctionCall: GATED_CALL,
|
|
79
|
+
toolConfirmation: { hint: "Delete /tmp/a?" },
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
},
|
|
85
|
+
longRunningToolIds: ["adk-confirmation-1"],
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const serverResultEvent = (): AdkEvent => ({
|
|
89
|
+
id: "ev-2",
|
|
90
|
+
invocationId: "inv-1",
|
|
91
|
+
author: "agent",
|
|
92
|
+
content: {
|
|
93
|
+
role: "user",
|
|
94
|
+
parts: [
|
|
95
|
+
{
|
|
96
|
+
functionResponse: {
|
|
97
|
+
id: "adk-original-1",
|
|
98
|
+
name: "delete_file",
|
|
99
|
+
response: { server: "deleted" },
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Streams `first`, hands control back so the window between the two events is
|
|
108
|
+
* observable, then streams `second` once the returned `release` is called.
|
|
109
|
+
*/
|
|
110
|
+
const renderStreamingAdk = async (first: AdkEvent, second: AdkEvent) => {
|
|
111
|
+
let release!: () => void;
|
|
112
|
+
const held = new Promise<void>((r) => (release = r));
|
|
113
|
+
let firstDelivered!: () => void;
|
|
114
|
+
const firstDeliveredP = new Promise<void>((r) => (firstDelivered = r));
|
|
115
|
+
|
|
116
|
+
const stream = vi.fn(async function* (): AsyncGenerator<AdkEvent> {
|
|
117
|
+
yield first;
|
|
118
|
+
firstDelivered();
|
|
119
|
+
await held;
|
|
120
|
+
yield second;
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const execute = vi.fn(async () => ({ deleted: true }));
|
|
124
|
+
const capture: { runtime: AssistantRuntime | null } = { runtime: null };
|
|
125
|
+
|
|
126
|
+
const DeleteFileTool = () => {
|
|
127
|
+
useAssistantTool({
|
|
128
|
+
toolName: "delete_file",
|
|
129
|
+
description: "delete a file",
|
|
130
|
+
parameters: {
|
|
131
|
+
type: "object" as const,
|
|
132
|
+
properties: { path: { type: "string" } },
|
|
133
|
+
},
|
|
134
|
+
execute,
|
|
135
|
+
});
|
|
136
|
+
return null;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const Inner: FC = () => {
|
|
140
|
+
const runtime = useAdkRuntime({
|
|
141
|
+
stream: stream as never,
|
|
142
|
+
sessionAdapter: makeThreadListAdapter(),
|
|
143
|
+
});
|
|
144
|
+
capture.runtime = runtime;
|
|
145
|
+
return (
|
|
146
|
+
<AssistantRuntimeProvider runtime={runtime}>
|
|
147
|
+
<DeleteFileTool />
|
|
148
|
+
</AssistantRuntimeProvider>
|
|
149
|
+
);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
await act(async () => {
|
|
153
|
+
render(<Inner />);
|
|
154
|
+
});
|
|
155
|
+
await waitFor(() => expect(capture.runtime).not.toBeNull());
|
|
156
|
+
await act(async () => {
|
|
157
|
+
await capture.runtime!.threads.switchToThread("adk-1");
|
|
158
|
+
});
|
|
159
|
+
await act(async () => {
|
|
160
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
await act(async () => {
|
|
164
|
+
void capture.runtime!.thread.append({
|
|
165
|
+
role: "user",
|
|
166
|
+
content: [{ type: "text", text: "delete it" }],
|
|
167
|
+
});
|
|
168
|
+
await firstDeliveredP;
|
|
169
|
+
});
|
|
170
|
+
await act(async () => {
|
|
171
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const settle = async () => {
|
|
175
|
+
await act(async () => {
|
|
176
|
+
release();
|
|
177
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
178
|
+
});
|
|
179
|
+
await act(async () => {
|
|
180
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
181
|
+
});
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
return { capture, execute, settle };
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
describe("useAdkRuntime tool ownership", () => {
|
|
188
|
+
it("does not run a frontend execute on a call ADK is about to gate", async () => {
|
|
189
|
+
const { capture, execute, settle } = await renderStreamingAdk(
|
|
190
|
+
callEvent(),
|
|
191
|
+
confirmationEvent(),
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
const inWindow = toolCalls(capture.runtime!)[0]!;
|
|
195
|
+
expect(inWindow.argsText).toBe('{"path":"/tmp/a"}');
|
|
196
|
+
expect(inWindow.approval).toBeUndefined();
|
|
197
|
+
expect(inWindow.result).toBeUndefined();
|
|
198
|
+
expect(execute).not.toHaveBeenCalled();
|
|
199
|
+
|
|
200
|
+
await settle();
|
|
201
|
+
|
|
202
|
+
const gated = toolCalls(capture.runtime!).find(
|
|
203
|
+
(part) => part.toolCallId === "adk-original-1",
|
|
204
|
+
)!;
|
|
205
|
+
expect(gated.approval).toEqual({ id: "adk-confirmation-1" });
|
|
206
|
+
expect(gated.result).toBeUndefined();
|
|
207
|
+
expect(execute).not.toHaveBeenCalled();
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it("does not run a frontend execute on a call ADK resolves itself", async () => {
|
|
211
|
+
const { capture, execute, settle } = await renderStreamingAdk(
|
|
212
|
+
callEvent(),
|
|
213
|
+
serverResultEvent(),
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
expect(toolCalls(capture.runtime!)[0]!.result).toBeUndefined();
|
|
217
|
+
expect(execute).not.toHaveBeenCalled();
|
|
218
|
+
|
|
219
|
+
await settle();
|
|
220
|
+
|
|
221
|
+
expect(toolCalls(capture.runtime!)[0]!.result).toBe('{"server":"deleted"}');
|
|
222
|
+
expect(execute).not.toHaveBeenCalled();
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it("runs a frontend execute on a call ADK marks long-running", async () => {
|
|
226
|
+
const { capture, execute } = await renderStreamingAdk(
|
|
227
|
+
callEvent(["adk-original-1"]),
|
|
228
|
+
serverResultEvent(),
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
|
|
232
|
+
await waitFor(() =>
|
|
233
|
+
expect(toolCalls(capture.runtime!)[0]!.result).toBeDefined(),
|
|
234
|
+
);
|
|
235
|
+
});
|
|
236
|
+
});
|
package/src/useAdkRuntime.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
useCallback,
|
|
3
|
+
useEffect,
|
|
4
|
+
useInsertionEffect,
|
|
5
|
+
useMemo,
|
|
6
|
+
useRef,
|
|
7
|
+
useState,
|
|
8
|
+
} from "react";
|
|
2
9
|
import {
|
|
3
10
|
pickExternalStoreSharedOptions,
|
|
4
11
|
type AttachmentAdapter,
|
|
@@ -8,6 +15,7 @@ import {
|
|
|
8
15
|
type RealtimeVoiceAdapter,
|
|
9
16
|
type SpeechSynthesisAdapter,
|
|
10
17
|
type AppendMessage,
|
|
18
|
+
type ToolCallMessagePart,
|
|
11
19
|
type ToolExecutionStatus,
|
|
12
20
|
generateId,
|
|
13
21
|
} from "@assistant-ui/core";
|
|
@@ -135,10 +143,14 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
135
143
|
});
|
|
136
144
|
|
|
137
145
|
const loadRef = useRef(load);
|
|
138
|
-
|
|
146
|
+
useInsertionEffect(() => {
|
|
147
|
+
loadRef.current = load;
|
|
148
|
+
}, [load]);
|
|
139
149
|
const loadController = useMemo(createAbortableThreadLoad, []);
|
|
140
150
|
const messagesRef = useRef(messages);
|
|
141
|
-
|
|
151
|
+
useInsertionEffect(() => {
|
|
152
|
+
messagesRef.current = messages;
|
|
153
|
+
}, [messages]);
|
|
142
154
|
const [isLoadingThread, setIsLoadingThread] = useState(
|
|
143
155
|
() =>
|
|
144
156
|
load !== undefined && aui.threadListItem.getState().externalId != null,
|
|
@@ -153,7 +165,9 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
153
165
|
);
|
|
154
166
|
const effectiveIsRunning = isRunning || hasExecutingTools;
|
|
155
167
|
const isRunningRef = useRef(effectiveIsRunning);
|
|
156
|
-
|
|
168
|
+
useInsertionEffect(() => {
|
|
169
|
+
isRunningRef.current = effectiveIsRunning;
|
|
170
|
+
}, [effectiveIsRunning]);
|
|
157
171
|
|
|
158
172
|
const handleSendMessage = async (
|
|
159
173
|
msgs: AdkMessage[],
|
|
@@ -169,9 +183,26 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
169
183
|
|
|
170
184
|
const { approvals: toolApprovals, key: toolApprovalsKey } =
|
|
171
185
|
projectAdkToolApprovals(messages);
|
|
186
|
+
// The messageConverter memo below reads this during render, where the ref
|
|
187
|
+
// must carry the same render's approvals; a commit-scoped write would feed
|
|
188
|
+
// the memo the previous commit's approvals whenever the key changes. No
|
|
189
|
+
// callback reads it — approval replies project from the committed messages.
|
|
172
190
|
const toolApprovalsRef = useRef(toolApprovals);
|
|
173
191
|
toolApprovalsRef.current = toolApprovals;
|
|
174
192
|
|
|
193
|
+
const longRunningToolIdsRef = useRef(longRunningToolIds);
|
|
194
|
+
useInsertionEffect(() => {
|
|
195
|
+
longRunningToolIdsRef.current = longRunningToolIds;
|
|
196
|
+
}, [longRunningToolIds]);
|
|
197
|
+
// ADK resolves every call it did not mark long-running itself, and yields
|
|
198
|
+
// that call to the client one or more events before its own response, so
|
|
199
|
+
// only a long-running call is the client's to execute.
|
|
200
|
+
const isClientToolCall = useCallback(
|
|
201
|
+
(toolCall: ToolCallMessagePart) =>
|
|
202
|
+
longRunningToolIdsRef.current.includes(toolCall.toolCallId),
|
|
203
|
+
[],
|
|
204
|
+
);
|
|
205
|
+
|
|
175
206
|
const messageConverter = useMemo(
|
|
176
207
|
() =>
|
|
177
208
|
toolApprovalsKey === ""
|
|
@@ -187,10 +218,17 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
187
218
|
});
|
|
188
219
|
|
|
189
220
|
const threadMessagesRef = useRef(threadMessages);
|
|
190
|
-
|
|
221
|
+
useInsertionEffect(() => {
|
|
222
|
+
threadMessagesRef.current = threadMessages;
|
|
223
|
+
}, [threadMessages]);
|
|
191
224
|
|
|
225
|
+
// Staging assigns adkMessagesRef.current directly, so the effect must key on
|
|
226
|
+
// the committed messages alone; a dep-less publication would clobber the
|
|
227
|
+
// optimistic value on any unrelated commit.
|
|
192
228
|
const adkMessagesRef = useRef(messages);
|
|
193
|
-
|
|
229
|
+
useInsertionEffect(() => {
|
|
230
|
+
adkMessagesRef.current = messages;
|
|
231
|
+
}, [messages]);
|
|
194
232
|
|
|
195
233
|
const stagedMessagesRef = useRef(
|
|
196
234
|
new Map<
|
|
@@ -300,6 +338,7 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
300
338
|
isLoading: isLoadingThread,
|
|
301
339
|
messages: threadMessages,
|
|
302
340
|
unstable_enableToolInvocations: true,
|
|
341
|
+
unstable_isClientToolCall: isClientToolCall,
|
|
303
342
|
setToolStatuses,
|
|
304
343
|
adapters: { attachments, dictation, feedback, speech, voice },
|
|
305
344
|
extras: adkExtras.provide({
|
|
@@ -431,7 +470,12 @@ const useAdkRuntimeImpl = (options: UseAdkRuntimeOptions) => {
|
|
|
431
470
|
},
|
|
432
471
|
onRespondToToolApproval: async (options) => {
|
|
433
472
|
await handleSendMessage(
|
|
434
|
-
[
|
|
473
|
+
[
|
|
474
|
+
toAdkToolConfirmationReply(
|
|
475
|
+
options,
|
|
476
|
+
projectAdkToolApprovals(adkMessagesRef.current).approvals,
|
|
477
|
+
),
|
|
478
|
+
],
|
|
435
479
|
{},
|
|
436
480
|
);
|
|
437
481
|
},
|