diff --git a/.changeset/address-fields.md b/.changeset/address-fields.md new file mode 100644 index 0000000..2098539 --- /dev/null +++ b/.changeset/address-fields.md @@ -0,0 +1,5 @@ +--- +"web": minor +--- + +The label's free-text details become a ship-to form: recipient, country, street with address suggestions from Photon in the chosen country, postcode and city, printed as three lines. diff --git a/.changeset/inspector-panel.md b/.changeset/inspector-panel.md new file mode 100644 index 0000000..e447d6c --- /dev/null +++ b/.changeset/inspector-panel.md @@ -0,0 +1,5 @@ +--- +"web": minor +--- + +The station's Cmd-K omnibox becomes the Inspector, a docked agent panel built on AI Elements: one thread per order, live tool steps, cited moments that play in place with the detector's boxes, suggestions per bench state, hold Space to talk with a live Canary transcript, and the after-seal check with Repack or Ship as short. diff --git a/apps/web/package.json b/apps/web/package.json index ef124d0..ded6f03 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -11,12 +11,15 @@ "deploy": "vp run build && wrangler deploy" }, "dependencies": { + "@ai-sdk/react": "catalog:", "@base-ui/react": "^1.9.0", "@dicebear/collection": "catalog:", "@dicebear/core": "catalog:", "@fontsource-variable/instrument-sans": "^5.2.0", + "@shadcn/react": "catalog:", "@tailwindcss/vite": "^4", "@workos-inc/authkit-react": "catalog:", + "ai": "catalog:", "barcode-detector": "catalog:", "class-variance-authority": "^0.7.1", "cn": "^0.4.0", @@ -25,6 +28,7 @@ "react-dom": "^19.3.0", "react-error-boundary": "catalog:", "shadcn": "^4.21.5", + "streamdown": "catalog:", "tailwindcss": "^4", "tw-animate-css": "^1.4.0", "zxing-wasm": "catalog:" diff --git a/apps/web/src/components/address-fields.tsx b/apps/web/src/components/address-fields.tsx new file mode 100644 index 0000000..d4f35fa --- /dev/null +++ b/apps/web/src/components/address-fields.tsx @@ -0,0 +1,187 @@ +import { MapPinIcon } from "lucide-react"; +import { useEffect, useState } from "react"; + +import { + Combobox, + ComboboxContent, + ComboboxInput, + ComboboxItem, + ComboboxList, +} from "@/components/ui/combobox"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + type Address, + type AddressSuggestion, + COUNTRIES, + countryName, + suggestAddresses, +} from "@/lib/address"; + +const SUGGEST_AFTER_CHARS = 3; +const SUGGEST_DEBOUNCE_MS = 250; +const COUNTRY_ITEMS = COUNTRIES.map((code) => ({ value: code, label: countryName(code) })); + +function useAddressSuggestions(street: string, country: string) { + const [suggestions, setSuggestions] = useState([]); + useEffect(() => { + const query = street.trim(); + if (query.length < SUGGEST_AFTER_CHARS) { + setSuggestions([]); + return; + } + const controller = new AbortController(); + const timer = setTimeout(() => { + suggestAddresses(query, country, controller.signal) + .then(setSuggestions) + // suggestions only speed typing up; without them the fields still take any address + .catch(() => undefined); + }, SUGGEST_DEBOUNCE_MS); + return () => { + clearTimeout(timer); + controller.abort(); + }; + }, [street, country]); + return suggestions; +} + +/** Recipient and address as separate fields; the street suggests real addresses in the chosen country. */ +export function AddressFields({ + address, + onChange, +}: { + address: Address; + onChange: (update: (current: Address) => Address) => void; +}) { + const suggestions = useAddressSuggestions(address.street, address.country); + const set = (field: keyof Address) => (value: string) => + onChange((current) => ({ ...current, [field]: value })); + + return ( +
+ Ship to +
+ + set("recipient")(event.target.value)} + /> +
+
+ + +
+
+ + + items={suggestions} + filter={null} + autoHighlight + inputValue={address.street} + onInputValueChange={set("street")} + itemToStringLabel={(suggestion) => suggestion.street} + onValueChange={(picked) => { + if (!picked) return; + onChange((current) => ({ + ...current, + street: picked.street, + postcode: picked.postcode || current.postcode, + city: picked.city || current.city, + })); + }} + > + + + + {(suggestion: AddressSuggestion) => ( + + + + {suggestion.street} + + {[suggestion.postcode, suggestion.city].filter(Boolean).join(" ")} + {suggestion.district && `, ${suggestion.district}`} + + + + )} + + + +
+
+
+ + set("postcode")(event.target.value)} + /> +
+
+ + set("city")(event.target.value)} + /> +
+
+
+ ); +} diff --git a/apps/web/src/components/app-header.tsx b/apps/web/src/components/app-header.tsx index 68cd712..8f7598d 100644 --- a/apps/web/src/components/app-header.tsx +++ b/apps/web/src/components/app-header.tsx @@ -2,7 +2,7 @@ import { notionists } from "@dicebear/collection"; import { createAvatar } from "@dicebear/core"; import { type User, useAuth } from "@workos-inc/authkit-react"; import { LogOutIcon } from "lucide-react"; -import { useMemo } from "react"; +import { type ReactNode, useMemo } from "react"; import { ThemeSwitch } from "@/components/theme-switch"; import { Avatar, AvatarImage } from "@/components/ui/avatar"; @@ -67,17 +67,18 @@ export function UserMenu({ user, onSignOut }: { user: Account; onSignOut: () => ); } -export function AppHeader() { +export function AppHeader({ children }: { children?: ReactNode }) { const { user, signOut } = useAuth(); return (
-
+
ProofBox Packing station
+ {children} {user && signOut()} />}
diff --git a/apps/web/src/components/inspector/evidence.tsx b/apps/web/src/components/inspector/evidence.tsx new file mode 100644 index 0000000..b3e0fda --- /dev/null +++ b/apps/web/src/components/inspector/evidence.tsx @@ -0,0 +1,161 @@ +import { ExternalLinkIcon, PlayIcon, VideoOffIcon } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { labelColor, VisionOverlay } from "@/components/vision-overlay"; +import { Button } from "@/components/ui/button"; +import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card"; +import { getTrack, packVideoUrl } from "@/lib/api"; +import { clipRange, type PlayableClip } from "@/lib/inspector"; +import { cn } from "@/lib/utils"; +import { detectionsAt, type Frame, framesOf } from "@/proof/pack-model"; + +const tracks = new Map>(); + +function framesFor(packId: string) { + let frames = tracks.get(packId); + if (!frames) { + frames = getTrack(packId) + .then(framesOf) + .catch(() => { + tracks.delete(packId); + return []; + }); + tracks.set(packId, frames); + } + return frames; +} + +// a cited moment is a few seconds at most; replaying a little past it keeps the item in frame +const TAIL_S = 0.75; + +/** Plays one cited moment of a pack's clip in place, looping it, with the detector's boxes on top. */ +function EvidencePlayer({ clip }: { clip: PlayableClip }) { + const player = useRef(null); + const [frames, setFrames] = useState([]); + const [ms, setMs] = useState(0); + const [frameSize, setFrameSize] = useState<{ width: number; height: number } | null>(null); + const [failed, setFailed] = useState(false); + const start = clip.start_s ?? 0; + + useEffect(() => { + let live = true; + void framesFor(clip.pack_id).then((loaded) => live && setFrames(loaded)); + return () => { + live = false; + }; + }, [clip.pack_id]); + + useEffect(() => { + const element = player.current; + if (!element) return; + let handle = element.requestVideoFrameCallback(function tick(_, frame) { + setMs(frame.mediaTime * 1000); + if (clip.end_s !== null && frame.mediaTime > clip.end_s + TAIL_S) element.currentTime = start; + handle = element.requestVideoFrameCallback(tick); + }); + return () => element.cancelVideoFrameCallback(handle); + }, [clip.end_s, start]); + + return ( +
+
+
+
+ + {clip.order_id ?? `Pack ${clip.pack_id.slice(0, 8)}`}, {clipRange(clip) ?? "whole clip"} + + {clip.order_id && ( + + Proof page + + + )} +
+
+ ); +} + +/** The answer's citations as chips; choosing one plays that moment right under the answer. */ +export function EvidenceRow({ clips }: { clips: PlayableClip[] }) { + const [playing, setPlaying] = useState(null); + const shown = playing === null ? null : clips[playing]; + return ( +
+
+ {clips.map((clip, index) => ( + + setPlaying(playing === index ? null : index)} + className="tabular-nums" + /> + } + > + + {clip.label} + + {clipRange(clip) ?? clip.pack_id.slice(0, 8)} + + + +

+ {clip.order_id ?? clip.pack_id.slice(0, 8)} {clipRange(clip)} +

+

{clip.text}

+

+ + Click to play this moment here +

+
+
+ ))} +
+ {shown && } +
+ ); +} diff --git a/apps/web/src/components/inspector/inspector.tsx b/apps/web/src/components/inspector/inspector.tsx new file mode 100644 index 0000000..b056828 --- /dev/null +++ b/apps/web/src/components/inspector/inspector.tsx @@ -0,0 +1,461 @@ +import { Chat, useChat } from "@ai-sdk/react"; +import { DefaultChatTransport, isStaticToolUIPart } from "ai"; +import { + ArrowUpIcon, + CircleAlertIcon, + ExternalLinkIcon, + MicIcon, + SparklesIcon, + SquareIcon, + SquarePenIcon, + XIcon, +} from "lucide-react"; +import { type FormEvent, type ReactNode, useEffect, useRef, useState } from "react"; +import { Streamdown } from "streamdown"; + +import { EvidenceRow } from "@/components/inspector/evidence"; +import { type CheckChoice, SealCheckCard } from "@/components/inspector/seal-check"; +import { ToolStep } from "@/components/inspector/tool-step"; +import { Bubble, BubbleContent } from "@/components/ui/bubble"; +import { Button } from "@/components/ui/button"; +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupTextarea, +} from "@/components/ui/input-group"; +import { Kbd } from "@/components/ui/kbd"; +import { Message, MessageContent, MessageFooter } from "@/components/ui/message"; +import { + MessageScroller, + MessageScrollerButton, + MessageScrollerContent, + MessageScrollerItem, + MessageScrollerProvider, + MessageScrollerViewport, +} from "@/components/ui/message-scroller"; +import { Spinner } from "@/components/ui/spinner"; +import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"; +import { usePushToTalk } from "@/hooks/use-push-to-talk"; +import type { CheckState } from "@/hooks/use-seal-check"; +import { useVoice, type VoiceState } from "@/hooks/use-voice"; +import { + type BenchPhase, + type InspectorMessage, + type PlayableClip, + suggestionsFor, +} from "@/lib/inspector"; +import { cn } from "@/lib/utils"; + +const ANY_ORDER = "*"; + +function newChat(scope: string | null) { + return new Chat({ + id: scope ?? ANY_ORDER, + transport: new DefaultChatTransport({ api: "/api/chat", body: { order_id: scope } }), + }); +} + +function Thinking({ children = "Thinking with W&B Inference" }: { children?: ReactNode }) { + return ( + + + + + + {children} + + + ); +} + +function AgentMessage({ message, streaming }: { message: InspectorMessage; streaming: boolean }) { + const clips: PlayableClip[] = []; + const body: ReactNode[] = []; + let waiting = streaming; + message.parts.forEach((part, index) => { + if (isStaticToolUIPart(part)) { + waiting = streaming && part.state === "output-available"; + body.push(); + } else if (part.type === "text") { + waiting = false; + body.push( + + {part.text} + , + ); + } else if (part.type === "data-evidence" && part.data.pack_id !== null) + clips.push({ ...part.data, pack_id: part.data.pack_id }); + }); + const traceUrl = message.metadata?.traceUrl; + return ( + + + {body} + {waiting && } + {clips.length > 0 && !streaming && } + {!streaming && ( + + W&B Inference + {traceUrl && ( + <> + {" "} + {"·"} + + Weave trace + + + + )} + + )} + + + ); +} + +function UserMessage({ message }: { message: InspectorMessage }) { + const text = message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); + return ( + + + + {text} + + + + ); +} + +function EmptyThread({ scope }: { scope: string | null }) { + return ( +
+ + + +

