| 735 | } |
| 736 | |
| 737 | function useAgentTranscript(agentRunId: string | null): AgentTranscriptState { |
| 738 | const [state, setState] = useState<AgentTranscriptState>({ |
| 739 | loading: false, |
| 740 | error: null, |
| 741 | cursor: 0, |
| 742 | messages: null, |
| 743 | parts: [], |
| 744 | steps: [], |
| 745 | }); |
| 746 | |
| 747 | useEffect(() => { |
| 748 | let cancelled = false; |
| 749 | if (!agentRunId) { |
| 750 | setState({ loading: false, error: null, cursor: 0, messages: null, parts: [], steps: [] }); |
| 751 | return; |
| 752 | } |
| 753 | |
| 754 | const load = async () => { |
| 755 | setState((prev) => ({ ...prev, loading: true, error: null })); |
| 756 | try { |
| 757 | const headers = await getApiAuthHeaders(); |
| 758 | const response = await fetch(`${API_V1_URL}/agents/${agentRunId}/parts`, { |
| 759 | headers, |
| 760 | }); |
| 761 | if (!response.ok) { |
| 762 | throw new Error(`Failed to load agent trace for ${agentRunId}`); |
| 763 | } |
| 764 | const data = await response.json(); |
| 765 | const parts: AgentTraceChunk[] = Array.isArray(data?.parts) |
| 766 | ? data.parts |
| 767 | .map( |
| 768 | (entry: { |
| 769 | sequence?: number | null; |
| 770 | timestamp?: string | null; |
| 771 | chunk?: UIMessageChunk | null; |
| 772 | }) => { |
| 773 | if (!entry?.chunk) { |
| 774 | return null; |
| 775 | } |
| 776 | return { |
| 777 | sequence: typeof entry.sequence === 'number' ? entry.sequence : 0, |
| 778 | timestamp: |
| 779 | typeof entry.timestamp === 'string' |
| 780 | ? entry.timestamp |
| 781 | : new Date().toISOString(), |
| 782 | chunk: entry.chunk, |
| 783 | }; |
| 784 | }, |
| 785 | ) |
| 786 | .filter((entry: AgentTraceChunk | null): entry is AgentTraceChunk => Boolean(entry)) |
| 787 | : []; |
| 788 | const chunks: UIMessageChunk[] = parts.map((entry) => entry.chunk); |
| 789 | const messages = await chunksToMessages(chunks); |
| 790 | const steps = deriveAgentSteps(parts); |
| 791 | if (!cancelled) { |
| 792 | setState({ |
| 793 | loading: false, |
| 794 | error: null, |