|
| 1 | +import { useMemo } from "react"; |
| 2 | +import { useAuiState } from "@assistant-ui/store"; |
| 3 | +import { |
| 4 | + getPartialJsonObjectFieldState, |
| 5 | + getPartialJsonObjectMeta, |
| 6 | +} from "assistant-stream/utils"; |
| 7 | + |
| 8 | +type PropFieldStatus = "streaming" | "complete"; |
| 9 | + |
| 10 | +export type ToolArgsStatus< |
| 11 | + TArgs extends Record<string, unknown> = Record<string, unknown>, |
| 12 | +> = { |
| 13 | + status: "running" | "complete" | "incomplete" | "requires-action"; |
| 14 | + propStatus: Partial<Record<keyof TArgs, PropFieldStatus>>; |
| 15 | +}; |
| 16 | + |
| 17 | +export const useToolArgsStatus = < |
| 18 | + TArgs extends Record<string, unknown> = Record<string, unknown>, |
| 19 | +>(): ToolArgsStatus<TArgs> => { |
| 20 | + const part = useAuiState((s) => s.part); |
| 21 | + |
| 22 | + return useMemo(() => { |
| 23 | + const statusType = part.status.type; |
| 24 | + |
| 25 | + if (part.type !== "tool-call") { |
| 26 | + throw new Error( |
| 27 | + "useToolArgsStatus can only be used inside tool-call message parts", |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + const isStreaming = statusType === "running"; |
| 32 | + const args = part.args as Record<string, unknown>; |
| 33 | + const meta = getPartialJsonObjectMeta(args as Record<symbol, unknown>); |
| 34 | + const propStatus: Partial<Record<string, PropFieldStatus>> = {}; |
| 35 | + |
| 36 | + for (const key of Object.keys(args)) { |
| 37 | + if (meta) { |
| 38 | + const fieldState = getPartialJsonObjectFieldState(args, [key]); |
| 39 | + propStatus[key] = |
| 40 | + fieldState === "complete" || !isStreaming ? "complete" : "streaming"; |
| 41 | + } else { |
| 42 | + propStatus[key] = isStreaming ? "streaming" : "complete"; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return { |
| 47 | + status: statusType, |
| 48 | + propStatus: propStatus as Partial<Record<keyof TArgs, PropFieldStatus>>, |
| 49 | + }; |
| 50 | + }, [part]); |
| 51 | +}; |
0 commit comments