import { useEffect, useId, useRef, useState } from 'react';
import { tr } from '../lib/i18n';
import { deliveryFolder, dirOf, fileAction, fileSize, fileTypeLabel, previewOf, rawUrlOf, rootOf, type ActivityGroup, type Deliverable } from '../lib/deliverables';
import { useChatFolder } from '../lib/chat-folder';
import type { PreviewArtifact } from '../lib/artifacts';
import { draftSize, groupFromDraft } from '../lib/draft-view';
import type { ToolDraft } from '../lib/types';
import { pushToast } from '../lib/store';
import { plainFailureText } from '../lib/plain-errors';
import { FloatingMenu } from './FloatingMenu';
import { CopyMenuItem } from './CopyBtn';
import { Icon } from './ui';
const problem = (title: string, e: unknown) => pushToast('error', tr(title), plainFailureText(e instanceof Error ? e.message : String(e)).message);
/** A line's numbers ("+225 −0") shown as a pair of small figures; the sentence itself stays plain grey. */
export function Plusminus({ added, removed }: { added: number; removed: number }) {
return +{added}−{removed};
}
const showOf = (file: { path: string; name: string }, sessionId: string, onPreview: (a: PreviewArtifact) => void, kind?: string) =>
previewOf(sessionId, file).then(onPreview, e => {
// A file with no preview opens in its own app instead.
if (kind === 'other') return fileAction.open(sessionId, file.path, 'app').catch(err => problem('The file was not opened', err));
return problem('The file has no preview', e);
});
/** One file the assistant made or changed: its type, name and size, and Open (in the file's own app or the browser) with a menu for the other things to do with it, among them Open in sidebar. */
export function FileCard({ file, sessionId, onPreview }: { file: Deliverable; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
const more = useRef(null);
const [menu, setMenu] = useState(false), [busy, setBusy] = useState(false);
const run = async (fn: () => Promise, failed: string) => { setMenu(false); try { await fn(); } catch (e) { problem(failed, e); } };
return
;
}
/** "Edited N files": each with its lines added and removed, and the total under See all. */
export function EditedFiles({ files, sessionId, onPreview }: { files: Deliverable[]; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
const [all, setAll] = useState(false);
const textual = files.filter(f => f.lines !== null);
if (textual.length < 2) return null;
const shown = all ? textual : textual.slice(0, 3);
const added = textual.reduce((n, f) => n + f.added, 0), removed = textual.reduce((n, f) => n + f.removed, 0);
return
{tr('Edited {0} files', [textual.length])}
{shown.map(f => )}
;
}
/**
* A run that made many files (379 after one stopped agent run) as one compact block instead of a card per file: where the result was delivered, the folder the
* chat works in, and the count ("379 files") that opens the full list. The list is closed by default, scrolls inside the block, and every row is a button.
*/
export function FilesSummary({ files, answer, sessionId, onPreview }: { files: Deliverable[]; answer: string; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
const [open, setOpen] = useState(false), id = useId(), folder = useChatFolder(sessionId);
const delivery = deliveryFolder(files, answer);
const rootPath = folder?.path ?? rootOf(files[0]), rootName = folder?.name ?? (rootPath.split(/[\\/]/).filter(Boolean).at(-1) ?? '');
const added = files.reduce((n, f) => n + f.added, 0), removed = files.reduce((n, f) => n + f.removed, 0);
const openFolder = (path: string) => void fileAction.open(sessionId, path, 'app').catch(err => problem('The folder was not opened', err));
const places: { key: string; label: string; name: string; full: string; open: string }[] = [];
if (delivery) places.push({ key: 'delivered', label: 'Delivered to', name: delivery, full: rootPath ? `${rootPath}/${delivery}` : delivery, open: delivery });
if (rootPath) places.push({ key: 'working', label: delivery ? 'Working folder' : 'Delivered to', name: rootName, full: rootPath, open: rootPath });
return
{places.length ?
{places.map(p =>
{tr(p.label)}{p.name}
)}
: null}
{open ?
{files.map(f => { const dir = dirOf(f.path); return
; })}
: null}
;
}
/**
* The saved skills an answer used, as one quiet line under the answer in the same style as the activity line ("Ran 2 commands, read a file"):
* "Used 2 skills: Weekly report, Brand voice"; opened, each skill with its one-line description.
*/
export function SkillsUsed({ skills }: { skills: { name: string; description: string }[] }) {
const [open, setOpen] = useState(false);
if (!skills.length) return null;
const names = skills.map(s => s.name).join(', ');
return
{open ?
{skills.map(s =>
{s.name}{s.description ? {s.description} : null}
)}
: null}
;
}
/** A run of tool use between two pieces of text, as one quiet line: "Ran 2 commands, read monitor.png", with a thumbnail when it touched a picture. */
export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityGroup; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
const [open, setOpen] = useState(false);
const picture = group.files.find(f => f.kind === 'image');
// The host's sentence may end with the numbers ("… +225 −0"): they are drawn as figures instead.
const sentence = group.line.replace(/\s*\+\d+\s*[−-]\s*\d+\s*$/, '');
// While the run is open this is the live step: the host's own words for it when it sends them, else the line it already had.
const live = !group.closed;
return <>
: null}
>;
}
/** The value, at most every `ms` (a file arrives about five times a second; the eye needs two). A cleared value is shown at once. */
function useThrottled(value: T, ms: number, cleared: (v: T) => boolean): T {
const [shown, setShown] = useState(value), last = useRef(0), timer = useRef | undefined>(undefined);
useEffect(() => {
clearTimeout(timer.current);
if (cleared(value)) { setShown(value); return; }
const wait = Math.max(0, last.current + ms - Date.now());
timer.current = setTimeout(() => { last.current = Date.now(); setShown(value); }, wait);
return () => clearTimeout(timer.current);
}, [value, ms]);
return shown;
}
/**
* The files (or commands) the model is writing right now, from `message.drafts`: each is one open activity line with the file's name, its growing size
* and the last lines of its text. It draws nothing while there is nothing being written, and takes the place of the ordinary card when the call is whole.
*/
export function DraftLines({ drafts, sessionId, onPreview }: { drafts: ToolDraft[] | undefined; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
const shown = useThrottled(drafts, 350, v => !v?.length);
if (!drafts?.length || !shown?.length) return null;
return <>{shown.map(d => {
const file = d.target ? d.target.split(/[\\/]/).filter(Boolean).at(-1) : '';
const verb = tr(d.verb ?? (d.scope === 'shell' ? 'Running a command' : 'Writing a file'));
return ;
})}>;
}