{scope ? `Ask about ${scope}` : "Ask about any pack"}

+

+ The agent reads orders from VastDB, has Cosmos watch the pack video and searches the VAST + archive, then cites the moments it saw. +

+
+ ); +} + +function voiceHint(voice: VoiceState) { + if (voice.tag === "recording") + return ( + + + Listening, release to send + + ); + if (voice.tag === "transcribing") + return ( + + + Finishing with Canary-1B + + ); + if (voice.tag === "failed") return {voice.detail}; + return ( + + Hold Space to talk + + ); +} + +/** + * The station's agent panel: one thread per order, tool steps as they run, cited moments that + * play in place, and the after-seal check. Docked beside the station on wide screens. + */ +export function Inspector({ + open, + onOpenChange, + orderId, + phase, + check, + onRepack, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + orderId: string | null; + phase: BenchPhase; + check: CheckState; + onRepack: () => void; +}) { + const [unscopedFrom, setUnscopedFrom] = useState(null); + const scope = orderId && unscopedFrom !== orderId ? orderId : null; + const chats = useRef(new Map>()); + const key = scope ?? ANY_ORDER; + if (!chats.current.has(key)) chats.current.set(key, newChat(scope)); + const { messages, status, error, sendMessage, stop, regenerate, setMessages } = useChat({ + chat: chats.current.get(key)!, + }); + const busy = status === "submitted" || status === "streaming"; + + const [draft, setDraft] = useState(""); + const textarea = useRef(null); + const [choices, setChoices] = useState>({}); + + function ask(text: string) { + const question = text.trim(); + if (!question) return; + if (busy) return setDraft(question); + setDraft(""); + void sendMessage({ text: question }); + } + + const voice = useVoice((text) => { + onOpenChange(true); + ask(text); + }); + usePushToTalk(() => { + onOpenChange(true); + void voice.start(); + }, voice.stop); + const heard = + voice.state.tag === "recording" || voice.state.tag === "transcribing" + ? voice.state.partial + : null; + const listening = heard !== null; + + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") { + event.preventDefault(); + onOpenChange(!open); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [open, onOpenChange]); + + useEffect(() => { + if (open) textarea.current?.focus(); + }, [open]); + + const flagged = check.tag === "ready" && check.check.verdict !== "complete"; + useEffect(() => { + if (flagged) onOpenChange(true); + }, [flagged, onOpenChange]); + + if (!open) return null; + + const sealedHere = phase.tag === "sealed" && scope === phase.orderId; + const checkPackId = + check.tag === "ready" ? check.check.pack_id : check.tag === "none" ? null : check.packId; + const suggestions = suggestionsFor(phase, scope !== null); + const last = messages.at(-1); + + return ( + + ); +} diff --git a/apps/web/src/components/inspector/seal-check.tsx b/apps/web/src/components/inspector/seal-check.tsx new file mode 100644 index 0000000..8dbc0e6 --- /dev/null +++ b/apps/web/src/components/inspector/seal-check.tsx @@ -0,0 +1,107 @@ +import { CircleCheckIcon, RotateCcwIcon, ScanEyeIcon, TriangleAlertIcon } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { + Item, + ItemActions, + ItemContent, + ItemDescription, + ItemMedia, + ItemTitle, +} from "@/components/ui/item"; +import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"; +import type { CheckState } from "@/hooks/use-seal-check"; +import { assertNever } from "@/lib/assert-never"; + +export type CheckChoice = "repack" | "ship"; + +/** + * The agent's own look at a box right after it is sealed. A disagreement with the order + * asks the packer to repack or ship it as it is. + */ +export function SealCheckCard({ + state, + orderId, + choice, + onChoose, +}: { + state: CheckState; + orderId: string; + choice: CheckChoice | null; + onChoose: (choice: CheckChoice) => void; +}) { + switch (state.tag) { + case "none": + return null; + case "pending": + return ( + + + + + + Cosmos is checking the sealed box against {orderId} + + + ); + case "unavailable": + return ( +

+ The after-seal check did not finish, so the detector's count stands. +

+ ); + case "ready": { + const { verdict, text } = state.check; + if (verdict === "complete") + return ( + + + + + + Cosmos agrees, everything on {orderId} went in + {text} + + + ); + const shipAs = verdict === "short" ? "Ship as short" : "Ship as is"; + return ( + + + + + + + {verdict === "short" + ? `Cosmos counted less than ${orderId} needs` + : `Cosmos saw something not on ${orderId}`} + + {text} + + {choice ? ( +

+ {choice === "repack" ? "Repacking with a new recording." : `${shipAs}, noted.`} +

+ ) : ( + + + + + )} +
+ ); + } + default: + return assertNever(state); + } +} diff --git a/apps/web/src/components/inspector/tool-step.tsx b/apps/web/src/components/inspector/tool-step.tsx new file mode 100644 index 0000000..b1d4d75 --- /dev/null +++ b/apps/web/src/components/inspector/tool-step.tsx @@ -0,0 +1,143 @@ +import type { ToolUIPart } from "ai"; +import { DatabaseIcon, ScanEyeIcon, SearchIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import { + Trace, + TraceCollapsible, + TraceCollapsibleContent, + TraceCollapsibleTrigger, + TraceDescription, + TraceIcon, + TraceLine, + TraceTitle, +} from "@/components/ui/trace"; +import { assertNever } from "@/lib/assert-never"; +import { clipRange, type InspectorTools } from "@/lib/inspector"; + +export type ToolPart = ToolUIPart; + +type Step = { icon: ReactNode; running: string; done: string; detail?: string; body?: ReactNode }; + +const shortId = (packId: string | null | undefined) => (packId ? packId.slice(0, 8) : ""); + +function describe(part: ToolPart): Step { + switch (part.type) { + case "tool-getOrder": { + const id = part.output?.order_id ?? part.input?.order_id ?? "the order"; + const order = part.output; + return { + icon: , + running: `Reading ${id} from VastDB`, + done: `Read ${id} from VastDB`, + detail: + order && + `${order.items.length} lines, ${order.packs.length} ${order.packs.length === 1 ? "pack" : "packs"}`, + body: order && ( +
    + {order.items.map((item) => ( +
  • + {item.qty}x {item.name} +
  • + ))} + {order.packs.map((pack) => ( +
  • + Pack {shortId(pack.pack_id)}: {pack.verdict} +
  • + ))} +
+ ), + }; + } + case "tool-watchPack": { + const pack = shortId(part.output?.pack_id ?? part.input?.pack_id); + return { + icon: , + running: `Cosmos is watching pack ${pack}`, + done: `Cosmos watched pack ${pack}`, + detail: part.output && `${part.output.seconds.toFixed(1)} s`, + body: part.output &&

{part.output.seen}

, + }; + } + case "tool-searchArchive": { + const query = part.output?.query ?? part.input?.query; + const hits = part.output?.hits; + return { + icon: , + running: query ? `Searching the VAST archive for "${query}"` : "Searching the VAST archive", + done: query ? `Searched the VAST archive for "${query}"` : "Searched the VAST archive", + detail: hits && `${hits.length} ${hits.length === 1 ? "clip" : "clips"}`, + body: part.output && ( +
+

{part.output.answer}

+
    + {part.output.hits.map((hit, index) => ( +
  • + + {hit.order_id ?? shortId(hit.pack_id)} {clipRange(hit)} + {" "} + {hit.text} +
  • + ))} +
+
+ ), + }; + } + default: + return assertNever(part); + } +} + +/** One agent tool call: present tense with a shimmer while it runs, past tense and expandable after. */ +export function ToolStep({ part }: { part: ToolPart }) { + const step = describe(part); + switch (part.state) { + case "input-streaming": + case "input-available": + case "approval-requested": + case "approval-responded": + return ( + + + {step.icon} + {step.running} + + + ); + case "output-error": + case "output-denied": + return ( + + + + + {step.icon} + {step.running} failed + + + + {"errorText" in part ? part.errorText : "The tool call was refused."} + + + + ); + case "output-available": + return ( + + + + + {step.icon} + {step.done} + {step.detail && {step.detail}} + + + {step.body} + + + ); + default: + return assertNever(part); + } +} diff --git a/apps/web/src/components/label-panel.tsx b/apps/web/src/components/label-panel.tsx index da68a66..c63983b 100644 --- a/apps/web/src/components/label-panel.tsx +++ b/apps/web/src/components/label-panel.tsx @@ -16,11 +16,12 @@ import { CardHeader, CardTitle, } from "@/components/ui/card"; +import { AddressFields } from "@/components/address-fields"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Skeleton } from "@/components/ui/skeleton"; -import { Textarea } from "@/components/ui/textarea"; import type { PrinterStatus } from "@/hooks/use-probe"; +import { type Address, addressLines, EMPTY_ADDRESS } from "@/lib/address"; import { assertNever } from "@/lib/assert-never"; import { type LabelRequest, @@ -32,7 +33,6 @@ import { import { cn } from "@/lib/utils"; import { formatTime } from "@/components/status-strip"; -export const MAX_LINES = 3; const PREVIEW_DEBOUNCE_MS = 350; // the QR must open somewhere a phone can reach, so a demo on localhost points it at a public origin const PROOF_ORIGIN: string = import.meta.env.VITE_PROOF_ORIGIN || window.location.origin; @@ -217,26 +217,18 @@ export function LabelPanel({ onPrinted: (label: PrintedLabel) => void; }) { const [orderId, setOrderId] = useState(""); - const [details, setDetails] = useState(""); + const [address, setAddress] = useState
(EMPTY_ADDRESS); const [preview, setPreview] = useState({ tag: "waiting" }); const [job, setJob] = useState({ tag: "idle" }); const orderInput = useRef(null); const shownUrl = useRef(null); - const lines = details - .split("\n") - .map((line) => line.trim()) - .filter(Boolean); const label: LabelRequest = { order_id: orderId.trim(), proof_url: `${PROOF_ORIGIN}/proof/${encodeURIComponent(orderId.trim())}`, - lines, + lines: addressLines(address), }; - const linesError = - lines.length > MAX_LINES - ? `Keep it to ${MAX_LINES} lines; the label has room for three.` - : null; - const valid = Boolean(label.order_id) && !linesError; + const valid = Boolean(label.order_id); const labelKey = valid ? JSON.stringify(label) : null; useEffect(() => { @@ -286,7 +278,6 @@ export function LabelPanel({ orderInput.current?.focus(); return; } - if (!valid) return; setJob({ tag: "printing" }); try { await printLabel(label); @@ -294,7 +285,7 @@ export function LabelPanel({ onPrinted(printed); setJob({ tag: "printed", ...printed }); setOrderId(""); - setDetails(""); + setAddress((current) => ({ ...EMPTY_ADDRESS, country: current.country })); orderInput.current?.focus(); } catch (cause) { setJob({ tag: "failed", failure: toPrinterFailure(cause) }); @@ -326,34 +317,7 @@ export function LabelPanel({ onChange={(event) => edit(() => setOrderId(event.target.value))} />
-
-
- - - {lines.length}/{MAX_LINES} lines - -
-