Repository Public
1"use client";2import { useCallback, useEffect, useRef, useState } from "react";3import { apiGet } from "@/api/client";4import { ApiError } from "@/api/errors";5import { useEvent } from "@/shell/realtime";6import type { LogLine } from "@/ui";78/**9 * Bounded output of one action: pages through GET /actions/{id}/output and appends `action.output` events.10 * Same approach as the live action view (features/actions/ActionView.tsx), kept here because that hook is private.11 */12export function useActionOutput(id: string, live: boolean) {13 const [lines, setLines] = useState<Map<number, LogLine>>(new Map());14 const [truncated, setTruncated] = useState(false);15 const [error, setError] = useState<ApiError | null>(null);16 const after = useRef(0);17 const running = useRef(false);1819 const add = useCallback((events: { id: number; data: string; stream?: "stdout" | "stderr" | undefined; kind?: string }[]) => {20 if (events.length === 0) return;21 setLines((prev) => {22 const next = new Map(prev);23 for (const e of events) next.set(e.id, { id: e.id, text: e.data, stream: e.stream ?? (e.kind && e.kind !== "output" ? "system" : undefined) });24 return next;25 });26 }, []);2728 const pull = useCallback(async () => {29 if (running.current) return;30 running.current = true;31 try {32 for (let guard = 0; guard < 20; guard++) {33 const page = await apiGet("/actions/{id}/output", { path: { id }, query: { after: after.current, limit: 500 } });34 add(page.items);35 if (page.truncated) setTruncated(true);36 const advanced = page.next_after > after.current;37 after.current = Math.max(after.current, page.next_after);38 if (page.items.length === 0 || !advanced) break;39 }40 setError(null);41 } catch (e) {42 if (e instanceof ApiError) setError(e);43 } finally {44 running.current = false;45 }46 }, [id, add]);4748 useEffect(() => {49 void pull();50 if (!live) return;51 const timer = window.setInterval(() => void pull(), 2500);52 return () => window.clearInterval(timer);53 }, [pull, live]);5455 useEvent("action.output", (e) => {56 if (e.action_id === id) add([{ id: e.event_id, data: e.data, stream: e.stream }]);57 });5859 return { lines: [...lines.values()].sort((a, b) => Number(a.id) - Number(b.id)), truncated, error };60}61