diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 5d322f5f9f310..4c6ced71fd5c7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,4 +1,4 @@ -import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; +import { AgentAsks, type CoordinatorAsk } from "./chat/AgentAsks"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; @@ -75,6 +75,7 @@ import { type ScopedThreadRef, type ThreadId, type OrchestrationV2Milestone, + type OrchestrationV2Subagent, ProviderInteractionMode, resolveIdleCompaction, RuntimeMode, @@ -396,7 +397,6 @@ import { import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition"; import { useLocalDispatchState } from "./chat/useLocalDispatchState"; import { ThreadMilestonesView } from "./chat/ThreadMilestonesView"; -import type { CoordinatorAsk } from "./chat/MilestoneBoard"; import { formatMilestoneCommentPrefix, pendingAskCard, @@ -418,6 +418,8 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_TURN_ITEMS: ThreadStructure["turnItems"] = []; const EMPTY_RUNS: ThreadStructure["runs"] = []; +const EMPTY_SUBAGENTS: ReadonlyArray = []; +const EMPTY_MILESTONES: ReadonlyArray = []; const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray = []; const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray = []; @@ -3745,6 +3747,7 @@ export default function ChatView(props: ChatViewProps) { {showMilestones && activeThreadRef !== null ? ( - +
({ respond: vi.fn(), approvalsAtom: null as unkno vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.respond })); vi.mock("./SecretRequestCard", () => ({ SecretRequestCard: () => null })); +vi.mock("./LinkRequestCard", () => ({ LinkRequestCard: () => null })); +vi.mock("./MilestoneMapCards", () => ({ ProviderTile: () => null })); +vi.mock("../../state/entities", () => ({ useChildThreadInputs: () => [] })); vi.mock("../../state/threads", () => ({ childThreadApprovalsAtom: () => state.approvalsAtom, childThreadSecretRequestsAtom: () => Atom.make([]), threadEnvironment: { respondToApproval: {} }, })); -import { ChildThreadApprovals } from "./ChildThreadApprovals"; +import { AgentAsks } from "./AgentAsks"; function setup() { state.respond.mockReset(); @@ -46,7 +49,9 @@ function setup() { it("shows a failed decision and clears the error when the user retries", async () => { const thread = setup(); - await using screen = await render(); + await using screen = await render( + , + ); await screen.getByRole("button", { name: "Approve", exact: true }).click(); await expect.element(screen.getByRole("alert")).toHaveTextContent("Child environment offline"); await screen.getByRole("button", { name: "Approve", exact: true }).click(); diff --git a/apps/web/src/components/chat/AgentAsks.tsx b/apps/web/src/components/chat/AgentAsks.tsx new file mode 100644 index 0000000000000..a80f5e31b6b67 --- /dev/null +++ b/apps/web/src/components/chat/AgentAsks.tsx @@ -0,0 +1,287 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { LinkRequestItem } from "@t3tools/client-runtime/link-request"; +import type { SecretRequestItem } from "@t3tools/client-runtime/secret-request"; +import { agentThreadRef, type AgentAsk } from "@t3tools/client-runtime/state/thread-milestone-map"; +import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; +import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + AuthOrchestrationOperateScope, + type OrchestrationV2Milestone, + type OrchestrationV2Subagent, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { useState } from "react"; +import { flushSync } from "react-dom"; +import { create } from "zustand"; + +import { cn } from "~/lib/utils"; +import { useChildThreadInputs } from "../../state/entities"; +import { useEnvironmentScope } from "../../state/session"; +import { + childThreadApprovalsAtom, + childThreadSecretRequestsAtom, + threadEnvironment, +} from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; +import { LinkRequestCard } from "./LinkRequestCard"; +import { ProviderTile } from "./MilestoneMapCards"; +import { SecretRequestCard, type SecretRequestAttribution } from "./SecretRequestCard"; + +/** What the coordinator is asking you right now, shown on the milestone it is working on. */ +export type CoordinatorAsk = + | { readonly kind: "input"; readonly question: string | null } + | { readonly kind: "approval" } + /** A secret or link card is answered in place, never in the composer. */ + | { readonly kind: "card"; readonly item: SecretRequestItem | LinkRequestItem }; + +/** The ask an agent card's Answer picked, so the dock opens and flashes it. */ +const useAskFocusStore = create<{ readonly key: string | null; readonly nonce: number }>(() => ({ + key: null, + nonce: 0, +})); + +/** Opens the ask of the agent thread `key` in the dock and moves focus to its answer. */ +export function focusAgentAsk(key: string) { + flushSync(() => useAskFocusStore.setState((state) => ({ key, nonce: state.nonce + 1 }))); + const row = document.querySelector(`[data-agent-ask="${CSS.escape(key)}"]`); + row + ?.querySelector("input:not(:disabled), [data-ask-actions] button:not(:disabled)") + ?.focus(); +} + +/** What each of the thread's agents waits on you for, by the agent thread's key. */ +export function useAgentAsks(threadRef: ScopedThreadRef): ReadonlyMap { + const inputs = useChildThreadInputs(threadRef); + const approvals = useAtomValue(childThreadApprovalsAtom(threadRef)); + const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef)); + const asks = new Map(); + for (const child of inputs) { + if (child.hasPendingUserInput) { + asks.set(scopedThreadKey({ environmentId: child.environmentId, threadId: child.id }), { + kind: "input", + }); + } + } + for (const { thread, approval } of approvals) { + asks.set(scopedThreadKey(thread), { kind: "approval", command: approval.detail || null }); + } + for (const { thread, item } of secrets) { + asks.set(scopedThreadKey(thread), { kind: "secret", label: item.label }); + } + return asks; +} + +type Attribution = SecretRequestAttribution; + +function attributionOf( + thread: ScopedThreadRef, + fallbackTitle: string, + subagents: ReadonlyArray, + milestones: ReadonlyArray, +): Attribution { + const key = scopedThreadKey(thread); + const subagent = + subagents.findLast((agent) => { + const ref = agentThreadRef(agent, thread.environmentId); + return ref !== null && scopedThreadKey(ref) === key; + }) ?? null; + const milestone = + subagent?.milestoneId === undefined + ? undefined + : milestones.find(({ id }) => id === subagent.milestoneId); + return { + icon: , + title: subagent?.title ?? fallbackTitle, + subtitle: [subagent?.model ? formatModelSlugName(subagent.model) : null, milestone?.title] + .filter(Boolean) + .join(" · "), + }; +} + +function ApprovalRow({ + entry, + attribution, + flash, +}: { + entry: ChildThreadApproval; + attribution: Attribution; + flash: boolean; +}) { + const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope); + const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false }); + const [responding, setResponding] = useState(false); + const [error, setError] = useState(null); + const { approval } = entry; + const notes = [ + approval.appName ?? null, + approval.responseCapability === "live" + ? null + : "Provider process is gone. Interrupt or restart the child thread to respond.", + approval.reason ?? null, + approval.fullAccessOverride ? fullAccessOverrideExplanation(approval.fullAccessOverride) : null, + ].filter((note) => note !== null); + return ( +
+
+ {attribution.icon} + + {attribution.title}{" "} + {approval.detail ? ( + <> + wants to run{" "} + + {approval.detail} + + + ) : ( + <>needs approval for {approval.requestKind} + )} + + + { + if (!canRespond || responding) return; + setResponding(true); + setError(null); + const result = await respond({ + environmentId: entry.thread.environmentId, + input: { threadId: entry.thread.threadId, requestId, decision }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const failure = squashAtomCommandFailure(result); + setError( + failure instanceof Error + ? failure.message + : "Failed to submit approval decision.", + ); + } + setResponding(false); + return result; + }} + /> + +
+ {notes.map((note) => ( +

+ {note} +

+ ))} + {error !== null ? ( +

+ {error} +

+ ) : null} +
+ ); +} + +function AgentSecret(props: { + readonly askKey: string; + readonly environmentId: ScopedThreadRef["environmentId"]; + readonly item: SecretRequestItem; + readonly attribution: Attribution; + readonly flash: boolean; +}) { + const nonce = useAskFocusStore((state) => (state.key === props.askKey ? state.nonce : 0)); + const [collapsedAt, setCollapsedAt] = useState(null); + return ( + setCollapsedAt(useAskFocusStore.getState().nonce)} + onExpand={() => focusAgentAsk(props.askKey)} + /> + ); +} + +/** + * Asks waiting on you above the composer: each agent's secret, then each approval as one row, + * named after the agent and its milestone. A coordinator card joins them while Chat is hidden. + */ +export function AgentAsks(props: { + readonly threadRef: ScopedThreadRef | null; + readonly subagents: ReadonlyArray; + readonly milestones: ReadonlyArray; + readonly coordinatorCard: SecretRequestItem | LinkRequestItem | null; +}) { + const approvals = useAtomValue(childThreadApprovalsAtom(props.threadRef)); + const secrets = useAtomValue(childThreadSecretRequestsAtom(props.threadRef)); + const flashKey = useAskFocusStore((state) => state.key); + const card = props.coordinatorCard; + if (approvals.length === 0 && secrets.length === 0 && card === null) return null; + const attribution = (thread: ScopedThreadRef, title: string) => + attributionOf(thread, title, props.subagents, props.milestones); + return ( +
+ {card === null || props.threadRef === null ? null : card.type === "secret_request" ? ( + + ) : ( + + )} + {secrets.map((entry) => { + const key = scopedThreadKey(entry.thread); + return ( +
+ +
+ ); + })} + {approvals.map((entry) => { + const key = scopedThreadKey(entry.thread); + return ( +
+ +
+ ); + })} +
+ ); +} diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index e05d3befcc138..7a0365dacdc65 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -89,6 +89,7 @@ export function ChatCanvas({ detailsCardTopInset: model.detailsCardTopInset, preferredDetailsCard: model.preferredDetailsCard, detailsCardPlacement: model.detailsCardPlacement, + detailsCardInsetEnd: model.detailsCardInsetEnd, }; const { layout } = context; return ( diff --git a/apps/web/src/components/chat/ChatCanvasContext.ts b/apps/web/src/components/chat/ChatCanvasContext.ts index 4db2229f4d411..b009ee07f160e 100644 --- a/apps/web/src/components/chat/ChatCanvasContext.ts +++ b/apps/web/src/components/chat/ChatCanvasContext.ts @@ -22,6 +22,8 @@ export const ChatCanvasContext = createContext<{ preferredDetailsCard: ReturnType; /** Where the inline card sits now; null when it shows as a popover. */ detailsCardPlacement: ReturnType; + /** How far the open inline card reaches in from the canvas's right edge; 0 when it is not shown. */ + detailsCardInsetEnd: number; } | null>(null); export const useChatCanvas = () => useContext(ChatCanvasContext); diff --git a/apps/web/src/components/chat/ChildThreadApprovals.tsx b/apps/web/src/components/chat/ChildThreadApprovals.tsx deleted file mode 100644 index 1c69fba07f444..0000000000000 --- a/apps/web/src/components/chat/ChildThreadApprovals.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; -import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; -import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests"; -import { - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; -import { useState } from "react"; -import { useEnvironmentScope } from "../../state/session"; -import { - childThreadApprovalsAtom, - childThreadSecretRequestsAtom, - threadEnvironment, -} from "../../state/threads"; -import { useAtomCommand } from "../../state/use-atom-command"; -import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; -import { SecretRequestCard } from "./SecretRequestCard"; - -function ChildApproval({ entry }: { entry: ChildThreadApproval }) { - const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope); - const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false }); - const [responding, setResponding] = useState(false); - const [error, setError] = useState(null); - const { approval } = entry; - return ( -
-

Approval needed from {entry.title}

-
-        {approval.detail || approval.requestKind}
-      
- {approval.appName ?

{approval.appName}

: null} - {approval.responseCapability !== "live" ? ( -

- Provider process is gone. Interrupt or restart the child thread to respond. -

- ) : null} - {approval.reason ?

{approval.reason}

: null} - {approval.fullAccessOverride ? ( -

- {fullAccessOverrideExplanation(approval.fullAccessOverride)} -

- ) : null} -
- { - if (!canRespond || responding) return; - setResponding(true); - setError(null); - const result = await respond({ - environmentId: entry.thread.environmentId, - input: { threadId: entry.thread.threadId, requestId, decision }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const failure = squashAtomCommandFailure(result); - setError( - failure instanceof Error ? failure.message : "Failed to submit approval decision.", - ); - } - setResponding(false); - return result; - }} - /> -
- {error !== null ? ( -

- {error} -

- ) : null} -
- ); -} - -export function ChildThreadApprovals({ threadRef }: { threadRef: ScopedThreadRef | null }) { - const approvals = useAtomValue(childThreadApprovalsAtom(threadRef)); - const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef)); - if (approvals.length === 0 && secrets.length === 0) return null; - return ( -
- {secrets.map((entry) => ( - - ))} - {approvals.map((entry) => ( - - ))} -
- ); -} diff --git a/apps/web/src/components/chat/MilestoneBoard.tsx b/apps/web/src/components/chat/MilestoneBoard.tsx deleted file mode 100644 index 416c348f009e0..0000000000000 --- a/apps/web/src/components/chat/MilestoneBoard.tsx +++ /dev/null @@ -1,237 +0,0 @@ -import type { LinkRequestItem } from "@t3tools/client-runtime/link-request"; -import type { SecretRequestItem } from "@t3tools/client-runtime/secret-request"; -import type { MilestoneBoardItem } from "@t3tools/client-runtime/state/thread-milestone-board"; -import type { ChatImageAttachment, EnvironmentId } from "@t3tools/contracts"; -import { - AppWindowIcon, - CornerDownLeftIcon, - MessageSquareIcon, - MessageSquarePlusIcon, - StickyNoteIcon, - TriangleAlertIcon, -} from "lucide-react"; -import { useState } from "react"; - -import { useAssetUrls } from "../../assets/assetUrls"; -import { Button } from "../ui/button"; -import { LinkRequestCard } from "./LinkRequestCard"; -import { SecretRequestCard } from "./SecretRequestCard"; - -/** What the coordinator is asking you right now, shown on the milestone it is working on. */ -export type CoordinatorAsk = - | { readonly kind: "input"; readonly question: string | null } - | { readonly kind: "approval" } - /** A secret or link card is answered in place, never in the composer. */ - | { readonly kind: "card"; readonly item: SecretRequestItem | LinkRequestItem }; - -/** How many board items show before the older ones fold. */ -const BOARD_LIMIT = 4; - -const BOARD_KINDS = [ - { kind: "post", icon: StickyNoteIcon, label: "post" }, - { kind: "visual", icon: AppWindowIcon, label: "visual" }, - { kind: "comment", icon: MessageSquareIcon, label: "comment" }, -] as const; - -/** Counts per kind, such as "3 posts · 1 visual", for headers and folded milestones. */ -export function boardCounts(items: ReadonlyArray) { - return BOARD_KINDS.flatMap(({ kind, icon, label }) => { - const count = items.filter((item) => item.kind === kind).length; - return count === 0 - ? [] - : [{ kind, icon, text: `${count} ${count === 1 ? label : `${label}s`}` }]; - }); -} - -function AskHeading() { - return ( -
- - Coordinator asks you -
- ); -} - -export function CoordinatorAskCard(props: { - readonly environmentId: EnvironmentId; - readonly ask: CoordinatorAsk; - readonly onAnswerInChat: () => void; -}) { - if (props.ask.kind === "card") { - const { item } = props.ask; - return ( -
- - {item.type === "secret_request" ? ( - - ) : ( - - )} -
- ); - } - const question = props.ask.kind === "input" ? props.ask.question : null; - return ( -
- - {question === null ? null :

{question}

} -
- {props.ask.kind === "approval" ? ( - <> - It needs your approval to continue. - - - ) : ( - Answer in the composer below. - )} -
-
- ); -} - -function PostImages(props: { - readonly environmentId: EnvironmentId; - readonly attachments: ReadonlyArray; -}) { - const urls = useAssetUrls( - props.environmentId, - props.attachments.map((attachment) => ({ - _tag: "attachment" as const, - attachmentId: attachment.id, - })), - ); - return ( -
- {props.attachments.map((attachment, index) => { - const url = urls[index]; - return ( - - {url ? ( - {attachment.name} - ) : null} - - ); - })} -
- ); -} - -type Block = - | { - readonly kind: "visuals"; - readonly items: ReadonlyArray; - } - | { readonly kind: "single"; readonly item: MilestoneBoardItem }; - -/** Visuals in a row share a grid; posts and comments stand alone. */ -function blocksOf(items: ReadonlyArray): ReadonlyArray { - const blocks: Array = []; - for (const item of items) { - const last = blocks.at(-1); - if (item.kind === "visual" && last?.kind === "visuals") { - blocks[blocks.length - 1] = { kind: "visuals", items: [...last.items, item] }; - } else if (item.kind === "visual") { - blocks.push({ kind: "visuals", items: [item] }); - } else { - blocks.push({ kind: "single", item }); - } - } - return blocks; -} - -/** - * A milestone's board: the coordinator's posts and visuals and your comments, newest last, with - * older items folded. Visuals open where they rendered in Chat rather than mounting a frame here. - */ -export function MilestoneBoard(props: { - readonly environmentId: EnvironmentId; - readonly items: ReadonlyArray; - readonly onJump: (entryId: string) => void; -}) { - const [showAll, setShowAll] = useState(false); - if (props.items.length === 0) return null; - const hidden = showAll ? 0 : Math.max(0, props.items.length - BOARD_LIMIT); - return ( -
- {props.items.length > BOARD_LIMIT ? ( - - ) : null} - {blocksOf(props.items.slice(hidden)).map((block) => - block.kind === "visuals" ? ( -
-
- {block.items.map((item) => ( - - ))} -
-
- ) : block.item.kind === "post" ? ( -
-
Coordinator
- {block.item.text === null ? null : ( -

{block.item.text}

- )} - {block.item.attachments.length === 0 ? null : ( - - )} -
- ) : block.item.kind === "comment" ? ( -
-
You · sent to the coordinator
-

{block.item.text}

-
- ) : null, - )} -
- ); -} - -export function CommentButton(props: { readonly onComment: () => void }) { - return ( - - ); -} diff --git a/apps/web/src/components/chat/MilestoneMapCards.tsx b/apps/web/src/components/chat/MilestoneMapCards.tsx new file mode 100644 index 0000000000000..47b94242804a3 --- /dev/null +++ b/apps/web/src/components/chat/MilestoneMapCards.tsx @@ -0,0 +1,408 @@ +import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; +import { + actionLine, + agentLine, + agentThreadRef, + type MapAgent, + type MapMilestone, + type MapRollupTone, + type MapStatus, +} from "@t3tools/client-runtime/state/thread-milestone-map"; +import type { ProviderDriverKind, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import * as DateTime from "effect/DateTime"; +import { + BotIcon, + CheckIcon, + CircleCheckIcon, + CircleXIcon, + ClockIcon, + LoaderCircleIcon, + UserIcon, + XIcon, +} from "lucide-react"; +import type { CSSProperties } from "react"; + +import { cn } from "~/lib/utils"; +import { useProject, useThreadShell } from "../../state/entities"; +import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; +import { AgentElapsed } from "./AgentElapsed"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { useSubagentLink } from "./V2LifecycleRow"; + +const iso = (ms: number | null) => + ms === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ms)); + +export function ProviderTile(props: { + readonly driver: ProviderDriverKind | null; + readonly size?: "md" | "sm" | "xs"; +}) { + const size = props.size ?? "md"; + return ( + + {props.driver === null ? ( + + ) : ( + + )} + + ); +} + +const BADGES: Record< + MapStatus, + { + readonly label: string; + readonly variant: "info" | "success" | "warning" | "error" | "secondary"; + readonly icon: typeof CheckIcon | null; + } +> = { + running: { label: "Running", variant: "info", icon: LoaderCircleIcon }, + done: { label: "Done", variant: "success", icon: CheckIcon }, + "needs-you": { label: "Needs you", variant: "warning", icon: ClockIcon }, + failed: { label: "Failed", variant: "error", icon: XIcon }, + planned: { label: "Planned", variant: "secondary", icon: null }, + dropped: { label: "Dropped", variant: "secondary", icon: null }, + stopped: { label: "Stopped", variant: "secondary", icon: null }, +}; + +function MapStatusBadge(props: { readonly status: MapStatus }) { + const { label, variant, icon: Icon } = BADGES[props.status]; + return ( + + {Icon === null ? null : } + {label} + + ); +} + +/** The milestone's status as a small mark, for lists. */ +export function MilestoneStatusIcon(props: { readonly status: MapStatus }) { + switch (props.status) { + case "done": + return ( + + + + ); + case "running": + case "needs-you": + return ( + + + + ); + case "failed": + return ( + + + + ); + case "dropped": + case "stopped": + return ( + + + + ); + case "planned": + return ( + + ); + } +} + +export function RailDot(props: { + readonly status: MapStatus | "you"; + readonly style: CSSProperties; +}) { + return ( + + ); +} + +const ROLLUP_ICON: Record = { + "needs-you": ClockIcon, + running: LoaderCircleIcon, + none: UserIcon, + failed: CircleXIcon, + done: CircleCheckIcon, +}; + +const cardClass = + "absolute flex flex-col justify-between rounded-xl border bg-card shadow-xs/5 transition-[opacity,box-shadow] duration-200 motion-reduce:transition-none"; + +/** A thread's latest step and the workspace its paths are relative to, as the chat shows them. */ +function useThreadAction(ref: ScopedThreadRef | null) { + const shell = useThreadShell(ref); + const project = useProject(shell ? scopeProjectRef(shell.environmentId, shell.projectId) : null); + return { + action: shell?.latestAction, + workspaceRoot: shell?.worktreePath ?? project?.workspaceRoot ?? null, + }; +} + +/** The coordinator's latest step, for the milestone it is working on now. */ +function CoordinatorLine(props: { + readonly threadRef: ScopedThreadRef; + readonly fallback: string | null; +}) { + const { action, workspaceRoot } = useThreadAction(props.threadRef); + return <>{actionLine(action, workspaceRoot) ?? props.fallback ?? ""}; +} + +export function MilestoneCard(props: { + readonly node: MapMilestone; + readonly threadRef: ScopedThreadRef; + readonly lead: ProviderDriverKind | null; + readonly style: CSSProperties; + readonly selected: boolean; + readonly faded: boolean; + readonly onSelect: () => void; +}) { + const { node } = props; + const label = `Zoom into ${node.title}`; + const fade = props.faded && "opacity-42"; + if (!node.started) { + const dropped = node.status === "dropped"; + return ( + + ); + } + const RollupIcon = ROLLUP_ICON[node.rollup.tone]; + return ( + + ); +} + +function AgentTask(props: { readonly entry: MapAgent; readonly threadRef: ScopedThreadRef }) { + const ref = agentThreadRef(props.entry.agent, props.threadRef.environmentId); + const { action, workspaceRoot } = useThreadAction(ref); + const line = agentLine(props.entry.ask, action, props.entry.agent, workspaceRoot); + return {line}; +} + +export function AgentCard(props: { + readonly entry: MapAgent; + readonly threadRef: ScopedThreadRef; + readonly style: CSSProperties; + readonly width: number; + readonly onOpenThread: (threadId: ThreadId) => void; + readonly onAnswer: (threadKey: string) => void; +}) { + const { entry } = props; + const { agent } = entry; + const title = formatSubagentDisplayTitle(agent.title ?? "Subagent"); + const ref = agentThreadRef(agent, props.threadRef.environmentId); + const link = useSubagentLink({ + parentRef: props.threadRef, + subagentId: agent.id, + providerInstanceId: agent.providerInstanceId, + origin: agent.origin, + status: agent.status, + driver: agent.driver, + title, + result: agent.result, + progress: agent.progress, + startedAt: agent.startedAt, + completedAt: agent.completedAt, + threadId: agent.childThreadId, + remote: agent.remoteChild, + onOpenThread: props.onOpenThread, + }); + // A question in the agent's own chat is answered there; secrets and approvals in the dock. + const answer = + entry.ask === null + ? null + : entry.ask.kind === "input" || ref === null + ? link.open + : () => props.onAnswer(scopedThreadKey(ref)); + return ( +
+
+ +
+ {link.open === null ? ( + {title} + ) : ( + + )} + + {[ + agent.model ? formatModelSlugName(agent.model) : null, + link.remote ? `on ${link.remote.label}` : null, + ] + .filter(Boolean) + .join(" · ")} + +
+ +
+
+ {agent.group === undefined ? null : ( + + {agent.group} + + )} + +
+
+ + + + + {answer === null ? null : ( + + )} +
+
+ ); +} diff --git a/apps/web/src/components/chat/MilestoneTrace.tsx b/apps/web/src/components/chat/MilestoneTrace.tsx deleted file mode 100644 index 0c83dac8208fb..0000000000000 --- a/apps/web/src/components/chat/MilestoneTrace.tsx +++ /dev/null @@ -1,368 +0,0 @@ -import { secondTick } from "@t3tools/client-runtime/clock"; -import { - formatTraceClock, - traceFraction, - tracePosition, - traceTicks, - type TraceAgentStatus, - type TraceDomain, - type TraceRowStatus, - type TraceSpan, -} from "@t3tools/client-runtime/state/thread-milestone-trace"; -import { CheckIcon, XIcon } from "lucide-react"; -import type { ScopedThreadRef } from "@t3tools/contracts"; -import type { CSSProperties, ReactNode } from "react"; - -import { cn } from "~/lib/utils"; -import { useChildThreadInputs } from "../../state/entities"; - -type TraceTone = TraceRowStatus | TraceAgentStatus | "coordinator" | "group"; - -const pct = (value: number) => `${(value * 100).toFixed(3)}%`; -const NOW = "var(--trace-now)"; - -/** Left and width of a span; a running span ends at the live now line. */ -export function spanStyle(domain: TraceDomain, span: TraceSpan, minWidth = "5px"): CSSProperties { - const left = tracePosition(domain, span.startMs); - return { - left: pct(left), - width: - span.endMs === null - ? `max(${minWidth}, calc((${NOW} - ${left}) * 100%))` - : `max(${minWidth}, ${pct(tracePosition(domain, span.endMs) - left)})`, - }; -} - -/** Something that has not run yet, placed `offsetMs` after the moving now line. */ -export function afterNowStyle( - domain: TraceDomain, - offsetMs: number, - widthMs: number, -): CSSProperties { - return { - left: `calc(${NOW} * 100% + ${pct(traceFraction(domain, offsetMs))})`, - width: pct(traceFraction(domain, widthMs)), - }; -} - -export const atStyle = (domain: TraceDomain, atMs: number): CSSProperties => ({ - left: pct(tracePosition(domain, atMs)), -}); - -export const atNowStyle: CSSProperties = { left: `calc(${NOW} * 100%)` }; - -const BAR_TONE: Record = { - done: "border-success/40 bg-success/15", - active: "border-info/50 border-r-2 border-r-info bg-linear-to-r from-info/13 to-info/26", - running: "border-info/50 border-r-2 border-r-info bg-linear-to-r from-info/13 to-info/26", - planned: "border-dashed border-foreground/20", - queued: "border-dashed border-foreground/20", - dropped: - "border-foreground/20 bg-[repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-foreground)_9%,transparent)_0_3px,transparent_3px_6px)]", - failed: "border-destructive/50 bg-destructive/13", - "needs-you": "border-warning/50 border-r-2 border-r-warning bg-warning/14", - stopped: "border-foreground/20 bg-foreground/8", - coordinator: "h-2.5 border-foreground/20 bg-foreground/8", - group: "h-2 border-transparent bg-foreground/8", -}; - -export function TraceBar(props: { - readonly tone: TraceTone; - readonly style: CSSProperties; - /** Moves the bar up to make room for agent strands under it. */ - readonly raised?: boolean; - readonly className?: string; -}) { - return ( - - ); -} - -const STRAND_TONE: Record = { - done: "bg-success/45", - running: "bg-info", - "needs-you": "bg-warning", - failed: "bg-destructive", - stopped: "bg-foreground/25", - queued: "h-0! border-t-2 border-dotted border-foreground/25 bg-transparent", -}; - -/** One agent as a thin line; overlapping lines ran at the same time. */ -export function TraceStrand(props: { - readonly status: TraceAgentStatus; - readonly style: CSSProperties; - readonly thick?: boolean; -}) { - return ( - - ); -} - -export function TracePin(props: { - readonly style: CSSProperties; - readonly ask?: boolean; - readonly raised?: boolean; -}) { - return ( - - ); -} - -export function MilestoneStatusIcon(props: { readonly status: TraceRowStatus }) { - switch (props.status) { - case "done": - return ( - - - - ); - case "active": - return ( - - - - ); - case "failed": - return ( - - - - ); - case "dropped": - case "stopped": - return ( - - - - ); - case "planned": - return ( - - ); - } -} - -/** Shared row grid: a label column, the plot, and in a zoomed chart a status column. */ -export const traceRowClass = - "relative grid grid-cols-[var(--trace-label)_minmax(0,1fr)_var(--trace-side)] items-stretch border-t border-foreground/7 first:border-t-0"; - -/** A row-wide button under the row's content; controls inside the row sit above it. */ -export const traceCoverClass = - "absolute inset-0 cursor-pointer outline-none hover:bg-foreground/4 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"; - -export function TraceLabel(props: { - readonly className?: string | undefined; - readonly children: ReactNode; -}) { - return ( -
- {props.children} -
- ); -} - -export function TraceText(props: { - readonly title: ReactNode; - readonly meta?: ReactNode; - readonly titleClassName?: string | undefined; - readonly metaClassName?: string | undefined; -}) { - return ( -
-
- {props.title} -
- {props.meta === undefined ? null : ( -
- {props.meta} -
- )} -
- ); -} - -export function TracePlot(props: { readonly children?: ReactNode }) { - return
{props.children}
; -} - -export function TraceLegendSwatch(props: { readonly tone: TraceTone; readonly label: string }) { - return ( - - - {props.label} - - ); -} - -/** - * The chart card: an axis row, the rows, and an overlay with ticks, idle breaks and the now line. - * While live, now moves through the `--trace-now` variable on the shared second tick, so rows - * never re-render for it; `onHorizon` fires once now passes the domain's headroom. - */ -export function TraceChart(props: { - readonly domain: TraceDomain; - readonly nowMs: number; - readonly live: boolean; - readonly zoomed: boolean; - readonly axisLabel: string; - readonly onHorizon: () => void; - readonly legend?: ReactNode; - readonly children: ReactNode; -}) { - const { domain, nowMs, live, onHorizon } = props; - const trackNow = (node: HTMLDivElement | null) => { - if (!node) return; - const write = () => { - const now = Math.max(Date.now(), nowMs); - if (live && now > domain.horizonMs) { - onHorizon(); - return; - } - const at = tracePosition(domain, live ? now : nowMs); - node.style.setProperty("--trace-now", String(at)); - // The now pill shares the tick row, so tick labels hide while it passes them. - if (!live) return; - for (const tick of node.querySelectorAll("[data-trace-tick]")) { - const position = Number(tick.dataset.traceTick); - tick.toggleAttribute("data-under-now", position > at - 0.15 && position < at + 0.06); - } - }; - write(); - return live ? secondTick.subscribe(write) : undefined; - }; - const showNow = live; - const nowAt = tracePosition(domain, nowMs); - // A label at the right edge would be cut off. - const ticks = traceTicks(domain).filter(({ position }) => position <= 0.93); - return ( -
-
-
-
-
- {props.axisLabel} -
-
- {props.children} -
- {ticks.map((tick, index) => ( -
span]:invisible", - index % 2 === 1 && "@max-xl:[&>span]:invisible", - )} - style={{ left: pct(tick.position) }} - > - - {formatTraceClock(tick.elapsedMs)} - -
- ))} - {domain.gaps.map((gap) => { - const at = tracePosition(domain, gap.startMs); - const left = pct(at); - return ( -
-
- {/* Work resuming after a break puts now just right of it, so the label moves left. */} - - {formatTraceClock(gap.endMs - gap.startMs)} idle - -
- ); - })} - {showNow ? ( - <> -
- - now - - - ) : null} -
-
- {props.legend === undefined ? null : ( -
- {props.legend} -
- )} -
-
- ); -} - -/** Child threads waiting on you, and which of them wait on an approval. */ -export function useAgentsWaitingOnYou(threadRef: ScopedThreadRef) { - const children = useChildThreadInputs(threadRef); - const waiting = children.filter( - (child) => child.hasPendingApprovals || child.hasPendingUserInput, - ); - return { - needsYou: new Set(waiting.map(({ id }) => id)), - approvals: new Set( - waiting.filter(({ hasPendingApprovals }) => hasPendingApprovals).map(({ id }) => id), - ), - }; -} diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index b6cdabb8a7b69..93d10f7159d62 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -22,22 +22,51 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; -import { CheckIcon, ExternalLinkIcon, LockIcon, MinusIcon, ShieldCheckIcon } from "lucide-react"; -import { useId, useRef, useState, type FormEvent } from "react"; +import { + CheckIcon, + ChevronDownIcon, + ClockIcon, + ExternalLinkIcon, + LockIcon, + MinusIcon, + ShieldCheckIcon, +} from "lucide-react"; +import { type FormEvent, type ReactNode, useId, useRef, useState } from "react"; +import { cn } from "~/lib/utils"; import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; +import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { SecretSourceSelect } from "../settings/SecretSourceInput"; import { WorkLogRow } from "./WorkLog"; -export function SecretRequestCard(props: { - readonly environmentId: EnvironmentId; - readonly item: SecretRequestItem; - readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; -}) { +/** Who is asking, for a card shown away from the thread that asked. */ +export interface SecretRequestAttribution { + readonly icon: ReactNode; + readonly title: string; + readonly subtitle: string; +} + +interface CardChrome { + readonly attribution?: SecretRequestAttribution | undefined; + /** Points the card out after you chose to answer it elsewhere. */ + readonly flash?: boolean | undefined; + /** Folds the card to its header and an Answer button; the draft survives. */ + readonly collapsed?: boolean | undefined; + readonly onCollapse?: (() => void) | undefined; + readonly onExpand?: (() => void) | undefined; +} + +export function SecretRequestCard( + props: { + readonly environmentId: EnvironmentId; + readonly item: SecretRequestItem; + readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; + } & CardChrome, +) { const { item } = props; const display = secretRequestDisplay(item, props.visibility); if (display.kind === "answered" || display.kind === "pending-elsewhere") { @@ -59,7 +88,29 @@ export function SecretRequestCard(props: { /> ); } - return ; + return ; +} + +function AttributionHeader(props: { + readonly attribution: SecretRequestAttribution; + readonly children: ReactNode; +}) { + return ( +
+ {props.attribution.icon} +
+ + {props.attribution.title} + + {props.attribution.subtitle ? ( + + {props.attribution.subtitle} + + ) : null} +
+ {props.children} +
+ ); } const NO_SOURCES: ReadonlyArray = []; @@ -71,10 +122,12 @@ function useSecretRequestSources(environmentId: EnvironmentId) { : NO_SOURCES; } -function PendingSecretRequestForm(props: { - readonly environmentId: EnvironmentId; - readonly item: SecretRequestItem; -}) { +function PendingSecretRequestForm( + props: { + readonly environmentId: EnvironmentId; + readonly item: SecretRequestItem; + } & CardChrome, +) { const { item } = props; const inputId = useId(); const errorId = useId(); @@ -128,11 +181,29 @@ function PendingSecretRequestForm(props: { const draft = source === null ? secret : reference; const link = secretRequestLink(item); const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId; + const { attribution } = props; + const frame = cn( + "flex min-w-0 flex-col rounded-xl border bg-card", + attribution === undefined ? "gap-3 border-border/60 p-4" : "gap-2.75 p-3 pb-2.5 shadow-lg/5", + props.flash && "border-warning/60", + ); + + if (attribution !== undefined && props.collapsed) { + return ( +
+ + + +
+ ); + } return (
+ {attribution === undefined ? null : ( + + + + Needs you + + {props.onCollapse === undefined ? null : ( + + )} + + )}