img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function CardAction({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function CardContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+export {
+ Card,
+ CardHeader,
+ CardFooter,
+ CardTitle,
+ CardAction,
+ CardDescription,
+ CardContent,
+}
diff --git a/web/src/components/ui/checkbox.tsx b/web/src/components/ui/checkbox.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9ae64e83c5c05a016af794c01398af705a1236f9
--- /dev/null
+++ b/web/src/components/ui/checkbox.tsx
@@ -0,0 +1,32 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Checkbox as CheckboxPrimitive } from "radix-ui"
+import { CheckIcon } from "lucide-react"
+
+function Checkbox({
+ className,
+ ...props
+}: React.ComponentProps
) {
+ return (
+
+
+
+
+
+ )
+}
+
+export { Checkbox }
diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6b61a5c207acbcb5ce4c7d517c6eeb6689fee552
--- /dev/null
+++ b/web/src/components/ui/dialog.tsx
@@ -0,0 +1,168 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Dialog as DialogPrimitive } from "radix-ui"
+
+import { Button } from "@/components/ui/button"
+import { XIcon } from "lucide-react"
+
+function Dialog({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogTrigger({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogPortal({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogClose({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps & {
+ showCloseButton?: boolean
+}) {
+ return (
+
+
+
+ {children}
+ {showCloseButton && (
+
+
+
+ Close
+
+
+ )}
+
+
+ )
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showCloseButton?: boolean
+}) {
+ return (
+
+ {children}
+ {showCloseButton && (
+
+ Close
+
+ )}
+
+ )
+}
+
+function DialogTitle({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+}
diff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f772add7906589b44ae371768eb09c9419e6c587
--- /dev/null
+++ b/web/src/components/ui/dropdown-menu.tsx
@@ -0,0 +1,268 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
+import { CheckIcon, ChevronRightIcon } from "lucide-react"
+
+function DropdownMenu({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DropdownMenuPortal({
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DropdownMenuTrigger({
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DropdownMenuContent({
+ className,
+ align = "start",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+ )
+}
+
+function DropdownMenuGroup({
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DropdownMenuItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps & {
+ inset?: boolean
+ variant?: "default" | "destructive"
+}) {
+ return (
+
+ )
+}
+
+function DropdownMenuCheckboxItem({
+ className,
+ children,
+ checked,
+ inset,
+ ...props
+}: React.ComponentProps & {
+ inset?: boolean
+}) {
+ return (
+
+
+
+
+
+
+ {children}
+
+ )
+}
+
+function DropdownMenuRadioGroup({
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DropdownMenuRadioItem({
+ className,
+ children,
+ inset,
+ ...props
+}: React.ComponentProps & {
+ inset?: boolean
+}) {
+ return (
+
+
+
+
+
+
+ {children}
+
+ )
+}
+
+function DropdownMenuLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps & {
+ inset?: boolean
+}) {
+ return (
+
+ )
+}
+
+function DropdownMenuSeparator({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DropdownMenuShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+
+ )
+}
+
+function DropdownMenuSub({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DropdownMenuSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps & {
+ inset?: boolean
+}) {
+ return (
+
+ {children}
+
+
+ )
+}
+
+function DropdownMenuSubContent({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export {
+ DropdownMenu,
+ DropdownMenuPortal,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuLabel,
+ DropdownMenuItem,
+ DropdownMenuCheckboxItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubTrigger,
+ DropdownMenuSubContent,
+}
diff --git a/web/src/components/ui/input.tsx b/web/src/components/ui/input.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ea0fe00b03978a54c8bed81ef69de112985e2ca2
--- /dev/null
+++ b/web/src/components/ui/input.tsx
@@ -0,0 +1,18 @@
+import * as React from "react"
+import { cn } from "cn"
+
+function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+ return (
+
+ )
+}
+
+export { Input }
diff --git a/web/src/components/ui/label.tsx b/web/src/components/ui/label.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..089924be887020f47bf56642802aa3f8e034c3e7
--- /dev/null
+++ b/web/src/components/ui/label.tsx
@@ -0,0 +1,23 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Label as LabelPrimitive } from "radix-ui"
+
+function Label({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Label }
diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..26282e44ebfcf7e1efaaf227fdd55dbefe0605f7
--- /dev/null
+++ b/web/src/components/ui/select.tsx
@@ -0,0 +1,191 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Select as SelectPrimitive } from "radix-ui"
+import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
+
+function Select({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function SelectGroup({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function SelectValue({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function SelectTrigger({
+ className,
+ size = "default",
+ children,
+ ...props
+}: React.ComponentProps & {
+ size?: "sm" | "default"
+}) {
+ return (
+
+ {children}
+
+
+
+
+ )
+}
+
+function SelectContent({
+ className,
+ children,
+ position = "item-aligned",
+ align = "center",
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+
+ {children}
+
+
+
+
+ )
+}
+
+function SelectLabel({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+
+
+
+ {children}
+
+ )
+}
+
+function SelectSeparator({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function SelectScrollUpButton({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+ )
+}
+
+function SelectScrollDownButton({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+ )
+}
+
+export {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectScrollDownButton,
+ SelectScrollUpButton,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+}
diff --git a/web/src/components/ui/separator.tsx b/web/src/components/ui/separator.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..307f0365a8d450abcfbdfaefeb6fded35b156d36
--- /dev/null
+++ b/web/src/components/ui/separator.tsx
@@ -0,0 +1,27 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Separator as SeparatorPrimitive } from "radix-ui"
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ decorative = true,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Separator }
diff --git a/web/src/components/ui/sheet.tsx b/web/src/components/ui/sheet.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6563be60940f6fa690bdba72b9246336c322a7ea
--- /dev/null
+++ b/web/src/components/ui/sheet.tsx
@@ -0,0 +1,147 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Dialog as SheetPrimitive } from "radix-ui"
+
+import { Button } from "@/components/ui/button"
+import { XIcon } from "lucide-react"
+
+function Sheet({ ...props }: React.ComponentProps) {
+ return
+}
+
+function SheetTrigger({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function SheetClose({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function SheetPortal({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function SheetOverlay({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps & {
+ side?: "top" | "right" | "bottom" | "left"
+ showCloseButton?: boolean
+}) {
+ return (
+
+
+
+ {children}
+ {showCloseButton && (
+
+
+
+ Close
+
+
+ )}
+
+
+ )
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function SheetTitle({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export {
+ Sheet,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+}
diff --git a/web/src/components/ui/skeleton.tsx b/web/src/components/ui/skeleton.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..185a5064333e3565ed494dfdf2bd1f35cad2d107
--- /dev/null
+++ b/web/src/components/ui/skeleton.tsx
@@ -0,0 +1,13 @@
+import { cn } from "cn"
+
+function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+export { Skeleton }
diff --git a/web/src/components/ui/sonner.tsx b/web/src/components/ui/sonner.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..bfc3ca51de167f2a7735494e7907545ebc053abb
--- /dev/null
+++ b/web/src/components/ui/sonner.tsx
@@ -0,0 +1,49 @@
+"use client"
+
+import { useTheme } from "next-themes"
+import { Toaster as Sonner, type ToasterProps } from "sonner"
+import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
+
+const Toaster = ({ ...props }: ToasterProps) => {
+ const { theme = "system" } = useTheme()
+
+ return (
+
+ ),
+ info: (
+
+ ),
+ warning: (
+
+ ),
+ error: (
+
+ ),
+ loading: (
+
+ ),
+ }}
+ style={
+ {
+ "--normal-bg": "var(--popover)",
+ "--normal-text": "var(--popover-foreground)",
+ "--normal-border": "var(--border)",
+ "--border-radius": "var(--radius)",
+ } as React.CSSProperties
+ }
+ toastOptions={{
+ classNames: {
+ toast: "cn-toast",
+ },
+ }}
+ {...props}
+ />
+ )
+}
+
+export { Toaster }
diff --git a/web/src/components/ui/switch.tsx b/web/src/components/ui/switch.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..422947ff51d5772db8dde4898cb5a93bae13d1a5
--- /dev/null
+++ b/web/src/components/ui/switch.tsx
@@ -0,0 +1,32 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Switch as SwitchPrimitive } from "radix-ui"
+
+function Switch({
+ className,
+ size = "default",
+ ...props
+}: React.ComponentProps & {
+ size?: "sm" | "default"
+}) {
+ return (
+
+
+
+ )
+}
+
+export { Switch }
diff --git a/web/src/components/ui/table.tsx b/web/src/components/ui/table.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..14e60a2e9d8518d5d6d368dbe8fa8920b3ee97fe
--- /dev/null
+++ b/web/src/components/ui/table.tsx
@@ -0,0 +1,115 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+
+function Table({ className, ...props }: React.ComponentProps<"table">) {
+ return (
+
+ )
+}
+
+function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
+ return (
+
+ )
+}
+
+function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+ return (
+
+ )
+}
+
+function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+ return (
+ tr]:last:border-b-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+ return (
+
+ )
+}
+
+function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+ return (
+
+ )
+}
+
+function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+ return (
+
+ )
+}
+
+function TableCaption({
+ className,
+ ...props
+}: React.ComponentProps<"caption">) {
+ return (
+
+ )
+}
+
+export {
+ Table,
+ TableHeader,
+ TableBody,
+ TableFooter,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableCaption,
+}
diff --git a/web/src/components/ui/tabs.tsx b/web/src/components/ui/tabs.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f95dd8d003d7bd84bfffa75b21a2ad038f25aad4
--- /dev/null
+++ b/web/src/components/ui/tabs.tsx
@@ -0,0 +1,89 @@
+"use client"
+
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+import { cn } from "cn"
+import { Tabs as TabsPrimitive } from "radix-ui"
+
+function Tabs({
+ className,
+ orientation = "horizontal",
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+const tabsListVariants = cva(
+ "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
+ {
+ variants: {
+ variant: {
+ default: "bg-muted",
+ line: "gap-1 bg-transparent",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+function TabsList({
+ className,
+ variant = "default",
+ ...props
+}: React.ComponentProps &
+ VariantProps) {
+ return (
+
+ )
+}
+
+function TabsTrigger({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function TabsContent({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
diff --git a/web/src/components/ui/textarea.tsx b/web/src/components/ui/textarea.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5ffcaf70950a3b9f4f8aaf005ea9ac1cdf8050cf
--- /dev/null
+++ b/web/src/components/ui/textarea.tsx
@@ -0,0 +1,17 @@
+import * as React from "react"
+import { cn } from "cn"
+
+function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+ return (
+
+ )
+}
+
+export { Textarea }
diff --git a/web/src/components/ui/tooltip.tsx b/web/src/components/ui/tooltip.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..120b36abf6189da4643c1c8ad6afa1d29e59e620
--- /dev/null
+++ b/web/src/components/ui/tooltip.tsx
@@ -0,0 +1,56 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "cn"
+import { Tooltip as TooltipPrimitive } from "radix-ui"
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function Tooltip({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function TooltipTrigger({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function TooltipContent({
+ className,
+ sideOffset = 0,
+ children,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+ {children}
+
+
+
+ )
+}
+
+export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }
diff --git a/web/src/components/workflows/dsl.test.ts b/web/src/components/workflows/dsl.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5687a60bbefb692f5bae9a5ad28bf5bf5192f908
--- /dev/null
+++ b/web/src/components/workflows/dsl.test.ts
@@ -0,0 +1,183 @@
+import { describe as suite, expect, it } from "vitest";
+
+import {
+ addStep,
+ blankStep,
+ canonical,
+ deleteStep,
+ describe,
+ describeCondition,
+ issuesFromBody,
+ lineTone,
+ moveStep,
+ parseDefinition,
+ refText,
+ sameDefinition,
+ toFlow,
+ TRIGGER_NODE_ID,
+ updateStep,
+ versionActions,
+ type StepNodeData,
+} from "./dsl";
+import type { WorkflowDefinition } from "./types";
+
+const ORDER_CHECK: WorkflowDefinition = {
+ id: "morning_order_check",
+ name: "Morning order check",
+ description: "",
+ trigger: { type: "schedule", cron: "0 8 * * *", tz: "Asia/Karachi" },
+ steps: [
+ { id: "lookup", tool: "demo.lookup_order", args: { order_number: "ORD-1021" } },
+ {
+ id: "note",
+ tool: "demo.add_note",
+ args: { order_number: "$.lookup.number", note: "Morning check: status {{ $.lookup.status }}" },
+ },
+ ],
+};
+
+suite("describer (port of core/workflows/dsl.py describe)", () => {
+ it("renders the demo template exactly like the server", () => {
+ expect(describe(ORDER_CHECK)).toEqual([
+ "On schedule '0 8 * * *' (Asia/Karachi):",
+ "1. [lookup] call demo.lookup_order(order_number=ORD-1021)",
+ "2. [note] call demo.add_note(order_number=«lookup.number», note=Morning check: status {{ $.lookup.status }})",
+ ]);
+ });
+
+ it("handles events, conditions, for_each, approvals, waits and sign-offs", () => {
+ const d: WorkflowDefinition = {
+ id: "cod_followup",
+ name: "COD follow-up",
+ trigger: {
+ type: "event",
+ event_type: "order.created",
+ when: [{ left: "$.event.payment", op: "eq", right: "cod" }],
+ },
+ steps: [
+ { id: "find", tool: "shop.search", args: { tags: ["a", "$.event.tag"], opts: { deep: true, n: null } } },
+ { id: "pause", wait: { seconds: 300 } },
+ { id: "gate", approval: { summary: "Check the list" }, when: [{ left: "$.find.count", op: "gt", right: 0 }] },
+ {
+ id: "msg",
+ tool: "shop.send_message",
+ for_each: "$.find.items",
+ requires_approval: true,
+ args: { to: "$.item.phone" },
+ when: [{ left: "$.item.phone", op: "exists" }],
+ },
+ ],
+ };
+ expect(describe(d)).toEqual([
+ "When event 'order.created' arrives when «event.payment» is cod:",
+ "1. [find] call shop.search(tags=[a, «event.tag»], opts={deep: True, n: None})",
+ "2. [pause] wait 300 seconds",
+ "3. [gate] ask the owner to sign off: Check the list only if «find.count» > 0",
+ "4. [msg] for each item in «find.items», call shop.send_message(to=«item.phone») after a human approves only if «item.phone» exists",
+ ]);
+ expect(describe({ ...d, trigger: { type: "manual" } })[0]).toBe("When started by hand:");
+ });
+
+ it("formats values like Python str()", () => {
+ expect(refText("$.a.b")).toBe("«a.b»");
+ expect(refText(false)).toBe("False");
+ expect(refText(12)).toBe("12");
+ expect(describeCondition({ left: "$.x", op: "not_in", right: [1, 2] })).toBe("«x» is not one of [1, 2]");
+ expect(describeCondition({ left: "$.x", op: "falsy" })).toBe("«x» is not set");
+ });
+});
+
+suite("definition -> canvas graph", () => {
+ it("makes a trigger node plus one node per step, chained in order", () => {
+ const { nodes, edges } = toFlow(ORDER_CHECK, 1);
+ expect(nodes.map((n) => n.type)).toEqual(["trigger", "step", "step"]);
+ expect(nodes[0].id).toBe(TRIGGER_NODE_ID);
+ expect(nodes.map((n) => n.position.y)).toEqual([0, 150, 300]);
+ expect((nodes[2].data as StepNodeData).step.id).toBe("note");
+ expect((nodes[2].data as StepNodeData).kind).toBe("tool");
+ expect(nodes[2].selected).toBe(true);
+ expect(edges.map((e) => [e.source, e.target])).toEqual([
+ [TRIGGER_NODE_ID, nodes[1].id],
+ [nodes[1].id, nodes[2].id],
+ ]);
+ });
+
+ it("includes conditions as text", () => {
+ const d = updateStep(ORDER_CHECK, 0, { when: [{ left: "$.event.x", op: "truthy" }] });
+ expect((toFlow(d).nodes[1].data as StepNodeData).conditions).toEqual(["«event.x» is set"]);
+ });
+});
+
+suite("JSON sync and step edits", () => {
+ it("compares definitions independent of key order", () => {
+ const reordered = JSON.parse(
+ '{"steps":' + JSON.stringify(ORDER_CHECK.steps) + ',"trigger":{"tz":"Asia/Karachi","cron":"0 8 * * *","type":"schedule"},"name":"Morning order check","id":"morning_order_check","description":""}',
+ );
+ expect(sameDefinition(ORDER_CHECK, reordered)).toBe(true);
+ expect(canonical({ b: 1, a: { d: 2, c: 3 } })).toBe('{"a":{"c":3,"d":2},"b":1}');
+ expect(sameDefinition(ORDER_CHECK, updateStep(ORDER_CHECK, 1, { args: { note: "x" } }))).toBe(false);
+ });
+
+ it("parses editor text and reports errors", () => {
+ expect(parseDefinition(JSON.stringify(ORDER_CHECK))).toEqual({ ok: true, value: ORDER_CHECK });
+ expect(parseDefinition("{").ok).toBe(false);
+ expect(parseDefinition("[]").ok).toBe(false);
+ expect(parseDefinition('{"trigger":{"type":"manual"}}')).toEqual({
+ ok: false,
+ error: '"steps" must be a list.',
+ });
+ });
+
+ it("moves, adds, deletes and updates steps without mutating the input", () => {
+ const before = JSON.stringify(ORDER_CHECK);
+ const moved = moveStep(ORDER_CHECK, 1, -1);
+ expect(moved.steps.map((s) => s.id)).toEqual(["note", "lookup"]);
+ expect(moveStep(ORDER_CHECK, 0, -1)).toBe(ORDER_CHECK);
+
+ const added = addStep(ORDER_CHECK, blankStep(ORDER_CHECK, "wait"), 0);
+ expect(added.steps.map((s) => s.id)).toEqual(["lookup", "step_3", "note"]);
+ expect(added.steps[1].wait).toEqual({ seconds: 60 });
+ expect(addStep(ORDER_CHECK, blankStep(ORDER_CHECK, "approval")).steps[2].approval).toBeTruthy();
+
+ expect(deleteStep(ORDER_CHECK, 0).steps.map((s) => s.id)).toEqual(["note"]);
+
+ const updated = updateStep(ORDER_CHECK, 0, { for_each: "$.x", tool: undefined });
+ expect(updated.steps[0]).toEqual({ id: "lookup", args: { order_number: "ORD-1021" }, for_each: "$.x" });
+ expect(JSON.stringify(ORDER_CHECK)).toBe(before);
+ });
+
+ it("reads the structured 422 detail", () => {
+ const body = {
+ detail: {
+ message: "check failed",
+ ok: false,
+ errors: [{ code: "unknown_tool", message: "no such tool", step: "note" }],
+ warnings: [],
+ },
+ };
+ expect(issuesFromBody(body)).toEqual({
+ message: "check failed",
+ errors: [{ code: "unknown_tool", message: "no such tool", step: "note" }],
+ warnings: [],
+ });
+ expect(issuesFromBody({ detail: "nope" })).toBeNull();
+ });
+
+ it("gates lifecycle buttons by status", () => {
+ expect(versionActions({ status: "dry_run_ok", dry_run_current: true }, null)).toEqual({
+ approve: true,
+ activate: false,
+ rollback: false,
+ });
+ expect(versionActions({ status: "dry_run_ok", dry_run_current: false }, 1).approve).toBe(false);
+ expect(versionActions({ status: "rolled_back", dry_run_current: true }, 1)).toEqual({
+ approve: false,
+ activate: true,
+ rollback: true,
+ });
+ expect(lineTone(" + demo.add_note(x)")).toBe("execute");
+ expect(lineTone(" ? demo.refund(x) [needs_approval: big]")).toBe("approval");
+ expect(lineTone(" x demo.cancel()")).toBe("denied");
+ expect(lineTone("[lookup] read")).toBe("plain");
+ });
+});
diff --git a/web/src/components/workflows/dsl.ts b/web/src/components/workflows/dsl.ts
new file mode 100644
index 0000000000000000000000000000000000000000..9babb520408e1c6d79a161481ed8b8e193ef54dc
--- /dev/null
+++ b/web/src/components/workflows/dsl.ts
@@ -0,0 +1,318 @@
+// Pure helpers for the workflow editor: the plain-language describer (a port of
+// core/workflows/dsl.py `describe`), definition -> canvas graph, JSON sync and step edits.
+// Every edit returns a NEW definition object; the three views render the same one.
+
+import type { Condition, ConditionOp, Issue, Step, Trigger, WorkflowDefinition } from "./types";
+
+// ---------------------------------------------------------------- describer
+
+/** Python's str() for scalars, so the client text matches the server's exactly. */
+function pyStr(v: unknown): string {
+ if (v === null || v === undefined) return "None";
+ if (v === true) return "True";
+ if (v === false) return "False";
+ return String(v);
+}
+
+export function refText(v: unknown): string {
+ if (typeof v === "string" && v.startsWith("$.")) return `«${v.slice(2)}»`;
+ if (Array.isArray(v)) return `[${v.map(refText).join(", ")}]`;
+ if (v && typeof v === "object") {
+ return `{${Object.entries(v as Record)
+ .map(([k, x]) => `${k}: ${refText(x)}`)
+ .join(", ")}}`;
+ }
+ return pyStr(v);
+}
+
+export const OP_TEXT: Record = {
+ eq: "is",
+ ne: "is not",
+ gt: ">",
+ gte: ">=",
+ lt: "<",
+ lte: "<=",
+ in: "is one of",
+ not_in: "is not one of",
+ contains: "contains",
+ exists: "exists",
+ not_exists: "is missing",
+ truthy: "is set",
+ falsy: "is not set",
+};
+
+const UNARY = new Set(["exists", "not_exists", "truthy", "falsy"]);
+
+export function describeCondition(c: Condition): string {
+ const op = OP_TEXT[c.op] ?? c.op;
+ if (UNARY.has(c.op)) return `${refText(c.left)} ${op}`;
+ return `${refText(c.left)} ${op} ${refText(c.right ?? null)}`;
+}
+
+export function describeTrigger(t: Trigger): string {
+ if (t.type === "schedule") return `On schedule '${t.cron}' (${t.tz ?? "Asia/Karachi"})`;
+ if (t.type === "event") {
+ const extra = t.when?.length ? " when " + t.when.map(describeCondition).join(" and ") : "";
+ return `When event '${t.event_type}' arrives${extra}`;
+ }
+ return "When started by hand";
+}
+
+export type StepKind = "tool" | "wait" | "approval";
+
+export function stepKind(s: Step): StepKind {
+ if (s.wait) return "wait";
+ if (s.approval) return "approval";
+ return "tool";
+}
+
+export function describeStep(s: Step, i: number): string {
+ const kind = stepKind(s);
+ let text: string;
+ if (kind === "wait") {
+ text = `wait ${pyStr(s.wait?.seconds)} seconds`;
+ } else if (kind === "approval") {
+ text = `ask the owner to sign off: ${s.approval?.summary ?? ""}`;
+ } else {
+ const args = Object.entries(s.args ?? {})
+ .map(([k, v]) => `${k}=${refText(v)}`)
+ .join(", ");
+ text = `call ${pyStr(s.tool)}(${args})`;
+ if (s.for_each) text = `for each item in ${refText(s.for_each)}, ${text}`;
+ if (s.requires_approval) text += " after a human approves";
+ }
+ if (s.when?.length) text += " only if " + s.when.map(describeCondition).join(" and ");
+ return `${i}. [${s.id}] ${text}`;
+}
+
+/** Deterministic plain-language rendering, identical to the server's ``describe``. */
+export function describe(defn: WorkflowDefinition): string[] {
+ return [
+ describeTrigger(defn.trigger) + ":",
+ ...(defn.steps ?? []).map((s, i) => describeStep(s, i + 1)),
+ ];
+}
+
+// ---------------------------------------------------------------- canvas graph
+
+export interface TriggerNodeData extends Record {
+ label: string;
+ trigger: Trigger;
+}
+
+export interface StepNodeData extends Record {
+ index: number;
+ step: Step;
+ kind: StepKind;
+ conditions: string[];
+}
+
+export interface FlowNode {
+ id: string;
+ type: "trigger" | "step";
+ position: { x: number; y: number };
+ data: TriggerNodeData | StepNodeData;
+ selected?: boolean;
+}
+
+export interface FlowEdge {
+ id: string;
+ source: string;
+ target: string;
+}
+
+export const TRIGGER_NODE_ID = "__trigger";
+export const NODE_GAP_Y = 150;
+
+/** Trigger node, then one node per step in a vertical column; edges in order. */
+export function toFlow(
+ defn: WorkflowDefinition,
+ selected: number | null = null,
+): { nodes: FlowNode[]; edges: FlowEdge[] } {
+ const nodes: FlowNode[] = [
+ {
+ id: TRIGGER_NODE_ID,
+ type: "trigger",
+ position: { x: 0, y: 0 },
+ data: { label: describeTrigger(defn.trigger), trigger: defn.trigger },
+ },
+ ];
+ const edges: FlowEdge[] = [];
+ let prev = TRIGGER_NODE_ID;
+ (defn.steps ?? []).forEach((step, index) => {
+ const id = `step:${index}:${step.id}`;
+ nodes.push({
+ id,
+ type: "step",
+ position: { x: 0, y: (index + 1) * NODE_GAP_Y },
+ data: {
+ index,
+ step,
+ kind: stepKind(step),
+ conditions: (step.when ?? []).map(describeCondition),
+ },
+ selected: selected === index,
+ });
+ edges.push({ id: `e:${prev}->${id}`, source: prev, target: id });
+ prev = id;
+ });
+ return { nodes, edges };
+}
+
+// ---------------------------------------------------------------- JSON sync
+
+/** JSON with sorted object keys: two definitions are the same iff these strings match. */
+export function canonical(v: unknown): string {
+ return JSON.stringify(sortKeys(v));
+}
+
+function sortKeys(v: unknown): unknown {
+ if (Array.isArray(v)) return v.map(sortKeys);
+ if (v && typeof v === "object") {
+ return Object.fromEntries(
+ Object.keys(v as Record)
+ .sort()
+ .filter((k) => (v as Record)[k] !== undefined)
+ .map((k) => [k, sortKeys((v as Record)[k])]),
+ );
+ }
+ return v;
+}
+
+export function sameDefinition(a: unknown, b: unknown): boolean {
+ return canonical(a) === canonical(b);
+}
+
+export function formatDefinition(defn: WorkflowDefinition): string {
+ return JSON.stringify(defn, null, 2);
+}
+
+export type ParseResult =
+ | { ok: true; value: WorkflowDefinition }
+ | { ok: false; error: string };
+
+/** Parse editor text into a definition-shaped object (shape only; the server checks it). */
+export function parseDefinition(text: string): ParseResult {
+ let v: unknown;
+ try {
+ v = JSON.parse(text);
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+ if (!v || typeof v !== "object" || Array.isArray(v)) {
+ return { ok: false, error: "The definition must be a JSON object." };
+ }
+ const o = v as Record;
+ if (!o.trigger || typeof o.trigger !== "object") {
+ return { ok: false, error: "Missing \"trigger\" object." };
+ }
+ if (!Array.isArray(o.steps)) return { ok: false, error: "\"steps\" must be a list." };
+ if (o.steps.some((s) => !s || typeof s !== "object" || Array.isArray(s))) {
+ return { ok: false, error: "Every step must be an object." };
+ }
+ return { ok: true, value: v as WorkflowDefinition };
+}
+
+// ---------------------------------------------------------------- step edits
+
+function withSteps(defn: WorkflowDefinition, steps: Step[]): WorkflowDefinition {
+ return { ...defn, steps };
+}
+
+export function moveStep(defn: WorkflowDefinition, index: number, delta: number): WorkflowDefinition {
+ const to = index + delta;
+ if (index < 0 || index >= defn.steps.length || to < 0 || to >= defn.steps.length) return defn;
+ const steps = [...defn.steps];
+ const [s] = steps.splice(index, 1);
+ steps.splice(to, 0, s);
+ return withSteps(defn, steps);
+}
+
+export function deleteStep(defn: WorkflowDefinition, index: number): WorkflowDefinition {
+ if (index < 0 || index >= defn.steps.length) return defn;
+ return withSteps(
+ defn,
+ defn.steps.filter((_, i) => i !== index),
+ );
+}
+
+export function newStepId(defn: WorkflowDefinition, base = "step"): string {
+ const taken = new Set(defn.steps.map((s) => s.id));
+ for (let n = defn.steps.length + 1; ; n++) {
+ const id = `${base}_${n}`;
+ if (!taken.has(id)) return id;
+ }
+}
+
+export function blankStep(defn: WorkflowDefinition, kind: StepKind, tool = ""): Step {
+ const id = newStepId(defn);
+ if (kind === "wait") return { id, wait: { seconds: 60 } };
+ if (kind === "approval") return { id, approval: { summary: "Check before continuing" } };
+ return { id, tool, args: {} };
+}
+
+/** Insert ``step`` after ``after`` (or at the end). */
+export function addStep(defn: WorkflowDefinition, step: Step, after: number | null = null): WorkflowDefinition {
+ const steps = [...defn.steps];
+ const at = after === null ? steps.length : Math.min(after + 1, steps.length);
+ steps.splice(at, 0, step);
+ return withSteps(defn, steps);
+}
+
+/** Replace step ``index``; keys set to ``undefined`` in ``patch`` are removed. */
+export function updateStep(
+ defn: WorkflowDefinition,
+ index: number,
+ patch: Partial,
+): WorkflowDefinition {
+ if (index < 0 || index >= defn.steps.length) return defn;
+ const merged: Record = { ...defn.steps[index], ...patch };
+ for (const k of Object.keys(merged)) if (merged[k] === undefined) delete merged[k];
+ return withSteps(
+ defn,
+ defn.steps.map((s, i) => (i === index ? (merged as unknown as Step) : s)),
+ );
+}
+
+// ---------------------------------------------------------------- errors
+
+export interface IssueReport {
+ message: string;
+ errors: Issue[];
+ warnings: Issue[];
+}
+
+/** The structured 422 ``detail`` of create/version calls, if the body has one. */
+export function issuesFromBody(body: unknown): IssueReport | null {
+ if (!body || typeof body !== "object" || !("detail" in body)) return null;
+ const d = (body as { detail: unknown }).detail;
+ if (!d || typeof d !== "object" || Array.isArray(d)) return null;
+ const o = d as Record;
+ if (!Array.isArray(o.errors)) return null;
+ return {
+ message: typeof o.message === "string" ? o.message : "",
+ errors: o.errors as Issue[],
+ warnings: Array.isArray(o.warnings) ? (o.warnings as Issue[]) : [],
+ };
+}
+
+/** Which lifecycle actions the selected version allows. */
+export function versionActions(
+ v: { status: string; dry_run_current: boolean },
+ activeVersion: number | null,
+) {
+ return {
+ approve: v.status === "dry_run_ok" && v.dry_run_current,
+ activate: ["approved", "superseded", "rolled_back"].includes(v.status),
+ rollback: activeVersion !== null,
+ };
+}
+
+/** Classify a dry-run line by its marker: + would execute, ? needs approval, x denied. */
+export function lineTone(line: string): "execute" | "approval" | "denied" | "plain" {
+ const c = line.trimStart().charAt(0);
+ if (c === "+") return "execute";
+ if (c === "?") return "approval";
+ if (c === "x") return "denied";
+ return "plain";
+}
diff --git a/web/src/components/workflows/parts.tsx b/web/src/components/workflows/parts.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..50acfea84b72d567cee07f94d8fec0590b9c64b0
--- /dev/null
+++ b/web/src/components/workflows/parts.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import { CheckCircle2Icon, XCircleIcon } from "lucide-react";
+
+import { useI18n } from "@/lib/i18n";
+import { cn } from "@/lib/utils";
+
+import { lineTone } from "./dsl";
+import type { DryRun, DryRunItem, Issue } from "./types";
+
+const TONE: Record = {
+ active: "border-success/30 bg-success-soft text-success",
+ approved: "border-success/30 bg-success-soft text-success",
+ dry_run_ok: "border-info/30 bg-info-soft text-info",
+ draft: "border-border bg-muted text-muted-foreground",
+ paused: "border-warning/40 bg-warning-soft text-warning",
+ superseded: "border-border bg-muted text-muted-foreground",
+ archived: "border-border bg-muted text-muted-foreground",
+ rolled_back: "border-warning/40 bg-warning-soft text-warning",
+ dry_run_failed: "border-destructive/30 bg-destructive/10 text-destructive",
+ would_execute: "border-success/30 bg-success-soft text-success",
+ needs_approval: "border-warning/40 bg-warning-soft text-warning",
+ denied: "border-destructive/30 bg-destructive/10 text-destructive",
+ error: "border-destructive/30 bg-destructive/10 text-destructive",
+};
+
+/** Badge for workflow / version statuses and dry-run outcomes. */
+export function WfBadge({ status, className }: { status: string; className?: string }) {
+ const { m } = useI18n();
+ const label = (m.workflows.statuses as Record)[status] ?? status.replace(/_/g, " ");
+ return (
+
+ {label}
+
+ );
+}
+
+export function IssueList({
+ errors,
+ warnings,
+ testId,
+}: {
+ errors: Issue[];
+ warnings: Issue[];
+ testId?: string;
+}) {
+ const { t } = useI18n();
+ if (!errors.length && !warnings.length) return null;
+ const row = (i: Issue, kind: "error" | "warning", n: number) => (
+
+ {i.code}
+ {i.step && (
+
+ [{i.step}]
+
+ )}
+ {i.message}
+
+ );
+ return (
+
+ {errors.length > 0 && (
+
+
{t("workflows.errors")}
+
{errors.map((i, n) => row(i, "error", n))}
+
+ )}
+ {warnings.length > 0 && (
+
+
{t("workflows.warnings")}
+
{warnings.map((i, n) => row(i, "warning", n))}
+
+ )}
+
+ );
+}
+
+const LINE_TONE = {
+ execute: "text-success",
+ approval: "text-warning",
+ denied: "text-destructive",
+ plain: "text-foreground",
+} as const;
+
+function short(v: unknown): string {
+ if (v === null || v === undefined) return "";
+ const s = typeof v === "string" ? v : JSON.stringify(v);
+ return s.length > 240 ? `${s.slice(0, 240)}…` : s;
+}
+
+function ItemRow({ item }: { item: DryRunItem }) {
+ return (
+
+
+
+ {item.tier !== null && item.tier !== undefined && (
+ T{item.tier}
+ )}
+ {item.reason && {item.reason} }
+
+
+ {short(item.args)}
+
+ {item.effect !== null && item.effect !== undefined && (
+
+ → {short(item.effect)}
+
+ )}
+
+ );
+}
+
+/** The dry-run diff: verdict, totals, marked lines and per-step cards. */
+export function DryRunView({ dryRun, current = true }: { dryRun: DryRun; current?: boolean }) {
+ const { t, m } = useI18n();
+ const totals = dryRun.totals;
+ return (
+
+
+
+ {dryRun.ok ? (
+
+ ) : (
+
+ )}
+ {dryRun.ok ? t("workflows.dryRunOk") : t("workflows.dryRunFailed")}
+
+ {!current &&
{t("workflows.dryRunStale")} }
+
+ {(Object.keys(totals) as (keyof DryRun["totals"])[]).map((k) => (
+
+ {m.workflows.totals[k]}: {totals[k]}
+
+ ))}
+
+
+ {dryRun.problems.length > 0 && (
+
+ {dryRun.problems.map((p, i) => (
+ {p}
+ ))}
+
+ )}
+
+ {dryRun.lines.map((line, i) => {
+ const tone = lineTone(line);
+ return (
+
+ {line}
+
+ );
+ })}
+
+
+ {dryRun.steps.map((s) => (
+
+
+ {s.id}
+ {s.tool && (
+
+ {s.tool}
+
+ )}
+
+
+ {s.summary &&
{s.summary}
}
+ {s.reason &&
{s.reason}
}
+ {(s.items ?? []).length > 0 && (
+
+ {s.items.map((it, i) => (
+
+ ))}
+
+ )}
+
+ ))}
+
+
+ );
+}
diff --git a/web/src/components/workflows/types.ts b/web/src/components/workflows/types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..dd61a8f0d8aa68c29c8bb4d76359d85dc8d1f834
--- /dev/null
+++ b/web/src/components/workflows/types.ts
@@ -0,0 +1,224 @@
+// Workflow API shapes (Phase 11). See core/api/routes/workflows.py.
+
+export type WorkflowStatus = "draft" | "active" | "paused" | "archived";
+export type VersionStatus =
+ | "draft"
+ | "dry_run_ok"
+ | "dry_run_failed"
+ | "approved"
+ | "active"
+ | "superseded"
+ | "rolled_back";
+
+export interface Issue {
+ code: string;
+ message: string;
+ step: string | null;
+}
+
+export interface Checks {
+ ok: boolean;
+ errors: Issue[];
+ warnings: Issue[];
+}
+
+export interface Workflow {
+ id: string;
+ key: string;
+ name: string;
+ description: string;
+ status: WorkflowStatus;
+ active_version: number | null;
+ source: "nl" | "json" | "template";
+ template: string | null;
+ created_at: string;
+ updated_at: string;
+ latest_version: { version: number; status: VersionStatus } | null;
+}
+
+export interface WorkflowList {
+ items: Workflow[];
+ pending_proposals: number;
+}
+
+export type ItemOutcome = "would_execute" | "needs_approval" | "denied" | "error";
+
+export interface DryRunItem {
+ outcome: ItemOutcome;
+ args: Record;
+ effect: unknown;
+ reason: string | null;
+ tier: number | null;
+ index?: number;
+}
+
+export interface DryRunStep {
+ id: string;
+ kind: string;
+ tool: string | null;
+ status: string;
+ summary?: string;
+ reason?: string;
+ count?: number;
+ selected?: number;
+ signoff?: string;
+ items: DryRunItem[];
+}
+
+export interface DryRun {
+ ok: boolean;
+ problems: string[];
+ totals: {
+ would_execute: number;
+ needs_approval: number;
+ denied: number;
+ error: number;
+ skipped: number;
+ };
+ messages: number;
+ steps: DryRunStep[];
+ lines: string[];
+ plan: string[];
+ definition_hash: string;
+}
+
+export interface Version {
+ version: number;
+ status: VersionStatus;
+ definition: WorkflowDefinition;
+ definition_hash: string;
+ nl_source: string | null;
+ plan: string[];
+ checks: Checks;
+ dry_run: DryRun | null;
+ dry_run_at: string | null;
+ dry_run_current: boolean;
+ created_by: string | null;
+ created_at: string;
+ approved_by: string | null;
+ approved_at: string | null;
+ activated_at: string | null;
+ deactivated_at: string | null;
+ parent_version: number | null;
+ note: string | null;
+}
+
+export interface Proposal {
+ id: string;
+ workflow_id: string;
+ version: number;
+ run_id: string;
+ step_id: string;
+ failure_class: "rate_limit" | "transient" | "auth" | "schema" | "data";
+ error: string;
+ summary: string;
+ patch: { op: string; path: string; value?: unknown; from?: string }[];
+ status: string;
+ applied_version: number | null;
+ created_at: string;
+ decided_at: string | null;
+}
+
+export interface WorkflowDetail extends Workflow {
+ versions: Version[];
+ proposals: Proposal[];
+}
+
+export interface Template {
+ id: string;
+ pack: string;
+ name: string;
+ description: string;
+ trigger: "schedule" | "event" | "manual";
+ nl: string;
+ tags: string[];
+ definition: WorkflowDefinition;
+ plan: string[];
+ ok: boolean;
+ errors: Issue[];
+ warnings: Issue[];
+}
+
+export interface CatalogTool {
+ name: string;
+ description: string;
+ tier: number;
+ sensitive_args: string[];
+ tags: string[];
+ input_schema: Record;
+}
+
+export interface ValidateResult extends Checks {
+ definition: WorkflowDefinition | null;
+ plan: string[];
+}
+
+export interface WorkflowRun {
+ run_id: string;
+ status: string;
+ version: number | null;
+ trigger: string | null;
+ output: string | null;
+ error: string | null;
+ started_at: string;
+ ended_at: string | null;
+}
+
+// ---------------------------------------------------------------- the DSL
+
+export type ConditionOp =
+ | "eq"
+ | "ne"
+ | "gt"
+ | "gte"
+ | "lt"
+ | "lte"
+ | "in"
+ | "not_in"
+ | "contains"
+ | "exists"
+ | "not_exists"
+ | "truthy"
+ | "falsy";
+
+export interface Condition {
+ left: string;
+ op: ConditionOp;
+ right?: unknown;
+}
+
+export type Trigger =
+ | { type: "schedule"; cron: string; tz?: string }
+ | { type: "event"; event_type: string; when?: Condition[] }
+ | { type: "manual" };
+
+export interface Step {
+ id: string;
+ title?: string | null;
+ tool?: string | null;
+ args?: Record;
+ for_each?: string | null;
+ when?: Condition[];
+ wait?: { seconds: number } | null;
+ approval?: { summary: string } | null;
+ requires_approval?: boolean;
+ max_items?: number | null;
+ on_error?: "stop" | "continue";
+ retry?: { max_attempts?: number; backoff_s?: number };
+}
+
+export interface WorkflowDefinition {
+ id: string;
+ version?: number | null;
+ name: string;
+ description?: string;
+ trigger: Trigger;
+ steps: Step[];
+ policy_overrides?: {
+ max_tier?: number;
+ max_items_per_step?: number;
+ max_tool_calls?: number;
+ max_messages?: number;
+ require_approval_for?: string[];
+ };
+}
diff --git a/web/src/components/workflows/workflow-canvas.tsx b/web/src/components/workflows/workflow-canvas.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..347012140d4f485b2c4388bd86f64a4662d491c4
--- /dev/null
+++ b/web/src/components/workflows/workflow-canvas.tsx
@@ -0,0 +1,394 @@
+"use client";
+
+import "@xyflow/react/dist/style.css";
+
+import {
+ Background,
+ Controls,
+ Handle,
+ Position,
+ ReactFlow,
+ type Node,
+ type NodeProps,
+} from "@xyflow/react";
+import {
+ ArrowDownIcon,
+ ArrowUpIcon,
+ ClockIcon,
+ PlusIcon,
+ ShieldCheckIcon,
+ Trash2Icon,
+ WrenchIcon,
+ ZapIcon,
+} from "lucide-react";
+import { useMemo, useState } from "react";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { useI18n } from "@/lib/i18n";
+import { cn } from "@/lib/utils";
+
+import {
+ addStep,
+ blankStep,
+ deleteStep,
+ moveStep,
+ toFlow,
+ TRIGGER_NODE_ID,
+ updateStep,
+ type StepKind,
+ type StepNodeData,
+ type TriggerNodeData,
+} from "./dsl";
+import type { CatalogTool, Condition, Step, WorkflowDefinition } from "./types";
+
+type TriggerFlowNode = Node;
+type StepFlowNode = Node;
+
+function TriggerNode({ data }: NodeProps) {
+ return (
+
+
+
+ {data.trigger.type}
+
+
+ {data.label}
+
+
+
+ );
+}
+
+const KIND_ICON = { tool: WrenchIcon, wait: ClockIcon, approval: ShieldCheckIcon } as const;
+
+function StepNode({ data, selected }: NodeProps) {
+ const { m } = useI18n();
+ const Icon = KIND_ICON[data.kind];
+ const s = data.step;
+ return (
+
+
+
+
+ {s.id}
+ · {m.workflows.kinds[data.kind]}
+ {s.requires_approval && (
+
+ {m.workflows.needsSignoff}
+
+ )}
+
+
+ {data.kind === "tool" &&
{s.tool || "—"}
}
+ {data.kind === "wait" &&
{s.wait?.seconds}s
}
+ {data.kind === "approval" &&
{s.approval?.summary}
}
+ {s.for_each &&
for_each {s.for_each}
}
+ {data.conditions.map((c, i) => (
+
+ if {c}
+
+ ))}
+
+
+
+ );
+}
+
+const NODE_TYPES = { trigger: TriggerNode, step: StepNode };
+
+/** JSON textarea that applies its value only when it parses. */
+function JsonField({
+ id,
+ label,
+ value,
+ onValid,
+ testId,
+}: {
+ id: string;
+ label: string;
+ value: unknown;
+ onValid: (v: unknown) => void;
+ testId?: string;
+}) {
+ const { t } = useI18n();
+ const [text, setText] = useState(() => JSON.stringify(value ?? null, null, 2));
+ const [err, setErr] = useState(null);
+ return (
+
+ );
+}
+
+function StepPanel({
+ defn,
+ index,
+ tools,
+ onChange,
+ onSelect,
+}: {
+ defn: WorkflowDefinition;
+ index: number;
+ tools: CatalogTool[];
+ onChange: (d: WorkflowDefinition) => void;
+ onSelect: (i: number | null) => void;
+}) {
+ const { t } = useI18n();
+ const step = defn.steps[index];
+ const kind = step.wait ? "wait" : step.approval ? "approval" : "tool";
+ const set = (patch: Partial) => onChange(updateStep(defn, index, patch));
+ const tool = tools.find((x) => x.name === step.tool);
+ return (
+
+
+
+ {t("workflows.editStep")} {index + 1}
+
+
{
+ onChange(moveStep(defn, index, -1));
+ onSelect(index - 1);
+ }}
+ >
+
+
+
{
+ onChange(moveStep(defn, index, 1));
+ onSelect(index + 1);
+ }}
+ >
+
+
+
{
+ onChange(deleteStep(defn, index));
+ onSelect(null);
+ }}
+ >
+
+
+
+
+ {t("workflows.stepId")}
+ set({ id: e.target.value })}
+ />
+
+ {kind === "tool" && (
+ <>
+
+
{t("workflows.tool")}
+
set({ tool: e.target.value })}
+ />
+
+ {tools.map((x) => (
+
+ {x.description}
+
+ ))}
+
+ {tool && (
+
+ T{tool.tier} · {tool.description}
+
+ )}
+
+
+ v && typeof v === "object" && !Array.isArray(v)
+ ? set({ args: v as Record })
+ : undefined
+ }
+ />
+
+ {t("workflows.forEach")}
+ set({ for_each: e.target.value || undefined })}
+ />
+
+
+ set({ requires_approval: e.target.checked || undefined })}
+ />
+ {t("workflows.requiresApproval")}
+
+ >
+ )}
+ {kind === "wait" && (
+
+ {t("workflows.waitSeconds")}
+ set({ wait: { seconds: Number(e.target.value) || 1 } })}
+ />
+
+ )}
+ {kind === "approval" && (
+
+ {t("workflows.signoffSummary")}
+ set({ approval: { summary: e.target.value } })}
+ />
+
+ )}
+
+ Array.isArray(v) ? set({ when: v.length ? (v as Condition[]) : undefined }) : undefined
+ }
+ />
+
+ );
+}
+
+/** Canvas view: trigger + one node per step, top to bottom; edits go through ``onChange``. */
+export default function WorkflowCanvas({
+ defn,
+ tools,
+ onChange,
+ panelKey,
+}: {
+ defn: WorkflowDefinition;
+ tools: CatalogTool[];
+ onChange: (d: WorkflowDefinition) => void;
+ /** Changes when the definition was replaced from outside the canvas (resets the panel). */
+ panelKey: number;
+}) {
+ const { t } = useI18n();
+ const [selected, setSelected] = useState(null);
+ const sel = selected !== null && selected < defn.steps.length ? selected : null;
+ const { nodes, edges } = useMemo(() => toFlow(defn, sel), [defn, sel]);
+
+ const add = (kind: StepKind) => {
+ const at = sel ?? defn.steps.length - 1;
+ onChange(addStep(defn, blankStep(defn, kind), at));
+ setSelected(at + 1);
+ };
+
+ return (
+
+
+ {
+ if (node.id === TRIGGER_NODE_ID) return setSelected(null);
+ setSelected((node.data as StepNodeData).index);
+ }}
+ onPaneClick={() => setSelected(null)}
+ >
+
+
+
+
+
+
+
add("tool")} data-testid="add-tool-step">
+ {t("workflows.kinds.tool")}
+
+
add("wait")}>
+ {t("workflows.kinds.wait")}
+
+
add("approval")}>
+ {t("workflows.kinds.approval")}
+
+
+ {sel === null ? (
+
{t("workflows.selectStep")}
+ ) : (
+
+ )}
+
+
+ );
+}
diff --git a/web/src/components/workflows/workflow-detail.tsx b/web/src/components/workflows/workflow-detail.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..51f800acc96794596256887869a9c4a953551d66
--- /dev/null
+++ b/web/src/components/workflows/workflow-detail.tsx
@@ -0,0 +1,474 @@
+"use client";
+
+import {
+ CheckIcon,
+ FlaskConicalIcon,
+ PlayIcon,
+ RocketIcon,
+ RotateCcwIcon,
+ SaveIcon,
+ ShieldCheckIcon,
+ Undo2Icon,
+} from "lucide-react";
+import dynamic from "next/dynamic";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { RunStatusBadge } from "@/components/runs/status-badge";
+import { ErrorState, PageHeader } from "@/components/shell/page";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Textarea } from "@/components/ui/textarea";
+import { api, ApiError } from "@/lib/api";
+import { useAuth } from "@/lib/auth";
+import { formatDateTime } from "@/lib/format";
+import { useI18n } from "@/lib/i18n";
+import { useApi } from "@/lib/use-api";
+import { cn } from "@/lib/utils";
+
+import {
+ describe,
+ formatDefinition,
+ issuesFromBody,
+ parseDefinition,
+ sameDefinition,
+ versionActions,
+ type IssueReport,
+} from "./dsl";
+import { DryRunView, IssueList, WfBadge } from "./parts";
+import type {
+ CatalogTool,
+ ValidateResult,
+ Version,
+ WorkflowDefinition,
+ WorkflowDetail as Detail,
+ WorkflowRun,
+} from "./types";
+import { ProposalList } from "./workflows-view";
+
+const WorkflowCanvas = dynamic(() => import("./workflow-canvas"), {
+ loading: () => ,
+});
+
+function errorText(e: unknown, fallback: string): string {
+ if (e instanceof ApiError) return issuesFromBody(e.body)?.message || e.detail || fallback;
+ return e instanceof Error ? e.message : fallback;
+}
+
+/** JSON view: local text, applied to the shared definition whenever it parses. */
+function JsonEditor({
+ defn,
+ onChange,
+}: {
+ defn: WorkflowDefinition;
+ onChange: (d: WorkflowDefinition) => void;
+}) {
+ const { t } = useI18n();
+ const [text, setText] = useState(() => formatDefinition(defn));
+ const [err, setErr] = useState(null);
+ return (
+
+ );
+}
+
+function PlainView({ defn, nl }: { defn: WorkflowDefinition; nl: string | null }) {
+ const { t } = useI18n();
+ const lines = describe(defn);
+ return (
+
+ {nl && (
+
+
{t("workflows.nlSource")}
+
“{nl}”
+
+ )}
+
+ {lines.map((l, i) => (
+
+ {l}
+
+ ))}
+
+
+ );
+}
+
+/** Editor + lifecycle for one saved version. Remounted when the version (or its content) changes. */
+function VersionWorkspace({
+ wf,
+ v,
+ tools,
+ onSaved,
+ onChanged,
+}: {
+ wf: Detail;
+ v: Version;
+ tools: CatalogTool[];
+ onSaved: (n: number) => void;
+ onChanged: () => void;
+}) {
+ const { t, locale } = useI18n();
+ const { me } = useAuth();
+ const isOwner = me?.role === "owner";
+ const [defn, setDefn] = useState(v.definition);
+ const [jsonKey, setJsonKey] = useState(0);
+ const [panelKey, setPanelKey] = useState(0);
+ const [tab, setTab] = useState("plain");
+ const [busy, setBusy] = useState(null);
+ const [report, setReport] = useState(null);
+ const [validation, setValidation] = useState(null);
+ const dirty = !sameDefinition(defn, v.definition);
+ const can = versionActions(v, wf.active_version);
+
+ const edit = (d: WorkflowDefinition, from: "json" | "canvas" | "reset") => {
+ setDefn(d);
+ setValidation(null);
+ if (from !== "json") setJsonKey((k) => k + 1);
+ if (from !== "canvas") setPanelKey((k) => k + 1);
+ };
+
+ const run = async (name: string, fn: () => Promise) => {
+ setBusy(name);
+ try {
+ await fn();
+ } catch (e) {
+ toast.error(errorText(e, t("common.error")));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const base = `/workflows/${wf.id}/versions/${v.version}`;
+
+ const save = () =>
+ run("save", async () => {
+ setReport(null);
+ try {
+ const nv = await api(`/workflows/${wf.id}/versions`, {
+ method: "POST",
+ body: { definition: defn },
+ });
+ toast.success(t("workflows.saved", { n: nv.version }));
+ onSaved(nv.version);
+ } catch (e) {
+ const r = e instanceof ApiError ? issuesFromBody(e.body) : null;
+ if (!r) throw e;
+ setReport(r);
+ }
+ });
+
+ const validate = () =>
+ run("validate", async () => {
+ setReport(null);
+ const r = await api("/workflows/validate", {
+ method: "POST",
+ body: { definition: defn },
+ });
+ setValidation(r);
+ });
+
+ const lifecycle = (name: string, path: string, msg: string) =>
+ run(name, async () => {
+ await api(`${base}/${path}`, { method: "POST", body: path === "dry-run" ? {} : undefined });
+ toast.success(msg);
+ onChanged();
+ });
+
+ return (
+
+
+
+
+ {t("workflows.version")} {v.version}
+
+
+ {v.note && {v.note} }
+
+ {formatDateTime(v.created_at, locale)}
+ {v.parent_version ? ` · ${t("workflows.from", { n: v.parent_version })}` : ""}
+
+
+
+ void lifecycle("dry", "dry-run", t("workflows.dryRunDone"))}
+ data-testid="dry-run-btn"
+ >
+ {t("workflows.dryRun")}
+
+ void lifecycle("approve", "approve", t("workflows.approvedToast"))}
+ data-testid="approve-btn"
+ >
+ {t("workflows.approve")}
+
+ void lifecycle("activate", "activate", t("workflows.activatedToast"))}
+ data-testid="activate-btn"
+ >
+ {t("workflows.activate")}
+
+
+
+ {v.dry_run && (
+
+
+ {t("workflows.dryRunTitle")}
+ {v.dry_run_at && (
+
+ {formatDateTime(v.dry_run_at, locale)}
+
+ )}
+
+
+
+ )}
+
+
+
+
+
{t("workflows.definition")}
+ {dirty && (
+
+ {t("workflows.unsaved")}
+
+ )}
+
+ {dirty && (
+ edit(v.definition, "reset")}>
+ {t("workflows.discard")}
+
+ )}
+ void validate()} data-testid="validate-btn">
+ {t("workflows.validate")}
+
+ {dirty && (
+ void save()} data-testid="save-version">
+ {t("workflows.saveVersion")}
+
+ )}
+
+
+ {report && (
+
+
{report.message || t("workflows.saveFailed")}
+
+
+ )}
+ {validation && (
+
+
+ {validation.ok ? t("workflows.valid") : t("workflows.invalid")}
+
+
+
+ )}
+
+
+ {t("workflows.tabs.plain")}
+ {t("workflows.tabs.canvas")}
+ {t("workflows.tabs.json")}
+
+
+
+
+
+ {tab === "canvas" && (
+ edit(d, "canvas")}
+ />
+ )}
+
+
+ edit(d, "json")} />
+
+
+
+
+ );
+}
+
+function RecentRuns({ id }: { id: string }) {
+ const { t, locale } = useI18n();
+ const runs = useApi(`/workflows/${id}/runs`, { pollMs: 10_000 });
+ if (!runs.data) return null;
+ if (!runs.data.length) return {t("workflows.noRuns")}
;
+ return (
+
+ {runs.data.map((r) => (
+
+
+
+ {r.run_id.slice(0, 8)}
+
+
+ {r.version ? `v${r.version}` : ""} {r.trigger ?? ""}
+
+ {r.error ?? r.output ?? ""}
+ {formatDateTime(r.started_at, locale)}
+
+ ))}
+
+ );
+}
+
+export function WorkflowDetailView({ id }: { id: string }) {
+ const { t } = useI18n();
+ const { me } = useAuth();
+ const wf = useApi(`/workflows/${id}`);
+ const tools = useApi("/workflows/tools");
+ const [selected, setSelected] = useState(null);
+ const [busy, setBusy] = useState(false);
+
+ if (wf.error && !wf.data) return ;
+ if (!wf.data) return ;
+ const d = wf.data;
+ const v = d.versions.find((x) => x.version === selected) ?? d.versions[0];
+
+ const action = async (path: "rollback" | "run" | "deactivate") => {
+ setBusy(true);
+ try {
+ const out = await api<{ active_version?: number | null; version?: number }>(
+ `/workflows/${d.id}/${path}`,
+ { method: "POST", body: path === "run" ? { input: {} } : undefined },
+ );
+ if (path === "run") toast.success(t("workflows.runQueued", { n: out.version ?? "" }));
+ else if (path === "rollback")
+ toast.success(
+ out.active_version
+ ? t("workflows.rolledBackTo", { n: out.active_version })
+ : t("workflows.paused"),
+ );
+ else toast.success(t("workflows.paused"));
+ wf.reload();
+ } catch (e) {
+ toast.error(errorText(e, t("common.error")));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+
+
+ void action("rollback")}
+ data-testid="rollback-btn"
+ >
+ {t("workflows.rollback")}
+
+ void action("run")}
+ data-testid="run-now-btn"
+ >
+ {t("workflows.runNow")}
+
+ >
+ }
+ />
+
+
+
+ {t("workflows.activeVersion")}: {d.active_version ? `v${d.active_version}` : "—"}
+
+
+ {d.key}
+
+
+
+
+ {d.versions.map((x) => (
+ setSelected(x.version)}
+ data-testid={`version-${x.version}`}
+ data-status={x.status}
+ className={cn(
+ "flex items-center gap-2 rounded-md border px-2.5 py-1 text-sm transition-colors",
+ x.version === v?.version ? "border-primary bg-primary/5" : "hover:bg-muted",
+ )}
+ >
+ v{x.version}
+
+
+ ))}
+
+
+ {v && (
+ {
+ setSelected(n);
+ wf.reload();
+ }}
+ onChanged={wf.reload}
+ />
+ )}
+
+ {d.proposals.length > 0 && (
+
+ {t("workflows.proposals")}
+
+
+ )}
+
+
+ {t("workflows.recentRuns")}
+
+
+
+ );
+}
diff --git a/web/src/components/workflows/workflows-view.tsx b/web/src/components/workflows/workflows-view.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..47fce2b0be26b90722db1ed00938bec6cf446400
--- /dev/null
+++ b/web/src/components/workflows/workflows-view.tsx
@@ -0,0 +1,310 @@
+"use client";
+
+import { LayoutTemplateIcon, SparklesIcon, WorkflowIcon, WrenchIcon } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState, type FormEvent } from "react";
+import { toast } from "sonner";
+
+import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { Textarea } from "@/components/ui/textarea";
+import { api, ApiError } from "@/lib/api";
+import { formatDateTime } from "@/lib/format";
+import { useI18n } from "@/lib/i18n";
+import { useApi } from "@/lib/use-api";
+
+import { issuesFromBody, type IssueReport } from "./dsl";
+import { IssueList, WfBadge } from "./parts";
+import type { Proposal, Template, WorkflowDetail, WorkflowList } from "./types";
+
+/** POST /workflows; returns the created workflow or throws with the 422 issue report. */
+export async function createWorkflow(
+ body: { text: string } | { template: string },
+): Promise<{ ok: true; wf: WorkflowDetail } | { ok: false; report: IssueReport | null; error: Error }> {
+ try {
+ const wf = await api("/workflows", { method: "POST", body });
+ return { ok: true, wf };
+ } catch (e) {
+ const err = e instanceof Error ? e : new Error(String(e));
+ return { ok: false, report: e instanceof ApiError ? issuesFromBody(e.body) : null, error: err };
+ }
+}
+
+function NewWorkflowForm() {
+ const { t } = useI18n();
+ const router = useRouter();
+ const [text, setText] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [report, setReport] = useState(null);
+
+ const submit = async (e: FormEvent) => {
+ e.preventDefault();
+ if (!text.trim()) return;
+ setBusy(true);
+ setReport(null);
+ const res = await createWorkflow({ text: text.trim() });
+ setBusy(false);
+ if (res.ok) {
+ toast.success(t("workflows.created"));
+ router.push(`/workflows/${res.wf.id}`);
+ } else {
+ setReport(res.report);
+ if (!res.report) toast.error(res.error.message || t("common.error"));
+ }
+ };
+
+ return (
+
+ );
+}
+
+function Templates() {
+ const { t, m } = useI18n();
+ const router = useRouter();
+ const tpls = useApi("/workflows/templates");
+ const [busy, setBusy] = useState(null);
+
+ const use = async (id: string) => {
+ setBusy(id);
+ const res = await createWorkflow({ template: id });
+ setBusy(null);
+ if (res.ok) {
+ toast.success(t("workflows.created"));
+ router.push(`/workflows/${res.wf.id}`);
+ } else {
+ toast.error(res.report?.message || res.error.message || t("common.error"));
+ }
+ };
+
+ if (tpls.error && !tpls.data) return ;
+ if (!tpls.data) return ;
+ if (!tpls.data.length) return {t("workflows.noTemplates")}
;
+ return (
+
+ {tpls.data.map((tp) => (
+
+
+
+
+
{tp.name}
+
{tp.description}
+
+
{m.workflows.triggers[tp.trigger]}
+
+
“{tp.nl}”
+
+ {tp.pack}
+ {tp.tags.map((tag) => (
+
+ {tag}
+
+ ))}
+ void use(tp.id)}
+ >
+ {t("workflows.useTemplate")}
+
+
+
+ ))}
+
+ );
+}
+
+export function ProposalList({
+ proposals,
+ onChanged,
+ showWorkflow = false,
+}: {
+ proposals: Proposal[];
+ onChanged: () => void;
+ showWorkflow?: boolean;
+}) {
+ const { t, m, locale } = useI18n();
+ const [busy, setBusy] = useState(null);
+ const act = async (p: Proposal, action: "apply" | "dismiss") => {
+ setBusy(p.id);
+ try {
+ const out = await api<{ version?: number }>(`/workflows/proposals/${p.id}/${action}`, {
+ method: "POST",
+ });
+ toast.success(
+ action === "apply"
+ ? t("workflows.proposalApplied", { n: out.version ?? "" })
+ : t("workflows.proposalDismissed"),
+ );
+ onChanged();
+ } catch (e) {
+ const r = e instanceof ApiError ? issuesFromBody(e.body) : null;
+ toast.error(r?.message || (e instanceof Error ? e.message : t("common.error")));
+ } finally {
+ setBusy(null);
+ }
+ };
+ return (
+
+ {proposals.map((p) => (
+
+
+
+ {p.summary}
+ {m.workflows.failureClasses[p.failure_class] ?? p.failure_class}
+
+ {formatDateTime(p.created_at, locale)}
+
+
+ {showWorkflow && (
+
+ {t("workflows.open")}
+
+ )}
+ v{p.version} · [{p.step_id}] {p.error}
+
+ {p.patch.length > 0 && (
+
+ {p.patch.map((op) => `${op.op} ${op.path} ${op.value !== undefined ? JSON.stringify(op.value) : ""}`).join("\n")}
+
+ )}
+ {p.status === "pending" && (
+
+ void act(p, "apply")}>
+ {t("workflows.apply")}
+
+ void act(p, "dismiss")}>
+ {t("workflows.dismiss")}
+
+
+ )}
+
+ ))}
+
+ );
+}
+
+export function WorkflowsView() {
+ const { t, locale } = useI18n();
+ const list = useApi("/workflows", { pollMs: 15_000 });
+ const pending = useApi(
+ list.data && list.data.pending_proposals > 0 ? "/workflows/proposals" : null,
+ { query: { status: "pending" } },
+ );
+ const reload = () => {
+ list.reload();
+ pending.reload();
+ };
+
+ return (
+
+
+
+ {list.data && list.data.pending_proposals > 0 && (
+
+
+ {t("workflows.pendingProposals", { n: list.data.pending_proposals })}
+
+ {pending.data &&
}
+
+ )}
+
+ {list.error && !list.data ? (
+
+ ) : !list.data ? (
+
+ ) : !list.data.items.length ? (
+
+ ) : (
+
+
+
+
+ {t("workflows.name")}
+ {t("workflows.status")}
+ {t("workflows.activeVersion")}
+ {t("workflows.latestVersion")}
+ {t("workflows.updated")}
+
+
+
+ {list.data.items.map((w) => (
+
+
+
+ {w.name}
+
+ {w.description}
+
+
+
+
+ {w.active_version ? `v${w.active_version}` : "—"}
+
+ {w.latest_version ? (
+
+ v{w.latest_version.version}
+
+
+ ) : (
+ "—"
+ )}
+
+
+ {formatDateTime(w.updated_at, locale)}
+
+
+ ))}
+
+
+
+ )}
+
+
+
+
+ {t("workflows.templates")}
+
+
+
+ );
+}
diff --git a/web/src/components/workflows/workflows.test.tsx b/web/src/components/workflows/workflows.test.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c3f2eb3c4f2e3b2879a63e57066f3aaffb649ba5
--- /dev/null
+++ b/web/src/components/workflows/workflows.test.tsx
@@ -0,0 +1,176 @@
+import { screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { setAccessToken } from "@/lib/session";
+import { mockFetch } from "@/test/fixtures";
+import { renderUi } from "@/test/render";
+
+import { DryRunView } from "./parts";
+import type { DryRun } from "./types";
+import { WorkflowsView } from "./workflows-view";
+
+const push = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push, replace: vi.fn() }),
+ usePathname: () => "/workflows",
+}));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ setAccessToken(null);
+ push.mockReset();
+});
+
+const DRY_RUN: DryRun = {
+ ok: false,
+ problems: ["stops at step cancel"],
+ totals: { would_execute: 1, needs_approval: 1, denied: 1, error: 0, skipped: 0 },
+ messages: 0,
+ steps: [
+ {
+ id: "note",
+ kind: "tool",
+ tool: "demo.add_note",
+ status: "would_execute",
+ summary: "demo.add_note: 1 call",
+ items: [
+ {
+ outcome: "would_execute",
+ args: { order_number: "ORD-1021", note: "Morning check" },
+ effect: { notes_after: 2 },
+ reason: null,
+ tier: 1,
+ },
+ ],
+ },
+ {
+ id: "refund",
+ kind: "tool",
+ tool: "demo.refund_order",
+ status: "needs_approval",
+ items: [{ outcome: "needs_approval", args: { amount: 500 }, effect: null, reason: "over limit", tier: 2 }],
+ },
+ {
+ id: "cancel",
+ kind: "tool",
+ tool: "demo.cancel_order",
+ status: "denied",
+ reason: "policy forbids",
+ items: [{ outcome: "denied", args: {}, effect: null, reason: "policy forbids", tier: 3 }],
+ },
+ ],
+ lines: [
+ "[note] demo.add_note: 1 call",
+ " + demo.add_note(order_number=ORD-1021, note=Morning check)",
+ "[refund] needs approval",
+ " ? demo.refund_order(amount=500) [needs_approval: over limit]",
+ "[cancel] policy forbids",
+ " x demo.cancel_order() [denied: policy forbids]",
+ ],
+ plan: [],
+ definition_hash: "h",
+};
+
+describe("DryRunView", () => {
+ it("renders the verdict, totals, colour-coded lines and per-step items", () => {
+ renderUi( );
+ expect(screen.getByTestId("dry-run-verdict")).toHaveTextContent("Problems found");
+ expect(screen.getByText("The definition changed after this dry run.")).toBeInTheDocument();
+ expect(screen.getByTestId("dry-run-problems")).toHaveTextContent("stops at step cancel");
+ const totals = screen.getByTestId("dry-run-totals");
+ expect(within(totals).getByText("Would execute", { exact: false })).toHaveTextContent("1");
+
+ const lines = screen.getAllByTestId("dry-run-line");
+ expect(lines.map((l) => l.dataset.tone)).toEqual([
+ "plain",
+ "execute",
+ "plain",
+ "approval",
+ "plain",
+ "denied",
+ ]);
+ expect(lines[1]).toHaveClass("text-success");
+ expect(lines[3]).toHaveClass("text-warning");
+ expect(lines[5]).toHaveClass("text-destructive");
+
+ const note = screen.getByTestId("dry-run-step-note");
+ expect(note).toHaveTextContent("demo.add_note: 1 call");
+ expect(within(note).getByTestId("dry-run-item")).toHaveAttribute("data-outcome", "would_execute");
+ expect(note).toHaveTextContent('"notes_after":2');
+ expect(screen.getByTestId("dry-run-step-cancel")).toHaveTextContent("policy forbids");
+ });
+
+ it("shows a passing verdict", () => {
+ renderUi( );
+ expect(screen.getByTestId("dry-run-verdict")).toHaveAttribute("data-ok", "true");
+ expect(screen.queryByTestId("dry-run-problems")).toBeNull();
+ });
+});
+
+const WF = {
+ id: "w1",
+ key: "morning_order_check",
+ name: "Morning order check",
+ description: "Every morning",
+ status: "draft",
+ active_version: null,
+ source: "nl",
+ template: null,
+ created_at: "2026-12-05T08:00:00Z",
+ updated_at: "2026-12-05T08:00:00Z",
+ latest_version: { version: 1, status: "draft" },
+};
+
+describe("WorkflowsView", () => {
+ it("lists workflows and templates and shows compile errors from a 422", async () => {
+ const { calls } = mockFetch({
+ "GET /workflows": () => ({ items: [WF], pending_proposals: 0 }),
+ "GET /workflows/templates": () => [
+ {
+ id: "demo.morning_order_check",
+ pack: "demo",
+ name: "Morning order check",
+ description: "Look up an order every morning",
+ trigger: "schedule",
+ nl: "Every morning at 8, add a note to ORD-1021 with its status",
+ tags: ["demo"],
+ definition: {},
+ plan: [],
+ ok: true,
+ errors: [],
+ warnings: [],
+ },
+ ],
+ "POST /workflows": () =>
+ new Response(
+ JSON.stringify({
+ detail: {
+ message: "compile failed",
+ ok: false,
+ errors: [{ code: "unknown_tool", message: "tool shop.nuke is not available", step: "go" }],
+ warnings: [],
+ },
+ }),
+ { status: 422, headers: { "Content-Type": "application/json" } },
+ ),
+ });
+ renderUi( );
+ const table = await screen.findByTestId("workflows-table");
+ expect(within(table).getByText("Morning order check")).toBeInTheDocument();
+ expect(within(table).getAllByText("Draft")).toHaveLength(2);
+ const card = await screen.findByTestId("template-card");
+ expect(card).toHaveTextContent("Every morning at 8, add a note to ORD-1021");
+
+ await userEvent.type(screen.getByLabelText("New workflow"), "nuke the shop");
+ await userEvent.click(screen.getByRole("button", { name: "Create draft" }));
+ const errs = await screen.findByTestId("create-errors");
+ expect(errs).toHaveTextContent("compile failed");
+ expect(errs).toHaveTextContent("tool shop.nuke is not available");
+ expect(errs).toHaveTextContent("[go]");
+ expect(calls.find((c) => c.method === "POST" && c.path === "/workflows")?.body).toEqual({
+ text: "nuke the shop",
+ });
+ expect(push).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1bea4c9d941556f17ac8e3b2a22a26077a074ee1
--- /dev/null
+++ b/web/src/lib/api.ts
@@ -0,0 +1,101 @@
+import {
+ getAccessToken,
+ getStepupToken,
+ notifySessionExpired,
+ refreshAccessToken,
+} from "@/lib/session";
+
+export const API_URL = (process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000").replace(
+ /\/$/,
+ "",
+);
+
+export class ApiError extends Error {
+ constructor(
+ public status: number,
+ public detail: string,
+ /** The parsed error body (e.g. a structured 422 ``detail``), when there is one. */
+ public body?: unknown,
+ ) {
+ super(detail);
+ this.name = "ApiError";
+ }
+}
+
+export function detailOf(body: unknown, fallback: string): string {
+ if (body && typeof body === "object" && "detail" in body) {
+ const d = (body as { detail: unknown }).detail;
+ if (typeof d === "string") return d;
+ if (Array.isArray(d)) {
+ return d
+ .map((e) => (e && typeof e === "object" && "msg" in e ? String(e.msg) : JSON.stringify(e)))
+ .join("; ");
+ }
+ }
+ return fallback;
+}
+
+export interface RequestOptions {
+ method?: "GET" | "POST" | "PUT" | "DELETE";
+ body?: unknown;
+ signal?: AbortSignal;
+ /** Send the in-memory step-up token as X-Stepup-Token. */
+ stepup?: boolean;
+ query?: Record;
+}
+
+export function buildUrl(path: string, query?: RequestOptions["query"]): string {
+ // API_URL may be same-origin relative ("/backend" behind the deploy/hf proxy).
+ const base = typeof window === "undefined" ? "http://127.0.0.1" : window.location.origin;
+ const url = new URL(path.startsWith("http") ? path : `${API_URL}${path}`, base);
+ for (const [k, v] of Object.entries(query ?? {})) {
+ if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
+ }
+ return url.toString();
+}
+
+export async function authHeaders(stepup = false): Promise> {
+ const token = getAccessToken() ?? (await refreshAccessToken());
+ const h: Record = {};
+ if (token) h.Authorization = `Bearer ${token}`;
+ const s = stepup ? getStepupToken() : null;
+ if (s) h["X-Stepup-Token"] = s;
+ return h;
+}
+
+/** Fetch JSON from the API with the in-memory bearer token. On a 401 it refreshes once
+ * (httpOnly cookie via the BFF) and retries; if that fails the session is over. */
+export async function api(path: string, opts: RequestOptions = {}): Promise {
+ const send = async () =>
+ fetch(buildUrl(path, opts.query), {
+ method: opts.method ?? "GET",
+ headers: {
+ ...(opts.body !== undefined ? { "Content-Type": "application/json" } : {}),
+ ...(await authHeaders(opts.stepup)),
+ },
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
+ signal: opts.signal,
+ cache: "no-store",
+ });
+ let res = await send();
+ if (res.status === 401) {
+ const token = await refreshAccessToken();
+ if (!token) {
+ notifySessionExpired();
+ throw new ApiError(401, "session expired");
+ }
+ res = await send();
+ }
+ const text = await res.text();
+ const body: unknown = text ? safeJson(text) : null;
+ if (!res.ok) throw new ApiError(res.status, detailOf(body, res.statusText || "request failed"), body);
+ return body as T;
+}
+
+function safeJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
diff --git a/web/src/lib/auth.tsx b/web/src/lib/auth.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5ae9b419fa01c2bb844e066ee037cd018a03e88f
--- /dev/null
+++ b/web/src/lib/auth.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from "react";
+
+import { api } from "@/lib/api";
+import * as session from "@/lib/session";
+import type { Me, Role } from "@/lib/types";
+
+type Status = "loading" | "anonymous" | "authenticated";
+
+interface AuthValue {
+ status: Status;
+ me: Me | null;
+ login: (email: string, password: string) => Promise;
+ signup: (business: string, email: string, password: string) => Promise;
+ logout: () => Promise;
+ switchTenant: (tenantId: string) => Promise;
+ reload: () => Promise;
+ hasRole: (min: Role) => boolean;
+}
+
+export const ROLE_RANK: Record = {
+ viewer: 0,
+ agent_operator: 1,
+ manager: 2,
+ owner: 3,
+};
+
+const AuthContext = createContext(null);
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const [status, setStatus] = useState("loading");
+ const [me, setMe] = useState(null);
+
+ const loadMe = useCallback(async () => {
+ try {
+ const m = await api("/me");
+ setMe(m);
+ setStatus("authenticated");
+ } catch {
+ setMe(null);
+ setStatus("anonymous");
+ }
+ }, []);
+
+ useEffect(() => {
+ let alive = true;
+ // A reload has no access token in memory: trade the httpOnly refresh cookie for one.
+ session.refreshAccessToken().then((token) => {
+ if (!alive) return;
+ if (token) void loadMe();
+ else setStatus("anonymous");
+ });
+ const off = session.onSessionExpired(() => {
+ setMe(null);
+ setStatus("anonymous");
+ });
+ return () => {
+ alive = false;
+ off();
+ };
+ }, [loadMe]);
+
+ const value = useMemo(
+ () => ({
+ status,
+ me,
+ login: async (email, password) => {
+ await session.login(email, password);
+ await loadMe();
+ },
+ signup: async (business, email, password) => {
+ await session.signup(business, email, password);
+ await loadMe();
+ },
+ logout: async () => {
+ await session.logout();
+ setMe(null);
+ setStatus("anonymous");
+ },
+ switchTenant: async (tenantId) => {
+ await session.switchTenant(tenantId);
+ await loadMe();
+ },
+ reload: loadMe,
+ hasRole: (min) => (me ? ROLE_RANK[me.role] >= ROLE_RANK[min] : false),
+ }),
+ [status, me, loadMe],
+ );
+
+ return {children} ;
+}
+
+export function useAuth(): AuthValue {
+ const v = useContext(AuthContext);
+ if (!v) throw new Error("useAuth outside AuthProvider");
+ return v;
+}
diff --git a/web/src/lib/decide.ts b/web/src/lib/decide.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4d7759e1874a1d1506cb7b708211978cf2485b0d
--- /dev/null
+++ b/web/src/lib/decide.ts
@@ -0,0 +1,38 @@
+import { api, ApiError } from "@/lib/api";
+import type { ApprovalItem, Decision, DecisionResult } from "@/lib/types";
+
+export interface DecideInput {
+ decision: Decision;
+ note?: string;
+ edited_args?: Record;
+}
+
+export function needsStepUp(item: Pick, d: Decision): boolean {
+ return item.requires_stepup && (d === "approve" || d === "edit");
+}
+
+/** POST a decision. Step-up is collected first when the item says it needs it, and once more
+ * if the server still asks for it (e.g. the 5-minute token expired in between). */
+export async function decide(
+ item: Pick,
+ input: DecideInput,
+ requestStepUp: () => Promise,
+): Promise {
+ const stepup = needsStepUp(item, input.decision);
+ if (stepup && !(await requestStepUp())) return null;
+ const send = () =>
+ api(`/approvals/${item.id}/decision`, {
+ method: "POST",
+ body: input,
+ stepup,
+ });
+ try {
+ return await send();
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 409 && /step-up/i.test(e.detail)) {
+ if (!(await requestStepUp())) return null;
+ return send();
+ }
+ throw e;
+ }
+}
diff --git a/web/src/lib/diff.ts b/web/src/lib/diff.ts
new file mode 100644
index 0000000000000000000000000000000000000000..777dc91c62d56eb3ce2a9de178f80378174667a2
--- /dev/null
+++ b/web/src/lib/diff.ts
@@ -0,0 +1,84 @@
+// Turn a tool's dry-run preview into a before → after diff the approver can read.
+//
+// Tools describe effects in a few shapes; we recognise:
+// { refunded_before: 0, refunded_after: 20000 } -> paired *_before / *_after keys
+// { status_after: "cancelled" } -> an after value with no before
+// { before: {...}, after: {...} } -> nested snapshots, per field
+// Everything else is listed as an effect detail.
+
+export interface DiffRow {
+ field: string;
+ before: unknown;
+ after: unknown;
+ changed: boolean;
+ hasBefore: boolean;
+}
+
+export interface PreviewDiff {
+ rows: DiffRow[];
+ details: [string, unknown][];
+}
+
+const AFTER = /^(.*?)_?after$/;
+
+function isRecord(v: unknown): v is Record {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+export function same(a: unknown, b: unknown): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+export function previewDiff(preview: Record | null | undefined): PreviewDiff {
+ const rows: DiffRow[] = [];
+ const details: [string, unknown][] = [];
+ if (!preview) return { rows, details };
+ const used = new Set();
+
+ if (isRecord(preview.before) || isRecord(preview.after)) {
+ const b = isRecord(preview.before) ? preview.before : {};
+ const a = isRecord(preview.after) ? preview.after : {};
+ for (const k of new Set([...Object.keys(b), ...Object.keys(a)])) {
+ rows.push({
+ field: k,
+ before: b[k],
+ after: a[k],
+ changed: !same(b[k], a[k]),
+ hasBefore: k in b,
+ });
+ }
+ used.add("before").add("after");
+ }
+
+ for (const key of Object.keys(preview)) {
+ if (used.has(key)) continue;
+ const m = AFTER.exec(key);
+ if (!m || !m[1]) continue;
+ const base = m[1];
+ const beforeKey = [`${base}_before`, `${base}before`].find((k) => k in preview);
+ rows.push({
+ field: base,
+ before: beforeKey ? preview[beforeKey] : undefined,
+ after: preview[key],
+ changed: beforeKey ? !same(preview[beforeKey], preview[key]) : true,
+ hasBefore: Boolean(beforeKey),
+ });
+ used.add(key);
+ if (beforeKey) used.add(beforeKey);
+ }
+
+ for (const [k, v] of Object.entries(preview)) {
+ if (!used.has(k)) details.push([k, v]);
+ }
+ return { rows, details };
+}
+
+/** Field-level comparison of the original args and an edited copy. */
+export function argsChanges(
+ original: Record,
+ edited: Record,
+): { field: string; before: unknown; after: unknown }[] {
+ return Object.keys({ ...original, ...edited })
+ .filter((k) => !same(original[k], edited[k]))
+ .map((k) => ({ field: k, before: original[k], after: edited[k] }));
+}
diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts
new file mode 100644
index 0000000000000000000000000000000000000000..60c3d35449e790a3535f79a5ea61ee3e4255b768
--- /dev/null
+++ b/web/src/lib/format.ts
@@ -0,0 +1,79 @@
+// Display helpers. Amounts are whole rupees (Cedar has no floating point).
+
+const MONEY = /(amount|total|refund|price|cost|cod|outstanding|limit|balance|paid)/i;
+
+export function isMoneyField(name: string): boolean {
+ return MONEY.test(name) && !/(count|rate|pct|percent|score)/i.test(name);
+}
+
+export function formatMoney(n: number, locale = "en"): string {
+ const num = new Intl.NumberFormat(locale === "ur" ? "en-PK" : "en-PK", {
+ maximumFractionDigits: 0,
+ }).format(n);
+ return `Rs ${num}`;
+}
+
+export function formatNumber(n: number, digits = 0): string {
+ return new Intl.NumberFormat("en-PK", { maximumFractionDigits: digits }).format(n);
+}
+
+export function formatPct(n: number | null | undefined, digits = 0): string {
+ if (n === null || n === undefined || Number.isNaN(n)) return "—";
+ return `${(n * 100).toFixed(digits)}%`;
+}
+
+/** Compact duration: 45s, 3m 12s, 2h 5m, 1d 3h. */
+export function formatDuration(totalSeconds: number): string {
+ const s = Math.max(0, Math.floor(totalSeconds));
+ const d = Math.floor(s / 86400);
+ const h = Math.floor((s % 86400) / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ if (d) return h ? `${d}d ${h}h` : `${d}d`;
+ if (h) return m ? `${h}h ${m}m` : `${h}h`;
+ if (m) return sec ? `${m}m ${sec}s` : `${m}m`;
+ return `${sec}s`;
+}
+
+export function formatValue(field: string, v: unknown, locale = "en"): string {
+ if (v === undefined) return "—";
+ if (v === null) return "null";
+ if (typeof v === "number") return isMoneyField(field) ? formatMoney(v, locale) : formatNumber(v, 2);
+ if (typeof v === "boolean") return v ? "true" : "false";
+ if (typeof v === "string") return v;
+ return JSON.stringify(v);
+}
+
+export function formatDateTime(iso: string | null | undefined, locale = "en"): string {
+ if (!iso) return "—";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ return new Intl.DateTimeFormat(locale === "ur" ? "ur-PK" : "en-GB", {
+ dateStyle: "medium",
+ timeStyle: "short",
+ }).format(d);
+}
+
+export function formatTime(iso: string, locale = "en"): string {
+ const d = new Date(iso);
+ return new Intl.DateTimeFormat(locale === "ur" ? "ur-PK" : "en-GB", {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ }).format(d);
+}
+
+export function humanize(key: string): string {
+ const s = key.replace(/[._]/g, " ").trim();
+ return s.charAt(0).toUpperCase() + s.slice(1);
+}
+
+/** "demo.refund_order" -> "Refund order" */
+export function toolLabel(tool: string): string {
+ const name = tool.includes(".") ? tool.slice(tool.indexOf(".") + 1) : tool;
+ return humanize(name);
+}
+
+export function shortId(id: string | null | undefined): string {
+ return id ? id.slice(0, 8) : "—";
+}
diff --git a/web/src/lib/i18n/boot.ts b/web/src/lib/i18n/boot.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a4978f020246f0287a2c6c9ae2464fb0a9416425
--- /dev/null
+++ b/web/src/lib/i18n/boot.ts
@@ -0,0 +1,4 @@
+// Server-safe: runs inline in before paint so Urdu users never see an LTR flash.
+export const LOCALE_KEY = "wp-locale";
+
+export const localeBootScript = `try{var l=localStorage.getItem("${LOCALE_KEY}");if(l==="ur"){document.documentElement.lang="ur";document.documentElement.dir="rtl"}}catch(e){}`;
diff --git a/web/src/lib/i18n/coverage.test.ts b/web/src/lib/i18n/coverage.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..65a7d43ed8f0414f2127a2eb031637ad30cb8ccc
--- /dev/null
+++ b/web/src/lib/i18n/coverage.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+
+import { en, ur } from "./messages";
+
+type Tree = { [k: string]: string | readonly string[] | Tree };
+
+/** Flattens a message tree to dotted keys; arrays become key.0, key.1, ... */
+function flatten(tree: Tree, prefix = ""): Map {
+ const out = new Map();
+ for (const [k, v] of Object.entries(tree)) {
+ const key = prefix ? `${prefix}.${k}` : k;
+ if (typeof v === "string") out.set(key, v);
+ else if (Array.isArray(v)) v.forEach((s, i) => out.set(`${key}.${i}`, String(s)));
+ else for (const [ck, cv] of flatten(v as Tree, key)) out.set(ck, cv);
+ }
+ return out;
+}
+
+// Values that are legitimately the same in both languages: codes, formats, brand-free tokens.
+const SAME_ALLOWED = new Set(["workflows.tabs.json", "nlrules.version"]);
+
+const enFlat = flatten(en as unknown as Tree);
+const urFlat = flatten(ur as unknown as Tree);
+
+describe("Urdu translation coverage", () => {
+ it("has exactly the same keys as English", () => {
+ const missing = [...enFlat.keys()].filter((k) => !urFlat.has(k));
+ const extra = [...urFlat.keys()].filter((k) => !enFlat.has(k));
+ expect({ missing, extra }).toEqual({ missing: [], extra: [] });
+ });
+
+ it("has no empty Urdu values", () => {
+ const empty = [...urFlat].filter(([, v]) => !v.trim()).map(([k]) => k);
+ expect(empty).toEqual([]);
+ });
+
+ it("translates every value (except an explicit allowlist)", () => {
+ const same = [...enFlat]
+ .filter(([k, v]) => urFlat.get(k) === v && !SAME_ALLOWED.has(k))
+ .map(([k]) => k);
+ expect(same).toEqual([]);
+ });
+
+ it("keeps the same {placeholders} in both languages", () => {
+ const vars = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
+ const mismatched = [...enFlat]
+ .filter(([k, v]) => JSON.stringify(vars(v)) !== JSON.stringify(vars(urFlat.get(k) ?? "")))
+ .map(([k]) => k);
+ expect(mismatched).toEqual([]);
+ });
+
+ it("writes Urdu in Arabic script (Nastaliq), not transliterated Latin", () => {
+ // A value may embed codes (COD, JSON, ORD-1021, {vars}) but must contain Urdu letters.
+ const latinOnly = [...urFlat]
+ .filter(([k]) => !SAME_ALLOWED.has(k))
+ .filter(([, v]) => !/[-ۿ]/.test(v))
+ .map(([k, v]) => `${k}=${v}`);
+ expect(latinOnly).toEqual([]);
+ });
+});
diff --git a/web/src/lib/i18n/index.tsx b/web/src/lib/i18n/index.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..dec747b9a50be690bb847b67f5f2f732d709eb92
--- /dev/null
+++ b/web/src/lib/i18n/index.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import { Direction } from "radix-ui";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useSyncExternalStore,
+ type ReactNode,
+} from "react";
+
+import { messages, type Locale, type Messages } from "./messages";
+
+import { LOCALE_KEY } from "./boot";
+
+export { LOCALE_KEY };
+
+export function dirOf(locale: Locale): "ltr" | "rtl" {
+ return locale === "ur" ? "rtl" : "ltr";
+}
+
+
+type Leaf = string;
+type Path = T extends Leaf
+ ? ""
+ : T extends readonly unknown[]
+ ? ""
+ : { [K in keyof T & string]: T[K] extends Leaf ? K : `${K}.${Path}` }[keyof T & string];
+
+export type MessageKey = Path;
+
+export function translate(
+ dict: Messages,
+ key: string,
+ vars?: Record,
+): string {
+ let v: unknown = dict;
+ for (const part of key.split(".")) {
+ v = v && typeof v === "object" ? (v as Record)[part] : undefined;
+ }
+ if (typeof v !== "string") return key;
+ return vars ? v.replace(/\{(\w+)\}/g, (m, k: string) => String(vars[k] ?? m)) : v;
+}
+
+interface I18nValue {
+ locale: Locale;
+ dir: "ltr" | "rtl";
+ setLocale: (l: Locale) => void;
+ t: (key: MessageKey, vars?: Record) => string;
+ m: Messages;
+}
+
+const I18nContext = createContext(null);
+
+// The chosen locale lives in localStorage; React reads it as an external store so the
+// server render ("en") and the client never disagree during hydration.
+const localeListeners = new Set<() => void>();
+let memoryLocale: Locale | null = null;
+
+function readStoredLocale(): Locale {
+ if (memoryLocale) return memoryLocale;
+ try {
+ return window.localStorage.getItem(LOCALE_KEY) === "ur" ? "ur" : "en";
+ } catch {
+ return "en";
+ }
+}
+
+function subscribeLocale(fn: () => void): () => void {
+ localeListeners.add(fn);
+ return () => localeListeners.delete(fn);
+}
+
+export function I18nProvider({
+ children,
+ initialLocale,
+}: {
+ children: ReactNode;
+ initialLocale?: Locale;
+}) {
+ const stored = useSyncExternalStore(
+ subscribeLocale,
+ readStoredLocale,
+ () => initialLocale ?? "en",
+ );
+ const locale = initialLocale ?? stored;
+
+ useEffect(() => {
+ const el = document.documentElement;
+ el.lang = locale;
+ el.dir = dirOf(locale);
+ }, [locale]);
+
+ const setLocale = useCallback((l: Locale) => {
+ memoryLocale = l;
+ try {
+ window.localStorage.setItem(LOCALE_KEY, l);
+ } catch {
+ /* private mode: memoryLocale keeps it for this tab */
+ }
+ for (const fn of localeListeners) fn();
+ }, []);
+
+ const value = useMemo(() => {
+ const dict = messages[locale];
+ return {
+ locale,
+ dir: dirOf(locale),
+ setLocale,
+ m: dict,
+ t: (key, vars) => translate(dict, key, vars),
+ };
+ }, [locale, setLocale]);
+
+ return (
+
+ {children}
+
+ );
+}
+
+export function useI18n(): I18nValue {
+ const v = useContext(I18nContext);
+ if (!v) throw new Error("useI18n outside I18nProvider");
+ return v;
+}
diff --git a/web/src/lib/i18n/messages.ts b/web/src/lib/i18n/messages.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a9ef61badb86dae758bb4c59450888ab6b10f4ff
--- /dev/null
+++ b/web/src/lib/i18n/messages.ts
@@ -0,0 +1,1221 @@
+// UI strings. English is the source; Urdu (Nastaliq) mirrors every key.
+// Agent text (outputs, reasons from the API) is shown as returned.
+
+export const en = {
+ app: { name: "WorkPilot", tagline: "Safe AI operations for your shop" },
+ nav: {
+ inbox: "Inbox",
+ runs: "Runs",
+ chat: "Chat",
+ orders: "Orders",
+ cod: "COD",
+ analytics: "Analytics",
+ settings: "Settings",
+ operate: "Operate",
+ commerce: "Commerce",
+ insight: "Insight",
+ knowledge: "Knowledge",
+ memory: "Memory",
+ workflows: "Workflows",
+ integrations: "Integrations",
+ rules: "Rules",
+ },
+ common: {
+ loading: "Loading…",
+ retry: "Retry",
+ cancel: "Cancel",
+ save: "Save",
+ close: "Close",
+ back: "Back",
+ search: "Search",
+ all: "All",
+ none: "None",
+ yes: "Yes",
+ no: "No",
+ error: "Something went wrong",
+ previous: "Previous",
+ next: "Next",
+ of: "of",
+ signOut: "Sign out",
+ theme: "Theme",
+ light: "Light",
+ dark: "Dark",
+ system: "System",
+ language: "Language",
+ workspace: "Workspace",
+ role: "Role",
+ refresh: "Refresh",
+ notAvailable: "Not available yet",
+ mainNav: "Main",
+ menu: "Menu",
+ anyTool: "* (any)",
+ },
+ auth: {
+ login: "Sign in",
+ signup: "Create workspace",
+ email: "Email",
+ password: "Password",
+ businessName: "Business name",
+ noAccount: "New to WorkPilot?",
+ haveAccount: "Already have a workspace?",
+ invalid: "Email or password is incorrect.",
+ loginTitle: "Sign in to your workspace",
+ signupTitle: "Create your workspace",
+ passwordHint: "At least 10 characters.",
+ pitch:
+ "Every action the agent proposes passes a policy gateway. Anything risky waits here for a person, with the exact values and where each one came from.",
+ },
+ inbox: {
+ title: "Agent Inbox",
+ subtitle: "Actions waiting for a human decision. Approve facts, not summaries.",
+ empty: "Nothing is waiting for you.",
+ emptyHint: "New items appear here when the agent needs a decision.",
+ waiting: "Waiting {time}",
+ expires: "Expires {time}",
+ kind: { review: "Review", question: "Question", notify: "Notice" },
+ tier: "Tier T{n}",
+ reason: "Why it is here",
+ policyRule: "Policy rule",
+ requiredRole: "Needs role",
+ stepup: "Step-up required",
+ noStepup: "No step-up",
+ change: "Proposed change",
+ before: "Before",
+ after: "After",
+ field: "Field",
+ args: "Exact arguments",
+ value: "Value",
+ source: "Source",
+ facts: "From your records",
+ factsHint: "Read live from the system of record (trusted).",
+ details: "Effect details",
+ noPreview: "This tool has no dry-run preview.",
+ approve: "Approve",
+ edit: "Edit",
+ reject: "Reject",
+ respond: "Respond",
+ approveSelected: "Approve {n} selected",
+ selectAll: "Select all",
+ selected: "{n} selected",
+ excluded: "Excluded from bulk approval",
+ bulkNeedsStepup: "Items that need step-up or a higher role are approved one at a time.",
+ rejectTitle: "Reject this action",
+ rejectReason: "Reason (shown in the run and audit log)",
+ respondTitle: "Respond to the agent",
+ respondHint: "Your answer is recorded and the action does not run.",
+ respondPlaceholder: "Type your answer…",
+ editTitle: "Edit before approving",
+ editHint: "You can change the values. The tool cannot change.",
+ editChanges: "Your changes",
+ noChanges: "No changes yet.",
+ approveEdited: "Approve edited call",
+ approved: "Approved",
+ rejected: "Rejected",
+ edited: "Edited and approved",
+ responded: "Response sent",
+ runResult: "Run {status}",
+ viewRun: "View run",
+ undoIn: "Sends in {time}",
+ undo: "Undo",
+ undone: "Send cancelled",
+ sent: "Sent",
+ history: "Recently decided",
+ noHistory: "No decisions yet.",
+ decidedBy: "Decided {time}",
+ roleTooLow: "Needs the {role} role",
+ provenance: {
+ trusted: "Trusted",
+ untrusted: "Untrusted",
+ trustedHint: "From your system of record or a signed-in user.",
+ untrustedHint:
+ "Extracted from untrusted content (an email or a customer message). Check it before approving.",
+ },
+ totalOnOrder: "{amount} of {total} order total",
+ },
+ stepup: {
+ title: "Confirm it's you",
+ description: "This action needs a fresh code from your authenticator app.",
+ code: "6-digit code",
+ verify: "Verify and continue",
+ invalid: "That code did not work. Try the current one.",
+ enrollTitle: "Set up step-up authentication",
+ enrollDescription:
+ "Add this key to an authenticator app (Google Authenticator, 1Password, Authy), then enter the code it shows.",
+ secret: "Setup key",
+ enroll: "Generate setup key",
+ },
+ runs: {
+ title: "Runs",
+ subtitle: "Every agent run, its plan and every tool call through the gateway.",
+ empty: "No runs yet.",
+ started: "Started",
+ duration: "Duration",
+ intent: "Intent",
+ source: "Source",
+ status: "Status",
+ cost: "Cost",
+ pending: "{n} pending",
+ detail: "Run",
+ timeline: "Timeline",
+ plan: "Plan",
+ progress: "Progress",
+ output: "Output",
+ error: "Error",
+ event: "Trigger",
+ approvals: "Approvals",
+ live: "Live",
+ ended: "Stream ended",
+ trace: "Open trace",
+ noActions: "No tool calls yet.",
+ statuses: {
+ running: "Running",
+ waiting_approval: "Waiting for approval",
+ completed: "Completed",
+ rejected: "Rejected",
+ failed: "Failed",
+ unsupported: "Unsupported",
+ approved: "Approved",
+ edited: "Edited",
+ responded: "Responded",
+ expired: "Expired",
+ pending: "Pending",
+ confirmed: "Confirmed",
+ shipped: "Shipped",
+ delivered: "Delivered",
+ cancelled: "Cancelled",
+ returned: "Returned",
+ },
+ decisions: {
+ executed: "Executed",
+ replayed: "Replayed",
+ needs_approval: "Sent for approval",
+ denied: "Denied",
+ rejected: "Rejected",
+ failed: "Failed",
+ dry_run: "Dry run",
+ },
+ },
+ chat: {
+ title: "Chat",
+ subtitle: "Ask in plain language. Risky actions still go to the inbox.",
+ placeholder: "e.g. What is the status of ORD-1021?",
+ send: "Send",
+ thinking: "Working…",
+ empty: "Ask about an order, or ask the agent to do something.",
+ suggestions: ["Status of ORD-1021", "Cancel ORD-1001", "Show unconfirmed COD orders"],
+ needsApproval: "Waiting for approval in the inbox",
+ openInbox: "Open inbox",
+ },
+ orders: {
+ title: "Orders",
+ subtitle: "Live from your store: risk, confirmation and courier status.",
+ empty: "No orders match.",
+ unavailable: "Orders appear here once the e-commerce pack is installed.",
+ number: "Order",
+ customer: "Customer",
+ city: "City",
+ total: "Total",
+ payment: "Payment",
+ status: "Status",
+ risk: "Risk",
+ confirmation: "Confirmation",
+ courier: "Courier",
+ created: "Created",
+ searchPlaceholder: "Search order, customer or phone",
+ items: "Items",
+ shipments: "Shipments",
+ messages: "Messages",
+ tickets: "Tickets",
+ customerInfo: "Customer",
+ reasons: "Risk reasons",
+ bands: { low: "Low", medium: "Medium", high: "High" },
+ prepaid: "Prepaid",
+ },
+ cod: {
+ title: "Cash on delivery",
+ subtitle: "Confirmation, risk and reconciliation for COD orders.",
+ pending: "Awaiting confirmation",
+ confirmed: "Confirmed",
+ rto: "Return-to-origin rate",
+ outstanding: "COD outstanding",
+ byBand: "Orders by risk band",
+ unavailable: "COD data appears here once the e-commerce pack is installed.",
+ queue: "Unconfirmed COD orders",
+ },
+ analytics: {
+ title: "Analytics",
+ subtitle: "How much the agent resolves on its own, and what it costs.",
+ runs: "Runs",
+ autoResolution: "Auto-resolution rate",
+ autoResolutionHint: "Completed runs that needed no human approval.",
+ approvalRate: "Approval rate",
+ latency: "Median approval time",
+ toolCalls: "Tool calls",
+ cost: "Model cost",
+ costPerRun: "per run",
+ runsByStatus: "Runs by status",
+ approvals: "Approvals",
+ denials: "Top denial reasons",
+ noDenials: "No denials in this period.",
+ daily: "Runs per day",
+ period: "Last {n} days",
+ decisions: "Gateway decisions",
+ ops: {
+ title: "Operations health",
+ runErrorRate: "Run error rate",
+ runErrorHint: "{failed} of {total} runs failed",
+ toolErrorRate: "Tool error rate",
+ toolErrorHint: "{failed} failed, {denied} denied of {total}",
+ latencyP50: "Approval time (p50)",
+ latencyP95: "Approval time (p95)",
+ latencyHint: "{n} decided",
+ quotaTrips: "Quota trips",
+ breakerTrips: "Circuit-breaker trips",
+ injectionSignals: "Injection signals",
+ costTotal: "Model cost",
+ costPerRun: "Cost per run",
+ pricesUnverified: "Prices unverified",
+ denialsByCategory: "Denials by category",
+ noDenials: "No denials in this period.",
+ topReasons: "Top reasons",
+ costDaily: "Cost per day",
+ noCost: "No cost recorded in this period.",
+ runsCount: "{n} runs",
+ alerts: "Alerts",
+ noAlerts: "No alerts. Everything looks healthy.",
+ acknowledge: "Acknowledge",
+ acknowledged: "Acknowledged",
+ ackDone: "Alert acknowledged",
+ severity: {
+ info: "Info",
+ warning: "Warning",
+ critical: "Critical",
+ },
+ },
+ },
+ settings: {
+ title: "Settings",
+ subtitle: "Policies, kill switches and your team.",
+ policies: "Policy thresholds",
+ policiesHint: "Attributes your Cedar policies compare against. Whole numbers only.",
+ attr: "Attribute",
+ value: "Value",
+ addAttr: "Add attribute",
+ rules: "Approval rules",
+ rulesHint:
+ "Who must approve, and when a fresh authenticator code is required. The strictest matching rule wins.",
+ tool: "Tool",
+ arg: "Argument",
+ min: "At or above",
+ role: "Role",
+ stepup: "Step-up",
+ addRule: "Add rule",
+ remove: "Remove",
+ saved: "Settings saved",
+ ownerOnly: "Only the owner can change settings.",
+ killSwitches: "Kill switches",
+ killHint: "Stop the agent instantly, for the whole workspace or one tool.",
+ tenantSwitch: "Pause all agent actions",
+ toolSwitch: "Block a tool",
+ enabled: "On",
+ disabled: "Off",
+ noSwitches: "No switches set.",
+ team: "Team and roles",
+ security: "Security",
+ totp: "Authenticator (step-up)",
+ totpOn: "Enrolled",
+ totpOff: "Not enrolled",
+ channels: "Channels and connectors",
+ channelsHint: "WhatsApp, email and courier connections are configured by their packs.",
+ roles: {
+ owner: "Owner",
+ manager: "Manager",
+ agent_operator: "Operator",
+ viewer: "Viewer",
+ },
+ },
+ knowledge: {
+ title: "Knowledge",
+ subtitle:
+ "Policies, FAQs and SOPs the agent may quote. Answers always cite the document; document text is treated as untrusted and never decides an action.",
+ upload: "Add a document",
+ uploadHint: "PDF, DOCX, Markdown or plain text, or paste text below.",
+ file: "File",
+ docTitle: "Title",
+ pasteText: "Or paste text",
+ url: "Or a web page URL",
+ add: "Add to knowledge",
+ added: "Document added",
+ docs: "Documents",
+ noDocs: "No documents yet",
+ noDocsHint: "Upload your return policy or FAQ so the agent can answer customers from it.",
+ chunks: "{n} passages",
+ pages: "{n} pages",
+ flagged: "{n} flagged",
+ flaggedHint: "Some passages look like instructions to an AI. They are kept as data and never followed.",
+ remove: "Delete",
+ removed: "Document deleted",
+ searchTitle: "Try a question",
+ searchPlaceholder: "What is our return policy for damaged items?",
+ noHits: "Nothing in the documents matches this question.",
+ untrusted: "Untrusted text",
+ score: "score {s}",
+ },
+ memory: {
+ title: "Memory",
+ subtitle:
+ "What the agent remembers between conversations. Order status, stock, amounts and payment states are never stored here: they are always read live.",
+ kinds: { all: "All", customer: "Customers", prefs: "Preferences", case: "Resolved cases" },
+ empty: "Nothing remembered yet",
+ emptyHint: "Resolved support cases and customer preferences appear here.",
+ key: "Key",
+ value: "Content",
+ expires: "Expires",
+ namespace: "Scope",
+ tampered: "Integrity check failed; hidden from the agent",
+ forget: "Forget",
+ forgotten: "Removed from memory",
+ customerId: "Customer ID",
+ forgetCustomer: "Forget this customer",
+ forgetCustomerDone: "Removed {n} items about this customer",
+ managerOnly: "Only managers and owners can view memory.",
+ },
+ workflows: {
+ title: "Workflows",
+ subtitle:
+ "Automations described in plain language, checked, dry-run against live data and approved by the owner before they run.",
+ newTitle: "New workflow",
+ newHint: "Describe what should happen and when. You get a draft to review; nothing runs yet.",
+ newPlaceholder: "Every morning at 8, add a note to ORD-1021 with its status",
+ create: "Create draft",
+ compiling: "Drafting…",
+ created: "Workflow draft created",
+ templates: "Templates",
+ noTemplates: "No templates from the installed packs.",
+ useTemplate: "Use template",
+ triggers: { schedule: "Schedule", event: "Event", manual: "Manual" },
+ empty: "No workflows yet",
+ emptyHint: "Describe one below or start from a template.",
+ name: "Workflow",
+ status: "Status",
+ activeVersion: "Active version",
+ latestVersion: "Latest version",
+ updated: "Updated",
+ open: "Open",
+ pendingProposals: "{n} self-healing fixes waiting for review",
+ proposals: "Proposed fixes",
+ apply: "Apply as new draft",
+ dismiss: "Dismiss",
+ proposalApplied: "Fix saved as draft version {n}",
+ proposalDismissed: "Fix dismissed",
+ failureClasses: { rate_limit: "Rate limit", transient: "Temporary error", auth: "Authentication", schema: "Schema", data: "Data" },
+ statuses: {
+ draft: "Draft",
+ active: "Active",
+ paused: "Paused",
+ archived: "Archived",
+ dry_run_ok: "Dry run passed",
+ dry_run_failed: "Dry run failed",
+ approved: "Approved",
+ superseded: "Superseded",
+ rolled_back: "Rolled back",
+ would_execute: "Would execute",
+ needs_approval: "Needs approval",
+ denied: "Denied",
+ error: "Error",
+ skipped: "Skipped",
+ not_reached: "Not reached",
+ wait: "Wait",
+ pending: "Pending",
+ applied: "Applied",
+ dismissed: "Dismissed",
+ },
+ totals: {
+ would_execute: "Would execute",
+ needs_approval: "Needs approval",
+ denied: "Denied",
+ error: "Errors",
+ skipped: "Skipped",
+ },
+ kinds: { tool: "Tool", wait: "Wait", approval: "Sign-off" },
+ versions: "Versions",
+ version: "Version",
+ from: "from v{n}",
+ definition: "Definition",
+ tabs: { plain: "Plain language", canvas: "Canvas", json: "JSON" },
+ nlSource: "Described as",
+ unsaved: "Unsaved changes",
+ discard: "Discard",
+ validate: "Validate",
+ valid: "The definition passes all checks.",
+ invalid: "The definition has problems.",
+ saveVersion: "Save as new version",
+ saved: "Saved as version {n}",
+ saveFailed: "Could not save this version.",
+ errors: "Errors",
+ warnings: "Warnings",
+ jsonError: "Invalid JSON",
+ dryRun: "Dry run",
+ dryRunTitle: "Dry run",
+ dryRunDone: "Dry run finished",
+ dryRunOk: "Safe to approve",
+ dryRunFailed: "Problems found",
+ dryRunStale: "The definition changed after this dry run.",
+ approve: "Approve",
+ approvedToast: "Version approved",
+ activate: "Activate",
+ activatedToast: "Version activated",
+ ownerOnly: "Only the owner can do this.",
+ rollback: "Rollback",
+ rolledBackTo: "Rolled back to version {n}",
+ paused: "Workflow paused",
+ runNow: "Run now",
+ runQueued: "Run of version {n} queued",
+ recentRuns: "Recent runs",
+ noRuns: "No runs yet.",
+ needsSignoff: "Sign-off",
+ selectStep: "Select a step on the canvas to edit it.",
+ editStep: "Step",
+ moveUp: "Move up",
+ moveDown: "Move down",
+ deleteStep: "Delete step",
+ stepId: "Step ID",
+ tool: "Tool",
+ args: "Arguments (JSON)",
+ forEach: "For each",
+ when: "Only if (conditions, JSON)",
+ requiresApproval: "Ask a human before this step",
+ waitSeconds: "Wait (seconds)",
+ signoffSummary: "What the owner signs off",
+ },
+ integrations: {
+ title: "Integrations & tools",
+ subtitle:
+ "Connect your own systems without a deploy. New tools start at T3 (every call needs your approval) in test mode until you confirm them.",
+ tabTools: "Tools",
+ tabImport: "Import API",
+ tabMcp: "MCP servers",
+ tabConnectors: "Connectors",
+ noTools: "No tools added yet",
+ noToolsHint: "Import an OpenAPI spec, connect an MCP server or add a connector.",
+ tool: "Tool",
+ source: "Source",
+ suggested: "Suggested",
+ tier: "Tier",
+ mode: "Mode",
+ status: "Status",
+ live: "Live",
+ test: "Test",
+ enabled: "Enabled",
+ disabled: "Disabled",
+ blocked: "Blocked",
+ unconfirmed: "Not confirmed",
+ confirm: "Confirm",
+ confirmed: "Tool confirmed",
+ lowerTier: "Below the suggested tier: I understand the risk",
+ tryIt: "Dry run",
+ args: "Arguments (JSON)",
+ runDryRun: "Preview call",
+ preview: "Preview",
+ changed: "Definition changed. Review and confirm again.",
+ before: "Before",
+ after: "After",
+ ownerOnly: "Only the owner can import, confirm or enable tools.",
+ name: "Name",
+ nameHint: "Tool name prefix: lowercase letters, digits and _.",
+ spec: "OpenAPI spec (JSON or YAML)",
+ specUrl: "…or spec URL",
+ baseUrl: "Base URL (optional)",
+ sandboxUrl: "Sandbox base URL (optional)",
+ secretRef: "Secret reference",
+ secretRefHint: "The name of a stored secret, never the secret itself.",
+ sandboxSecretRef: "Sandbox secret reference",
+ importButton: "Import",
+ imported: "Imported {n} tools",
+ url: "Server URL",
+ auth: "Authentication",
+ authNone: "None",
+ authBearer: "Bearer token",
+ connect: "Connect",
+ connected: "Server connected: {n} tools",
+ refresh: "Refresh",
+ refreshed: "Refreshed",
+ lastDiff: "Last refresh",
+ noMcp: "No MCP servers connected",
+ kind: "Kind",
+ kinds: { table: "CSV / Excel", google_sheets: "Google Sheets", http_action: "HTTP action", webhook: "Webhook mapping" },
+ mcpStatuses: { new: "New", ok: "OK", changed: "Changed", error: "Error" },
+ config: "Configuration (JSON)",
+ create: "Add connector",
+ created: "Connector added",
+ upload: "Upload CSV / Excel",
+ uploaded: "Uploaded {n} rows",
+ noConnectors: "No connectors yet",
+ invalidJson: "That is not valid JSON.",
+ },
+ nlrules: {
+ title: "Rules",
+ subtitle:
+ "Write a rule in plain words. WorkPilot turns it into a policy, shows it back and tests it before you confirm.",
+ placeholder: "e.g. refunds over 10k need my approval",
+ compile: "Check rule",
+ draft: "Draft",
+ understood: "WorkPilot understood",
+ policy: "Policy (Cedar)",
+ tests: "Test calls",
+ call: "Call",
+ actor: "By",
+ outcome: "Result",
+ matched: "Applies",
+ notMatched: "Does not apply",
+ confirm: "Confirm rule",
+ confirmed: "Rule is active",
+ allowPermit: "Yes, let matching calls run without approval",
+ question: "WorkPilot needs a detail",
+ active: "Active rules",
+ history: "History",
+ noRules: "No rules yet",
+ version: "v{n}",
+ rollback: "Roll back",
+ rolledBack: "Rolled back",
+ disable: "Turn off",
+ disabledToast: "Rule turned off",
+ ownerOnly: "Only the owner can confirm, roll back or turn off rules.",
+ status: "Status",
+ statuses: {
+ draft: "Draft",
+ active: "Active",
+ superseded: "Superseded",
+ rolled_back: "Rolled back",
+ disabled: "Off",
+ discarded: "Discarded",
+ },
+ },
+ errors: {
+ stepupRequired: "Step-up authentication required",
+ forbidden: "You do not have permission for this.",
+ network: "Cannot reach the WorkPilot API.",
+ },
+ validation: {
+ number: "must be a number",
+ wholeNumber: "must be a whole number",
+ greaterThan: "must be greater than {n}",
+ atLeast: "must be at least {n}",
+ atMost: "must be at most {n}",
+ maxChars: "at most {n} characters",
+ minChars: "at least {n} characters",
+ pattern: "must match {pattern}",
+ invalidJson: "invalid JSON",
+ },
+};
+
+export type Messages = typeof en;
+
+export const ur: Messages = {
+ app: { name: "ورک پائلٹ", tagline: "آپ کی دکان کے لیے محفوظ اے آئی آپریشنز" },
+ nav: {
+ inbox: "ان باکس",
+ runs: "رنز",
+ chat: "چیٹ",
+ orders: "آرڈرز",
+ cod: "کیش آن ڈیلیوری",
+ analytics: "تجزیات",
+ settings: "ترتیبات",
+ operate: "کارروائی",
+ commerce: "کاروبار",
+ insight: "بصیرت",
+ knowledge: "معلومات",
+ memory: "یادداشت",
+ workflows: "ورک فلوز",
+ integrations: "انٹیگریشنز",
+ rules: "اصول",
+ },
+ common: {
+ loading: "لوڈ ہو رہا ہے…",
+ retry: "دوبارہ کوشش کریں",
+ cancel: "منسوخ",
+ save: "محفوظ کریں",
+ close: "بند کریں",
+ back: "واپس",
+ search: "تلاش",
+ all: "سب",
+ none: "کوئی نہیں",
+ yes: "ہاں",
+ no: "نہیں",
+ error: "کچھ غلط ہو گیا",
+ previous: "پچھلا",
+ next: "اگلا",
+ of: "میں سے",
+ signOut: "سائن آؤٹ",
+ theme: "تھیم",
+ light: "روشن",
+ dark: "تاریک",
+ system: "سسٹم",
+ language: "زبان",
+ workspace: "ورک اسپیس",
+ role: "کردار",
+ refresh: "تازہ کریں",
+ notAvailable: "ابھی دستیاب نہیں",
+ mainNav: "مرکزی",
+ menu: "مینو",
+ anyTool: "* (کوئی بھی)",
+ },
+ auth: {
+ login: "سائن ان",
+ signup: "ورک اسپیس بنائیں",
+ email: "ای میل",
+ password: "پاس ورڈ",
+ businessName: "کاروبار کا نام",
+ noAccount: "ورک پائلٹ پر نئے ہیں؟",
+ haveAccount: "پہلے سے ورک اسپیس ہے؟",
+ invalid: "ای میل یا پاس ورڈ درست نہیں۔",
+ loginTitle: "اپنی ورک اسپیس میں سائن ان کریں",
+ signupTitle: "اپنی ورک اسپیس بنائیں",
+ passwordHint: "کم از کم 10 حروف۔",
+ pitch:
+ "ایجنٹ کا ہر مجوزہ عمل پالیسی گیٹ وے سے گزرتا ہے۔ ہر خطرناک کام یہاں انسان کے فیصلے کا انتظار کرتا ہے، درست اقدار اور ہر قدر کے ماخذ کے ساتھ۔",
+ },
+ inbox: {
+ title: "ایجنٹ ان باکس",
+ subtitle: "وہ کام جو انسانی فیصلے کے منتظر ہیں۔ خلاصے نہیں، حقائق منظور کریں۔",
+ empty: "آپ کے لیے کچھ زیرِ التوا نہیں۔",
+ emptyHint: "جب ایجنٹ کو فیصلہ درکار ہو گا تو نئی چیزیں یہاں آئیں گی۔",
+ waiting: "{time} سے منتظر",
+ expires: "{time} میں ختم",
+ kind: { review: "جائزہ", question: "سوال", notify: "اطلاع" },
+ tier: "درجہ T{n}",
+ reason: "یہ یہاں کیوں ہے",
+ policyRule: "پالیسی اصول",
+ requiredRole: "درکار کردار",
+ stepup: "اضافی تصدیق درکار",
+ noStepup: "اضافی تصدیق نہیں",
+ change: "مجوزہ تبدیلی",
+ before: "پہلے",
+ after: "بعد میں",
+ field: "خانہ",
+ args: "درست دلائل",
+ value: "قدر",
+ source: "ماخذ",
+ facts: "آپ کے ریکارڈ سے",
+ factsHint: "اصل ریکارڈ سے براہِ راست پڑھا گیا (قابلِ اعتماد)۔",
+ details: "اثر کی تفصیل",
+ noPreview: "اس ٹول کا پیشگی جائزہ دستیاب نہیں۔",
+ approve: "منظور",
+ edit: "ترمیم",
+ reject: "مسترد",
+ respond: "جواب دیں",
+ approveSelected: "{n} منتخب منظور کریں",
+ selectAll: "سب منتخب کریں",
+ selected: "{n} منتخب",
+ excluded: "اجتماعی منظوری سے خارج",
+ bulkNeedsStepup: "اضافی تصدیق یا اعلیٰ کردار والی چیزیں ایک ایک کر کے منظور ہوتی ہیں۔",
+ rejectTitle: "یہ کام مسترد کریں",
+ rejectReason: "وجہ (رن اور آڈٹ لاگ میں دکھائی جائے گی)",
+ respondTitle: "ایجنٹ کو جواب دیں",
+ respondHint: "آپ کا جواب محفوظ ہوگا اور یہ کام نہیں چلے گا۔",
+ respondPlaceholder: "اپنا جواب لکھیں…",
+ editTitle: "منظوری سے پہلے ترمیم کریں",
+ editHint: "آپ اقدار بدل سکتے ہیں۔ ٹول نہیں بدل سکتا۔",
+ editChanges: "آپ کی تبدیلیاں",
+ noChanges: "ابھی کوئی تبدیلی نہیں۔",
+ approveEdited: "ترمیم شدہ منظور کریں",
+ approved: "منظور ہو گیا",
+ rejected: "مسترد ہو گیا",
+ edited: "ترمیم کے ساتھ منظور",
+ responded: "جواب بھیج دیا",
+ runResult: "رن: {status}",
+ viewRun: "رن دیکھیں",
+ undoIn: "{time} میں بھیجا جائے گا",
+ undo: "واپس لیں",
+ undone: "بھیجنا منسوخ",
+ sent: "بھیج دیا",
+ history: "حالیہ فیصلے",
+ noHistory: "ابھی کوئی فیصلہ نہیں۔",
+ decidedBy: "{time} فیصلہ ہوا",
+ roleTooLow: "{role} کا کردار درکار ہے",
+ provenance: {
+ trusted: "قابلِ اعتماد",
+ untrusted: "غیر مصدقہ",
+ trustedHint: "آپ کے ریکارڈ یا سائن ان صارف سے۔",
+ untrustedHint: "غیر مصدقہ مواد (ای میل یا گاہک کے پیغام) سے نکالا گیا۔ منظوری سے پہلے جانچ لیں۔",
+ },
+ totalOnOrder: "آرڈر کے کل {total} میں سے {amount}",
+ },
+ stepup: {
+ title: "تصدیق کریں کہ یہ آپ ہیں",
+ description: "اس کام کے لیے آپ کی آتھنٹیکیٹر ایپ کا تازہ کوڈ درکار ہے۔",
+ code: "6 ہندسوں کا کوڈ",
+ verify: "تصدیق کر کے جاری رکھیں",
+ invalid: "یہ کوڈ کام نہیں کیا۔ موجودہ کوڈ آزمائیں۔",
+ enrollTitle: "اضافی تصدیق ترتیب دیں",
+ enrollDescription: "یہ کلید آتھنٹیکیٹر ایپ میں شامل کریں، پھر اس کا دکھایا گیا کوڈ درج کریں۔",
+ secret: "سیٹ اپ کلید",
+ enroll: "سیٹ اپ کلید بنائیں",
+ },
+ runs: {
+ title: "رنز",
+ subtitle: "ایجنٹ کا ہر رن، اس کا منصوبہ اور گیٹ وے سے ہر ٹول کال۔",
+ empty: "ابھی کوئی رن نہیں۔",
+ started: "شروع",
+ duration: "دورانیہ",
+ intent: "مقصد",
+ source: "ماخذ",
+ status: "حالت",
+ cost: "لاگت",
+ pending: "{n} زیرِ التوا",
+ detail: "رن",
+ timeline: "ٹائم لائن",
+ plan: "منصوبہ",
+ progress: "پیش رفت",
+ output: "نتیجہ",
+ error: "خرابی",
+ event: "محرک",
+ approvals: "منظوریاں",
+ live: "براہِ راست",
+ ended: "اسٹریم ختم",
+ trace: "ٹریس کھولیں",
+ noActions: "ابھی کوئی ٹول کال نہیں۔",
+ statuses: {
+ running: "جاری",
+ waiting_approval: "منظوری کا منتظر",
+ completed: "مکمل",
+ rejected: "مسترد",
+ failed: "ناکام",
+ unsupported: "غیر معاون",
+ approved: "منظور",
+ edited: "ترمیم شدہ",
+ responded: "جواب دیا",
+ expired: "میعاد ختم",
+ pending: "زیرِ التوا",
+ confirmed: "تصدیق شدہ",
+ shipped: "روانہ",
+ delivered: "پہنچا دیا گیا",
+ cancelled: "منسوخ",
+ returned: "واپس",
+ },
+ decisions: {
+ executed: "انجام دیا",
+ replayed: "دہرایا گیا",
+ needs_approval: "منظوری کے لیے بھیجا",
+ denied: "روک دیا",
+ rejected: "مسترد",
+ failed: "ناکام",
+ dry_run: "آزمائشی",
+ },
+ },
+ chat: {
+ title: "چیٹ",
+ subtitle: "سادہ زبان میں پوچھیں۔ خطرناک کام پھر بھی ان باکس میں جائیں گے۔",
+ placeholder: "مثلاً ORD-1021 کی کیا صورتحال ہے؟",
+ send: "بھیجیں",
+ thinking: "کام جاری ہے…",
+ empty: "کسی آرڈر کے بارے میں پوچھیں، یا ایجنٹ سے کوئی کام کروائیں۔",
+ suggestions: ["ORD-1021 کی صورتحال", "ORD-1001 منسوخ کریں", "غیر تصدیق شدہ COD آرڈرز دکھائیں"],
+ needsApproval: "ان باکس میں منظوری کا منتظر",
+ openInbox: "ان باکس کھولیں",
+ },
+ orders: {
+ title: "آرڈرز",
+ subtitle: "آپ کے اسٹور سے براہِ راست: خطرہ، تصدیق اور کوریئر کی حالت۔",
+ empty: "کوئی آرڈر نہیں ملا۔",
+ unavailable: "ای کامرس پیک انسٹال ہونے کے بعد آرڈرز یہاں نظر آئیں گے۔",
+ number: "آرڈر",
+ customer: "گاہک",
+ city: "شہر",
+ total: "کل",
+ payment: "ادائیگی",
+ status: "حالت",
+ risk: "خطرہ",
+ confirmation: "تصدیق",
+ courier: "کوریئر",
+ created: "تاریخ",
+ searchPlaceholder: "آرڈر، گاہک یا فون تلاش کریں",
+ items: "اشیاء",
+ shipments: "ترسیل",
+ messages: "پیغامات",
+ tickets: "ٹکٹس",
+ customerInfo: "گاہک",
+ reasons: "خطرے کی وجوہات",
+ bands: { low: "کم", medium: "درمیانہ", high: "زیادہ" },
+ prepaid: "پیشگی ادائیگی",
+ },
+ cod: {
+ title: "کیش آن ڈیلیوری",
+ subtitle: "COD آرڈرز کی تصدیق، خطرہ اور حساب کتاب۔",
+ pending: "تصدیق کے منتظر",
+ confirmed: "تصدیق شدہ",
+ rto: "واپسی کی شرح",
+ outstanding: "واجب الادا COD",
+ byBand: "خطرے کے لحاظ سے آرڈرز",
+ unavailable: "ای کامرس پیک انسٹال ہونے کے بعد COD ڈیٹا یہاں نظر آئے گا۔",
+ queue: "غیر تصدیق شدہ COD آرڈرز",
+ },
+ analytics: {
+ title: "تجزیات",
+ subtitle: "ایجنٹ خود کتنا حل کرتا ہے، اور اس کی لاگت کیا ہے۔",
+ runs: "رنز",
+ autoResolution: "خودکار حل کی شرح",
+ autoResolutionHint: "مکمل رنز جن میں انسانی منظوری درکار نہیں ہوئی۔",
+ approvalRate: "منظوری کی شرح",
+ latency: "منظوری کا درمیانی وقت",
+ toolCalls: "ٹول کالز",
+ cost: "ماڈل کی لاگت",
+ costPerRun: "فی رن",
+ runsByStatus: "حالت کے لحاظ سے رنز",
+ approvals: "منظوریاں",
+ denials: "انکار کی بڑی وجوہات",
+ noDenials: "اس مدت میں کوئی انکار نہیں۔",
+ daily: "روزانہ رنز",
+ period: "پچھلے {n} دن",
+ decisions: "گیٹ وے فیصلے",
+ ops: {
+ title: "آپریشنز کی صحت",
+ runErrorRate: "رنز میں خرابی کی شرح",
+ runErrorHint: "{total} میں سے {failed} رنز ناکام",
+ toolErrorRate: "ٹول خرابی کی شرح",
+ toolErrorHint: "{total} میں سے {failed} ناکام، {denied} مسترد",
+ latencyP50: "منظوری کا وقت (p50)",
+ latencyP95: "منظوری کا وقت (p95)",
+ latencyHint: "{n} فیصلے",
+ quotaTrips: "کوٹا کی حد عبور",
+ breakerTrips: "سرکٹ بریکر کا کھلنا",
+ injectionSignals: "انجیکشن کے اشارے",
+ costTotal: "ماڈل کی لاگت",
+ costPerRun: "فی رن لاگت",
+ pricesUnverified: "قیمتوں کی تصدیق نہیں ہوئی",
+ denialsByCategory: "زمرے کے لحاظ سے انکار",
+ noDenials: "اس مدت میں کوئی انکار نہیں۔",
+ topReasons: "بڑی وجوہات",
+ costDaily: "روزانہ لاگت",
+ noCost: "اس مدت میں کوئی لاگت درج نہیں۔",
+ runsCount: "{n} رنز",
+ alerts: "انتباہات",
+ noAlerts: "کوئی انتباہ نہیں۔ سب ٹھیک لگ رہا ہے۔",
+ acknowledge: "تسلیم کریں",
+ acknowledged: "تسلیم شدہ",
+ ackDone: "انتباہ تسلیم کر لیا گیا",
+ severity: {
+ info: "معلومات",
+ warning: "انتباہ",
+ critical: "سنگین",
+ },
+ },
+ },
+ settings: {
+ title: "ترتیبات",
+ subtitle: "پالیسیاں، کِل سوئچ اور آپ کی ٹیم۔",
+ policies: "پالیسی حدیں",
+ policiesHint: "وہ اقدار جن سے آپ کی پالیسیاں موازنہ کرتی ہیں۔ صرف مکمل اعداد۔",
+ attr: "خصوصیت",
+ value: "قدر",
+ addAttr: "خصوصیت شامل کریں",
+ rules: "منظوری کے اصول",
+ rulesHint: "کون منظور کرے، اور کب تازہ کوڈ درکار ہو۔ سب سے سخت اصول لاگو ہوتا ہے۔",
+ tool: "ٹول",
+ arg: "دلیل",
+ min: "اس یا زیادہ پر",
+ role: "کردار",
+ stepup: "اضافی تصدیق",
+ addRule: "اصول شامل کریں",
+ remove: "ہٹائیں",
+ saved: "ترتیبات محفوظ ہو گئیں",
+ ownerOnly: "صرف مالک ترتیبات بدل سکتا ہے۔",
+ killSwitches: "کِل سوئچ",
+ killHint: "ایجنٹ کو فوراً روکیں، پوری ورک اسپیس یا کسی ایک ٹول کے لیے۔",
+ tenantSwitch: "ایجنٹ کے تمام کام روکیں",
+ toolSwitch: "ٹول بند کریں",
+ enabled: "آن",
+ disabled: "آف",
+ noSwitches: "کوئی سوئچ نہیں۔",
+ team: "ٹیم اور کردار",
+ security: "سیکیورٹی",
+ totp: "آتھنٹیکیٹر (اضافی تصدیق)",
+ totpOn: "فعال",
+ totpOff: "غیر فعال",
+ channels: "چینلز اور کنیکٹرز",
+ channelsHint: "واٹس ایپ، ای میل اور کوریئر کنکشن ان کے پیکس ترتیب دیتے ہیں۔",
+ roles: {
+ owner: "مالک",
+ manager: "مینیجر",
+ agent_operator: "آپریٹر",
+ viewer: "ناظر",
+ },
+ },
+ knowledge: {
+ title: "معلومات",
+ subtitle:
+ "پالیسیاں، عام سوالات اور طریقۂ کار جن کا ایجنٹ حوالہ دے سکتا ہے۔ ہر جواب دستاویز کا حوالہ دیتا ہے؛ دستاویز کا متن غیر معتبر سمجھا جاتا ہے اور کوئی کارروائی طے نہیں کرتا۔",
+ upload: "دستاویز شامل کریں",
+ uploadHint: "پی ڈی ایف، ورڈ، مارک ڈاؤن یا سادہ متن، یا نیچے متن چسپاں کریں۔",
+ file: "فائل",
+ docTitle: "عنوان",
+ pasteText: "یا متن چسپاں کریں",
+ url: "یا ویب صفحے کا یو آر ایل",
+ add: "معلومات میں شامل کریں",
+ added: "دستاویز شامل ہو گئی",
+ docs: "دستاویزات",
+ noDocs: "ابھی کوئی دستاویز نہیں",
+ noDocsHint: "اپنی واپسی کی پالیسی یا عام سوالات اپ لوڈ کریں تاکہ ایجنٹ ان سے گاہکوں کو جواب دے سکے۔",
+ chunks: "{n} حصے",
+ pages: "{n} صفحات",
+ flagged: "{n} نشان زدہ",
+ flaggedHint: "کچھ حصے اے آئی کے لیے ہدایات جیسے لگتے ہیں۔ انہیں صرف ڈیٹا کے طور پر رکھا جاتا ہے، ان پر عمل نہیں ہوتا۔",
+ remove: "حذف کریں",
+ removed: "دستاویز حذف ہو گئی",
+ searchTitle: "سوال آزمائیں",
+ searchPlaceholder: "خراب اشیاء کے لیے ہماری واپسی کی پالیسی کیا ہے؟",
+ noHits: "دستاویزات میں اس سوال سے متعلق کچھ نہیں ملا۔",
+ untrusted: "غیر معتبر متن",
+ score: "اسکور {s}",
+ },
+ memory: {
+ title: "یادداشت",
+ subtitle:
+ "ایجنٹ گفتگو کے درمیان کیا یاد رکھتا ہے۔ آرڈر کی حالت، اسٹاک، رقوم اور ادائیگی کی حالت یہاں کبھی محفوظ نہیں ہوتیں: یہ ہمیشہ براہِ راست پڑھی جاتی ہیں۔",
+ kinds: { all: "سب", customer: "گاہک", prefs: "ترجیحات", case: "حل شدہ معاملات" },
+ empty: "ابھی کچھ یاد نہیں",
+ emptyHint: "حل شدہ سپورٹ معاملات اور گاہکوں کی ترجیحات یہاں نظر آئیں گی۔",
+ key: "کلید",
+ value: "مواد",
+ expires: "میعاد ختم",
+ namespace: "دائرہ",
+ tampered: "سالمیت کی جانچ ناکام؛ ایجنٹ سے چھپا دیا گیا",
+ forget: "بھلا دیں",
+ forgotten: "یادداشت سے ہٹا دیا گیا",
+ customerId: "گاہک آئی ڈی",
+ forgetCustomer: "اس گاہک کو بھلا دیں",
+ forgetCustomerDone: "اس گاہک کے بارے میں {n} اندراجات ہٹا دیے گئے",
+ managerOnly: "یادداشت صرف مینیجر اور مالک دیکھ سکتے ہیں۔",
+ },
+ workflows: {
+ title: "ورک فلوز",
+ subtitle:
+ "سادہ زبان میں بیان کی گئی خودکار کارروائیاں، جو چلنے سے پہلے جانچی جاتی ہیں، اصل ڈیٹا پر آزمائی جاتی ہیں اور مالک سے منظور ہوتی ہیں۔",
+ newTitle: "نیا ورک فلو",
+ newHint: "بتائیں کیا اور کب ہونا چاہیے۔ آپ کو جائزے کے لیے ایک مسودہ ملے گا؛ ابھی کچھ نہیں چلے گا۔",
+ newPlaceholder: "ہر صبح 8 بجے ORD-1021 پر اس کی حالت کا نوٹ لکھیں",
+ create: "مسودہ بنائیں",
+ compiling: "مسودہ تیار ہو رہا ہے…",
+ created: "ورک فلو کا مسودہ بن گیا",
+ templates: "سانچے",
+ noTemplates: "انسٹال شدہ پیکس میں کوئی سانچہ نہیں۔",
+ useTemplate: "سانچہ استعمال کریں",
+ triggers: { schedule: "شیڈول", event: "واقعہ", manual: "دستی" },
+ empty: "ابھی کوئی ورک فلو نہیں",
+ emptyHint: "نیچے ایک بیان کریں یا کسی سانچے سے شروع کریں۔",
+ name: "ورک فلو",
+ status: "حالت",
+ activeVersion: "فعال ورژن",
+ latestVersion: "تازہ ترین ورژن",
+ updated: "تازہ کاری",
+ open: "کھولیں",
+ pendingProposals: "{n} خودکار اصلاحات جائزے کی منتظر ہیں",
+ proposals: "تجویز کردہ اصلاحات",
+ apply: "نئے مسودے کے طور پر لاگو کریں",
+ dismiss: "مسترد کریں",
+ proposalApplied: "اصلاح مسودہ ورژن {n} کے طور پر محفوظ ہو گئی",
+ proposalDismissed: "اصلاح مسترد کر دی گئی",
+ failureClasses: { rate_limit: "حدِ رفتار", transient: "عارضی خرابی", auth: "تصدیق", schema: "اسکیما", data: "ڈیٹا" },
+ statuses: {
+ draft: "مسودہ",
+ active: "فعال",
+ paused: "موقوف",
+ archived: "محفوظ شدہ",
+ dry_run_ok: "آزمائشی رن کامیاب",
+ dry_run_failed: "آزمائشی رن ناکام",
+ approved: "منظور شدہ",
+ superseded: "تبدیل شدہ",
+ rolled_back: "واپس لیا گیا",
+ would_execute: "چلے گا",
+ needs_approval: "منظوری درکار",
+ denied: "مسترد",
+ error: "خرابی",
+ skipped: "چھوڑ دیا گیا",
+ not_reached: "نہیں پہنچا",
+ wait: "انتظار",
+ pending: "زیرِ التوا",
+ applied: "لاگو شدہ",
+ dismissed: "مسترد شدہ",
+ },
+ totals: {
+ would_execute: "چلیں گے",
+ needs_approval: "منظوری درکار",
+ denied: "مسترد",
+ error: "خرابیاں",
+ skipped: "چھوڑے گئے",
+ },
+ kinds: { tool: "ٹول", wait: "انتظار", approval: "دستخط" },
+ versions: "ورژنز",
+ version: "ورژن",
+ from: "v{n} سے",
+ definition: "تعریف",
+ tabs: { plain: "سادہ زبان", canvas: "کینوس", json: "JSON" },
+ nlSource: "بیان",
+ unsaved: "غیر محفوظ تبدیلیاں",
+ discard: "ترک کریں",
+ validate: "جانچیں",
+ valid: "تعریف تمام جانچوں پر پوری اترتی ہے۔",
+ invalid: "تعریف میں مسائل ہیں۔",
+ saveVersion: "نئے ورژن کے طور پر محفوظ کریں",
+ saved: "ورژن {n} کے طور پر محفوظ ہو گیا",
+ saveFailed: "یہ ورژن محفوظ نہیں ہو سکا۔",
+ errors: "خرابیاں",
+ warnings: "انتباہات",
+ jsonError: "غلط JSON",
+ dryRun: "آزمائشی رن",
+ dryRunTitle: "آزمائشی رن",
+ dryRunDone: "آزمائشی رن مکمل",
+ dryRunOk: "منظوری کے لیے محفوظ",
+ dryRunFailed: "مسائل ملے",
+ dryRunStale: "اس آزمائشی رن کے بعد تعریف بدل گئی۔",
+ approve: "منظور کریں",
+ approvedToast: "ورژن منظور ہو گیا",
+ activate: "فعال کریں",
+ activatedToast: "ورژن فعال ہو گیا",
+ ownerOnly: "یہ صرف مالک کر سکتا ہے۔",
+ rollback: "واپس لیں",
+ rolledBackTo: "ورژن {n} پر واپس",
+ paused: "ورک فلو موقوف",
+ runNow: "ابھی چلائیں",
+ runQueued: "ورژن {n} کا رن قطار میں",
+ recentRuns: "حالیہ رنز",
+ noRuns: "ابھی کوئی رن نہیں۔",
+ needsSignoff: "دستخط",
+ selectStep: "ترمیم کے لیے کینوس پر کوئی مرحلہ منتخب کریں۔",
+ editStep: "مرحلہ",
+ moveUp: "اوپر",
+ moveDown: "نیچے",
+ deleteStep: "مرحلہ حذف کریں",
+ stepId: "مرحلے کی شناخت",
+ tool: "ٹول",
+ args: "دلائل (JSON)",
+ forEach: "ہر ایک کے لیے",
+ when: "صرف اگر (شرائط، JSON)",
+ requiresApproval: "اس مرحلے سے پہلے انسان سے پوچھیں",
+ waitSeconds: "انتظار (سیکنڈ)",
+ signoffSummary: "مالک کس چیز پر دستخط کرے",
+ },
+ integrations: {
+ title: "انٹیگریشنز اور ٹولز",
+ subtitle:
+ "ڈیپلائے کے بغیر اپنے سسٹمز جوڑیں۔ نئے ٹولز T3 پر شروع ہوتے ہیں (ہر کال کے لیے آپ کی منظوری) اور تصدیق تک ٹیسٹ موڈ میں رہتے ہیں۔",
+ tabTools: "ٹولز",
+ tabImport: "API درآمد کریں",
+ tabMcp: "MCP سرورز",
+ tabConnectors: "کنیکٹرز",
+ noTools: "ابھی کوئی ٹول شامل نہیں",
+ noToolsHint: "OpenAPI سپیک درآمد کریں، MCP سرور جوڑیں یا کنیکٹر شامل کریں۔",
+ tool: "ٹول",
+ source: "ذریعہ",
+ suggested: "تجویز کردہ",
+ tier: "درجہ",
+ mode: "موڈ",
+ status: "حالت",
+ live: "لائیو",
+ test: "ٹیسٹ",
+ enabled: "فعال",
+ disabled: "غیر فعال",
+ blocked: "روکا گیا",
+ unconfirmed: "تصدیق نہیں ہوئی",
+ confirm: "تصدیق کریں",
+ confirmed: "ٹول کی تصدیق ہو گئی",
+ lowerTier: "تجویز سے کم درجہ: میں خطرہ سمجھتا/سمجھتی ہوں",
+ tryIt: "آزمائشی رن",
+ args: "آرگیومنٹس (JSON)",
+ runDryRun: "کال کا پیش منظر",
+ preview: "پیش منظر",
+ changed: "تعریف بدل گئی ہے۔ جائزہ لے کر دوبارہ تصدیق کریں۔",
+ before: "پہلے",
+ after: "بعد میں",
+ ownerOnly: "صرف مالک ٹولز درآمد، تصدیق یا فعال کر سکتا ہے۔",
+ name: "نام",
+ nameHint: "ٹول نام کا سابقہ: چھوٹے انگریزی حروف، ہندسے اور _۔",
+ spec: "OpenAPI سپیک (JSON یا YAML)",
+ specUrl: "…یا سپیک کا URL",
+ baseUrl: "بیس URL (اختیاری)",
+ sandboxUrl: "سینڈ باکس بیس URL (اختیاری)",
+ secretRef: "سیکرٹ حوالہ",
+ secretRefHint: "محفوظ سیکرٹ کا نام، خود سیکرٹ کبھی نہیں۔",
+ sandboxSecretRef: "سینڈ باکس سیکرٹ حوالہ",
+ importButton: "درآمد کریں",
+ imported: "{n} ٹولز درآمد ہو گئے",
+ url: "سرور URL",
+ auth: "تصدیق",
+ authNone: "کوئی نہیں",
+ authBearer: "بیئرر ٹوکن",
+ connect: "جوڑیں",
+ connected: "سرور جڑ گیا: {n} ٹولز",
+ refresh: "تازہ کریں",
+ refreshed: "تازہ ہو گیا",
+ lastDiff: "آخری تازہ کاری",
+ noMcp: "کوئی MCP سرور نہیں جڑا",
+ kind: "قسم",
+ kinds: { table: "CSV / ایکسل", google_sheets: "گوگل شیٹس", http_action: "HTTP ایکشن", webhook: "ویب ہک میپنگ" },
+ mcpStatuses: { new: "نیا", ok: "ٹھیک", changed: "تبدیل ہوا", error: "خرابی" },
+ config: "ترتیبات (JSON)",
+ create: "کنیکٹر شامل کریں",
+ created: "کنیکٹر شامل ہو گیا",
+ upload: "CSV / ایکسل اپ لوڈ کریں",
+ uploaded: "{n} قطاریں اپ لوڈ ہو گئیں",
+ noConnectors: "ابھی کوئی کنیکٹر نہیں",
+ invalidJson: "یہ درست JSON نہیں ہے۔",
+ },
+ nlrules: {
+ title: "اصول",
+ subtitle:
+ "سادہ الفاظ میں اصول لکھیں۔ ورک پائلٹ اسے پالیسی میں بدل کر واپس دکھاتا ہے اور آپ کی تصدیق سے پہلے جانچتا ہے۔",
+ placeholder: "مثلاً 10 ہزار سے زیادہ کی واپسی کے لیے میری منظوری چاہیے",
+ compile: "اصول جانچیں",
+ draft: "مسودہ",
+ understood: "ورک پائلٹ نے یہ سمجھا",
+ policy: "پالیسی (Cedar)",
+ tests: "آزمائشی کالز",
+ call: "کال",
+ actor: "کس نے",
+ outcome: "نتیجہ",
+ matched: "لاگو ہوتا ہے",
+ notMatched: "لاگو نہیں ہوتا",
+ confirm: "اصول کی تصدیق کریں",
+ confirmed: "اصول فعال ہے",
+ allowPermit: "ہاں، ملتی جلتی کالز منظوری کے بغیر چلنے دیں",
+ question: "ورک پائلٹ کو ایک تفصیل چاہیے",
+ active: "فعال اصول",
+ history: "تاریخ",
+ noRules: "ابھی کوئی اصول نہیں",
+ version: "v{n}",
+ rollback: "واپس لائیں",
+ rolledBack: "پچھلا ورژن بحال ہو گیا",
+ disable: "بند کریں",
+ disabledToast: "اصول بند ہو گیا",
+ ownerOnly: "صرف مالک اصولوں کی تصدیق، واپسی یا بندش کر سکتا ہے۔",
+ status: "حالت",
+ statuses: {
+ draft: "مسودہ",
+ active: "فعال",
+ superseded: "تبدیل شدہ",
+ rolled_back: "واپس لیا گیا",
+ disabled: "بند",
+ discarded: "مسترد",
+ },
+ },
+ errors: {
+ stepupRequired: "اضافی تصدیق درکار ہے",
+ forbidden: "آپ کو اس کی اجازت نہیں۔",
+ network: "ورک پائلٹ API سے رابطہ نہیں ہو سکا۔",
+ },
+ validation: {
+ number: "عدد ہونا چاہیے",
+ wholeNumber: "پورا عدد ہونا چاہیے",
+ greaterThan: "{n} سے زیادہ ہونا چاہیے",
+ atLeast: "کم از کم {n} ہونا چاہیے",
+ atMost: "زیادہ سے زیادہ {n} ہونا چاہیے",
+ maxChars: "زیادہ سے زیادہ {n} حروف",
+ minChars: "کم از کم {n} حروف",
+ pattern: "{pattern} کے مطابق ہونا چاہیے",
+ invalidJson: "غلط JSON",
+ },
+};
+
+export const messages = { en, ur } as const;
+export type Locale = keyof typeof messages;
+export const LOCALES: Locale[] = ["en", "ur"];
diff --git a/web/src/lib/lib.test.ts b/web/src/lib/lib.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3d13d32a042e50fa2052319ece140023983c4a1e
--- /dev/null
+++ b/web/src/lib/lib.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vitest";
+
+import { pickComponent } from "@/components/chat/gen-ui";
+import { validateField } from "@/components/inbox/edit-args-form";
+import { argsChanges, previewDiff } from "@/lib/diff";
+import { formatDuration, formatMoney, formatValue, isMoneyField } from "@/lib/format";
+import { translate } from "@/lib/i18n";
+import { en, ur } from "@/lib/i18n/messages";
+import { parseSse } from "@/lib/sse";
+
+describe("previewDiff", () => {
+ it("pairs *_before / *_after keys and keeps the rest as details", () => {
+ const d = previewDiff({ order: "ORD-1021", amount: 20000, refunded_before: 0, refunded_after: 20000 });
+ expect(d.rows).toEqual([
+ { field: "refunded", before: 0, after: 20000, changed: true, hasBefore: true },
+ ]);
+ expect(d.details).toEqual([
+ ["order", "ORD-1021"],
+ ["amount", 20000],
+ ]);
+ });
+
+ it("handles an after value with no before, and nested snapshots", () => {
+ expect(previewDiff({ status_after: "cancelled" }).rows[0]).toMatchObject({
+ field: "status",
+ hasBefore: false,
+ changed: true,
+ });
+ const nested = previewDiff({ before: { status: "pending", city: "Lahore" }, after: { status: "cancelled", city: "Lahore" } });
+ expect(nested.rows.map((r) => [r.field, r.changed])).toEqual([
+ ["status", true],
+ ["city", false],
+ ]);
+ expect(nested.details).toEqual([]);
+ });
+
+ it("is empty for no preview", () => {
+ expect(previewDiff(undefined)).toEqual({ rows: [], details: [] });
+ });
+});
+
+describe("argsChanges", () => {
+ it("lists only changed fields", () => {
+ expect(argsChanges({ a: 1, b: "x" }, { a: 2, b: "x" })).toEqual([{ field: "a", before: 1, after: 2 }]);
+ });
+});
+
+describe("format", () => {
+ it("formats durations compactly", () => {
+ expect(formatDuration(45)).toBe("45s");
+ expect(formatDuration(192)).toBe("3m 12s");
+ expect(formatDuration(7500)).toBe("2h 5m");
+ expect(formatDuration(97200)).toBe("1d 3h");
+ });
+ it("formats rupees and recognises money fields", () => {
+ expect(formatMoney(25000)).toBe("Rs 25,000");
+ expect(isMoneyField("order_total")).toBe(true);
+ expect(isMoneyField("rto_rate")).toBe(false);
+ expect(formatValue("amount", 1500)).toBe("Rs 1,500");
+ expect(formatValue("to", "a@b.pk")).toBe("a@b.pk");
+ });
+});
+
+describe("i18n", () => {
+ const keys = (o: object, p = ""): string[] =>
+ Object.entries(o).flatMap(([k, v]) =>
+ v && typeof v === "object" && !Array.isArray(v) ? keys(v, `${p}${k}.`) : [`${p}${k}`],
+ );
+ it("has every English key in Urdu", () => {
+ expect(keys(ur).sort()).toEqual(keys(en).sort());
+ });
+ it("interpolates variables and falls back to the key", () => {
+ expect(translate(en, "inbox.waiting", { time: "3m" })).toBe("Waiting 3m");
+ expect(translate(ur, "inbox.waiting", { time: "3m" })).toBe("3m سے منتظر");
+ expect(translate(en, "nope.missing")).toBe("nope.missing");
+ });
+});
+
+describe("parseSse", () => {
+ it("parses complete events and keeps the remainder", () => {
+ const { events, rest } = parseSse(
+ 'retry: 2000\n\nid: 7\nevent: action\ndata: {"seq":7}\n\nevent: status\ndata: {"a"',
+ );
+ expect(events).toEqual([{ event: "action", data: '{"seq":7}', id: "7" }]);
+ expect(rest).toBe('event: status\ndata: {"a"');
+ });
+ it("joins multi-line data and handles CRLF", () => {
+ expect(parseSse("data: a\r\ndata: b\r\n\r\n").events).toEqual([{ event: "message", data: "a\nb", id: undefined }]);
+ });
+});
+
+describe("edit form validation", () => {
+ it("mirrors the JSON schema", () => {
+ expect(validateField({ type: "integer", exclusiveMinimum: 0 }, 0)).toMatch(/greater than 0/);
+ expect(validateField({ type: "integer" }, 1.5)).toMatch(/whole number/);
+ expect(validateField({ type: "string", pattern: "^ORD-\d{3,8}$" }, "X-1")).toMatch(/must match/);
+ expect(validateField({ type: "string", maxLength: 3 }, "abcd")).toMatch(/at most 3/);
+ expect(validateField({ type: "integer", exclusiveMinimum: 0 }, 15000)).toBeNull();
+ });
+});
+
+describe("generative UI selection", () => {
+ it("picks a component from tool name and data shape", () => {
+ expect(pickComponent({ tool: "ecommerce.list_orders", data: { items: [{ number: "A" }] } })).toBe("order_table");
+ expect(pickComponent({ tool: "ecommerce.score_rto_risk", data: { score: 0.7, band: "high" } })).toBe("risk_card");
+ expect(pickComponent({ tool: "demo.lookup_order", data: { number: "ORD-1", status: "paid" } })).toBe("status_card");
+ expect(pickComponent({ tool: "demo.send_message", data: { to: "x" } })).toBe("generic");
+ expect(pickComponent({ tool: "demo.lookup_order", data: null })).toBe("generic");
+ });
+});
diff --git a/web/src/lib/session.ts b/web/src/lib/session.ts
new file mode 100644
index 0000000000000000000000000000000000000000..82f3b65c4d3eeac2e5f5bd493b5ebcfb2172cb2a
--- /dev/null
+++ b/web/src/lib/session.ts
@@ -0,0 +1,124 @@
+// Token storage for the browser.
+//
+// - The access token (15 min) lives only in this module's memory: never in localStorage or
+// a readable cookie, so a page reload drops it and an XSS payload cannot lift it from storage.
+// - The refresh token (14 days) is held by the Next.js server in an httpOnly, SameSite=Strict
+// cookie scoped to /api/session (see src/app/api/session/[action]/route.ts). Browser JS never
+// sees it; a reload calls /api/session/refresh to get a fresh access token.
+// - The step-up token (5 min, from POST /auth/stepup) is memory-only too.
+//
+// Trade-off: the refresh exchange goes through the Next.js server (a small BFF), so the web
+// app needs a Node runtime rather than static hosting, and an XSS can still *use* the session
+// while the page is open (it cannot exfiltrate the long-lived token).
+
+let accessToken: string | null = null;
+let stepup: { token: string; expiresAt: number } | null = null;
+let refreshing: Promise | null = null;
+
+const listeners = new Set<() => void>();
+
+export function getAccessToken(): string | null {
+ return accessToken;
+}
+
+export function setAccessToken(token: string | null): void {
+ accessToken = token;
+ if (!token) stepup = null;
+}
+
+export function getStepupToken(now = Date.now()): string | null {
+ return stepup && stepup.expiresAt > now ? stepup.token : null;
+}
+
+export function setStepupToken(token: string, ttlMs = 4.5 * 60_000): void {
+ stepup = { token, expiresAt: Date.now() + ttlMs };
+}
+
+export function onSessionExpired(fn: () => void): () => void {
+ listeners.add(fn);
+ return () => listeners.delete(fn);
+}
+
+export function notifySessionExpired(): void {
+ for (const fn of listeners) fn();
+}
+
+export class SessionError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ ) {
+ super(message);
+ }
+}
+
+async function sessionCall(
+ action: "login" | "signup" | "refresh" | "logout" | "switch",
+ body?: unknown,
+): Promise<{ access_token: string; tenant_id: string } | null> {
+ const headers: Record = {
+ "Content-Type": "application/json",
+ // Custom header: a cross-site form cannot send it, and fetch would need a preflight.
+ "X-Requested-With": "workpilot",
+ };
+ if (action === "switch" && accessToken) headers.Authorization = `Bearer ${accessToken}`;
+ const res = await fetch(`/api/session/${action}`, {
+ method: "POST",
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ credentials: "same-origin",
+ cache: "no-store",
+ });
+ if (action === "logout") return null;
+ const data = (await res.json().catch(() => ({}))) as {
+ access_token?: string;
+ tenant_id?: string;
+ detail?: unknown;
+ };
+ if (!res.ok || !data.access_token || !data.tenant_id) {
+ const detail = typeof data.detail === "string" ? data.detail : res.statusText;
+ throw new SessionError(detail || "request failed", res.status);
+ }
+ return { access_token: data.access_token, tenant_id: data.tenant_id };
+}
+
+export async function login(email: string, password: string): Promise {
+ const r = await sessionCall("login", { email, password });
+ setAccessToken(r?.access_token ?? null);
+}
+
+export async function signup(business_name: string, email: string, password: string) {
+ const r = await sessionCall("signup", { business_name, email, password });
+ setAccessToken(r?.access_token ?? null);
+}
+
+export async function switchTenant(tenant_id: string): Promise {
+ const r = await sessionCall("switch", { tenant_id });
+ setAccessToken(r?.access_token ?? null);
+ stepup = null;
+}
+
+export async function logout(): Promise {
+ setAccessToken(null);
+ await sessionCall("logout").catch(() => null);
+}
+
+/** Exchange the httpOnly refresh cookie for a new access token. Concurrent callers share one
+ * request (the refresh token rotates, so parallel refreshes would race). */
+export function refreshAccessToken(): Promise {
+ if (!refreshing) {
+ refreshing = sessionCall("refresh")
+ .then((r) => {
+ setAccessToken(r?.access_token ?? null);
+ return accessToken;
+ })
+ .catch(() => {
+ setAccessToken(null);
+ return null;
+ })
+ .finally(() => {
+ refreshing = null;
+ });
+ }
+ return refreshing;
+}
diff --git a/web/src/lib/sse.ts b/web/src/lib/sse.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3cb32a09024eb9324843cd2bdc47dbf4222a2948
--- /dev/null
+++ b/web/src/lib/sse.ts
@@ -0,0 +1,60 @@
+// Server-sent events over fetch (EventSource cannot send an Authorization header).
+
+export interface SseEvent {
+ event: string;
+ data: string;
+ id?: string;
+}
+
+/** Parse complete events out of a text buffer; returns the unparsed remainder. */
+export function parseSse(buffer: string): { events: SseEvent[]; rest: string } {
+ const normalized = buffer.replace(/\r\n?/g, "\n");
+ const blocks = normalized.split("\n\n");
+ const rest = blocks.pop() ?? "";
+ const events: SseEvent[] = [];
+ for (const block of blocks) {
+ let event = "message";
+ let id: string | undefined;
+ const data: string[] = [];
+ for (const line of block.split("\n")) {
+ if (!line || line.startsWith(":")) continue;
+ const i = line.indexOf(":");
+ const field = i === -1 ? line : line.slice(0, i);
+ const value = i === -1 ? "" : line.slice(i + 1).replace(/^ /, "");
+ if (field === "event") event = value;
+ else if (field === "data") data.push(value);
+ else if (field === "id") id = value;
+ }
+ if (data.length) events.push({ event, data: data.join("\n"), id });
+ }
+ return { events, rest };
+}
+
+export interface StreamOptions {
+ headers?: Record;
+ signal?: AbortSignal;
+ onEvent: (e: SseEvent) => void;
+}
+
+/** Read one SSE response to the end. Resolves when the server closes the stream. */
+export async function streamSse(url: string, opts: StreamOptions): Promise {
+ const res = await fetch(url, {
+ headers: { Accept: "text/event-stream", ...opts.headers },
+ signal: opts.signal,
+ cache: "no-store",
+ });
+ if (!res.ok || !res.body) return res.status;
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
+ let buffer = "";
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += value;
+ const { events, rest } = parseSse(buffer);
+ buffer = rest;
+ for (const e of events) opts.onEvent(e);
+ }
+ const { events } = parseSse(buffer + "\n\n");
+ for (const e of events) opts.onEvent(e);
+ return res.status;
+}
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..898e03ace98f496db1bd656c7f08d1a978cf9605
--- /dev/null
+++ b/web/src/lib/types.ts
@@ -0,0 +1,283 @@
+// Shapes returned by the WorkPilot API (see core/api/routes/*.py and core/api/schemas.py).
+
+export type Role = "owner" | "manager" | "agent_operator" | "viewer";
+export type Provenance = "trusted" | "untrusted";
+
+export interface TokenPair {
+ access_token: string;
+ refresh_token: string;
+ tenant_id: string;
+ token_type: string;
+}
+
+export interface Me {
+ user: { id: string; email: string; totp_enrolled: boolean };
+ tenant: { id: string; name: string; plan: string; locale: string; timezone: string };
+ role: Role;
+ tenants: { id: string; name: string; role: Role }[];
+}
+
+export interface JsonSchemaProp {
+ type?: string;
+ title?: string;
+ description?: string;
+ pattern?: string;
+ maxLength?: number;
+ minLength?: number;
+ exclusiveMinimum?: number;
+ minimum?: number;
+ maximum?: number;
+ enum?: (string | number)[];
+ anyOf?: JsonSchemaProp[];
+ default?: unknown;
+}
+
+export interface ArgsSchema {
+ properties?: Record;
+ required?: string[];
+ title?: string;
+}
+
+export interface ApprovalItem {
+ id: string;
+ tool: string;
+ status: string;
+ reason: string;
+ policy_rule: string | null;
+ args: Record;
+ provenance: Record;
+ preview: Record;
+ required_role: Role;
+ requires_stepup: boolean;
+ run_id: string | null;
+ created_at: string;
+ expires_at: string;
+ wait_seconds: number;
+ // /inbox extras
+ kind?: "notify" | "question" | "review" | string;
+ risk_tier?: number | null;
+ args_schema?: ArgsSchema;
+ facts?: Record;
+ decided_at?: string | null;
+ decision_note?: string | null;
+ replaced_by?: string | null;
+ // Phase 7: queued T2 sends carry an undo window.
+ send_after?: string | null;
+ undo_url?: string | null;
+}
+
+export type Decision = "approve" | "edit" | "reject" | "respond";
+
+export interface DecisionResult {
+ approval: ApprovalItem;
+ replacement_id: string | null;
+ run: { run_id: string; status: string; output: string | null } | null;
+}
+
+export type RunStatus =
+ | "running"
+ | "waiting_approval"
+ | "completed"
+ | "rejected"
+ | "failed"
+ | "unsupported";
+
+export interface RunRow {
+ run_id: string;
+ thread_id: string;
+ status: RunStatus | string;
+ intent: string | null;
+ event_type: string | null;
+ source: string | null;
+ text: string | null;
+ output: string | null;
+ error: string | null;
+ cost_usd: number;
+ started_at: string;
+ ended_at: string | null;
+ pending_approvals: number;
+}
+
+export interface Page {
+ items: T[];
+ total: number;
+}
+
+export interface AuditAction {
+ seq: number;
+ at: string;
+ actor: string;
+ tool: string;
+ args: Record;
+ taint: Record;
+ decision: string;
+ reason: string | null;
+ approval_id: string | null;
+ result_status: string | null;
+ latency_ms: number;
+ cost_usd: number;
+}
+
+export interface ApprovalBrief {
+ id: string;
+ tool: string;
+ status: string;
+ reason: string;
+ created_at: string;
+ decided_at: string | null;
+ decision_note: string | null;
+ replaced_by: string | null;
+}
+
+export interface GraphState {
+ plan?: { intent: string; instruction: string }[];
+ cursor?: number;
+ log?: string[];
+ actions?: RunAction[];
+}
+
+export interface RunTimeline {
+ run: RunRow;
+ event: Record;
+ state: GraphState;
+ actions: AuditAction[];
+ approvals: ApprovalBrief[];
+ trace_url: string | null;
+}
+
+export interface RunStatusEvent {
+ run: RunRow;
+ state: GraphState;
+ approvals: ApprovalBrief[];
+}
+
+/** One entry of RunResult.actions (core/agent/tools.py action_record). */
+export interface RunAction {
+ step: string;
+ tool: string;
+ status: string;
+ reason: string | null;
+ approval_id: string | null;
+ data: Record | null;
+}
+
+export interface ChatResult {
+ run_id: string;
+ thread_id: string;
+ status: string;
+ intent: string | null;
+ output: string | null;
+ error: string | null;
+ pending: { type: string; approval_id: string; tool: string; reason: string }[];
+ actions: RunAction[];
+}
+
+export interface AnalyticsSummary {
+ days: number;
+ runs: { total: number; by_status: Record };
+ approvals: {
+ approved: number;
+ rejected: number;
+ pending: number;
+ by_status: Record;
+ approval_rate: number | null;
+ };
+ auto_resolution_rate: number | null;
+ median_approval_latency_s: number | null;
+ top_denial_reasons: { reason: string; count: number }[];
+ tool_calls: { total: number; by_decision: Record };
+ cost_usd: number;
+ cost_per_run_usd: number | null;
+ daily: ({ date: string } & Record)[];
+}
+
+export interface OpsAlert {
+ id: string;
+ kind: string;
+ severity: "info" | "warning" | "critical" | (string & {});
+ message: string;
+ status: "open" | "acknowledged" | (string & {});
+ detail: Record;
+ created_at: string;
+}
+
+export interface OperationsHealth {
+ days: number;
+ runs: { total: number; failed: number; by_status: Record };
+ run_error_rate: number | null;
+ tool_calls: { total: number; failed: number; denied: number; by_decision: Record };
+ tool_error_rate: number | null;
+ approval_latency_s: { p50: number | null; p95: number | null; decided: number };
+ denials: {
+ by_category: Record;
+ top_reasons: { reason: string; count: number; category: string }[];
+ };
+ quota_trips: number;
+ circuit_breaker_trips: number;
+ injection_signals: number;
+ cost: {
+ total_usd: number;
+ per_run_usd: number | null;
+ daily: { date: string; cost_usd: number; runs: number }[];
+ prices_verified: boolean;
+ };
+ errors_daily: { date: string; calls: number; failed_or_denied: number }[];
+ alerts: OpsAlert[];
+}
+
+export interface ApprovalRule {
+ tool: string;
+ arg?: string | null;
+ min?: number | null;
+ role: Role;
+ stepup: boolean;
+}
+
+export interface TenantSettings {
+ policy_attrs: Record