import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import type { ActivityEvent, ApiMode, DeskHistory, FileNode, FilePreviewData, LiveState, ReasoningEffort, Session, SubagentRecord, WorkerEvent } from "../types"; import { DESK_PANEL_Z_BASE } from "../floatingPanelStack"; import { usePanelDrag } from "../usePanelDrag"; import { centeredAnchorToDeskOffset, defaultBelowDeskOffset, deskOffsetFromViewport, useDeskAnchoredRowPosition, rowToViewport, viewportToRow, type DeskOffset, } from "../deskPanelAnchor"; import { scrollContainerToBottom, scrollIntoContainer } from "../scrollContainer"; import { useTeamRowPanel } from "../TeamRowPanelContext"; import { usePanelResize, type PanelSize } from "../usePanelResize"; import { PanelResizeHandle } from "./PanelResizeHandle"; import { SubagentDesk, applySubagentLive, groupSubagentsIntoRounds } from "./SubagentDesk"; import { api } from "../api/client"; import { ActivityFeed } from "./ActivityFeed"; import { FileExplorer } from "./FileExplorer"; import { InspectPanel } from "./InspectPanel"; import { ActivityOverview } from "./ActivityOverview"; import { MarkdownView } from "./FilePreview"; import { deskDisplayTitle } from "../taskDisplay"; import { toolIcon } from "../toolIcons"; const _TEXT_EXTS = new Set([ "txt","md","py","js","ts","jsx","tsx","json","csv","yaml","yml", "html","css","xml","sh","bash","sql","r","toml","ini","cfg","log", "rst","java","c","cpp","h","hpp","go","rs","rb","php","swift","kt", ]); const _IMAGE_EXTS = new Set(["jpg","jpeg","png","gif","webp","svg"]); // Heartbeat auto-continue is still unreliable on open-ended/looping tasks // (the completion judge stops perpetual goals, the 25-resume cap ends loops, // and errored turns halt it). Keep the UI control hidden until that's fixed. // The backend remains opt-in and OFF by default, so this is dead code, not a risk. const AUTO_CONTINUE_UI_ENABLED = false; // Floating desk panel (opens when you click the desk "monitor"). Anchored below the // desk in viewport space (portaled to document.body). Double-click / ⊞ maximizes to // nearly full screen instead of squeezing into the team row. const PANEL_WIDTH = 480; // The Inspect tab shows a tool form + a wide command/output area, so it gets a // roomier panel than the default desk width (still clamps to the viewport). const INSPECT_PANEL_WIDTH = 640; const PANEL_MIN_WIDTH = 320; const PANEL_MIN_HEIGHT = 340; const PANEL_PREF_HEIGHT = 560; const PANEL_VIEWPORT_PAD = 16; function computeFloatingPanelLayout(anchorTop: number, rowHeight: number) { // Prefer up to one team-row tall; may extend past the row bottom (overflow visible). const height = Math.max(PANEL_MIN_HEIGHT, Math.min(PANEL_PREF_HEIGHT, rowHeight)); return { top: anchorTop, height }; } /** Maximized desk panel — nearly full viewport (not the team row). */ function computeMaximizedPanelLayout(viewportW: number, viewportH: number) { const pad = PANEL_VIEWPORT_PAD; return { top: pad, left: pad, width: viewportW - pad * 2, height: viewportH - pad * 2, }; } async function _processFiles(files: File[]): Promise<{ text: string; images: { name: string; data: string; url: string }[] }> { const parts: string[] = []; const images: { name: string; data: string; url: string }[] = []; for (const file of files) { const ext = (file.name.split(".").pop() ?? "").toLowerCase(); if (_IMAGE_EXTS.has(ext) || file.type.startsWith("image/")) { const dataUrl = await new Promise((res) => { const fr = new FileReader(); fr.onload = (e) => res(e.target!.result as string); fr.readAsDataURL(file); }); images.push({ name: file.name, data: dataUrl, url: dataUrl }); } else if (_TEXT_EXTS.has(ext) || file.type.startsWith("text/")) { const content = await new Promise((res) => { const fr = new FileReader(); fr.onload = (e) => res(e.target!.result as string); fr.readAsText(file); }); parts.push(`\`\`\`${ext}\n# ${file.name}\n${content.slice(0, 12000)}\n\`\`\``); } else { parts.push(`[Attached file: ${file.name}]`); } } return { text: parts.join("\n"), images }; } interface Props { session: Session; scene?: string; isActive: boolean; searchMatch?: boolean; index: number; autoExpand?: boolean; /** Screen coords for the panel top-center when auto-opening after the first prompt. */ openAnchor?: { top: number; left: number } | null; workspacePath?: string; taskContent?: string; taskImages?: { name: string; url: string }[]; verbose?: boolean; reasoningEffort?: ReasoningEffort; apiMode?: ApiMode; onPreview: (data: FilePreviewData) => void; panelZIndex?: number; onPanelActivate?: () => void; onSelect: () => void; onFocus?: () => void; onOpen?: () => void; /** Fired whenever the panel expands/collapses, so the parent can keep the * desk's hovering agent visible for as long as its panel is open. */ onOpenChange?: (open: boolean) => void; deskFocused?: boolean; onClose: () => void; /** Fired once after autoExpand opens the panel (so the parent can clear justStartedId). */ onAutoExpanded?: () => void; onActivity?: () => void; onAskManager?: () => void; onInterrupt?: (id: string) => void; // Resolved profile for the desk's "profile · model" status line. profileLabel?: string; profileColor?: string; profileModel?: string; } type DeskTab = "activity" | "tasks" | "files" | "console"; // Sub-views inside the merged Console tab: the clean "human's-eye" shell I/O, the // full worker debug stream (tool calls, args, results, reasoning, logs), and the // Inspect tool form for ad-hoc command/output probing. type ConsoleView = "agent" | "debug" | "inspect"; function statusColor(session: Session): string { if (session.is_running) return "var(--green)"; if (session.ended_at) return "var(--text-dim)"; return "var(--yellow)"; } function statusLabel(session: Session): string { if (session.is_running) return "active"; if (session.ended_at) return "done"; return "idle"; } // Actual execution span, not wall-clock since spawn: start at the first command, // and for an idle desk stop at its last activity (so it freezes instead of // counting overnight hours). A live desk keeps ticking to now. function elapsedLabel(session: Session): string { const startIso = session.first_activity_at || session.started_at; if (!startIso) return ""; const start = new Date(startIso).getTime(); let end: number; if (session.is_running) { end = Date.now(); } else { const endIso = session.last_activity_at || session.ended_at; end = endIso ? new Date(endIso).getTime() : Date.now(); } const mins = Math.round((end - start) / 60000); if (mins < 1) return "<1m"; if (mins < 60) return `${mins}m`; return `${Math.floor(mins / 60)}h ${mins % 60}m`; } function stripAnsi(s: string): string { return s.replace(/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, ""); } // Apply terminal carriage-return semantics: progress bars (e.g. dataset/pip // downloads) emit "0.3%\r0.7%\r…" expecting each value to overwrite the line in // place. We capture the raw stream, so collapse each \r-run to its final state // instead of printing every step on its own line. function applyCarriageReturns(s: string): string { if (!s.includes("\r")) return s; return s.split("\n").map((line) => { if (!line.includes("\r")) return line; let out = ""; for (const seg of line.split("\r")) out = seg + out.slice(seg.length); return out; }).join("\n"); } // Escape HTML before injecting console output via dangerouslySetInnerHTML. // Agent terminal output is untrusted (it can echo file contents, web results, // etc.), so raw markup like must not reach the DOM. Run this // BEFORE the `$ command` colorize regex, which intentionally adds markup. function escapeHtml(s: string): string { return s.replace(/[&<>"']/g, (c) => c === "&" ? "&" : c === "<" ? "<" : c === ">" ? ">" : c === '"' ? """ : "'"); } function TaskFileEditor({ sessionId, onSaved }: { sessionId: string; onSaved?: () => void }) { const [content, setContent] = useState(null); const [draft, setDraft] = useState(""); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(false); useEffect(() => { api.sessions.taskFile.get(sessionId) .then((r) => { setContent(r.content); setDraft(r.content); }) .catch(() => { setContent(""); setDraft(""); }); }, [sessionId]); async function save() { if (saving) return; setSaving(true); try { await api.sessions.taskFile.save(sessionId, draft); setContent(draft); setSaved(true); setTimeout(() => setSaved(false), 1800); onSaved?.(); } catch { // workspace not found for older sessions — silently ignore } finally { setSaving(false); } } // content===null means still loading; empty string means no workspace (old session) if (content === null) return (
Loading…
); const dirty = draft !== content; return (
TASK.md {(dirty || saved) && ( )}