diff --git a/apps/web/src/components/model.tsx b/apps/web/src/components/model.tsx index 8867b655..a58d05d2 100644 --- a/apps/web/src/components/model.tsx +++ b/apps/web/src/components/model.tsx @@ -91,6 +91,26 @@ const lookup =

(providers: ReadonlyArray

, ref: Model return provider === undefined || model === undefined ? undefined : { provider, model }; }; +/** Display name of `value` (or the settings default when `value` is absent), once `models.list` has loaded. */ +export function useModelName(hostDir: string | undefined, value: ModelRef | undefined): string | undefined { + const result = useAtomValue(modelsAtom(hostDir)); + const list = AsyncResult.isSuccess(result) ? result.value : undefined; + const current = value ?? list?.default; + if (current === undefined) return undefined; + if (list !== undefined) { + const found = lookup(list.providers, current); + if (found !== undefined) return found.model.name; + if ( + current.provider === list.default.provider && + current.id === list.default.id && + list.default.name !== undefined + ) { + return list.default.name; + } + } + return current.id; +} + /** * Picks the model a new session uses: providers down a rail on the left, their models on the * right, and a search across all of them. `value` undefined means settings decide; the trigger diff --git a/apps/web/src/landing/empty.tsx b/apps/web/src/landing/empty.tsx index dc62698d..7e6abe36 100644 --- a/apps/web/src/landing/empty.tsx +++ b/apps/web/src/landing/empty.tsx @@ -1,10 +1,74 @@ import type { ReactNode } from "react"; +const GRID_W = 16; + +const TERMINAL = [ + "..############..", + ".##..........##.", + ".#............#.", + ".#..#.........#.", + ".#...#...###..#.", + ".#..#....###..#.", + ".#............#.", + ".#............#.", + ".##..........##.", + "..############..", + "......####......", + "....########....", +] as const; + +const GLOW = [ + "#.#..........#.#", + "................", + "#..............#", + "................", + "................", + "................", + "................", + "#..............#", + "................", + "#.#..........#.#", + "................", + "..#..........#..", +] as const; + +/** Merges each row's filled runs into one rect so the path stays short. */ +function spritePath(rows: readonly string[]) { + let path = ""; + rows.forEach((row, y) => { + let x = 0; + while (x < row.length) { + if (row[x] !== "#") { + x += 1; + continue; + } + let run = 1; + while (row[x + run] === "#") run += 1; + path += `M${x} ${y}h${run}v1h-${run}z`; + x += run; + } + }); + return path; +} + +const TERMINAL_PATH = spritePath(TERMINAL); +const GLOW_PATH = spritePath(GLOW); + /** The sidebar's message when it has nothing to list: a few quiet lines, centered, and what to do next. */ export function Empty({ children }: { children: ReactNode }) { return ( -

- {children} +
+
{children}
+ + + +
); } diff --git a/apps/web/src/landing/sidebar.tsx b/apps/web/src/landing/sidebar.tsx index 25da8b54..34fda496 100644 --- a/apps/web/src/landing/sidebar.tsx +++ b/apps/web/src/landing/sidebar.tsx @@ -22,6 +22,7 @@ import { useOpenElsewhere } from "../wm/open"; import { ago } from "../widgets/time"; import { Monogram } from "@/components/monogram"; import { OpenProviderSettings } from "@/components/offline"; +import { ProviderIcon } from "@/components/provider"; import { problemAtom } from "../kernel/servers"; import { Empty, EmptyAction } from "./empty"; import { placeAtom, usePickFolder } from "./place"; @@ -145,16 +146,36 @@ export function SessionsSidebar() { type="button" title={`${session.project.path}\n${isMac ? "⌘" : "Ctrl"}-click opens it in a new frame\n⇧-click opens it in a new workspace`} aria-current={sessionAddress(session.id) === current ? "true" : undefined} - className="block w-full rounded-md px-2.5 py-2 text-left outline-none hover:bg-selection-subtle focus-visible:ring-2 focus-visible:ring-ring aria-current:bg-selection" + className="group relative flex w-full flex-col rounded-md px-2 py-1.5 text-left text-ink/80 outline-none hover:bg-selection-subtle hover:text-ink focus-visible:ring-2 focus-visible:ring-ring aria-current:bg-selection aria-current:text-ink" onClick={(event) => open(session, event)} onAuxClick={(event) => open(session, event)} > -
- - {session.project.name} - {ago(session.updated)} -
-
{session.title}
+ + + {session.title} + + + {ago(session.updated)} + + + + + + {session.project.name} + + {session.model !== undefined && ( + + + {session.model.id} + + + + )} + ))} diff --git a/apps/web/src/style.css b/apps/web/src/style.css index 9ff62d77..bc3cde1f 100644 --- a/apps/web/src/style.css +++ b/apps/web/src/style.css @@ -52,6 +52,7 @@ --cw-warning: light-dark(#d97706, #fbbf24); --cw-success: light-dark(#16a34a, #4ade80); --cw-info: light-dark(#2563eb, #60a5fa); + --cw-link: light-dark(hsl(211 92% 40%), #7dd3fc); --cw-highlight: light-dark(rgb(255 255 255 / 0.9), color-mix(in oklab, var(--t-text) 9%, transparent)); --cw-drop-shadow: color-mix(in oklab, var(--t-text) 20%, transparent); --cw-shadow-near: light-dark(rgb(0 0 0 / 0.06), rgb(0 0 0 / 0.22)); @@ -103,6 +104,7 @@ --color-ink-muted: var(--cw-ink-muted); --color-brand: var(--cw-brand); --color-brand-ink: var(--cw-brand-ink); + --color-link: var(--cw-link); /* shadcn/ui's color names, mapped onto the --cw-* contract. */ --color-background: var(--cw-frame); @@ -271,6 +273,267 @@ --transcript-top: transparent; } +/* After a send, the live turn fills the transcript viewport so the prompt sits + at the top, then follows the reply when it outgrows the viewport. */ +.transcript-turn-anchor { + min-height: var(--transcript-viewport, 0px); +} + +/* While a sent prompt rises into place, the rest of its turn waits for it. */ +.transcript-turn[data-prompt-rise="rising"] > [data-assistant-reply] { + opacity: 0; +} + +.transcript-turn[data-prompt-rise="revealing"] > [data-assistant-reply] { + animation: prompt-turn-reveal 320ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +@keyframes prompt-turn-reveal { + from { + opacity: 0; + transform: translateY(10px); + } + to { + opacity: 1; + transform: none; + } +} + +/* Touch layouts keep actions in flow. Desktop places them in the existing + turn gap so revealing the controls never shifts or over-spaces the chat. */ +.user-message-actions { + width: fit-content; +} + +@media (hover: hover) and (pointer: fine) { + .user-message-hover-zone { + position: relative; + isolation: isolate; + } + + .user-message-actions { + position: absolute; + top: 100%; + right: 0; + z-index: 1; + opacity: 0; + transition: opacity 120ms ease; + } + + .user-message-row:hover .user-message-actions, + .user-message-row:focus-within .user-message-actions { + opacity: 1; + } +} + +/* The connector: a line dropping out of the chevron and curving into each + step the fold holds, so opened work reads as hanging off that line. + 23px is the chevron's centre (16px row padding + half a 14px icon). */ +.zen-fold-drop, +.zen-fold-rail { + position: relative; + --zen-rail: color-mix(in srgb, var(--cw-ink) 14%, var(--cw-frame)); +} + +.zen-fold-drop::after { + content: ""; + position: absolute; + left: 23px; + top: 22px; + bottom: -4px; + width: 1px; + background: var(--zen-rail); +} + +.zen-fold-rail::before { + content: ""; + position: absolute; + left: 23px; + top: 0; + bottom: 0; + width: 1px; + background: var(--zen-rail); +} + +.zen-fold-tail::before { + bottom: auto; + height: 7px; +} + +.zen-fold-rail::after { + content: ""; + position: absolute; + left: 23px; + top: 6px; + width: 8px; + height: 8px; + border-left: 1px solid var(--zen-rail); + border-bottom: 1px solid var(--zen-rail); + border-bottom-left-radius: 8px; +} + +.zen-phase-body { + display: grid; + grid-template-rows: 1fr; + transition: + grid-template-rows 320ms cubic-bezier(0.22, 1, 0.36, 1), + opacity 220ms ease; +} + +.zen-phase-body[data-open="false"] { + grid-template-rows: 0fr; + opacity: 0; +} + +.zen-phase-body > * { + min-height: 0; + overflow: hidden; +} + +/* Live work stays in a bounded scrolling window so a long tool run never pushes + the turn off screen; settling collapses from this window without flashing full height. */ +.zen-phase-body > .zen-phase-live { + max-height: min(17.5rem, 45vh); +} + +.zen-phase-body[data-open="true"] > .zen-phase-live { + overflow: auto; + overscroll-behavior: contain; + overflow-anchor: none; + scrollbar-width: none; +} + +.zen-phase-body > .zen-phase-live::-webkit-scrollbar { + display: none; +} + +@property --zen-phase-fade-top { + syntax: ""; + inherits: false; + initial-value: 0px; +} + +@property --zen-phase-fade-bottom { + syntax: ""; + inherits: false; + initial-value: 0px; +} + +.zen-phase-body[data-open="true"] > .zen-phase-live { + --zen-phase-mask: linear-gradient( + to bottom, + transparent, + #000 var(--zen-phase-fade-top), + #000 calc(100% - var(--zen-phase-fade-bottom)), + transparent + ); + -webkit-mask-image: var(--zen-phase-mask); + mask-image: var(--zen-phase-mask); + transition: + --zen-phase-fade-top 160ms ease-out, + --zen-phase-fade-bottom 160ms ease-out; +} + +.zen-phase-live[data-fade-top="true"] { + --zen-phase-fade-top: 1.5rem; +} + +.zen-phase-live[data-fade-bottom="true"] { + --zen-phase-fade-bottom: 2rem; +} + +@keyframes zen-thinking-pulse { + 0%, + 100% { + opacity: 0.35; + } + 50% { + opacity: 0.9; + } +} + +.zen-thinking-pulse { + animation: zen-thinking-pulse 1.8s ease-in-out infinite; +} + +@keyframes shimmer-text { + 0% { + background-position: 100% center; + } + 100% { + background-position: 0% center; + } +} + +.shimmer-text { + --spread: 24px; + background-image: + linear-gradient( + 90deg, + transparent calc(50% - var(--spread)), + var(--cw-ink) 50%, + transparent calc(50% + var(--spread)) + ), + linear-gradient( + color-mix(in srgb, var(--cw-ink) 45%, transparent), + color-mix(in srgb, var(--cw-ink) 45%, transparent) + ); + background-size: + 250% 100%, + auto; + background-repeat: no-repeat, padding-box; + background-clip: text; + -webkit-background-clip: text; + color: transparent; + animation: shimmer-text 1.6s linear infinite; +} + +@keyframes zen-spin { + to { + transform: rotate(360deg); + } +} + +.zen-tool-spin { + animation: zen-spin 3.6s linear infinite; +} + +.agent-markdown p, +.agent-markdown li { + color: color-mix(in srgb, var(--cw-ink) 78%, transparent); +} + +.agent-markdown p strong, +.agent-markdown p em, +.agent-markdown li strong, +.agent-markdown li em { + color: var(--cw-ink); +} + +.agent-reasoning.agent-markdown p, +.agent-reasoning.agent-markdown li { + color: color-mix(in srgb, var(--cw-ink) 48%, transparent); +} + +.agent-reasoning.agent-markdown p strong, +.agent-reasoning.agent-markdown p em, +.agent-reasoning.agent-markdown li strong, +.agent-reasoning.agent-markdown li em { + color: color-mix(in srgb, var(--cw-ink) 62%, transparent); +} + +.zen-fold-prose .agent-markdown p, +.zen-fold-prose .agent-markdown li { + color: color-mix(in srgb, var(--cw-ink) 65%, transparent); +} + +.zen-fold-prose .agent-markdown p strong, +.zen-fold-prose .agent-markdown p em, +.zen-fold-prose .agent-markdown li strong, +.zen-fold-prose .agent-markdown li em { + color: color-mix(in srgb, var(--cw-ink) 80%, transparent); +} + /* Only soften edges that have more settings content beyond them. */ .settings-scroll { mask-image: linear-gradient( diff --git a/apps/web/src/widgets/session/composer.tsx b/apps/web/src/widgets/session/composer.tsx index 42c53784..cb5f0dac 100644 --- a/apps/web/src/widgets/session/composer.tsx +++ b/apps/web/src/widgets/session/composer.tsx @@ -1,9 +1,9 @@ import { useBus, useKv } from "@codeworksh/widget/view"; import { Option, Schema } from "effect"; -import { Reply, Square } from "lucide-react"; +import { Square } from "lucide-react"; import { useEffect, useRef, useState } from "react"; -import { Composer, ComposerHeader, ComposerSubmit, ComposerButton, type Submit } from "@/components/composer"; +import { Composer, ComposerButton, ComposerSubmit, type Submit } from "@/components/composer"; import { ModelPicker, type ModelRef, ThinkingPicker } from "@/components/model"; import type { Delivery, ThinkingLevel } from "@codeworksh/widget/codework"; import { type Info, Json, type ThreadRef, topics } from "./schema"; @@ -45,64 +45,7 @@ export function SessionComposer({ /** A queued prompt taken back: its text goes above the draft, once per `key`. */ readonly restored?: { readonly text: string; readonly key: number } | undefined; }) { - const root = useRef(null); const input = useRef(null); - const [expanded, setExpanded] = useState(false); - const expand = () => setExpanded(true); - const collapse = () => { - input.current?.blur(); - setExpanded(false); - }; - useEffect(() => { - if (expanded) input.current?.focus(); - }, [expanded]); - useEffect(() => { - const onKeyDown = (event: KeyboardEvent) => { - if ( - event.key === "Escape" && - expanded && - !event.defaultPrevented && - root.current?.closest("article[data-focused='true']") && - !Array.from(document.querySelectorAll("[role='dialog'], [role='menu']")).some( - (element) => element.getClientRects().length > 0, - ) - ) { - event.preventDefault(); - input.current?.blur(); - setExpanded(false); - return; - } - if ( - event.defaultPrevented || - event.repeat || - event.isComposing || - event.metaKey || - event.ctrlKey || - event.altKey || - event.shiftKey || - event.key.toLowerCase() !== "r" - ) - return; - const target = event.target; - if ( - target instanceof HTMLElement && - (target.isContentEditable || target.closest("input, textarea, select, [role='dialog'], [role='menu']")) - ) - return; - if ( - root.current?.closest("article[data-focused='true']") === null || - !root.current?.getClientRects().length || - window.getSelection()?.toString() - ) - return; - event.preventDefault(); - setExpanded(true); - }; - window.addEventListener("keydown", onKeyDown); - return () => { - window.removeEventListener("keydown", onKeyDown); - }; - }, [expanded]); const bus = useBus(); const kv = useKv(); const [text, setText] = useState(""); @@ -131,7 +74,7 @@ export function SessionComposer({ useEffect(() => { if (restored === undefined) return; setText((current) => (current.trim() === "" ? restored.text : `${restored.text}\n\n${current}`)); - setExpanded(true); + input.current?.focus(); }, [restored]); // Saved only once loaded, so the empty initial text never overwrites a stored draft. @@ -181,68 +124,37 @@ export function SessionComposer({ const empty = text.trim() === ""; return ( -
{ - if (expanded && event.key === "Escape" && !event.defaultPrevented) { - event.preventDefault(); - event.stopPropagation(); - collapse(); - } - }} - > - {!expanded ? ( - - ) : ( - } - - value={text} - onChange={setText} - onSubmit={(submit) => void send(submit)} - placeholder={running ? "Steer the agent, or queue a follow-up" : "Ask for changes or send a follow-up"} - controls={ - <> - configure({ model: next })} - /> - configure({ thinkingLevel: level })} - /> - - } - actions={ - <> - {running && ( - void ask(topics.interrupt, { ...thread })}> - - - )} - - - } - /> - )} -
+ void send(submit)} + placeholder={running ? "Steer the agent, or queue a follow-up…" : "Ask for changes or send a follow-up…"} + controls={ + <> + configure({ model: next })} /> + configure({ thinkingLevel: level })} + /> + + } + actions={ + <> + {running && ( + void ask(topics.interrupt, { ...thread })}> + + + )} + + + } + /> ); } diff --git a/apps/web/src/widgets/session/markdown.tsx b/apps/web/src/widgets/session/markdown.tsx index 1b203566..9f6f0e6e 100644 --- a/apps/web/src/widgets/session/markdown.tsx +++ b/apps/web/src/widgets/session/markdown.tsx @@ -50,7 +50,7 @@ function CopyButton({ text }: { readonly text: string }) { type="button" aria-label={copied ? "Copied" : "Copy code"} title="Copy code" - className="press grid size-6 place-items-center rounded-md text-ink-muted hover:bg-ink/8 hover:text-ink" + className="grid size-6 place-items-center rounded-md text-ink-muted hover:bg-ink/10 hover:text-ink press" onClick={() => void navigator.clipboard.writeText(text).then(() => setCopied(true))} > @@ -66,9 +66,9 @@ function CodeBlock(props: ComponentProps<"pre"> & ExtraProps) { const highlighted = useHighlight(block?.code ?? "", language, theme); if (block === undefined) return
{props.children}
; return ( -
-
- {block.language ?? "text"} +
+
+ {block.language ?? "text"}
@@ -78,37 +78,38 @@ function CodeBlock(props: ComponentProps<"pre"> & ExtraProps) {
 	);
 }
 
-const preClass = "overflow-x-auto px-3 py-2 font-mono text-code";
-const Table = styled("table", "border-collapse text-body");
+const preClass = "overflow-x-auto px-3 py-2.5 font-mono text-xs leading-5 text-ink";
+const Table = styled("table", "w-full border-collapse text-xs");
 
 // GitHub-flavoured markdown at reading size.
 const components: Components = {
-	p: styled("p", "my-2 first:mt-0 last:mb-0"),
-	ul: styled("ul", "my-2 list-disc pl-5"),
-	ol: styled("ol", "my-2 list-decimal pl-5"),
+	p: styled("p", "my-3 first:mt-0 last:mb-0"),
+	ul: styled("ul", "my-2 list-disc pl-6"),
+	ol: styled("ol", "my-2 list-decimal pl-6"),
 	li: styled("li", "my-0.5"),
-	h1: styled("h1", "mt-4 mb-2 text-[22px] font-semibold tracking-tight"),
-	h2: styled("h2", "mt-4 mb-2 text-lg font-semibold tracking-tight"),
-	h3: styled("h3", "mt-3 mb-1.5 text-2xs font-semibold tracking-[0.08em] uppercase"),
+	h1: styled("h1", "mt-5 mb-2 text-xl font-semibold tracking-tight text-ink first:mt-0"),
+	h2: styled("h2", "mt-4 mb-2 text-lg font-semibold tracking-tight text-ink first:mt-0"),
+	h3: styled("h3", "mt-3 mb-1.5 text-2xs font-semibold tracking-wider text-ink uppercase first:mt-0"),
 	strong: styled("strong", "font-semibold text-ink"),
-	blockquote: styled("blockquote", "my-2 border-l-2 border-edge pl-3 text-ink-muted"),
+	blockquote: styled("blockquote", "my-3 border-l-4 border-ink/20 pl-4 text-ink-muted"),
+	hr: styled("hr", "my-5 border-0 border-t border-ink/10"),
 	pre: CodeBlock,
 	// Inline code reads as a small chip; inside a fence the block renders the text itself.
-	code: styled("code", "rounded-md border border-edge bg-ink/5 px-1.5 py-px font-mono text-xs text-ink"),
-	th: styled("th", "border border-edge px-2 py-1 text-left font-semibold"),
-	td: styled("td", "border border-edge px-2 py-1"),
+	code: styled("code", "rounded-sm bg-ink/8 px-1.5 py-0.5 font-mono text-xs text-ink"),
+	th: styled("th", "border-b border-ink/10 px-2.5 py-2 text-left font-semibold text-ink"),
+	td: styled("td", "border-t border-ink/5 px-2.5 py-2 align-top"),
 	a: (props) => {
 		const rest: Record = { ...props };
 		delete rest.node;
 		return createElement("a", {
 			...rest,
-			className: "text-brand underline underline-offset-2",
+			className: "text-link hover:underline",
 			target: "_blank",
 			rel: "noreferrer",
 		});
 	},
 	table: (props) => (
-		
+
), @@ -124,16 +125,20 @@ const plugins = [remarkGfm]; export const Markdown = memo(function Markdown({ text, streaming = false, + className, }: { readonly text: string; readonly streaming?: boolean; + readonly className?: string; }) { const incremental = useMemo(() => incrementalMarkdown(), []); const fenced = streaming && /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); const remarkPlugins = useMemo(() => (fenced ? [remarkGfm, incremental] : plugins), [fenced, incremental]); return ( - - {text} - +
+ + {text} + +
); }); diff --git a/apps/web/src/widgets/session/message.tsx b/apps/web/src/widgets/session/message.tsx index 774a530c..8bdeaf57 100644 --- a/apps/web/src/widgets/session/message.tsx +++ b/apps/web/src/widgets/session/message.tsx @@ -1,43 +1,116 @@ -import type { ReactNode } from "react"; +import { Check, Copy } from "lucide-react"; +import { type ReactNode, useEffect, useState } from "react"; -import { ago } from "../time"; +/** Wall-clock stamp for a message or finished turn, in the reader's own locale. */ +function clockTime(epochMs: number) { + return new Date(epochMs).toLocaleTimeString(undefined, { + hour: "numeric", + minute: "2-digit", + }); +} + +function CopyButton({ text, label }: { readonly text: string; readonly label: string }) { + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) return; + const timer = setTimeout(() => setCopied(false), 2000); + return () => clearTimeout(timer); + }, [copied]); + const Icon = copied ? Check : Copy; + return ( + + ); +} -/** Both speakers share one reading edge; a quiet tint distinguishes the user's messages. */ +/** + * A user message sits in a right-aligned bubble with its actions and timestamp tucked beneath; an + * assistant reply flows directly down the reading column and signs off with its copy action and time. + */ export function Message({ role, + promptId, at, + ended, + copyText, children, }: { readonly role: "user" | "assistant"; + readonly promptId?: string | undefined; readonly at: number | undefined; + readonly ended?: number | undefined; + readonly copyText?: string | undefined; readonly children: ReactNode; }) { - const user = role === "user"; - return ( -
-
- {user ? "U" : "A"} -
-
-
- {user ? "You" : "Assistant"} - {at !== undefined && ( - +
+
+ {children} +
+ {(hasCopy || at !== undefined) && ( +
+ {hasCopy && } + {at !== undefined && ( + + )} +
+ )} +
+
+ ); + } + + const hasCopy = copyText !== undefined && copyText !== ""; + return ( +
+ {children} + {ended !== undefined && ( +
+ + {hasCopy ? ( + + ) : ( + + )} + + {ended > 0 && ( + + + + )} - -
{children}
-
+ + )}
); } diff --git a/apps/web/src/widgets/session/queue.tsx b/apps/web/src/widgets/session/queue.tsx index b97e842e..96a903bb 100644 --- a/apps/web/src/widgets/session/queue.tsx +++ b/apps/web/src/widgets/session/queue.tsx @@ -96,11 +96,11 @@ export function Queue({ const many = queued.length > 4; return ( -
- {queued.length > 3 &&

{queued.length} queued

} +
+ {queued.length > 3 &&

{queued.length} queued

}
    {queued.map((prompt) => { const steer = prompt.delivery === "steer"; @@ -116,7 +116,7 @@ export function Queue({ return (
  1. {steer ? "Steer" : "Follow-up"} @@ -137,10 +137,10 @@ export function Queue({ } }} onBlur={() => save(prompt, draft)} - className="h-5 min-w-0 flex-1 rounded-md border border-edge bg-frame-top px-1.5 text-ink outline-none focus-visible:border-edge-focus" + className="h-6 min-w-0 flex-1 rounded-md border border-ink/15 bg-ink/5 px-1.5 text-ink outline-none focus-visible:border-edge-focus" /> ) : ( - + {prompt.text} )} @@ -199,9 +199,9 @@ function Action({ title={label} disabled={disabled} onClick={onClick} - className={`grid size-5 place-items-center rounded-md text-ink-muted transition-colors outline-none hover:bg-ink/8 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none ${danger ? "hover:text-destructive" : "hover:text-ink"}`} + className={`grid size-6 shrink-0 place-items-center rounded-md text-ink-muted transition-colors outline-none hover:bg-ink/8 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none ${danger ? "hover:text-destructive" : "hover:text-ink"}`} > - + ); } diff --git a/apps/web/src/widgets/session/view.tsx b/apps/web/src/widgets/session/view.tsx index 039d8849..9a5c1cdd 100644 --- a/apps/web/src/widgets/session/view.tsx +++ b/apps/web/src/widgets/session/view.tsx @@ -1,14 +1,14 @@ import { useAtomRefresh } from "@effect/atom-react"; -import { LegendList, type MaintainScrollAtEndOptions } from "@legendapp/list/react"; import type { HistoryEntry, Part, QueuedPrompt, ToolCall } from "@codeworksh/widget/codework"; import { useBus, useEvents, useFrame, type WidgetProps } from "@codeworksh/widget/view"; import { Option, Schema } from "effect"; -import { Brain, ChevronDown, ChevronRight, CircleAlert, Terminal, Wrench } from "lucide-react"; -import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { ChevronRight, CircleDashed, X } from "lucide-react"; +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import brand from "../../assets/codework.png"; import { ComposerNotice, type Notice } from "@/components/banner"; import { Monogram } from "@/components/monogram"; -import { useModelsNotice } from "@/components/model"; +import { useModelName, useModelsNotice } from "@/components/model"; import { threadRef } from "./address"; import { SessionComposer } from "./composer"; import { Markdown } from "./markdown"; @@ -158,23 +158,27 @@ function useConversation(thread: ThreadRef) { }); const oldest = state.status === "ready" && state.more ? state.messages[0]?.id : undefined; - const loadOlder = useCallback(() => { - if (oldest === undefined || paging.current) return; - paging.current = true; - void page(oldest) - .then((window) => { - if (window?._tag !== "Window") return; - setState((current) => { - if (current.status !== "ready") return current; - const known = new Set(current.messages.map((message) => message.id)); - const older = window.messages.filter((message) => !known.has(message.id)); - return { ...current, messages: [...older, ...current.messages], more: window.more }; + const loadOlder = useCallback( + (beforePrepend: () => void) => { + if (oldest === undefined || paging.current) return; + paging.current = true; + void page(oldest) + .then((window) => { + if (window?._tag !== "Window") return; + beforePrepend(); + setState((current) => { + if (current.status !== "ready") return current; + const known = new Set(current.messages.map((message) => message.id)); + const older = window.messages.filter((message) => !known.has(message.id)); + return { ...current, messages: [...older, ...current.messages], more: window.more }; + }); + }) + .finally(() => { + paging.current = false; }); - }) - .finally(() => { - paging.current = false; - }); - }, [oldest, page]); + }, + [oldest, page], + ); return { state, loadOlder }; } @@ -224,11 +228,16 @@ function Conversation({ thread, instanceId }: { readonly thread: ThreadRef; read const surface = useRef(null); const composer = useRef(null); useEffect(() => { + const root = surface.current; const element = composer.current; - if (element === null) return; - const observer = new ResizeObserver(() => { - surface.current?.style.setProperty("--composer-height", `${element.getBoundingClientRect().height}px`); - }); + if (root === null || element === null) return; + const sync = () => { + root.style.setProperty("--transcript-height", `${root.getBoundingClientRect().height}px`); + root.style.setProperty("--composer-height", `${element.getBoundingClientRect().height}px`); + }; + sync(); + const observer = new ResizeObserver(sync); + observer.observe(root); observer.observe(element); return () => observer.disconnect(); }, [state.status]); @@ -280,21 +289,63 @@ function Conversation({ thread, instanceId }: { readonly thread: ThreadRef; read ); } -// New turns, growing replies and a taller composer (queued prompts above it) keep the list at its -// end while the reader is there; a reader scrolled up stays where they are. -const follow = { - animated: false, - on: { dataChange: true, footerLayout: true, itemLayout: true, layout: true }, -} as const satisfies MaintainScrollAtEndOptions; +const turnKey = (turn: Turn) => turn.user?.id ?? turn.replies[0]?.id ?? "empty"; -// Prepending an older page, or a row growing above the viewport, keeps what the reader sees in place. -const anchor = { data: true, size: true } as const; +const PROMPT_JUST_SENT_MS = 1500; +const PROMPT_RISE_MS = 560; +const PROMPT_REVEAL_MS = 320; +const PROMPT_FADE_MS = 480; +const PROMPT_RISE_FROM = 0.3; -const turnKey = (turn: Turn) => turn.user?.id ?? turn.replies[0]?.id ?? "empty"; +/** + * Keeps the live turn's min-height equal to the visible transcript height above the composer, so + * pinning to the bottom places the latest user prompt at the very top of the viewport. + */ +function syncTranscriptViewport(el: HTMLElement | null) { + if (el === null || el.clientHeight <= 0) return; + const inner = el.querySelector("[data-transcript-content]"); + const style = inner !== null ? getComputedStyle(inner) : null; + const pad = + style !== null ? (Number.parseFloat(style.paddingBottom) || 0) + (Number.parseFloat(style.paddingTop) || 0) : 0; + el.style.setProperty("--transcript-viewport", `${Math.max(0, el.clientHeight - pad)}px`); +} + +/** Fades a freshly sent prompt in while sliding it from the upper viewport into its top anchor. */ +function riseIntoAnchor(scroller: HTMLElement | null, promptId: string) { + if (scroller === null) return undefined; + const row = scroller.querySelector(`[data-prompt-anchor="${CSS.escape(promptId)}"]`); + if (row === null || typeof row.animate !== "function") return undefined; + if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return undefined; + const view = scroller.getBoundingClientRect(); + const dy = view.top + view.height * PROMPT_RISE_FROM - row.getBoundingClientRect().top; + if (dy <= 1) return undefined; + const animation = row.animate([{ transform: `translateY(${dy}px)` }, { transform: "translateY(0)" }], { + duration: PROMPT_RISE_MS, + easing: "cubic-bezier(0.22, 1, 0.36, 1)", + }); + const fade = row.animate([{ opacity: 0 }, { opacity: 1 }], { + duration: PROMPT_FADE_MS, + easing: "ease-out", + }); + const turn = row.closest(".transcript-turn"); + let revealTimer: ReturnType | undefined; + turn?.setAttribute("data-prompt-rise", "rising"); + animation.onfinish = () => { + turn?.setAttribute("data-prompt-rise", "revealing"); + revealTimer = setTimeout(() => turn?.removeAttribute("data-prompt-rise"), PROMPT_REVEAL_MS); + }; + return () => { + animation.cancel(); + fade.cancel(); + clearTimeout(revealTimer); + turn?.removeAttribute("data-prompt-rise"); + }; +} /** - * The conversation as a virtualized list of turns: only those near the viewport are mounted, and an - * update re-renders only the turn whose messages changed. + * The conversation as a list of turns. Sending a prompt anchors the new turn to the top of the + * viewport (`.transcript-turn-anchor`) so older turns scroll above the screen unless the reader + * scrolls up. */ function Transcript({ state, @@ -303,16 +354,105 @@ function Transcript({ }: { readonly state: Ready; readonly running: boolean; - readonly loadOlder: () => void; + readonly loadOlder: (beforePrepend: () => void) => void; }) { + const scroller = useRef(null); + const stickToBottom = useRef(true); + const lastScrollTop = useRef(0); + const touchY = useRef(undefined); + const prependHeight = useRef(null); const [scrolled, setScrolled] = useState(false); + const modelName = useModelName(state.info.hostDir, state.info.model); const turns = useMemo(() => turnsOf(state.messages), [state.messages]); - const renderItem = useCallback( - ({ item, index }: { readonly item: Turn; readonly index: number }) => ( - - ), - [running, turns.length], + const lastUser = turns.at(-1)?.user; + const lastUserId = lastUser?.id; + const [anchorTurn, setAnchorTurn] = useState( + () => running || (lastUser !== undefined && Date.now() - lastUser.createdAt < 5000), ); + const seenUserId = useRef(lastUserId); + if (lastUserId !== seenUserId.current) { + seenUserId.current = lastUserId; + if (lastUserId !== undefined && !anchorTurn) setAnchorTurn(true); + } + + const pinToBottom = useCallback((el: HTMLElement | null) => { + if (el === null) return; + el.scrollTop = el.scrollHeight; + lastScrollTop.current = el.scrollTop; + setScrolled(el.scrollTop > 1); + }, []); + + useLayoutEffect(() => { + stickToBottom.current = true; + const el = scroller.current; + syncTranscriptViewport(el); + pinToBottom(el); + }, [lastUserId, anchorTurn, pinToBottom]); + + const introducedPrompt = useRef<{ id: string | undefined; cancel: (() => void) | undefined }>(undefined); + useLayoutEffect(() => { + const previous = introducedPrompt.current; + if (previous !== undefined && previous.id === lastUserId) return; + const mounting = previous === undefined; + previous?.cancel?.(); + const current: { id: string | undefined; cancel: (() => void) | undefined } = { + id: lastUserId, + cancel: undefined, + }; + introducedPrompt.current = current; + if (lastUserId === undefined || !anchorTurn) return; + if ( + mounting && + !( + running && + turns.length === 1 && + lastUser !== undefined && + Date.now() - lastUser.createdAt < PROMPT_JUST_SENT_MS + ) + ) + return; + current.cancel = riseIntoAnchor(scroller.current, lastUserId); + }, [lastUserId, anchorTurn, running, turns.length, lastUser]); + + const firstTurnKey = turns[0] !== undefined ? turnKey(turns[0]) : undefined; + const seenFirstTurnKey = useRef(firstTurnKey); + useLayoutEffect(() => { + const el = scroller.current; + if (el === null) return; + if (seenFirstTurnKey.current !== firstTurnKey && prependHeight.current !== null) { + const delta = el.scrollHeight - prependHeight.current; + prependHeight.current = null; + seenFirstTurnKey.current = firstTurnKey; + if (delta > 0) { + el.scrollTop += delta; + lastScrollTop.current = el.scrollTop; + } + return; + } + seenFirstTurnKey.current = firstTurnKey; + prependHeight.current = null; + if (stickToBottom.current) { + syncTranscriptViewport(el); + pinToBottom(el); + } + }, [turns, running, firstTurnKey, pinToBottom]); + + useLayoutEffect(() => { + const el = scroller.current; + const inner = el?.firstElementChild; + if (el === null || inner === null || inner === undefined) return; + const onResize = () => { + if (!el.isConnected) return; + syncTranscriptViewport(el); + if (stickToBottom.current) pinToBottom(el); + }; + const observer = new ResizeObserver(onResize); + observer.observe(el); + observer.observe(inner); + onResize(); + return () => observer.disconnect(); + }, [pinToBottom, turns.length]); + if (turns.length === 0) return (
    @@ -320,22 +460,66 @@ function Transcript({
    ); return ( - - data={turns} - keyExtractor={turnKey} - renderItem={renderItem} - extraData={running} - estimatedItemSize={160} - // Turns hold their own state (an open work log), so a reused row must not carry it over. - recycleItems={false} - initialScrollAtEnd - maintainScrollAtEnd={follow} - maintainVisibleContentPosition={anchor} - onStartReached={state.more ? loadOlder : undefined} - ListFooterComponent={
    } - onScroll={(event) => setScrolled(event.nativeEvent.contentOffset.y > 1)} - className={`session-transcript min-h-0 flex-1 overflow-x-hidden overscroll-y-contain [overflow-anchor:none] ${scrolled ? "session-transcript-scrolled" : ""}`} - /> +
    { + if (event.target !== event.currentTarget) return; + if (["ArrowUp", "PageUp", "Home"].includes(event.key) || (event.key === " " && event.shiftKey)) { + stickToBottom.current = false; + } + }} + onTouchStart={(event) => { + touchY.current = event.touches[0]?.clientY; + }} + onTouchMove={(event) => { + const next = event.touches[0]?.clientY; + if (next !== undefined && touchY.current !== undefined && next > touchY.current) { + stickToBottom.current = false; + } + touchY.current = next; + }} + onWheel={(event) => { + if (event.deltaY < 0) stickToBottom.current = false; + }} + onScroll={(event) => { + const el = event.currentTarget; + const nearBottom = el.scrollHeight - el.clientHeight - el.scrollTop <= 16; + if (el.scrollTop < lastScrollTop.current - 1 && !nearBottom) { + stickToBottom.current = false; + } else if (nearBottom && el.scrollTop > lastScrollTop.current) { + stickToBottom.current = true; + } + lastScrollTop.current = el.scrollTop; + setScrolled(el.scrollTop > 1); + if (state.more && el.scrollTop < 120 && prependHeight.current === null) { + // Capture just before insertion: streamed updates may arrive while the page loads. + loadOlder(() => { + prependHeight.current = el.scrollHeight; + }); + } + }} + className={`session-transcript min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain [overflow-anchor:none] ${scrolled ? "session-transcript-scrolled" : ""}`} + > +
    + {turns.map((item, index) => { + const last = index === turns.length - 1; + return ( + + ); + })} +
    +
    ); } @@ -359,10 +543,22 @@ function turnsOf(entries: readonly HistoryEntry[]): Turn[] { // Turns are rebuilt on every update, but their messages are the same objects unless they changed. const sameTurn = ( - a: { readonly turn: Turn; readonly active: boolean }, - b: { readonly turn: Turn; readonly active: boolean }, + a: { + readonly turn: Turn; + readonly active: boolean; + readonly anchored: boolean; + readonly modelName: string | undefined; + }, + b: { + readonly turn: Turn; + readonly active: boolean; + readonly anchored: boolean; + readonly modelName: string | undefined; + }, ) => a.active === b.active && + a.anchored === b.anchored && + a.modelName === b.modelName && a.turn.user === b.turn.user && a.turn.replies.length === b.turn.replies.length && a.turn.replies.every((reply, index) => reply === b.turn.replies[index]); @@ -380,39 +576,50 @@ const isWork = (part: Part) => * The answer is the last reply's text; everything before it (thinking, tool calls, notes between * calls) is the work that led there, folded under one line. */ -const TurnView = memo(function TurnView({ turn, active }: { readonly turn: Turn; readonly active: boolean }) { +const TurnView = memo(function TurnView({ + turn, + active, + anchored, + modelName, +}: { + readonly turn: Turn; + readonly active: boolean; + readonly anchored: boolean; + readonly modelName: string | undefined; +}) { const last = turn.replies.at(-1); const answer = last?.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])) ?? []; + const answerText = answer.join("\n\n"); const work = turn.replies .flatMap((reply) => reply.parts.filter((part) => !(reply === last && part.type === "text"))) .filter(isWork); const interrupted = last?.state === "aborted"; const failed = last?.error !== undefined; - // While the agent works and no answer is streaming, it is thinking or running a tool. - const thinking = active && (last?.state !== "draft" || answer.length === 0); + // While the agent works and no final answer is streaming yet (or a tool is still running), keep the work open. + const toolRunning = work.some( + (part) => part.type === "toolCall" && (part.status === "pending" || part.status === "running"), + ); + const working = active && (last?.state !== "draft" || answer.length === 0 || toolRunning); + const started = turn.user?.createdAt ?? turn.replies[0]?.createdAt; + const ended = active ? undefined : endOf(turn.replies); return ( -
    +
    {turn.user !== undefined && } - {(work.length > 0 || thinking || answer.length > 0 || interrupted || failed) && ( - - {work.length > 0 && ( - - )} - {thinking && } + {(work.length > 0 || working || answer.length > 0 || interrupted || failed) && ( + + {answer.length > 0 && ( -
    - +
    +
    )} {last?.error !== undefined ? ( -

    {last.error}

    +

    {last.error}

    ) : ( - interrupted &&

    Interrupted

    + interrupted &&

    Interrupted

    )} )} @@ -420,24 +627,46 @@ const TurnView = memo(function TurnView({ turn, active }: { readonly turn: Turn; ); }, sameTurn); -/** The agent at work with nothing to show yet; static, so it costs no repaints while it waits. */ -function ThinkingRow() { - return ( -
    - - - - Thinking -
    - ); -} - function UserMessage({ entry }: { readonly entry: HistoryEntry }) { + const [expanded, setExpanded] = useState(false); + const [overflows, setOverflows] = useState(false); + const textRef = useRef(null); const text = entry.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n\n"); const images = entry.parts.filter((part) => part.type === "image").length; + useEffect(() => { + const element = textRef.current; + if (element === null || text === "") { + setOverflows(false); + return; + } + const measure = () => { + if (!expanded) setOverflows(element.scrollHeight > element.clientHeight + 1); + }; + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, [text, expanded]); return ( - - {text !== "" &&

    {text}

    } + + {text !== "" && ( +

    + {text} +

    + )} + {overflows && ( + + )} {images > 0 &&

    {images === 1 ? "1 image" : `${images} images`}

    }
    ); @@ -454,141 +683,426 @@ function endOf(replies: readonly HistoryEntry[]) { ); } -const duration = (ms: number) => { - const seconds = ms / 1000; - if (seconds < 60) return `${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)}s`; - const minutes = Math.floor(seconds / 60); - if (minutes < 60) return `${minutes}m ${Math.round(seconds % 60)}s`; +function formatElapsed(elapsedMs: number | undefined): string | undefined { + if (elapsedMs === undefined || elapsedMs < 0) return undefined; + const totalSec = Math.max(1, Math.round(elapsedMs / 1000)); + if (totalSec < 60) return `${totalSec}s`; + const minutes = Math.floor(totalSec / 60); + const seconds = totalSec % 60; + if (minutes < 60) return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`; return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; -}; +} + +function formatWorkingDuration(elapsedMs: number | undefined, modelName: string | undefined, done: boolean): string { + const who = modelName?.trim(); + const elapsed = formatElapsed(elapsedMs); + const verb = done ? (who ? "worked" : "Worked") : who ? "working" : "Working"; + if (elapsed === undefined) { + if (done) return who ? `${who} ${verb}` : verb; + return who ? `${who} ${verb}…` : `${verb}…`; + } + return who ? `${who} ${verb} for ${elapsed}` : `${verb} for ${elapsed}`; +} + +function useElapsedFrom(startedAt: number | undefined, active: boolean): number | undefined { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (!active || startedAt === undefined) return; + setNow(Date.now()); + const id = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(id); + }, [startedAt, active]); + return active && startedAt !== undefined ? Math.max(0, now - startedAt) : undefined; +} + +/** Flags the edges with more to scroll to, so only those fade. */ +function markScrollEdges(el: HTMLElement) { + const below = el.scrollHeight - el.clientHeight - el.scrollTop; + el.dataset.fadeTop = String(el.scrollTop > 1); + el.dataset.fadeBottom = String(below > 1); +} + +function nestedScrollAbsorbsWheel( + el: { readonly scrollTop: number; readonly scrollHeight: number; readonly clientHeight: number }, + deltaY: number, +) { + if (el.scrollHeight <= el.clientHeight + 1) return false; + const atTop = el.scrollTop <= 0; + const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1; + return (deltaY < 0 && !atTop) || (deltaY > 0 && !atBottom); +} + +/** + * Keeps the open work scroller pinned to its newest step while live; scrolling up with the wheel + * pauses auto-follow until the reader scrolls back to the bottom. + */ +function useLivePhaseScroll(el: HTMLDivElement | null, enabled: boolean, parts: readonly Part[]) { + const stickToBottom = useRef(true); + const lastScrollTop = useRef(0); + const wasEnabled = useRef(false); + + const pin = useCallback(() => { + if (el === null) return; + const nearBottom = el.scrollHeight - el.clientHeight - el.scrollTop <= 16; + if (el.scrollTop < lastScrollTop.current - 1 && !nearBottom) { + stickToBottom.current = false; + } else if (nearBottom) { + stickToBottom.current = true; + } + if (stickToBottom.current) el.scrollTop = el.scrollHeight; + lastScrollTop.current = el.scrollTop; + markScrollEdges(el); + }, [el]); + + useLayoutEffect(() => { + if (!enabled) { + wasEnabled.current = false; + return; + } + if (!wasEnabled.current) { + stickToBottom.current = true; + lastScrollTop.current = el?.scrollTop ?? 0; + wasEnabled.current = true; + } + pin(); + }, [el, enabled, pin, parts]); + + useEffect(() => { + if (el === null || !enabled) return; + const onScroll = () => { + const nearBottom = el.scrollHeight - el.clientHeight - el.scrollTop <= 16; + if (el.scrollTop < lastScrollTop.current - 1 && !nearBottom) { + stickToBottom.current = false; + } else if (nearBottom) { + stickToBottom.current = true; + } + lastScrollTop.current = el.scrollTop; + markScrollEdges(el); + }; + const onWheel = (event: WheelEvent) => { + if (!nestedScrollAbsorbsWheel(el, event.deltaY)) return; + if (event.deltaY < 0) stickToBottom.current = false; + event.stopPropagation(); + }; + el.addEventListener("scroll", onScroll, { passive: true }); + el.addEventListener("wheel", onWheel, { passive: true }); + const inner = el.firstElementChild; + const observer = new ResizeObserver(pin); + if (inner !== null) observer.observe(inner); + pin(); + return () => { + el.removeEventListener("scroll", onScroll); + el.removeEventListener("wheel", onWheel); + observer.disconnect(); + }; + }, [el, enabled, pin]); +} function WorkLog({ parts, started, ended, + working, + modelName, }: { readonly parts: readonly Part[]; readonly started: number | undefined; /** Absent while the turn is still running. */ readonly ended: number | undefined; + /** True while the agent is in its work phase (thinking or running tools before the answer). */ + readonly working: boolean; + readonly modelName: string | undefined; }) { - const [open, setOpen] = useState(false); - const label = - ended === undefined - ? "Working" - : started !== undefined && ended > started - ? `Worked for ${duration(ended - started)}` - : "Worked"; - return ( -
    -
    - -
    - {open && ( -
    - {parts.map((part, index) => ( - - ))} -
    + )} + + ); + const text = live ? ( + {label} + ) : ( + + {label} + + ); + if (!expandable) { + return ( +
    + {icon} + {text} +
    + ); + } + return ( +
    + +
    + {open && ( +
    +
    + {parts.map((part, index) => ( +
    + +
    + ))} +
    +
    + )} +
    ); } -function WorkRow({ part }: { readonly part: Part }) { +/** First paragraph of a folded block, stripped to one plain line. */ +function proseSummary(text: string) { + const body = text.replace(/```[\s\S]*?(?:```|$)/g, " "); + const paragraph = + body + .split(/\n\s*\n/) + .map((part) => part.trim()) + .find(Boolean) ?? ""; + return paragraph + .replace(/^\s{0,3}(?:#{1,6}|>|[-*+]|\d+\.)\s+/gm, "") + .replace(/`([^`]*)`/g, "$1") + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/(\*\*|__)(.+?)\1/g, "$2") + .replace(/(\*|_)(.+?)\1/g, "$2") + .replace(/\s+/g, " ") + .trim(); +} + +function WorkRow({ part, live = false }: { readonly part: Part; readonly live?: boolean }) { switch (part.type) { case "toolCall": return ; case "thinking": return part.redacted === true || part.thinking === "" ? null : ( - } label="Thought"> -

    {part.thinking}

    -
    + ); case "text": - return ( -
    - -
    - ); + return ; case "image": return null; } } -function ToolRow({ call }: { readonly call: ToolCall }) { - const failed = call.status === "error" || call.status === "aborted" || call.status === "skipped"; - const output = call.result?.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"); - const icon = failed ? ( - - ) : call.name === "bash" ? ( - - ) : ( - +function ThinkingWorkRow({ text, live = false }: { readonly text: string; readonly live?: boolean }) { + const [open, setOpen] = useState(false); + const summary = proseSummary(text) || "Thinking"; + return ( +
    + + {open && ( +
    + +
    + )} +
    ); +} + +function NoteWorkRow({ text }: { readonly text: string }) { + const [open, setOpen] = useState(false); + const summary = proseSummary(text); return ( - -
    -
    -					{JSON.stringify(call.arguments, null, 2)}
    -				
    - {output && ( -
    -						{output}
    -					
    - )} -
    -
    +
    + + {open && ( +
    + +
    + )} +
    ); } -/** A compact work-log line: icon and one-line label; clicking it shows the details beneath. */ -function Row({ - icon, - label, - children, -}: { - readonly icon: ReactNode; - readonly label: string; - readonly children: ReactNode; -}) { +function ToolRow({ call }: { readonly call: ToolCall }) { const [open, setOpen] = useState(false); + const running = call.status === "pending" || call.status === "running"; + const failed = + call.status === "error" || + call.status === "aborted" || + call.status === "skipped" || + call.result?.isError === true; + const output = call.result?.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"); + const { action, target, chip } = describeTool(call, running); return ( -
    +
    - {open &&
    {children}
    } + {open && ( +
    +
    +						{JSON.stringify(call.arguments, null, 2)}
    +					
    + {output && ( +
    +							{output}
    +						
    + )} +
    + )}
    ); } -/** The command for `bash`, else the tool name and its first string argument. */ -function summarize(call: ToolCall) { - const command = call.arguments.command; - if (call.name === "bash" && typeof command === "string") return command; - const first = Object.values(call.arguments).find((value) => typeof value === "string"); - return typeof first === "string" ? `${call.name} ${first}` : call.name; +function firstString(args: Record, keys?: readonly string[]): string | undefined { + if (keys !== undefined) { + for (const key of keys) { + const value = args[key]; + if (typeof value === "string" && value !== "") return value; + } + } + const found = Object.values(args).find((value) => typeof value === "string" && value !== ""); + return typeof found === "string" ? found : undefined; +} + +/** Splits a tool call into its action verb and target chip, as in the activity trail. */ +function describeTool( + call: ToolCall, + running: boolean, +): { readonly action: string; readonly target: string | undefined; readonly chip: boolean } { + switch (call.name) { + case "bash": + case "shell": + case "exec": + return { + action: running ? "Running" : "Ran", + target: firstString(call.arguments, ["command", "cmd"]), + chip: true, + }; + case "read": + return { action: "Read", target: firstString(call.arguments, ["path", "file", "filePath"]), chip: true }; + case "write": + return { action: "Write", target: firstString(call.arguments, ["path", "file", "filePath"]), chip: true }; + case "edit": + case "multiedit": + case "patch": + return { action: "Edit", target: firstString(call.arguments, ["path", "file", "filePath"]), chip: true }; + case "ls": + case "list": + return { action: "List", target: firstString(call.arguments, ["path", "dir", "directory"]), chip: true }; + case "grep": + case "glob": + case "find": + case "search": + case "toolsearch": + return { + action: "Find", + target: firstString(call.arguments, ["pattern", "query", "glob", "path"]), + chip: false, + }; + default: + return { action: call.name, target: firstString(call.arguments), chip: false }; + } }