@tangle-network/agent-app 0.63.60 → 0.63.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DesignCanvas-Q65UV4D5.js → DesignCanvas-566V5KVC.js} +3 -2
- package/dist/{DesignCanvasEditor-THEFESEX.js → DesignCanvasEditor-YWDEFWYQ.js} +3 -2
- package/dist/app-auth/index.js +2 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/assistant/index.js +6 -5
- package/dist/assistant/index.js.map +1 -1
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/agent-producers.d.ts +38 -0
- package/dist/chat-routes/index.d.ts +1 -0
- package/dist/chat-routes/index.js +25 -8
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/turn-admission.d.ts +3 -3
- package/dist/chat-routes/turn-route-contracts.d.ts +38 -1
- package/dist/chat-routes/wire.d.ts +29 -4
- package/dist/chat-store/index.js +4 -2
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/parts.d.ts +19 -3
- package/dist/{chunk-P7UB7ZVP.js → chunk-75I4RXIE.js} +2 -2
- package/dist/{chunk-GGJYAV7R.js → chunk-DPZXCVVS.js} +2 -2
- package/dist/{chunk-GGJYAV7R.js.map → chunk-DPZXCVVS.js.map} +1 -1
- package/dist/{chunk-LAZCUQFZ.js → chunk-F2N55QQX.js} +47 -10
- package/dist/chunk-F2N55QQX.js.map +1 -0
- package/dist/{chunk-QGJOT6R6.js → chunk-F6UC2T6U.js} +49 -9
- package/dist/{chunk-QGJOT6R6.js.map → chunk-F6UC2T6U.js.map} +1 -1
- package/dist/{chunk-AICYKYYF.js → chunk-MIQL36JS.js} +17 -4
- package/dist/chunk-MIQL36JS.js.map +1 -0
- package/dist/{chunk-RILVJYXJ.js → chunk-N5KBDRSX.js} +2 -2
- package/dist/{chunk-IDQ7N36R.js → chunk-O2TYB3DH.js} +2 -2
- package/dist/{chunk-H6BRJU5M.js → chunk-RKNNMC6T.js} +1 -1
- package/dist/{chunk-HHPQMFKP.js → chunk-RNFVAAJJ.js} +2 -2
- package/dist/{chunk-KFO5R4SN.js → chunk-RVC7EHJI.js} +135 -64
- package/dist/chunk-RVC7EHJI.js.map +1 -0
- package/dist/{chunk-4E2MUVGL.js → chunk-TFV4QOCG.js} +3 -3
- package/dist/chunk-XBBXPZJI.js +47 -0
- package/dist/chunk-XBBXPZJI.js.map +1 -0
- package/dist/design-canvas/index.js +2 -1
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +2 -1
- package/dist/design-canvas-react/index.js +3 -2
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/operator/index.js +2 -2
- package/dist/platform/index.js +2 -1
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +4 -4
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +7 -6
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/sandbox/index.js +2 -2
- package/dist/sequences/index.js +2 -1
- package/dist/sequences/index.js.map +1 -1
- package/dist/stories/chat/fixtures.d.ts +4 -0
- package/dist/web/index.d.ts +1 -0
- package/dist/web/index.js +7 -1
- package/dist/web/speakers.d.ts +30 -0
- package/dist/web-react/chat-messages.d.ts +1 -1
- package/dist/web-react/chat-stream.d.ts +7 -0
- package/dist/web-react/entry-composer.d.ts +2 -2
- package/dist/web-react/index.js +8 -5
- package/dist/web-react/use-file-mentions.d.ts +23 -4
- package/dist/workspace-react/index.d.ts +29 -1
- package/dist/workspace-react/index.js +34 -0
- package/dist/workspace-react/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-AICYKYYF.js.map +0 -1
- package/dist/chunk-KFO5R4SN.js.map +0 -1
- package/dist/chunk-LAZCUQFZ.js.map +0 -1
- /package/dist/{DesignCanvas-Q65UV4D5.js.map → DesignCanvas-566V5KVC.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-THEFESEX.js.map → DesignCanvasEditor-YWDEFWYQ.js.map} +0 -0
- /package/dist/{chunk-P7UB7ZVP.js.map → chunk-75I4RXIE.js.map} +0 -0
- /package/dist/{chunk-RILVJYXJ.js.map → chunk-N5KBDRSX.js.map} +0 -0
- /package/dist/{chunk-IDQ7N36R.js.map → chunk-O2TYB3DH.js.map} +0 -0
- /package/dist/{chunk-H6BRJU5M.js.map → chunk-RKNNMC6T.js.map} +0 -0
- /package/dist/{chunk-HHPQMFKP.js.map → chunk-RNFVAAJJ.js.map} +0 -0
- /package/dist/{chunk-4E2MUVGL.js.map → chunk-TFV4QOCG.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workspace-react/index.tsx","../../src/workspace-react/rail-identity.tsx","../../src/workspace-react/companion.tsx","../../src/workspace-react/workspace-list.tsx"],"sourcesContent":["import { SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport { useWorkspacePrewarm, WorkspacePrewarmContext, type UseWorkspacePrewarmOptions } from '../web-react/workspace-prewarm'\n\nimport type { WorkspaceAppRecord } from '../workspace-apps'\nimport { AgentRailIdentity, type AgentProductIdentity, type AgentWorkspaceIdentity } from './rail-identity'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/**\n * Registered apps shown under one expandable workspace destination.\n * Products supply authorized rows and their real route; preview URLs never\n * become navigation hrefs.\n */\nexport interface AgentWorkspaceAppsConfig {\n icon: WorkspaceIcon\n items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[]\n hrefForApp: (appId: string) => string\n prefetch?: RailPrefetch\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /**\n * The product's name, mark, and home. With it the shell draws the canonical\n * rail top — mark, then the open workspace and product name — so products\n * stop hand-building `logo` and `railHeaderContent`.\n */\n product?: AgentProductIdentity\n /** The open workspace and where else this person can go. Omit on the listing. */\n workspace?: AgentWorkspaceIdentity | null\n /** Product-owned destinations. Shared Apps and History rows follow them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** Authorized app destinations, in the product's persisted order. */\n apps?: AgentWorkspaceAppsConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n /**\n * Warm the open workspace: the shell posts to the product's prewarm route\n * (`createWorkspacePrewarmRoute`) when the page opens in a visible tab, and\n * every `ChatComposer` inside reasserts on focus. Pass the route's URL and\n * whether this member may chat. Omit on pages with no workspace.\n */\n prewarm?: UseWorkspacePrewarmOptions\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable Apps and History rows, capped session composition, unread state,\n * and active route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n apps,\n activeRoute,\n activeId,\n product,\n workspace,\n prewarm,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const prewarmHandle = useWorkspacePrewarm(prewarm ?? { url: null })\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const appNavItems: SidebarLayoutNavItem[] = (apps?.items ?? []).map((app) => {\n const href = apps!.hrefForApp(app.id)\n if (!href.startsWith('/') || href.startsWith('//') || /[?#\\\\]/.test(href)) {\n throw new Error('Workspace app href must be a local route path')\n }\n return {\n id: 'workspace-app:' + app.id,\n label: app.name,\n icon: apps!.icon,\n href,\n prefetch: apps!.prefetch,\n }\n })\n const appRoutes: NavRouteDef[] = activeRoute\n ? appNavItems.map((item) => {\n const path = routePathFromHref(item.href!, activeRoute.base)\n if (!path) throw new Error('Workspace app href must be under the active workspace')\n return { id: item.id, path }\n })\n : []\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: [\n ...activeRoute.routes,\n ...appRoutes,\n ...(sessionNav && historyRoutePath\n ? [{ id: sessions?.id ?? 'history', path: historyRoutePath }]\n : []),\n ],\n })\n : activeId\n\n const activeAppId = appNavItems.some((item) => item.id === resolvedActiveId)\n ? resolvedActiveId\n : undefined\n const appGroup: SidebarLayoutNavItem | undefined = apps && appNavItems.length > 0\n ? {\n id: 'workspace-apps',\n label: 'Apps',\n icon: apps.icon,\n expandable: true,\n defaultOpen: activeAppId !== undefined,\n subItems: appNavItems.map(({ id, label, icon, href, prefetch }) => ({\n id,\n label,\n icon,\n href: href!,\n prefetch,\n })),\n subActiveIds: activeAppId ? [activeAppId] : undefined,\n }\n : undefined\n const workspaceNavItems: SidebarLayoutNavItem[] = [\n ...navItems,\n ...(appGroup ? [appGroup] : []),\n ...(sessionNav ? [sessionNav] : []),\n ]\n\n const hideBelow = sidebarProps.hideBelow ?? 'lg'\n const identityProps = product\n ? {\n logo: product.mark,\n logoHref: product.href,\n railHeaderContent: (\n <AgentRailIdentity\n product={product}\n workspace={workspace}\n hideBelow={hideBelow}\n LinkComponent={sidebarProps.LinkComponent}\n />\n ),\n }\n : {}\n const layoutProps = {\n hideBelow,\n railLabels: true,\n ...identityProps,\n ...sidebarProps,\n }\n\n return (\n <WorkspacePrewarmContext.Provider value={prewarm ? prewarmHandle : null}>\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={activeAppId ? appGroup?.id : resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n </WorkspacePrewarmContext.Provider>\n )\n}\n\nexport { AgentWorkspaceCompanion, createAgentWorkspaceCompanionTabs, type AgentWorkspaceCompanionHandle, type AgentWorkspaceCompanionProps, type AgentWorkspaceCompanionTab, type AgentWorkspaceCompanionTool, type AgentWorkspaceCompanionTools, type AgentWorkspaceCompanionNavigation } from './companion'\n\nexport { WorkspaceSwitcher, type WorkspaceSwitcherItem, type WorkspaceSwitcherProps } from '../web-react/workspace-switcher'\n\nexport { WorkspaceInitial } from '../web-react/workspace-switcher'\nexport {\n AgentRailIdentity,\n DEFAULT_WORKSPACE_NOUN,\n type AgentProductIdentity,\n type AgentRailIdentityProps,\n type AgentWorkspaceIdentity,\n type AgentWorkspaceNoun,\n} from './rail-identity'\n\nexport {\n WorkspaceList,\n type WorkspaceListAction,\n type WorkspaceListField,\n type WorkspaceListItem,\n type WorkspaceListProps,\n} from './workspace-list'\n","import { useCallback, useState, type ComponentType, type ReactNode } from 'react'\n\nimport { CheckGlyph, OVERLAY_SHADOW, PopoverSurface } from '../web-react/controls'\nimport { usePopoverDialog } from '../web-react/popover-dialog'\nimport { WorkspaceInitial } from '../web-react/workspace-switcher'\n\n/** What a product is called and how it is marked. The same three values for every product. */\nexport interface AgentProductIdentity {\n /** Short product name, for example `Legal` or `GTM`. */\n name: string\n /** Square brand mark, sized by the product for a 20px slot. */\n mark: ReactNode\n /** Where the mark leads: the workspace listing, or home when there is none. */\n href: string\n}\n\n/** The words a product uses for one workspace and for several. */\nexport interface AgentWorkspaceNoun {\n singular: string\n plural: string\n}\n\nexport const DEFAULT_WORKSPACE_NOUN: AgentWorkspaceNoun = { singular: 'workspace', plural: 'workspaces' }\n\n/** The workspace that is open, and where else this person can go. */\nexport interface AgentWorkspaceIdentity {\n id: string\n name: string\n /** Defaults to workspace / workspaces. */\n noun?: AgentWorkspaceNoun\n /** Every workspace this person can open, including the open one, in the product's order. */\n options?: readonly { id: string; name: string }[]\n /** Required with `options`: the route that opens a workspace. */\n hrefForWorkspace?: (workspaceId: string) => string\n /** The listing route. Adds an \"All …\" entry. */\n listHref?: string\n /** The creation route. Adds a \"New …\" entry. */\n createHref?: string\n}\n\n/** The number of workspaces past which the switcher offers a search field. */\nconst SEARCH_THRESHOLD = 7\n\nconst HIDE_ON_RAIL: Record<'md' | 'lg', string> = { md: 'md:hidden', lg: 'lg:hidden' }\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toLocaleUpperCase() + text.slice(1)\n}\n\nexport interface AgentRailIdentityProps {\n product: AgentProductIdentity\n workspace?: AgentWorkspaceIdentity | null\n /**\n * The breakpoint below which the fixed rail is hidden. The rail draws the\n * mark itself; below this width the same content heads the mobile bar and\n * drawer, which have no mark of their own.\n */\n hideBelow?: 'md' | 'lg'\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches SidebarLayout's router-agnostic link slot\n LinkComponent?: ComponentType<any>\n}\n\nfunction DefaultLink({ href, to, ...props }: { href?: string; to?: string; [key: string]: unknown }) {\n return <a href={href ?? to} {...props} />\n}\n\n/**\n * The top of every product's rail: which product, and which workspace.\n *\n * One line when no workspace is open (the listing), two when one is: the\n * workspace name, then the product beneath it. A name too long for one line\n * takes both lines and the product moves to the tooltip, which carries the\n * full text either way, so a long name can never push into the collapse\n * button, the page beside the rail, or the height of the header row. It is a switcher only when\n * there is somewhere to switch to; a menu that lists one item is not offered.\n */\nexport function AgentRailIdentity({ product, workspace, hideBelow = 'lg', LinkComponent }: AgentRailIdentityProps) {\n const Link = LinkComponent ?? DefaultLink\n const mobileMark = (\n <span aria-hidden className={`flex h-7 w-7 shrink-0 items-center justify-center ${HIDE_ON_RAIL[hideBelow]}`}>\n {product.mark}\n </span>\n )\n\n if (!workspace) {\n return (\n <Link\n href={product.href}\n to={product.href}\n title={product.name}\n className=\"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-accent\"\n >\n {mobileMark}\n <span className=\"min-w-0 flex-1 truncate text-sm font-semibold text-foreground\">{product.name}</span>\n </Link>\n )\n }\n\n // Two 20px lines, the height the header row already gives the stack. A\n // name that fits one line leaves the product beneath it; a longer name\n // wraps onto the second line and pushes the product out of the clipped\n // box, so the name is read in full instead of cut at a dozen characters.\n // Past two lines it ends in an ellipsis; the tooltip keeps the full name.\n const stack = (\n <span className=\"block max-h-10 min-w-0 flex-1 overflow-hidden text-left\">\n <span className=\"line-clamp-2 text-sm font-semibold leading-5 text-foreground [overflow-wrap:anywhere]\">{workspace.name}</span>\n <span className=\"block truncate text-sm leading-5 text-muted-foreground\">{product.name}</span>\n </span>\n )\n const others = (workspace.options ?? []).filter((option) => option.id !== workspace.id)\n const switchable = (others.length > 0 && workspace.hrefForWorkspace !== undefined) || Boolean(workspace.listHref) || Boolean(workspace.createHref)\n\n if (!switchable) {\n return (\n <div title={`${workspace.name} · ${product.name}`} className=\"flex w-full min-w-0 items-center gap-2 px-1.5 py-1\">\n {mobileMark}\n {stack}\n </div>\n )\n }\n\n return <WorkspaceMenu product={product} workspace={workspace} mobileMark={mobileMark} stack={stack} Link={Link} />\n}\n\nfunction WorkspaceMenu({\n product,\n workspace,\n mobileMark,\n stack,\n Link,\n}: {\n product: AgentProductIdentity\n workspace: AgentWorkspaceIdentity\n mobileMark: ReactNode\n stack: ReactNode\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n}) {\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const changeOpen = useCallback((next: boolean) => {\n setOpen(next)\n if (!next) setQuery('')\n }, [])\n // A non-modal dialog, like WorkspaceSwitcher: opening focuses the first\n // control, and Tab past the last one returns beside the trigger.\n const { containerRef, triggerRef, panelRef, triggerProps, id: panelId } = usePopoverDialog(open, changeOpen)\n const noun = workspace.noun ?? DEFAULT_WORKSPACE_NOUN\n const options = workspace.hrefForWorkspace ? workspace.options ?? [] : []\n const search = query.trim().toLocaleLowerCase()\n const visible = search ? options.filter((option) => option.name.toLocaleLowerCase().includes(search)) : options\n const close = () => changeOpen(false)\n const rowClass = 'flex min-h-9 w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-foreground transition-colors hover:bg-accent'\n\n return (\n <div ref={containerRef} className=\"w-full min-w-0\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-label={`${capitalize(noun.singular)}: ${workspace.name}. Switch ${noun.singular}`}\n title={`${workspace.name} · ${product.name}`}\n onClick={() => changeOpen(!open)}\n className=\"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-accent aria-expanded:bg-accent\"\n >\n {mobileMark}\n {stack}\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <path d=\"m8 9 4-4 4 4m-8 6 4 4 4-4\" />\n </svg>\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"dialog\"\n aria-label={`Switch ${noun.singular}`}\n side=\"below\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n contentKey={`${query}:${options.length}`}\n className={`w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-lg border border-card-edge bg-popover p-1.5 text-foreground ${OVERLAY_SHADOW}`}\n >\n {options.length > SEARCH_THRESHOLD && (\n <input\n data-autofocus\n aria-label={`Search ${noun.plural}`}\n placeholder={`Search ${noun.plural}`}\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n className=\"mb-1.5 h-9 w-full rounded-md border border-border bg-background px-2.5 text-sm text-foreground\"\n />\n )}\n {options.length > 0 && (\n <div className=\"max-h-72 overflow-y-auto\">\n {visible.map((option) => (\n <Link\n key={option.id}\n href={workspace.hrefForWorkspace!(option.id)}\n to={workspace.hrefForWorkspace!(option.id)}\n aria-current={option.id === workspace.id ? 'page' : undefined}\n title={option.name}\n onClick={close}\n className={rowClass}\n >\n <WorkspaceInitial name={option.name} />\n <span className=\"min-w-0 flex-1 truncate\">{option.name}</span>\n {option.id === workspace.id && <CheckGlyph className=\"h-4 w-4 shrink-0 text-primary\" />}\n </Link>\n ))}\n {visible.length === 0 && (\n <p role=\"status\" className=\"px-2 py-2 text-sm text-muted-foreground\">\n No {noun.plural} match “{query.trim()}”.\n </p>\n )}\n </div>\n )}\n {(workspace.listHref || workspace.createHref) && (\n <div className={options.length > 0 ? 'mt-1.5 border-t border-border pt-1.5' : undefined}>\n {workspace.listHref && (\n <Link href={workspace.listHref} to={workspace.listHref} onClick={close} className={rowClass}>\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <rect x=\"4\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"4\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" />\n </svg>\n <span className=\"min-w-0 flex-1 truncate\">All {noun.plural}</span>\n </Link>\n )}\n {workspace.createHref && (\n <Link href={workspace.createHref} to={workspace.createHref} onClick={close} className={rowClass}>\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n <span className=\"min-w-0 flex-1 truncate\">New {noun.singular}</span>\n </Link>\n )}\n </div>\n )}\n </PopoverSurface>\n </div>\n )\n}\n","import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from 'react'\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@tangle-network/sandbox-ui/primitives'\nimport { WorkspaceLayout } from '@tangle-network/sandbox-ui/workspace'\nimport { FlaskConical, FolderOpen, GitCompare, Monitor, ShieldCheck, Terminal } from 'lucide-react'\n\nexport interface AgentWorkspaceCompanionTab {\n id: string\n label: string\n icon?: ReactNode\n /** Retain a visited tab through tab switches, pane closure, and viewport changes. */\n keepMounted?: boolean\n /** A count that needs the person, such as approvals waiting. Hidden at zero. */\n badge?: number\n renderContent: (state: { active: boolean }) => ReactNode\n}\n\nexport type AgentWorkspaceCompanionTool = 'approvals' | 'files' | 'agent' | 'terminal' | 'changes' | 'preview'\n\n/** Supply only tools the product can actually serve. Content remains product-owned. */\nexport type AgentWorkspaceCompanionTools = Partial<Record<AgentWorkspaceCompanionTool, AgentWorkspaceCompanionTab['renderContent']>>\n\nconst companionTools = [\n { id: 'approvals', label: 'Approvals', Icon: ShieldCheck },\n { id: 'files', label: 'Files', Icon: FolderOpen },\n { id: 'agent', label: 'Agent', Icon: FlaskConical },\n { id: 'terminal', label: 'Terminal', Icon: Terminal },\n { id: 'changes', label: 'Changes', Icon: GitCompare },\n { id: 'preview', label: 'Preview', Icon: Monitor },\n] as const\n\n/** Canonical order, labels, icons and lazy retention for companion tools; `badges` counts what waits on the person. */\nexport function createAgentWorkspaceCompanionTabs(\n tools: AgentWorkspaceCompanionTools,\n badges: Partial<Record<AgentWorkspaceCompanionTool, number>> = {},\n): AgentWorkspaceCompanionTab[] {\n return companionTools.flatMap(({ id, label, Icon }) => {\n const renderContent = tools[id]\n const badge = badges[id]\n return renderContent\n ? [{ id, label, icon: <Icon className=\"h-3.5 w-3.5\" aria-hidden />, keepMounted: true, renderContent, ...(badge ? { badge } : {}) }]\n : []\n })\n}\n\nexport interface AgentWorkspaceCompanionNavigation {\n content: ReactNode\n header?: ReactNode\n open?: boolean\n onOpenChange?: (open: boolean) => void\n label?: string\n defaultWidth?: number\n minWidth?: number\n maxWidth?: number\n collapsedControl?: ReactNode\n}\n\nexport interface AgentWorkspaceCompanionHandle {\n openTab: (tabId: string) => boolean\n}\n\nexport interface AgentWorkspaceCompanionProps {\n children: ReactNode\n /**\n * Quiet content for the conversation's header row, such as its title or a\n * pending-review status. The row also holds the tools toggle, flat in its\n * top-right corner, and aligns with the open tools pane's header.\n */\n header?: ReactNode\n /** Use tools for shared defaults; tabs overrides them for product-specific navigation. */\n tabs?: readonly AgentWorkspaceCompanionTab[]\n tools?: AgentWorkspaceCompanionTools\n /** Counts on the shared tools' tabs, such as approvals waiting. */\n toolBadges?: Partial<Record<AgentWorkspaceCompanionTool, number>>\n /** Optional session navigation, composed in the same responsive layout. */\n navigation?: AgentWorkspaceCompanionNavigation\n keyboardShortcuts?: boolean\n open?: boolean\n onOpenChange?: (open: boolean) => void\n defaultOpen?: boolean\n activeTabId?: string\n onActiveTabChange?: (tabId: string) => void\n defaultActiveTabId?: string\n /** Namespace for remembered tab selection and underlying pane dimensions. */\n persistenceKey?: string\n label?: string\n defaultWidth?: number\n className?: string\n}\n\n/** Product-owned tools beside a conversation; omitted tools have no tabs or effects. */\nexport const AgentWorkspaceCompanion = forwardRef<AgentWorkspaceCompanionHandle, AgentWorkspaceCompanionProps>(function AgentWorkspaceCompanion({\n children,\n header,\n tabs: customTabs,\n tools,\n toolBadges,\n navigation,\n keyboardShortcuts,\n open: controlledOpen,\n onOpenChange,\n defaultOpen = false,\n activeTabId,\n onActiveTabChange,\n defaultActiveTabId,\n persistenceKey,\n label = 'Workspace tools',\n defaultWidth = 420,\n className,\n}, ref) {\n const tabs = customTabs ?? createAgentWorkspaceCompanionTabs(tools ?? {}, toolBadges)\n const [uncontrolledOpen, setOpen] = useState(defaultOpen)\n const open = controlledOpen ?? uncontrolledOpen\n const [selection, setSelection] = useState({ key: persistenceKey, id: defaultActiveTabId })\n const [visits, setVisits] = useState<{ key: string | undefined; ids: ReadonlySet<string> }>(() => ({ key: persistenceKey, ids: new Set() }))\n const requested = activeTabId ?? (selection.key === persistenceKey ? selection.id : defaultActiveTabId)\n const active = tabs.find((tab) => tab.id === requested)?.id ?? tabs[0]?.id\n const visited = visits.key === persistenceKey ? visits.ids : new Set<string>()\n const storageKey = persistenceKey ? `${persistenceKey}:companion-tab` : undefined\n\n const pendingRestoration = useRef<{ key: string | undefined; id: string | undefined } | undefined>(undefined)\n const reconciledSelection = useRef<string | undefined>(undefined)\n const restoredKey = useRef<string | undefined>(undefined)\n useEffect(() => {\n const key = JSON.stringify([persistenceKey, defaultActiveTabId])\n if (restoredKey.current === key || tabs.length === 0) return\n let id = activeTabId ?? defaultActiveTabId\n if (storageKey) {\n try { id = window.localStorage.getItem(storageKey) ?? id } catch { /* Browser storage is optional. */ }\n }\n const resolved = tabs.find((tab) => tab.id === id)?.id ?? tabs[0]?.id\n restoredKey.current = key\n pendingRestoration.current = { key: persistenceKey, id: resolved }\n setSelection({ key: persistenceKey, id: resolved })\n if (resolved && resolved !== activeTabId) {\n reconciledSelection.current = JSON.stringify([persistenceKey, requested, resolved])\n onActiveTabChange?.(resolved)\n }\n }, [storageKey, persistenceKey, defaultActiveTabId, activeTabId, requested, tabs, onActiveTabChange])\n\n useEffect(() => {\n // Let restored selection reach the controlled parent before reconciling stale props.\n const pending = pendingRestoration.current\n if (pending) {\n const acknowledged = activeTabId === undefined\n ? selection.key === pending.key && selection.id === pending.id\n : activeTabId === pending.id\n if (!acknowledged) return\n pendingRestoration.current = undefined\n }\n if (!active || tabs.some((tab) => tab.id === requested)) {\n reconciledSelection.current = undefined\n return\n }\n const key = JSON.stringify([persistenceKey, requested, active])\n if (reconciledSelection.current === key) return\n reconciledSelection.current = key\n setSelection({ key: persistenceKey, id: active })\n onActiveTabChange?.(active)\n }, [active, activeTabId, requested, selection, persistenceKey, tabs, onActiveTabChange])\n\n useEffect(() => {\n if (!open || !active) return\n setVisits((previous) => {\n const ids = previous.key === persistenceKey ? previous.ids : new Set<string>()\n return ids.has(active) ? previous : { key: persistenceKey, ids: new Set([...ids, active]) }\n })\n }, [open, active, persistenceKey])\n\n const selectTab = useCallback((id: string) => {\n if (!tabs.some((tab) => tab.id === id)) return false\n setSelection({ key: persistenceKey, id })\n onActiveTabChange?.(id)\n if (storageKey) {\n try { window.localStorage.setItem(storageKey, id) } catch { /* Selection still works without storage. */ }\n }\n return true\n }, [tabs, persistenceKey, storageKey, onActiveTabChange])\n const changeOpen = useCallback((next: boolean) => {\n setOpen(next)\n onOpenChange?.(next)\n }, [onOpenChange])\n\n useImperativeHandle(ref, () => ({\n openTab(id) {\n if (!selectTab(id)) return false\n changeOpen(true)\n return true\n },\n }), [selectTab, changeOpen])\n\n if (tabs.length === 0 && !navigation) return <>{children}</>\n const toolsName = inSentence(label)\n\n return (\n <Tabs key={persistenceKey} value={active} onValueChange={selectTab} className={`flex h-full min-h-0 min-w-0 flex-1 flex-col ${className ?? ''}`}>\n <WorkspaceLayout\n className=\"h-full min-h-0 min-w-0 flex-1\"\n // One raised surface in an even gutter. The tools toggle sits flat in\n // the conversation header's top-right corner instead of an edge column\n // (which cost the conversation a column and showed a strip of another\n // surface) or a float (which covered a right-aligned message on a phone).\n surface=\"inset\"\n centerHeader={header === undefined ? undefined : <div className=\"flex min-w-0 items-center gap-2 px-2\">{header}</div>}\n rightOpenLabel={`Open ${toolsName}`}\n rightCloseLabel={`Close ${toolsName}`}\n rightControlHint={tabs.length > 0 ? tabs.map((tab) => tab.label).join(', ') : undefined}\n keepRightMounted\n // The layout's center is a block scroller, so a conversation written as\n // `flex flex-1 flex-col` (message list `flex-1 overflow-y-auto`, then a\n // shrink-0 composer) got no height bound: the whole conversation grew\n // with its content and a tall composer was pushed below the fold. A\n // one-cell grid whose row is `minmax(0, 1fr)` gives the conversation\n // exactly the pane's height: a grid item spanning a track with a zero\n // minimum has no content-based minimum, which a flex column would still\n // impose on a child without `min-h-0`. The message list then scrolls on\n // its own and the composer stays on screen.\n center={<div data-companion-center className=\"grid h-full min-h-0 min-w-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]\">{children}</div>}\n left={navigation?.content}\n leftContentClassName=\"py-0\"\n leftHeader={navigation && (navigation.header !== undefined ? navigation.header : <span className=\"text-sm font-medium\">{navigation.label ?? 'Chats'}</span>)}\n leftOpen={navigation?.open}\n onLeftOpenChange={navigation?.onOpenChange}\n leftLabel={navigation?.label ?? 'Chats'}\n defaultLeftWidth={navigation?.defaultWidth ?? 260}\n minLeftWidth={navigation?.minWidth ?? 200}\n maxLeftWidth={navigation?.maxWidth ?? 400}\n leftCollapsedControl={navigation?.collapsedControl}\n keyboardShortcuts={keyboardShortcuts}\n rightOpen={open}\n onRightOpenChange={changeOpen}\n rightLabel={label}\n defaultRightWidth={defaultWidth}\n persistenceKey={persistenceKey}\n minRightWidth={280}\n rightContentClassName=\"flex flex-col overflow-hidden\"\n rightHeader={tabs.length > 0 ? <CompanionTabList tabs={tabs} active={active} label={label} /> : undefined}\n right={tabs.length > 0 ? tabs.map((tab) => {\n const isActive = tab.id === active\n const retained = tab.keepMounted && visited.has(tab.id)\n if (!(open && isActive) && !retained) return null\n return (\n <TabsContent\n key={tab.id}\n value={tab.id}\n forceMount={retained ? true : undefined}\n hidden={!open || !isActive}\n className=\"m-0 h-full min-h-0 min-w-0 flex-1 data-[state=inactive]:hidden\"\n >\n {tab.renderContent({ active: open && isActive })}\n </TabsContent>\n )\n }) : undefined}\n />\n </Tabs>\n )\n})\n\n/** \"Workspace tools\" reads as \"workspace tools\" mid-sentence; \"CRM tools\" keeps its acronym. */\nfunction inSentence(label: string): string {\n return /^[A-Z][a-z]/.test(label) ? `${label.charAt(0).toLowerCase()}${label.slice(1)}` : label\n}\n\n/**\n * The companion's tab row. When every labelled tab does not fit the pane (a\n * phone drawer, a narrow resized pane), inactive tabs that have an icon drop to\n * icon-only and the active tab keeps its label, so no tab hides behind the\n * close button. Labels stay in the accessibility tree either way. The row\n * returns to full labels once the pane is wide enough for them again.\n */\nfunction CompanionTabList({ tabs, active, label }: { tabs: readonly AgentWorkspaceCompanionTab[]; active: string | undefined; label: string }) {\n const frameRef = useRef<HTMLDivElement>(null)\n const fullWidth = useRef(0)\n const [compact, setCompact] = useState(false)\n const signature = tabs.map((tab) => `${tab.id}\\u0000${tab.label}\\u0000${tab.icon ? 1 : 0}\\u0000${tab.badge ?? 0}`).join('\\u0001')\n\n useLayoutEffect(() => {\n fullWidth.current = 0\n setCompact(false)\n }, [signature])\n\n useLayoutEffect(() => {\n const frame = frameRef.current\n const list = frame?.firstElementChild\n if (!frame || !(list instanceof HTMLElement)) return\n const fit = () => {\n const available = frame.clientWidth\n if (!compact) {\n fullWidth.current = list.scrollWidth\n if (list.scrollWidth > available + 1) setCompact(true)\n } else if (fullWidth.current > 0 && available >= fullWidth.current) {\n setCompact(false)\n }\n }\n fit()\n if (typeof ResizeObserver === 'undefined') return\n const observer = new ResizeObserver(fit)\n observer.observe(frame)\n return () => observer.disconnect()\n }, [compact, signature])\n\n useEffect(() => {\n const trigger = frameRef.current?.querySelector<HTMLElement>('[role=\"tab\"][data-state=\"active\"]')\n trigger?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })\n }, [active, compact])\n\n return (\n <div ref={frameRef} className=\"min-w-0\" data-compact={compact ? '' : undefined}>\n <TabsList aria-label={label} className=\"h-9 max-w-full justify-start overflow-x-auto bg-transparent p-0\">\n {tabs.map((tab) => {\n const iconOnly = compact && tab.icon && tab.id !== active\n return (\n <TabsTrigger\n key={tab.id}\n value={tab.id}\n title={iconOnly ? tab.label : undefined}\n className={iconOnly ? 'gap-1.5 px-2 text-sm' : 'gap-1.5 px-2.5 text-sm'}\n >\n {tab.icon}<span className={iconOnly ? 'sr-only' : undefined}>{tab.label}</span>\n {tab.badge ? (\n <span className=\"min-w-5 rounded-full bg-[var(--surface-warning-bg)] px-1.5 text-center text-sm font-medium tabular-nums leading-5 text-[var(--surface-warning-text)]\">\n {tab.badge}<span className=\"sr-only\"> waiting</span>\n </span>\n ) : null}\n </TabsTrigger>\n )\n })}\n </TabsList>\n </div>\n )\n}\n","import { useId, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { Input, PageHeader } from '@tangle-network/ui/primitives'\n\nimport { ActionDialog, ActionDialogButton } from '../web-react/action-dialog'\nimport { OVERLAY_SHADOW, PopoverSurface, usePopover } from '../web-react/controls'\nimport { WorkspaceInitial } from '../web-react/workspace-switcher'\nimport { DEFAULT_WORKSPACE_NOUN, type AgentWorkspaceNoun } from './rail-identity'\n\n/** One workspace as the listing shows it. */\nexport interface WorkspaceListItem {\n id: string\n name: string\n /** The route that opens it. */\n href: string\n /** One line under the name. Not shown when it only repeats the name. */\n description?: string | null\n /** Last activity. Shown as a short date. */\n updatedAt?: string | number | Date | null\n /** Values for the product's `fields`, keyed by field id. */\n values?: Readonly<Record<string, ReactNode>>\n /** Replaces the initial avatar, for example with a logo the product already has. */\n avatar?: ReactNode\n}\n\n/** A product column: a value the user compares across workspaces (tax year, status, owner). */\nexport interface WorkspaceListField {\n id: string\n label: string\n}\n\n/** A non-destructive product action in an item's overflow menu. */\nexport interface WorkspaceListAction {\n id: string\n label: string\n onSelect: (item: WorkspaceListItem) => void\n}\n\nexport interface WorkspaceListProps {\n items: readonly WorkspaceListItem[]\n /** The product's words for one workspace and several. Defaults to workspace / workspaces. */\n noun?: AgentWorkspaceNoun\n /** Page title. Defaults to the capitalized plural noun. */\n title?: string\n /** One sentence under the title, when the page needs one. */\n description?: ReactNode\n /** `list` rows for records people compare; `grid` cards for a handful of rich projects. */\n layout?: 'list' | 'grid'\n /** Product values, shown as columns (list) or under the description (grid). */\n fields?: readonly WorkspaceListField[]\n /**\n * The one primary action, labelled \"New {singular}\" unless `label` says otherwise.\n * `href` navigates; `onSelect` opens the product's own creation flow; `onCreate`\n * asks for a name in the shared dialog and hands it over — reject with an Error\n * to show its message, and navigate to the new workspace from inside it.\n */\n create?: {\n label?: string\n href?: string\n onSelect?: () => void\n onCreate?: (name: string) => Promise<void>\n /** Placeholder for the name field. Defaults to \"{Singular} name\". */\n namePlaceholder?: string\n }\n /** First-use copy. The create action is offered beneath it. */\n empty?: { title?: string; description?: string }\n /** Persist a new name. Reject with an Error to show its message in the dialog. */\n rename?: (item: WorkspaceListItem, name: string) => Promise<void>\n /** Delete for good. Offered in the overflow menu, behind a confirmation. */\n remove?: (item: WorkspaceListItem) => Promise<void>\n /**\n * Whether this viewer may delete this item. Delete is left out of the menu\n * when it returns false, so a member who does not own an item is never shown\n * a destructive action the server would refuse. Defaults to every item.\n */\n canRemove?: (item: WorkspaceListItem) => boolean\n /** What deleting loses, for the confirmation. */\n removeConsequence?: (item: WorkspaceListItem) => string\n /** Extra overflow-menu actions. */\n actions?: (item: WorkspaceListItem) => readonly WorkspaceListAction[]\n /** Product content between the header and the items, such as a home summary. */\n children?: ReactNode\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot, same as SidebarLayout\n LinkComponent?: ComponentType<any>\n /** Formats `updatedAt`. Defaults to a short month and day, with the year when it is not this year. */\n formatDate?: (value: Date) => string\n}\n\n/** The number of items past which the listing offers a search field. */\nconst SEARCH_THRESHOLD = 8\n\n// Fixed widths keep every row's columns on the same x, whatever a date or value renders as.\nconst FIELD_CELL = 'hidden w-32 min-w-0 shrink-0 md:block'\nconst DATE_CELL = 'w-20 shrink-0 text-right sm:w-24'\n\nfunction DefaultLink({ href, to, ...props }: { href?: string; to?: string; [key: string]: unknown }) {\n return <a href={href ?? to} {...props} />\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toLocaleUpperCase() + text.slice(1)\n}\n\nfunction defaultFormatDate(value: Date): string {\n const sameYear = value.getFullYear() === new Date().getFullYear()\n return value.toLocaleDateString(undefined, sameYear ? { month: 'short', day: 'numeric' } : { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction present(value: ReactNode): boolean {\n return value !== null && value !== undefined && value !== false && value !== ''\n}\n\nfunction toDate(value: WorkspaceListItem['updatedAt']): Date | null {\n if (value === null || value === undefined || value === '') return null\n const date = value instanceof Date ? value : new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\n/** A description is noise when it says the name again (\"GTM Agent / GTM Agent\"). */\nfunction usefulDescription(item: WorkspaceListItem): string | null {\n const text = item.description?.trim()\n if (!text) return null\n return text.toLocaleLowerCase() === item.name.trim().toLocaleLowerCase() ? null : text\n}\n\n/**\n * The listing every product opens on: one title, one primary action, the\n * workspaces, and nothing that counts them. Destructive actions live in each\n * item's overflow menu behind a confirmation, never as an icon on every row.\n * The product supplies its noun, its columns, and its create route; render it\n * inside `AgentWorkspaceLayout` (with no `workspace`) so the listing wears the\n * same shell as the workspace it opens.\n */\nexport function WorkspaceList({\n items,\n noun = DEFAULT_WORKSPACE_NOUN,\n title,\n description,\n layout = 'list',\n fields = [],\n create,\n empty,\n rename,\n remove,\n canRemove,\n removeConsequence,\n actions,\n children,\n LinkComponent,\n formatDate = defaultFormatDate,\n}: WorkspaceListProps) {\n const Link = LinkComponent ?? DefaultLink\n const headingId = useId()\n const [query, setQuery] = useState('')\n const [renaming, setRenaming] = useState<WorkspaceListItem | null>(null)\n const [renameValue, setRenameValue] = useState('')\n const [removing, setRemoving] = useState<WorkspaceListItem | null>(null)\n const [creating, setCreating] = useState(false)\n const [createValue, setCreateValue] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const search = query.trim().toLocaleLowerCase()\n const visible = useMemo(\n () => (search ? items.filter((item) => item.name.toLocaleLowerCase().includes(search)) : items),\n [items, search],\n )\n const createLabel = create?.label ?? `New ${noun.singular}`\n const openCreate = () => {\n setError(null)\n setCreateValue('')\n setCreating(true)\n }\n const createControl = create\n ? <CreateButton create={create.onCreate && !create.href ? { ...create, onSelect: openCreate } : create} label={createLabel} Link={Link} />\n : null\n const submitCreate = () => {\n const name = createValue.trim()\n if (!name || !create?.onCreate) return\n void run(() => create.onCreate!(name), () => setCreating(false))\n }\n\n const hasDates = items.some((item) => toDate(item.updatedAt) !== null)\n const removable = (item: WorkspaceListItem) => Boolean(remove) && (canRemove?.(item) ?? true)\n const hasMenu = Boolean(rename) || items.some(removable) || Boolean(actions)\n const menuFor = (item: WorkspaceListItem): MenuEntry[] => [\n ...(rename ? [{ id: 'rename', label: 'Rename', onSelect: () => { setError(null); setRenaming(item); setRenameValue(item.name) } }] : []),\n ...(actions?.(item) ?? []).map((action) => ({ id: action.id, label: action.label, onSelect: () => action.onSelect(item) })),\n ...(removable(item) ? [{ id: 'delete', label: 'Delete', destructive: true, onSelect: () => { setError(null); setRemoving(item) } }] : []),\n ]\n\n const run = async (work: () => Promise<void>, done: () => void) => {\n setBusy(true)\n setError(null)\n try {\n await work()\n done()\n } catch (cause) {\n setError(cause instanceof Error && cause.message ? cause.message : 'That did not save. Try again.')\n } finally {\n setBusy(false)\n }\n }\n\n const submitRename = () => {\n if (!renaming || !rename) return\n const name = renameValue.trim()\n if (!name || name === renaming.name) {\n setRenaming(null)\n return\n }\n void run(() => rename(renaming, name), () => setRenaming(null))\n }\n\n return (\n <section aria-labelledby={headingId} className=\"mx-auto w-full max-w-5xl px-4 py-6 sm:px-6 sm:py-8 lg:px-8\">\n <PageHeader\n className=\"mb-0\"\n titleId={headingId}\n title={title ?? capitalize(noun.plural)}\n description={description}\n actions={items.length > 0 ? createControl : null}\n />\n\n {children != null && <div className=\"mt-6\">{children}</div>}\n\n {items.length === 0 ? (\n <div className=\"mt-6 flex flex-col items-center rounded-xl border border-dashed border-border px-6 py-14 text-center\">\n <span aria-hidden className=\"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary\">\n <svg className=\"h-5 w-5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <rect x=\"4\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"4\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><path d=\"M16.75 13.5v6.5M13.5 16.75H20\" />\n </svg>\n </span>\n <h2 className=\"mt-4 text-base font-semibold text-foreground\">{empty?.title ?? `No ${noun.plural} yet`}</h2>\n {empty?.description && <p className=\"mt-1.5 max-w-sm text-sm text-muted-foreground\">{empty.description}</p>}\n {createControl && <div className=\"mt-5\">{createControl}</div>}\n </div>\n ) : (\n <>\n {items.length > SEARCH_THRESHOLD && (\n <div className=\"mt-6\">\n <Input\n type=\"search\"\n aria-label={`Search ${noun.plural}`}\n placeholder={`Search ${noun.plural}`}\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n className=\"max-w-sm\"\n />\n </div>\n )}\n {visible.length === 0 ? (\n <p role=\"status\" className=\"mt-6 rounded-xl border border-border px-4 py-8 text-center text-sm text-muted-foreground\">\n No {noun.plural} match “{query.trim()}”.{' '}\n <button type=\"button\" onClick={() => setQuery('')} className=\"font-medium text-foreground underline underline-offset-2\">\n Clear search\n </button>\n </p>\n ) : layout === 'grid' ? (\n <ul className={`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 ${items.length > SEARCH_THRESHOLD ? 'mt-3' : 'mt-6'}`}>\n {visible.map((item) => (\n <GridCard key={item.id} item={item} fields={fields} menu={menuFor(item)} Link={Link} formatDate={formatDate} />\n ))}\n </ul>\n ) : (\n <div className={`overflow-hidden rounded-xl border border-border bg-card ${items.length > SEARCH_THRESHOLD ? 'mt-3' : 'mt-6'}`}>\n {fields.length > 0 && (\n <div aria-hidden className=\"hidden items-center gap-3 border-b border-border px-4 py-2 text-sm font-medium text-muted-foreground md:flex\">\n <span className=\"w-10 shrink-0\" />\n <span className=\"min-w-0 flex-1\">Name</span>\n {fields.map((field) => (\n <span key={field.id} className={`${FIELD_CELL} truncate`}>{field.label}</span>\n ))}\n <span className={DATE_CELL}>{hasDates ? 'Updated' : ''}</span>\n {hasMenu && <span className=\"w-8 shrink-0 [@media(pointer:coarse)]:w-11\" />}\n </div>\n )}\n <ul className=\"divide-y divide-border\">\n {visible.map((item) => (\n <ListRow key={item.id} item={item} fields={fields} menu={menuFor(item)} reserveMenu={hasMenu} Link={Link} formatDate={formatDate} />\n ))}\n </ul>\n </div>\n )}\n </>\n )}\n\n {renaming && (\n <ActionDialog\n title={`Rename ${noun.singular}`}\n onClose={() => setRenaming(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setRenaming(null)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton onClick={submitRename} disabled={busy || !renameValue.trim()}>Save</ActionDialogButton>\n </>\n }\n >\n <label htmlFor={`${headingId}-rename`} className=\"text-sm text-muted-foreground\">Name</label>\n <Input\n id={`${headingId}-rename`}\n value={renameValue}\n autoFocus\n onChange={(event) => setRenameValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter' && !busy) {\n event.preventDefault()\n submitRename()\n }\n }}\n className=\"mt-1.5\"\n />\n </ActionDialog>\n )}\n\n {creating && create?.onCreate && (\n <ActionDialog\n title={createLabel}\n onClose={() => setCreating(false)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setCreating(false)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton onClick={submitCreate} disabled={busy || !createValue.trim()}>Create</ActionDialogButton>\n </>\n }\n >\n <label htmlFor={`${headingId}-create`} className=\"text-sm text-muted-foreground\">Name</label>\n <Input\n id={`${headingId}-create`}\n value={createValue}\n autoFocus\n placeholder={create.namePlaceholder ?? `${capitalize(noun.singular)} name`}\n onChange={(event) => setCreateValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter' && !busy) {\n event.preventDefault()\n submitCreate()\n }\n }}\n className=\"mt-1.5\"\n />\n </ActionDialog>\n )}\n\n {removing && remove && (\n <ActionDialog\n title={`Delete ${noun.singular}?`}\n onClose={() => setRemoving(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setRemoving(null)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton variant=\"destructive\" onClick={() => void run(() => remove(removing), () => setRemoving(null))} disabled={busy}>\n Delete\n </ActionDialogButton>\n </>\n }\n >\n <p className=\"break-words text-sm text-muted-foreground\">\n {removeConsequence?.(removing) ?? `“${removing.name}” and everything in it will be deleted. This cannot be undone.`}\n </p>\n </ActionDialog>\n )}\n </section>\n )\n}\n\ninterface MenuEntry {\n id: string\n label: string\n destructive?: boolean\n onSelect: () => void\n}\n\ninterface ItemProps {\n reserveMenu?: boolean\n item: WorkspaceListItem\n fields: readonly WorkspaceListField[]\n menu: MenuEntry[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n formatDate: (value: Date) => string\n}\n\nfunction UpdatedAt({ value, formatDate, className = 'shrink-0' }: { value: WorkspaceListItem['updatedAt']; formatDate: (value: Date) => string; className?: string }) {\n const date = toDate(value)\n if (!date) return <span className={className} />\n return (\n // Server and browser can format a date differently (zone, locale); the\n // browser's reading is the one the user should see.\n <time dateTime={date.toISOString()} suppressHydrationWarning className={`${className} text-sm tabular-nums text-muted-foreground`}>\n {formatDate(date)}\n </time>\n )\n}\n\n/**\n * The name is the row's link, stretched over the whole row with an `after:`\n * overlay, so the overflow menu can sit on top as a real sibling button\n * instead of a button nested inside a link.\n */\nfunction ListRow({ item, fields, menu, reserveMenu, Link, formatDate }: ItemProps) {\n const detail = usefulDescription(item)\n const mobileFields = fields.filter((field) => present(item.values?.[field.id]))\n return (\n <li className=\"group relative isolate flex min-h-16 items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/60\">\n {item.avatar ?? <WorkspaceInitial name={item.name} size=\"lg\" />}\n <div className=\"min-w-0 flex-1\">\n <Link\n href={item.href}\n to={item.href}\n title={item.name}\n className=\"block truncate text-sm font-medium text-foreground after:absolute after:inset-0 after:content-[''] focus-visible:outline-none focus-visible:after:rounded-[inherit] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring\"\n >\n {item.name}\n </Link>\n {detail && <p className=\"truncate text-sm text-muted-foreground\" title={detail}>{detail}</p>}\n {/* Below md the columns are hidden, so their values ride under the name instead. */}\n {mobileFields.length > 0 && (\n <p className=\"truncate text-sm text-muted-foreground md:hidden\">\n {mobileFields.map((field, index) => (\n <span key={field.id}>\n {index > 0 && ' · '}\n <span className=\"sr-only\">{field.label}: </span>\n {item.values![field.id]}\n </span>\n ))}\n </p>\n )}\n </div>\n {fields.map((field) => (\n <div key={field.id} className={`${FIELD_CELL} truncate text-sm text-muted-foreground`}>\n <span className=\"sr-only\">{field.label}: </span>\n {present(item.values?.[field.id]) ? item.values![field.id] : '—'}\n </div>\n ))}\n <UpdatedAt value={item.updatedAt} formatDate={formatDate} className={DATE_CELL} />\n {menu.length > 0 ? <ItemMenu item={item} entries={menu} /> : reserveMenu ? <span className=\"w-8 shrink-0 [@media(pointer:coarse)]:w-11\" /> : null}\n </li>\n )\n}\n\nfunction GridCard({ item, fields, menu, Link, formatDate }: ItemProps) {\n const detail = usefulDescription(item)\n const shownFields = fields.filter((field) => present(item.values?.[field.id]))\n return (\n <li className=\"group relative isolate flex min-h-36 flex-col overflow-hidden rounded-xl border border-border bg-card p-4 transition-[border-color,box-shadow] hover:border-primary/40 hover:shadow-sm\">\n <span aria-hidden className=\"pointer-events-none absolute inset-x-0 top-0 -z-10 h-16 bg-gradient-to-b from-primary/[0.07] to-transparent\" />\n <div className=\"flex items-start gap-3\">\n {item.avatar ?? <WorkspaceInitial name={item.name} size=\"lg\" />}\n <div className=\"min-w-0 flex-1 pt-0.5\">\n <Link\n href={item.href}\n to={item.href}\n title={item.name}\n className=\"line-clamp-2 break-words text-sm font-semibold text-foreground after:absolute after:inset-0 after:content-[''] focus-visible:outline-none focus-visible:after:rounded-xl focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring\"\n >\n {item.name}\n </Link>\n {detail && <p className=\"mt-0.5 truncate text-sm text-muted-foreground\" title={detail}>{detail}</p>}\n </div>\n {menu.length > 0 && <ItemMenu item={item} entries={menu} />}\n </div>\n <div className=\"mt-auto flex items-end justify-between gap-3 pt-4\">\n {shownFields.length > 0 ? (\n <dl className=\"flex min-w-0 flex-wrap gap-x-4 gap-y-1 text-sm\">\n {shownFields.map((field) => (\n <div key={field.id} className=\"flex min-w-0 gap-1\">\n <dt className=\"text-muted-foreground\">{field.label}</dt>\n <dd className=\"truncate font-medium text-foreground\">{item.values?.[field.id]}</dd>\n </div>\n ))}\n </dl>\n ) : <span />}\n <UpdatedAt value={item.updatedAt} formatDate={formatDate} />\n </div>\n </li>\n )\n}\n\nfunction ItemMenu({ item, entries }: { item: WorkspaceListItem; entries: MenuEntry[] }) {\n const [open, setOpen] = useState(false)\n const panelId = useId()\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen)\n return (\n <div ref={containerRef} className=\"relative z-10 shrink-0\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-label={`Actions for ${item.name}`}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen(!open)}\n // Hidden until hover only where hover exists; a touch screen of any width shows it.\n className=\"flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11 transition hover:bg-muted hover:text-foreground focus-visible:opacity-100 aria-expanded:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover:opacity-100\"\n >\n <svg aria-hidden className=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <circle cx=\"5\" cy=\"12\" r=\"1.6\" /><circle cx=\"12\" cy=\"12\" r=\"1.6\" /><circle cx=\"19\" cy=\"12\" r=\"1.6\" />\n </svg>\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"menu\"\n aria-label={`Actions for ${item.name}`}\n side=\"below\"\n align=\"end\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n className={`w-44 overflow-hidden rounded-md border border-card-edge bg-popover py-1 ${OVERLAY_SHADOW}`}\n >\n {entries.map((entry, index) => (\n <button\n key={entry.id}\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n setOpen(false)\n // The dialog this opens returns focus to whatever had it — the trigger, not <body>.\n triggerRef.current?.focus()\n entry.onSelect()\n }}\n className={`block w-full px-3 py-1.5 text-left text-sm transition ${\n entry.destructive ? 'text-destructive hover:bg-destructive/10' : 'text-foreground hover:bg-accent'\n } ${entry.destructive && index > 0 ? 'mt-1 border-t border-border pt-2' : ''}`}\n >\n {entry.label}\n </button>\n ))}\n </PopoverSurface>\n </div>\n )\n}\n\nfunction CreateButton({\n create,\n label,\n Link,\n}: {\n create: NonNullable<WorkspaceListProps['create']>\n label: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n}) {\n const className = 'inline-flex h-9 shrink-0 items-center gap-1.5 rounded-md bg-primary px-3.5 text-sm font-medium text-primary-foreground transition hover:opacity-90 active:scale-[0.98]'\n const icon = (\n <svg aria-hidden className=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n )\n if (create.href) {\n return (\n <Link href={create.href} to={create.href} className={className}>\n {icon}\n {label}\n </Link>\n )\n }\n return (\n <button type=\"button\" onClick={create.onSelect} className={className}>\n {icon}\n {label}\n </button>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAyE;;;ACAlF,SAAS,aAAa,gBAAoD;AA+DjE,cAuBH,YAvBG;AAzCF,IAAM,yBAA6C,EAAE,UAAU,aAAa,QAAQ,aAAa;AAmBxG,IAAM,mBAAmB;AAEzB,IAAM,eAA4C,EAAE,IAAI,aAAa,IAAI,YAAY;AAErF,SAAS,WAAW,MAAsB;AACxC,SAAO,KAAK,OAAO,CAAC,EAAE,kBAAkB,IAAI,KAAK,MAAM,CAAC;AAC1D;AAeA,SAAS,YAAY,EAAE,MAAM,IAAI,GAAG,MAAM,GAA2D;AACnG,SAAO,oBAAC,OAAE,MAAM,QAAQ,IAAK,GAAG,OAAO;AACzC;AAYO,SAAS,kBAAkB,EAAE,SAAS,WAAW,YAAY,MAAM,cAAc,GAA2B;AACjH,QAAM,OAAO,iBAAiB;AAC9B,QAAM,aACJ,oBAAC,UAAK,eAAW,MAAC,WAAW,qDAAqD,aAAa,SAAS,CAAC,IACtG,kBAAQ,MACX;AAGF,MAAI,CAAC,WAAW;AACd,WACE;AAAA,MAAC;AAAA;AAAA,QACC,MAAM,QAAQ;AAAA,QACd,IAAI,QAAQ;AAAA,QACZ,OAAO,QAAQ;AAAA,QACf,WAAU;AAAA,QAET;AAAA;AAAA,UACD,oBAAC,UAAK,WAAU,iEAAiE,kBAAQ,MAAK;AAAA;AAAA;AAAA,IAChG;AAAA,EAEJ;AAOA,QAAM,QACJ,qBAAC,UAAK,WAAU,2DACd;AAAA,wBAAC,UAAK,WAAU,yFAAyF,oBAAU,MAAK;AAAA,IACxH,oBAAC,UAAK,WAAU,0DAA0D,kBAAQ,MAAK;AAAA,KACzF;A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KAAK,OAAO,gBAAgB,IACvE,mBACA;AACJ,QAAM,WAA6C,QAAQ,YAAY,SAAS,IAC5E;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM,KAAK;AAAA,IACX,YAAY;AAAA,IACZ,aAAa,gBAAgB;AAAA,IAC7B,UAAU,YAAY,IAAI,CAAC,EAAE,IAAI,OAAO,MAAM,MAAM,SAAS,OAAO;AAAA,MAClE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE;AAAA,IACF,cAAc,cAAc,CAAC,WAAW,IAAI;AAAA,EAC9C,IACA;AACJ,QAAM,oBAA4C;AAAA,IAChD,GAAG;AAAA,IACH,GAAI,WAAW,CAAC,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,aAAa,CAAC,UAAU,IAAI,CAAC;AAAA,EACnC;AAEA,QAAM,YAAY,aAAa,aAAa;AAC5C,QAAM,gBAAgB,UAClB;AAAA,IACE,MAAM,QAAQ;AAAA,IACd,UAAU,QAAQ;AAAA,IAClB,mBACE,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA,eAAe,aAAa;AAAA;AAAA,IAC9B;AAAA,EAEJ,IACA,CAAC;AACL,QAAM,cAAc;AAAA,IAClB;AAAA,IACA,YAAY;AAAA,IACZ,GAAG;AAAA,IACH,GAAG;AAAA,EACL;AAEA,SACE,gBAAAA,KAAC,wBAAwB,UAAxB,EAAiC,OAAO,UAAU,gBAAgB,MACjE,0BAAAA;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,UAAU,cAAc,UAAU,KAAK;AAAA,MAEtC;AAAA;AAAA,EACH,GACF;AAEJ;","names":["useCallback","useState","jsx","jsxs","AgentWorkspaceCompanion","useState","Fragment","jsx","jsxs","SEARCH_THRESHOLD","DefaultLink","capitalize","useState","jsx"]}
|
|
1
|
+
{"version":3,"sources":["../../src/workspace-react/index.tsx","../../src/workspace-react/rail-identity.tsx","../../src/workspace-react/companion.tsx","../../src/workspace-react/workspace-list.tsx"],"sourcesContent":["import { SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport { useWorkspacePrewarm, WorkspacePrewarmContext, type UseWorkspacePrewarmOptions } from '../web-react/workspace-prewarm'\n\nimport type { WorkspaceAppRecord } from '../workspace-apps'\nimport { AgentRailIdentity, type AgentProductIdentity, type AgentWorkspaceIdentity } from './rail-identity'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/**\n * Registered apps shown under one expandable workspace destination.\n * Products supply authorized rows and their real route; preview URLs never\n * become navigation hrefs.\n */\nexport interface AgentWorkspaceAppsConfig {\n icon: WorkspaceIcon\n items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[]\n hrefForApp: (appId: string) => string\n prefetch?: RailPrefetch\n}\n\n/** One agent in the workspace roster the rail lists. */\nexport interface AgentWorkspaceAgentRow {\n /** The stable profile id. */\n id: string\n name: string\n /** What the composer's `@` carries; shown beside the name. */\n handle?: string\n}\n\n/**\n * The workspace's agents under one expandable rail row, like Apps: each row\n * opens the agent's own thread (its direct line and its feed), and an optional\n * create route adds \"New agent\". Products supply authorized rows and real\n * routes; the roster comes from the product's agent-profile catalog.\n */\nexport interface AgentWorkspaceAgentsConfig {\n icon: WorkspaceIcon\n items: readonly AgentWorkspaceAgentRow[]\n hrefForAgent: (agentId: string) => string\n /** Row label. Defaults to `Agents`. */\n label?: string\n /** Route that creates an agent; adds a \"New agent\" row at the end. */\n createHref?: string\n /** Label for the create row. Defaults to `New agent`. */\n createLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /**\n * The product's name, mark, and home. With it the shell draws the canonical\n * rail top — mark, then the open workspace and product name — so products\n * stop hand-building `logo` and `railHeaderContent`.\n */\n product?: AgentProductIdentity\n /** The open workspace and where else this person can go. Omit on the listing. */\n workspace?: AgentWorkspaceIdentity | null\n /** Product-owned destinations. Shared Apps and History rows follow them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** Authorized app destinations, in the product's persisted order. */\n apps?: AgentWorkspaceAppsConfig\n /** The workspace's agents, each opening its own thread. */\n agents?: AgentWorkspaceAgentsConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n /**\n * Warm the open workspace: the shell posts to the product's prewarm route\n * (`createWorkspacePrewarmRoute`) when the page opens in a visible tab, and\n * every `ChatComposer` inside reasserts on focus. Pass the route's URL and\n * whether this member may chat. Omit on pages with no workspace.\n */\n prewarm?: UseWorkspacePrewarmOptions\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable Apps and History rows, capped session composition, unread state,\n * and active route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n apps,\n agents,\n activeRoute,\n activeId,\n product,\n workspace,\n prewarm,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const prewarmHandle = useWorkspacePrewarm(prewarm ?? { url: null })\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const appNavItems: SidebarLayoutNavItem[] = (apps?.items ?? []).map((app) => {\n const href = apps!.hrefForApp(app.id)\n if (!href.startsWith('/') || href.startsWith('//') || /[?#\\\\]/.test(href)) {\n throw new Error('Workspace app href must be a local route path')\n }\n return {\n id: 'workspace-app:' + app.id,\n label: app.name,\n icon: apps!.icon,\n href,\n prefetch: apps!.prefetch,\n }\n })\n const agentNavItems: SidebarLayoutNavItem[] = [\n ...(agents?.items ?? []).map((agent) => {\n const href = agents!.hrefForAgent(agent.id)\n if (!href.startsWith('/') || href.startsWith('//') || /[?#\\\\]/.test(href)) {\n throw new Error('Workspace agent href must be a local route path')\n }\n return {\n id: 'workspace-agent:' + agent.id,\n label: agent.handle ? `${agent.name} · @${agent.handle}` : agent.name,\n icon: agents!.icon,\n href,\n prefetch: agents!.prefetch,\n }\n }),\n ...(agents?.createHref\n ? [{ id: 'workspace-agent:new', label: agents.createLabel ?? 'New agent', icon: agents.icon, href: agents.createHref, prefetch: agents.prefetch }]\n : []),\n ]\n const agentRoutes: NavRouteDef[] = activeRoute\n ? agentNavItems.map((item) => {\n const path = routePathFromHref(item.href!, activeRoute.base)\n if (!path) throw new Error('Workspace agent href must be under the active workspace')\n return { id: item.id, path }\n })\n : []\n const appRoutes: NavRouteDef[] = activeRoute\n ? appNavItems.map((item) => {\n const path = routePathFromHref(item.href!, activeRoute.base)\n if (!path) throw new Error('Workspace app href must be under the active workspace')\n return { id: item.id, path }\n })\n : []\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: [\n ...activeRoute.routes,\n ...appRoutes,\n ...agentRoutes,\n ...(sessionNav && historyRoutePath\n ? [{ id: sessions?.id ?? 'history', path: historyRoutePath }]\n : []),\n ],\n })\n : activeId\n\n const activeAppId = appNavItems.some((item) => item.id === resolvedActiveId)\n ? resolvedActiveId\n : undefined\n const appGroup: SidebarLayoutNavItem | undefined = apps && appNavItems.length > 0\n ? {\n id: 'workspace-apps',\n label: 'Apps',\n icon: apps.icon,\n expandable: true,\n defaultOpen: activeAppId !== undefined,\n subItems: appNavItems.map(({ id, label, icon, href, prefetch }) => ({\n id,\n label,\n icon,\n href: href!,\n prefetch,\n })),\n subActiveIds: activeAppId ? [activeAppId] : undefined,\n }\n : undefined\n const activeAgentId = agentNavItems.some((item) => item.id === resolvedActiveId) ? resolvedActiveId : undefined\n const agentGroup: SidebarLayoutNavItem | undefined = agents && agentNavItems.length > 0\n ? {\n id: 'workspace-agents',\n label: agents.label ?? 'Agents',\n icon: agents.icon,\n expandable: true,\n defaultOpen: true,\n subItems: agentNavItems.map(({ id, label, icon, href, prefetch }) => ({ id, label, icon, href: href!, prefetch })),\n subActiveIds: activeAgentId ? [activeAgentId] : undefined,\n }\n : undefined\n const workspaceNavItems: SidebarLayoutNavItem[] = [\n ...navItems,\n ...(agentGroup ? [agentGroup] : []),\n ...(appGroup ? [appGroup] : []),\n ...(sessionNav ? [sessionNav] : []),\n ]\n\n const hideBelow = sidebarProps.hideBelow ?? 'lg'\n const identityProps = product\n ? {\n logo: product.mark,\n logoHref: product.href,\n railHeaderContent: (\n <AgentRailIdentity\n product={product}\n workspace={workspace}\n hideBelow={hideBelow}\n LinkComponent={sidebarProps.LinkComponent}\n />\n ),\n }\n : {}\n const layoutProps = {\n hideBelow,\n railLabels: true,\n ...identityProps,\n ...sidebarProps,\n }\n\n return (\n <WorkspacePrewarmContext.Provider value={prewarm ? prewarmHandle : null}>\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={activeAppId ? appGroup?.id : resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n </WorkspacePrewarmContext.Provider>\n )\n}\n\nexport { AgentWorkspaceCompanion, createAgentWorkspaceCompanionTabs, type AgentWorkspaceCompanionHandle, type AgentWorkspaceCompanionProps, type AgentWorkspaceCompanionTab, type AgentWorkspaceCompanionTool, type AgentWorkspaceCompanionTools, type AgentWorkspaceCompanionNavigation } from './companion'\n\nexport { WorkspaceSwitcher, type WorkspaceSwitcherItem, type WorkspaceSwitcherProps } from '../web-react/workspace-switcher'\n\nexport { WorkspaceInitial } from '../web-react/workspace-switcher'\nexport {\n AgentRailIdentity,\n DEFAULT_WORKSPACE_NOUN,\n type AgentProductIdentity,\n type AgentRailIdentityProps,\n type AgentWorkspaceIdentity,\n type AgentWorkspaceNoun,\n} from './rail-identity'\n\nexport {\n WorkspaceList,\n type WorkspaceListAction,\n type WorkspaceListField,\n type WorkspaceListItem,\n type WorkspaceListProps,\n} from './workspace-list'\n","import { useCallback, useState, type ComponentType, type ReactNode } from 'react'\n\nimport { CheckGlyph, OVERLAY_SHADOW, PopoverSurface } from '../web-react/controls'\nimport { usePopoverDialog } from '../web-react/popover-dialog'\nimport { WorkspaceInitial } from '../web-react/workspace-switcher'\n\n/** What a product is called and how it is marked. The same three values for every product. */\nexport interface AgentProductIdentity {\n /** Short product name, for example `Legal` or `GTM`. */\n name: string\n /** Square brand mark, sized by the product for a 20px slot. */\n mark: ReactNode\n /** Where the mark leads: the workspace listing, or home when there is none. */\n href: string\n}\n\n/** The words a product uses for one workspace and for several. */\nexport interface AgentWorkspaceNoun {\n singular: string\n plural: string\n}\n\nexport const DEFAULT_WORKSPACE_NOUN: AgentWorkspaceNoun = { singular: 'workspace', plural: 'workspaces' }\n\n/** The workspace that is open, and where else this person can go. */\nexport interface AgentWorkspaceIdentity {\n id: string\n name: string\n /** Defaults to workspace / workspaces. */\n noun?: AgentWorkspaceNoun\n /** Every workspace this person can open, including the open one, in the product's order. */\n options?: readonly { id: string; name: string }[]\n /** Required with `options`: the route that opens a workspace. */\n hrefForWorkspace?: (workspaceId: string) => string\n /** The listing route. Adds an \"All …\" entry. */\n listHref?: string\n /** The creation route. Adds a \"New …\" entry. */\n createHref?: string\n}\n\n/** The number of workspaces past which the switcher offers a search field. */\nconst SEARCH_THRESHOLD = 7\n\nconst HIDE_ON_RAIL: Record<'md' | 'lg', string> = { md: 'md:hidden', lg: 'lg:hidden' }\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toLocaleUpperCase() + text.slice(1)\n}\n\nexport interface AgentRailIdentityProps {\n product: AgentProductIdentity\n workspace?: AgentWorkspaceIdentity | null\n /**\n * The breakpoint below which the fixed rail is hidden. The rail draws the\n * mark itself; below this width the same content heads the mobile bar and\n * drawer, which have no mark of their own.\n */\n hideBelow?: 'md' | 'lg'\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches SidebarLayout's router-agnostic link slot\n LinkComponent?: ComponentType<any>\n}\n\nfunction DefaultLink({ href, to, ...props }: { href?: string; to?: string; [key: string]: unknown }) {\n return <a href={href ?? to} {...props} />\n}\n\n/**\n * The top of every product's rail: which product, and which workspace.\n *\n * One line when no workspace is open (the listing), two when one is: the\n * workspace name, then the product beneath it. A name too long for one line\n * takes both lines and the product moves to the tooltip, which carries the\n * full text either way, so a long name can never push into the collapse\n * button, the page beside the rail, or the height of the header row. It is a switcher only when\n * there is somewhere to switch to; a menu that lists one item is not offered.\n */\nexport function AgentRailIdentity({ product, workspace, hideBelow = 'lg', LinkComponent }: AgentRailIdentityProps) {\n const Link = LinkComponent ?? DefaultLink\n const mobileMark = (\n <span aria-hidden className={`flex h-7 w-7 shrink-0 items-center justify-center ${HIDE_ON_RAIL[hideBelow]}`}>\n {product.mark}\n </span>\n )\n\n if (!workspace) {\n return (\n <Link\n href={product.href}\n to={product.href}\n title={product.name}\n className=\"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-accent\"\n >\n {mobileMark}\n <span className=\"min-w-0 flex-1 truncate text-sm font-semibold text-foreground\">{product.name}</span>\n </Link>\n )\n }\n\n // Two 20px lines, the height the header row already gives the stack. A\n // name that fits one line leaves the product beneath it; a longer name\n // wraps onto the second line and pushes the product out of the clipped\n // box, so the name is read in full instead of cut at a dozen characters.\n // Past two lines it ends in an ellipsis; the tooltip keeps the full name.\n const stack = (\n <span className=\"block max-h-10 min-w-0 flex-1 overflow-hidden text-left\">\n <span className=\"line-clamp-2 text-sm font-semibold leading-5 text-foreground [overflow-wrap:anywhere]\">{workspace.name}</span>\n <span className=\"block truncate text-sm leading-5 text-muted-foreground\">{product.name}</span>\n </span>\n )\n const others = (workspace.options ?? []).filter((option) => option.id !== workspace.id)\n const switchable = (others.length > 0 && workspace.hrefForWorkspace !== undefined) || Boolean(workspace.listHref) || Boolean(workspace.createHref)\n\n if (!switchable) {\n return (\n <div title={`${workspace.name} · ${product.name}`} className=\"flex w-full min-w-0 items-center gap-2 px-1.5 py-1\">\n {mobileMark}\n {stack}\n </div>\n )\n }\n\n return <WorkspaceMenu product={product} workspace={workspace} mobileMark={mobileMark} stack={stack} Link={Link} />\n}\n\nfunction WorkspaceMenu({\n product,\n workspace,\n mobileMark,\n stack,\n Link,\n}: {\n product: AgentProductIdentity\n workspace: AgentWorkspaceIdentity\n mobileMark: ReactNode\n stack: ReactNode\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n}) {\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const changeOpen = useCallback((next: boolean) => {\n setOpen(next)\n if (!next) setQuery('')\n }, [])\n // A non-modal dialog, like WorkspaceSwitcher: opening focuses the first\n // control, and Tab past the last one returns beside the trigger.\n const { containerRef, triggerRef, panelRef, triggerProps, id: panelId } = usePopoverDialog(open, changeOpen)\n const noun = workspace.noun ?? DEFAULT_WORKSPACE_NOUN\n const options = workspace.hrefForWorkspace ? workspace.options ?? [] : []\n const search = query.trim().toLocaleLowerCase()\n const visible = search ? options.filter((option) => option.name.toLocaleLowerCase().includes(search)) : options\n const close = () => changeOpen(false)\n const rowClass = 'flex min-h-9 w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-foreground transition-colors hover:bg-accent'\n\n return (\n <div ref={containerRef} className=\"w-full min-w-0\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-label={`${capitalize(noun.singular)}: ${workspace.name}. Switch ${noun.singular}`}\n title={`${workspace.name} · ${product.name}`}\n onClick={() => changeOpen(!open)}\n className=\"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-accent aria-expanded:bg-accent\"\n >\n {mobileMark}\n {stack}\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <path d=\"m8 9 4-4 4 4m-8 6 4 4 4-4\" />\n </svg>\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"dialog\"\n aria-label={`Switch ${noun.singular}`}\n side=\"below\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n contentKey={`${query}:${options.length}`}\n className={`w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-lg border border-card-edge bg-popover p-1.5 text-foreground ${OVERLAY_SHADOW}`}\n >\n {options.length > SEARCH_THRESHOLD && (\n <input\n data-autofocus\n aria-label={`Search ${noun.plural}`}\n placeholder={`Search ${noun.plural}`}\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n className=\"mb-1.5 h-9 w-full rounded-md border border-border bg-background px-2.5 text-sm text-foreground\"\n />\n )}\n {options.length > 0 && (\n <div className=\"max-h-72 overflow-y-auto\">\n {visible.map((option) => (\n <Link\n key={option.id}\n href={workspace.hrefForWorkspace!(option.id)}\n to={workspace.hrefForWorkspace!(option.id)}\n aria-current={option.id === workspace.id ? 'page' : undefined}\n title={option.name}\n onClick={close}\n className={rowClass}\n >\n <WorkspaceInitial name={option.name} />\n <span className=\"min-w-0 flex-1 truncate\">{option.name}</span>\n {option.id === workspace.id && <CheckGlyph className=\"h-4 w-4 shrink-0 text-primary\" />}\n </Link>\n ))}\n {visible.length === 0 && (\n <p role=\"status\" className=\"px-2 py-2 text-sm text-muted-foreground\">\n No {noun.plural} match “{query.trim()}”.\n </p>\n )}\n </div>\n )}\n {(workspace.listHref || workspace.createHref) && (\n <div className={options.length > 0 ? 'mt-1.5 border-t border-border pt-1.5' : undefined}>\n {workspace.listHref && (\n <Link href={workspace.listHref} to={workspace.listHref} onClick={close} className={rowClass}>\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <rect x=\"4\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"4\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" />\n </svg>\n <span className=\"min-w-0 flex-1 truncate\">All {noun.plural}</span>\n </Link>\n )}\n {workspace.createHref && (\n <Link href={workspace.createHref} to={workspace.createHref} onClick={close} className={rowClass}>\n <svg aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n <span className=\"min-w-0 flex-1 truncate\">New {noun.singular}</span>\n </Link>\n )}\n </div>\n )}\n </PopoverSurface>\n </div>\n )\n}\n","import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from 'react'\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@tangle-network/sandbox-ui/primitives'\nimport { WorkspaceLayout } from '@tangle-network/sandbox-ui/workspace'\nimport { FlaskConical, FolderOpen, GitCompare, Monitor, ShieldCheck, Terminal } from 'lucide-react'\n\nexport interface AgentWorkspaceCompanionTab {\n id: string\n label: string\n icon?: ReactNode\n /** Retain a visited tab through tab switches, pane closure, and viewport changes. */\n keepMounted?: boolean\n /** A count that needs the person, such as approvals waiting. Hidden at zero. */\n badge?: number\n renderContent: (state: { active: boolean }) => ReactNode\n}\n\nexport type AgentWorkspaceCompanionTool = 'approvals' | 'files' | 'agent' | 'terminal' | 'changes' | 'preview'\n\n/** Supply only tools the product can actually serve. Content remains product-owned. */\nexport type AgentWorkspaceCompanionTools = Partial<Record<AgentWorkspaceCompanionTool, AgentWorkspaceCompanionTab['renderContent']>>\n\nconst companionTools = [\n { id: 'approvals', label: 'Approvals', Icon: ShieldCheck },\n { id: 'files', label: 'Files', Icon: FolderOpen },\n { id: 'agent', label: 'Agent', Icon: FlaskConical },\n { id: 'terminal', label: 'Terminal', Icon: Terminal },\n { id: 'changes', label: 'Changes', Icon: GitCompare },\n { id: 'preview', label: 'Preview', Icon: Monitor },\n] as const\n\n/** Canonical order, labels, icons and lazy retention for companion tools; `badges` counts what waits on the person. */\nexport function createAgentWorkspaceCompanionTabs(\n tools: AgentWorkspaceCompanionTools,\n badges: Partial<Record<AgentWorkspaceCompanionTool, number>> = {},\n): AgentWorkspaceCompanionTab[] {\n return companionTools.flatMap(({ id, label, Icon }) => {\n const renderContent = tools[id]\n const badge = badges[id]\n return renderContent\n ? [{ id, label, icon: <Icon className=\"h-3.5 w-3.5\" aria-hidden />, keepMounted: true, renderContent, ...(badge ? { badge } : {}) }]\n : []\n })\n}\n\nexport interface AgentWorkspaceCompanionNavigation {\n content: ReactNode\n header?: ReactNode\n open?: boolean\n onOpenChange?: (open: boolean) => void\n label?: string\n defaultWidth?: number\n minWidth?: number\n maxWidth?: number\n collapsedControl?: ReactNode\n}\n\nexport interface AgentWorkspaceCompanionHandle {\n openTab: (tabId: string) => boolean\n}\n\nexport interface AgentWorkspaceCompanionProps {\n children: ReactNode\n /**\n * Quiet content for the conversation's header row, such as its title or a\n * pending-review status. The row also holds the tools toggle, flat in its\n * top-right corner, and aligns with the open tools pane's header.\n */\n header?: ReactNode\n /** Use tools for shared defaults; tabs overrides them for product-specific navigation. */\n tabs?: readonly AgentWorkspaceCompanionTab[]\n tools?: AgentWorkspaceCompanionTools\n /** Counts on the shared tools' tabs, such as approvals waiting. */\n toolBadges?: Partial<Record<AgentWorkspaceCompanionTool, number>>\n /** Optional session navigation, composed in the same responsive layout. */\n navigation?: AgentWorkspaceCompanionNavigation\n keyboardShortcuts?: boolean\n open?: boolean\n onOpenChange?: (open: boolean) => void\n defaultOpen?: boolean\n activeTabId?: string\n onActiveTabChange?: (tabId: string) => void\n defaultActiveTabId?: string\n /** Namespace for remembered tab selection and underlying pane dimensions. */\n persistenceKey?: string\n label?: string\n defaultWidth?: number\n className?: string\n}\n\n/** Product-owned tools beside a conversation; omitted tools have no tabs or effects. */\nexport const AgentWorkspaceCompanion = forwardRef<AgentWorkspaceCompanionHandle, AgentWorkspaceCompanionProps>(function AgentWorkspaceCompanion({\n children,\n header,\n tabs: customTabs,\n tools,\n toolBadges,\n navigation,\n keyboardShortcuts,\n open: controlledOpen,\n onOpenChange,\n defaultOpen = false,\n activeTabId,\n onActiveTabChange,\n defaultActiveTabId,\n persistenceKey,\n label = 'Workspace tools',\n defaultWidth = 420,\n className,\n}, ref) {\n const tabs = customTabs ?? createAgentWorkspaceCompanionTabs(tools ?? {}, toolBadges)\n const [uncontrolledOpen, setOpen] = useState(defaultOpen)\n const open = controlledOpen ?? uncontrolledOpen\n const [selection, setSelection] = useState({ key: persistenceKey, id: defaultActiveTabId })\n const [visits, setVisits] = useState<{ key: string | undefined; ids: ReadonlySet<string> }>(() => ({ key: persistenceKey, ids: new Set() }))\n const requested = activeTabId ?? (selection.key === persistenceKey ? selection.id : defaultActiveTabId)\n const active = tabs.find((tab) => tab.id === requested)?.id ?? tabs[0]?.id\n const visited = visits.key === persistenceKey ? visits.ids : new Set<string>()\n const storageKey = persistenceKey ? `${persistenceKey}:companion-tab` : undefined\n\n const pendingRestoration = useRef<{ key: string | undefined; id: string | undefined } | undefined>(undefined)\n const reconciledSelection = useRef<string | undefined>(undefined)\n const restoredKey = useRef<string | undefined>(undefined)\n useEffect(() => {\n const key = JSON.stringify([persistenceKey, defaultActiveTabId])\n if (restoredKey.current === key || tabs.length === 0) return\n let id = activeTabId ?? defaultActiveTabId\n if (storageKey) {\n try { id = window.localStorage.getItem(storageKey) ?? id } catch { /* Browser storage is optional. */ }\n }\n const resolved = tabs.find((tab) => tab.id === id)?.id ?? tabs[0]?.id\n restoredKey.current = key\n pendingRestoration.current = { key: persistenceKey, id: resolved }\n setSelection({ key: persistenceKey, id: resolved })\n if (resolved && resolved !== activeTabId) {\n reconciledSelection.current = JSON.stringify([persistenceKey, requested, resolved])\n onActiveTabChange?.(resolved)\n }\n }, [storageKey, persistenceKey, defaultActiveTabId, activeTabId, requested, tabs, onActiveTabChange])\n\n useEffect(() => {\n // Let restored selection reach the controlled parent before reconciling stale props.\n const pending = pendingRestoration.current\n if (pending) {\n const acknowledged = activeTabId === undefined\n ? selection.key === pending.key && selection.id === pending.id\n : activeTabId === pending.id\n if (!acknowledged) return\n pendingRestoration.current = undefined\n }\n if (!active || tabs.some((tab) => tab.id === requested)) {\n reconciledSelection.current = undefined\n return\n }\n const key = JSON.stringify([persistenceKey, requested, active])\n if (reconciledSelection.current === key) return\n reconciledSelection.current = key\n setSelection({ key: persistenceKey, id: active })\n onActiveTabChange?.(active)\n }, [active, activeTabId, requested, selection, persistenceKey, tabs, onActiveTabChange])\n\n useEffect(() => {\n if (!open || !active) return\n setVisits((previous) => {\n const ids = previous.key === persistenceKey ? previous.ids : new Set<string>()\n return ids.has(active) ? previous : { key: persistenceKey, ids: new Set([...ids, active]) }\n })\n }, [open, active, persistenceKey])\n\n const selectTab = useCallback((id: string) => {\n if (!tabs.some((tab) => tab.id === id)) return false\n setSelection({ key: persistenceKey, id })\n onActiveTabChange?.(id)\n if (storageKey) {\n try { window.localStorage.setItem(storageKey, id) } catch { /* Selection still works without storage. */ }\n }\n return true\n }, [tabs, persistenceKey, storageKey, onActiveTabChange])\n const changeOpen = useCallback((next: boolean) => {\n setOpen(next)\n onOpenChange?.(next)\n }, [onOpenChange])\n\n useImperativeHandle(ref, () => ({\n openTab(id) {\n if (!selectTab(id)) return false\n changeOpen(true)\n return true\n },\n }), [selectTab, changeOpen])\n\n if (tabs.length === 0 && !navigation) return <>{children}</>\n const toolsName = inSentence(label)\n\n return (\n <Tabs key={persistenceKey} value={active} onValueChange={selectTab} className={`flex h-full min-h-0 min-w-0 flex-1 flex-col ${className ?? ''}`}>\n <WorkspaceLayout\n className=\"h-full min-h-0 min-w-0 flex-1\"\n // One raised surface in an even gutter. The tools toggle sits flat in\n // the conversation header's top-right corner instead of an edge column\n // (which cost the conversation a column and showed a strip of another\n // surface) or a float (which covered a right-aligned message on a phone).\n surface=\"inset\"\n centerHeader={header === undefined ? undefined : <div className=\"flex min-w-0 items-center gap-2 px-2\">{header}</div>}\n rightOpenLabel={`Open ${toolsName}`}\n rightCloseLabel={`Close ${toolsName}`}\n rightControlHint={tabs.length > 0 ? tabs.map((tab) => tab.label).join(', ') : undefined}\n keepRightMounted\n // The layout's center is a block scroller, so a conversation written as\n // `flex flex-1 flex-col` (message list `flex-1 overflow-y-auto`, then a\n // shrink-0 composer) got no height bound: the whole conversation grew\n // with its content and a tall composer was pushed below the fold. A\n // one-cell grid whose row is `minmax(0, 1fr)` gives the conversation\n // exactly the pane's height: a grid item spanning a track with a zero\n // minimum has no content-based minimum, which a flex column would still\n // impose on a child without `min-h-0`. The message list then scrolls on\n // its own and the composer stays on screen.\n center={<div data-companion-center className=\"grid h-full min-h-0 min-w-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]\">{children}</div>}\n left={navigation?.content}\n leftContentClassName=\"py-0\"\n leftHeader={navigation && (navigation.header !== undefined ? navigation.header : <span className=\"text-sm font-medium\">{navigation.label ?? 'Chats'}</span>)}\n leftOpen={navigation?.open}\n onLeftOpenChange={navigation?.onOpenChange}\n leftLabel={navigation?.label ?? 'Chats'}\n defaultLeftWidth={navigation?.defaultWidth ?? 260}\n minLeftWidth={navigation?.minWidth ?? 200}\n maxLeftWidth={navigation?.maxWidth ?? 400}\n leftCollapsedControl={navigation?.collapsedControl}\n keyboardShortcuts={keyboardShortcuts}\n rightOpen={open}\n onRightOpenChange={changeOpen}\n rightLabel={label}\n defaultRightWidth={defaultWidth}\n persistenceKey={persistenceKey}\n minRightWidth={280}\n rightContentClassName=\"flex flex-col overflow-hidden\"\n rightHeader={tabs.length > 0 ? <CompanionTabList tabs={tabs} active={active} label={label} /> : undefined}\n right={tabs.length > 0 ? tabs.map((tab) => {\n const isActive = tab.id === active\n const retained = tab.keepMounted && visited.has(tab.id)\n if (!(open && isActive) && !retained) return null\n return (\n <TabsContent\n key={tab.id}\n value={tab.id}\n forceMount={retained ? true : undefined}\n hidden={!open || !isActive}\n className=\"m-0 h-full min-h-0 min-w-0 flex-1 data-[state=inactive]:hidden\"\n >\n {tab.renderContent({ active: open && isActive })}\n </TabsContent>\n )\n }) : undefined}\n />\n </Tabs>\n )\n})\n\n/** \"Workspace tools\" reads as \"workspace tools\" mid-sentence; \"CRM tools\" keeps its acronym. */\nfunction inSentence(label: string): string {\n return /^[A-Z][a-z]/.test(label) ? `${label.charAt(0).toLowerCase()}${label.slice(1)}` : label\n}\n\n/**\n * The companion's tab row. When every labelled tab does not fit the pane (a\n * phone drawer, a narrow resized pane), inactive tabs that have an icon drop to\n * icon-only and the active tab keeps its label, so no tab hides behind the\n * close button. Labels stay in the accessibility tree either way. The row\n * returns to full labels once the pane is wide enough for them again.\n */\nfunction CompanionTabList({ tabs, active, label }: { tabs: readonly AgentWorkspaceCompanionTab[]; active: string | undefined; label: string }) {\n const frameRef = useRef<HTMLDivElement>(null)\n const fullWidth = useRef(0)\n const [compact, setCompact] = useState(false)\n const signature = tabs.map((tab) => `${tab.id}\\u0000${tab.label}\\u0000${tab.icon ? 1 : 0}\\u0000${tab.badge ?? 0}`).join('\\u0001')\n\n useLayoutEffect(() => {\n fullWidth.current = 0\n setCompact(false)\n }, [signature])\n\n useLayoutEffect(() => {\n const frame = frameRef.current\n const list = frame?.firstElementChild\n if (!frame || !(list instanceof HTMLElement)) return\n const fit = () => {\n const available = frame.clientWidth\n if (!compact) {\n fullWidth.current = list.scrollWidth\n if (list.scrollWidth > available + 1) setCompact(true)\n } else if (fullWidth.current > 0 && available >= fullWidth.current) {\n setCompact(false)\n }\n }\n fit()\n if (typeof ResizeObserver === 'undefined') return\n const observer = new ResizeObserver(fit)\n observer.observe(frame)\n return () => observer.disconnect()\n }, [compact, signature])\n\n useEffect(() => {\n const trigger = frameRef.current?.querySelector<HTMLElement>('[role=\"tab\"][data-state=\"active\"]')\n trigger?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })\n }, [active, compact])\n\n return (\n <div ref={frameRef} className=\"min-w-0\" data-compact={compact ? '' : undefined}>\n <TabsList aria-label={label} className=\"h-9 max-w-full justify-start overflow-x-auto bg-transparent p-0\">\n {tabs.map((tab) => {\n const iconOnly = compact && tab.icon && tab.id !== active\n return (\n <TabsTrigger\n key={tab.id}\n value={tab.id}\n title={iconOnly ? tab.label : undefined}\n className={iconOnly ? 'gap-1.5 px-2 text-sm' : 'gap-1.5 px-2.5 text-sm'}\n >\n {tab.icon}<span className={iconOnly ? 'sr-only' : undefined}>{tab.label}</span>\n {tab.badge ? (\n <span className=\"min-w-5 rounded-full bg-[var(--surface-warning-bg)] px-1.5 text-center text-sm font-medium tabular-nums leading-5 text-[var(--surface-warning-text)]\">\n {tab.badge}<span className=\"sr-only\"> waiting</span>\n </span>\n ) : null}\n </TabsTrigger>\n )\n })}\n </TabsList>\n </div>\n )\n}\n","import { useId, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { Input, PageHeader } from '@tangle-network/ui/primitives'\n\nimport { ActionDialog, ActionDialogButton } from '../web-react/action-dialog'\nimport { OVERLAY_SHADOW, PopoverSurface, usePopover } from '../web-react/controls'\nimport { WorkspaceInitial } from '../web-react/workspace-switcher'\nimport { DEFAULT_WORKSPACE_NOUN, type AgentWorkspaceNoun } from './rail-identity'\n\n/** One workspace as the listing shows it. */\nexport interface WorkspaceListItem {\n id: string\n name: string\n /** The route that opens it. */\n href: string\n /** One line under the name. Not shown when it only repeats the name. */\n description?: string | null\n /** Last activity. Shown as a short date. */\n updatedAt?: string | number | Date | null\n /** Values for the product's `fields`, keyed by field id. */\n values?: Readonly<Record<string, ReactNode>>\n /** Replaces the initial avatar, for example with a logo the product already has. */\n avatar?: ReactNode\n}\n\n/** A product column: a value the user compares across workspaces (tax year, status, owner). */\nexport interface WorkspaceListField {\n id: string\n label: string\n}\n\n/** A non-destructive product action in an item's overflow menu. */\nexport interface WorkspaceListAction {\n id: string\n label: string\n onSelect: (item: WorkspaceListItem) => void\n}\n\nexport interface WorkspaceListProps {\n items: readonly WorkspaceListItem[]\n /** The product's words for one workspace and several. Defaults to workspace / workspaces. */\n noun?: AgentWorkspaceNoun\n /** Page title. Defaults to the capitalized plural noun. */\n title?: string\n /** One sentence under the title, when the page needs one. */\n description?: ReactNode\n /** `list` rows for records people compare; `grid` cards for a handful of rich projects. */\n layout?: 'list' | 'grid'\n /** Product values, shown as columns (list) or under the description (grid). */\n fields?: readonly WorkspaceListField[]\n /**\n * The one primary action, labelled \"New {singular}\" unless `label` says otherwise.\n * `href` navigates; `onSelect` opens the product's own creation flow; `onCreate`\n * asks for a name in the shared dialog and hands it over — reject with an Error\n * to show its message, and navigate to the new workspace from inside it.\n */\n create?: {\n label?: string\n href?: string\n onSelect?: () => void\n onCreate?: (name: string) => Promise<void>\n /** Placeholder for the name field. Defaults to \"{Singular} name\". */\n namePlaceholder?: string\n }\n /** First-use copy. The create action is offered beneath it. */\n empty?: { title?: string; description?: string }\n /** Persist a new name. Reject with an Error to show its message in the dialog. */\n rename?: (item: WorkspaceListItem, name: string) => Promise<void>\n /** Delete for good. Offered in the overflow menu, behind a confirmation. */\n remove?: (item: WorkspaceListItem) => Promise<void>\n /**\n * Whether this viewer may delete this item. Delete is left out of the menu\n * when it returns false, so a member who does not own an item is never shown\n * a destructive action the server would refuse. Defaults to every item.\n */\n canRemove?: (item: WorkspaceListItem) => boolean\n /** What deleting loses, for the confirmation. */\n removeConsequence?: (item: WorkspaceListItem) => string\n /** Extra overflow-menu actions. */\n actions?: (item: WorkspaceListItem) => readonly WorkspaceListAction[]\n /** Product content between the header and the items, such as a home summary. */\n children?: ReactNode\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot, same as SidebarLayout\n LinkComponent?: ComponentType<any>\n /** Formats `updatedAt`. Defaults to a short month and day, with the year when it is not this year. */\n formatDate?: (value: Date) => string\n}\n\n/** The number of items past which the listing offers a search field. */\nconst SEARCH_THRESHOLD = 8\n\n// Fixed widths keep every row's columns on the same x, whatever a date or value renders as.\nconst FIELD_CELL = 'hidden w-32 min-w-0 shrink-0 md:block'\nconst DATE_CELL = 'w-20 shrink-0 text-right sm:w-24'\n\nfunction DefaultLink({ href, to, ...props }: { href?: string; to?: string; [key: string]: unknown }) {\n return <a href={href ?? to} {...props} />\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toLocaleUpperCase() + text.slice(1)\n}\n\nfunction defaultFormatDate(value: Date): string {\n const sameYear = value.getFullYear() === new Date().getFullYear()\n return value.toLocaleDateString(undefined, sameYear ? { month: 'short', day: 'numeric' } : { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction present(value: ReactNode): boolean {\n return value !== null && value !== undefined && value !== false && value !== ''\n}\n\nfunction toDate(value: WorkspaceListItem['updatedAt']): Date | null {\n if (value === null || value === undefined || value === '') return null\n const date = value instanceof Date ? value : new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\n/** A description is noise when it says the name again (\"GTM Agent / GTM Agent\"). */\nfunction usefulDescription(item: WorkspaceListItem): string | null {\n const text = item.description?.trim()\n if (!text) return null\n return text.toLocaleLowerCase() === item.name.trim().toLocaleLowerCase() ? null : text\n}\n\n/**\n * The listing every product opens on: one title, one primary action, the\n * workspaces, and nothing that counts them. Destructive actions live in each\n * item's overflow menu behind a confirmation, never as an icon on every row.\n * The product supplies its noun, its columns, and its create route; render it\n * inside `AgentWorkspaceLayout` (with no `workspace`) so the listing wears the\n * same shell as the workspace it opens.\n */\nexport function WorkspaceList({\n items,\n noun = DEFAULT_WORKSPACE_NOUN,\n title,\n description,\n layout = 'list',\n fields = [],\n create,\n empty,\n rename,\n remove,\n canRemove,\n removeConsequence,\n actions,\n children,\n LinkComponent,\n formatDate = defaultFormatDate,\n}: WorkspaceListProps) {\n const Link = LinkComponent ?? DefaultLink\n const headingId = useId()\n const [query, setQuery] = useState('')\n const [renaming, setRenaming] = useState<WorkspaceListItem | null>(null)\n const [renameValue, setRenameValue] = useState('')\n const [removing, setRemoving] = useState<WorkspaceListItem | null>(null)\n const [creating, setCreating] = useState(false)\n const [createValue, setCreateValue] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const search = query.trim().toLocaleLowerCase()\n const visible = useMemo(\n () => (search ? items.filter((item) => item.name.toLocaleLowerCase().includes(search)) : items),\n [items, search],\n )\n const createLabel = create?.label ?? `New ${noun.singular}`\n const openCreate = () => {\n setError(null)\n setCreateValue('')\n setCreating(true)\n }\n const createControl = create\n ? <CreateButton create={create.onCreate && !create.href ? { ...create, onSelect: openCreate } : create} label={createLabel} Link={Link} />\n : null\n const submitCreate = () => {\n const name = createValue.trim()\n if (!name || !create?.onCreate) return\n void run(() => create.onCreate!(name), () => setCreating(false))\n }\n\n const hasDates = items.some((item) => toDate(item.updatedAt) !== null)\n const removable = (item: WorkspaceListItem) => Boolean(remove) && (canRemove?.(item) ?? true)\n const hasMenu = Boolean(rename) || items.some(removable) || Boolean(actions)\n const menuFor = (item: WorkspaceListItem): MenuEntry[] => [\n ...(rename ? [{ id: 'rename', label: 'Rename', onSelect: () => { setError(null); setRenaming(item); setRenameValue(item.name) } }] : []),\n ...(actions?.(item) ?? []).map((action) => ({ id: action.id, label: action.label, onSelect: () => action.onSelect(item) })),\n ...(removable(item) ? [{ id: 'delete', label: 'Delete', destructive: true, onSelect: () => { setError(null); setRemoving(item) } }] : []),\n ]\n\n const run = async (work: () => Promise<void>, done: () => void) => {\n setBusy(true)\n setError(null)\n try {\n await work()\n done()\n } catch (cause) {\n setError(cause instanceof Error && cause.message ? cause.message : 'That did not save. Try again.')\n } finally {\n setBusy(false)\n }\n }\n\n const submitRename = () => {\n if (!renaming || !rename) return\n const name = renameValue.trim()\n if (!name || name === renaming.name) {\n setRenaming(null)\n return\n }\n void run(() => rename(renaming, name), () => setRenaming(null))\n }\n\n return (\n <section aria-labelledby={headingId} className=\"mx-auto w-full max-w-5xl px-4 py-6 sm:px-6 sm:py-8 lg:px-8\">\n <PageHeader\n className=\"mb-0\"\n titleId={headingId}\n title={title ?? capitalize(noun.plural)}\n description={description}\n actions={items.length > 0 ? createControl : null}\n />\n\n {children != null && <div className=\"mt-6\">{children}</div>}\n\n {items.length === 0 ? (\n <div className=\"mt-6 flex flex-col items-center rounded-xl border border-dashed border-border px-6 py-14 text-center\">\n <span aria-hidden className=\"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary\">\n <svg className=\"h-5 w-5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\">\n <rect x=\"4\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"13.5\" y=\"4\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><rect x=\"4\" y=\"13.5\" width=\"6.5\" height=\"6.5\" rx=\"1.5\" /><path d=\"M16.75 13.5v6.5M13.5 16.75H20\" />\n </svg>\n </span>\n <h2 className=\"mt-4 text-base font-semibold text-foreground\">{empty?.title ?? `No ${noun.plural} yet`}</h2>\n {empty?.description && <p className=\"mt-1.5 max-w-sm text-sm text-muted-foreground\">{empty.description}</p>}\n {createControl && <div className=\"mt-5\">{createControl}</div>}\n </div>\n ) : (\n <>\n {items.length > SEARCH_THRESHOLD && (\n <div className=\"mt-6\">\n <Input\n type=\"search\"\n aria-label={`Search ${noun.plural}`}\n placeholder={`Search ${noun.plural}`}\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n className=\"max-w-sm\"\n />\n </div>\n )}\n {visible.length === 0 ? (\n <p role=\"status\" className=\"mt-6 rounded-xl border border-border px-4 py-8 text-center text-sm text-muted-foreground\">\n No {noun.plural} match “{query.trim()}”.{' '}\n <button type=\"button\" onClick={() => setQuery('')} className=\"font-medium text-foreground underline underline-offset-2\">\n Clear search\n </button>\n </p>\n ) : layout === 'grid' ? (\n <ul className={`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 ${items.length > SEARCH_THRESHOLD ? 'mt-3' : 'mt-6'}`}>\n {visible.map((item) => (\n <GridCard key={item.id} item={item} fields={fields} menu={menuFor(item)} Link={Link} formatDate={formatDate} />\n ))}\n </ul>\n ) : (\n <div className={`overflow-hidden rounded-xl border border-border bg-card ${items.length > SEARCH_THRESHOLD ? 'mt-3' : 'mt-6'}`}>\n {fields.length > 0 && (\n <div aria-hidden className=\"hidden items-center gap-3 border-b border-border px-4 py-2 text-sm font-medium text-muted-foreground md:flex\">\n <span className=\"w-10 shrink-0\" />\n <span className=\"min-w-0 flex-1\">Name</span>\n {fields.map((field) => (\n <span key={field.id} className={`${FIELD_CELL} truncate`}>{field.label}</span>\n ))}\n <span className={DATE_CELL}>{hasDates ? 'Updated' : ''}</span>\n {hasMenu && <span className=\"w-8 shrink-0 [@media(pointer:coarse)]:w-11\" />}\n </div>\n )}\n <ul className=\"divide-y divide-border\">\n {visible.map((item) => (\n <ListRow key={item.id} item={item} fields={fields} menu={menuFor(item)} reserveMenu={hasMenu} Link={Link} formatDate={formatDate} />\n ))}\n </ul>\n </div>\n )}\n </>\n )}\n\n {renaming && (\n <ActionDialog\n title={`Rename ${noun.singular}`}\n onClose={() => setRenaming(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setRenaming(null)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton onClick={submitRename} disabled={busy || !renameValue.trim()}>Save</ActionDialogButton>\n </>\n }\n >\n <label htmlFor={`${headingId}-rename`} className=\"text-sm text-muted-foreground\">Name</label>\n <Input\n id={`${headingId}-rename`}\n value={renameValue}\n autoFocus\n onChange={(event) => setRenameValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter' && !busy) {\n event.preventDefault()\n submitRename()\n }\n }}\n className=\"mt-1.5\"\n />\n </ActionDialog>\n )}\n\n {creating && create?.onCreate && (\n <ActionDialog\n title={createLabel}\n onClose={() => setCreating(false)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setCreating(false)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton onClick={submitCreate} disabled={busy || !createValue.trim()}>Create</ActionDialogButton>\n </>\n }\n >\n <label htmlFor={`${headingId}-create`} className=\"text-sm text-muted-foreground\">Name</label>\n <Input\n id={`${headingId}-create`}\n value={createValue}\n autoFocus\n placeholder={create.namePlaceholder ?? `${capitalize(noun.singular)} name`}\n onChange={(event) => setCreateValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter' && !busy) {\n event.preventDefault()\n submitCreate()\n }\n }}\n className=\"mt-1.5\"\n />\n </ActionDialog>\n )}\n\n {removing && remove && (\n <ActionDialog\n title={`Delete ${noun.singular}?`}\n onClose={() => setRemoving(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <ActionDialogButton variant=\"ghost\" onClick={() => setRemoving(null)} disabled={busy}>Cancel</ActionDialogButton>\n <ActionDialogButton variant=\"destructive\" onClick={() => void run(() => remove(removing), () => setRemoving(null))} disabled={busy}>\n Delete\n </ActionDialogButton>\n </>\n }\n >\n <p className=\"break-words text-sm text-muted-foreground\">\n {removeConsequence?.(removing) ?? `“${removing.name}” and everything in it will be deleted. This cannot be undone.`}\n </p>\n </ActionDialog>\n )}\n </section>\n )\n}\n\ninterface MenuEntry {\n id: string\n label: string\n destructive?: boolean\n onSelect: () => void\n}\n\ninterface ItemProps {\n reserveMenu?: boolean\n item: WorkspaceListItem\n fields: readonly WorkspaceListField[]\n menu: MenuEntry[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n formatDate: (value: Date) => string\n}\n\nfunction UpdatedAt({ value, formatDate, className = 'shrink-0' }: { value: WorkspaceListItem['updatedAt']; formatDate: (value: Date) => string; className?: string }) {\n const date = toDate(value)\n if (!date) return <span className={className} />\n return (\n // Server and browser can format a date differently (zone, locale); the\n // browser's reading is the one the user should see.\n <time dateTime={date.toISOString()} suppressHydrationWarning className={`${className} text-sm tabular-nums text-muted-foreground`}>\n {formatDate(date)}\n </time>\n )\n}\n\n/**\n * The name is the row's link, stretched over the whole row with an `after:`\n * overlay, so the overflow menu can sit on top as a real sibling button\n * instead of a button nested inside a link.\n */\nfunction ListRow({ item, fields, menu, reserveMenu, Link, formatDate }: ItemProps) {\n const detail = usefulDescription(item)\n const mobileFields = fields.filter((field) => present(item.values?.[field.id]))\n return (\n <li className=\"group relative isolate flex min-h-16 items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/60\">\n {item.avatar ?? <WorkspaceInitial name={item.name} size=\"lg\" />}\n <div className=\"min-w-0 flex-1\">\n <Link\n href={item.href}\n to={item.href}\n title={item.name}\n className=\"block truncate text-sm font-medium text-foreground after:absolute after:inset-0 after:content-[''] focus-visible:outline-none focus-visible:after:rounded-[inherit] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring\"\n >\n {item.name}\n </Link>\n {detail && <p className=\"truncate text-sm text-muted-foreground\" title={detail}>{detail}</p>}\n {/* Below md the columns are hidden, so their values ride under the name instead. */}\n {mobileFields.length > 0 && (\n <p className=\"truncate text-sm text-muted-foreground md:hidden\">\n {mobileFields.map((field, index) => (\n <span key={field.id}>\n {index > 0 && ' · '}\n <span className=\"sr-only\">{field.label}: </span>\n {item.values![field.id]}\n </span>\n ))}\n </p>\n )}\n </div>\n {fields.map((field) => (\n <div key={field.id} className={`${FIELD_CELL} truncate text-sm text-muted-foreground`}>\n <span className=\"sr-only\">{field.label}: </span>\n {present(item.values?.[field.id]) ? item.values![field.id] : '—'}\n </div>\n ))}\n <UpdatedAt value={item.updatedAt} formatDate={formatDate} className={DATE_CELL} />\n {menu.length > 0 ? <ItemMenu item={item} entries={menu} /> : reserveMenu ? <span className=\"w-8 shrink-0 [@media(pointer:coarse)]:w-11\" /> : null}\n </li>\n )\n}\n\nfunction GridCard({ item, fields, menu, Link, formatDate }: ItemProps) {\n const detail = usefulDescription(item)\n const shownFields = fields.filter((field) => present(item.values?.[field.id]))\n return (\n <li className=\"group relative isolate flex min-h-36 flex-col overflow-hidden rounded-xl border border-border bg-card p-4 transition-[border-color,box-shadow] hover:border-primary/40 hover:shadow-sm\">\n <span aria-hidden className=\"pointer-events-none absolute inset-x-0 top-0 -z-10 h-16 bg-gradient-to-b from-primary/[0.07] to-transparent\" />\n <div className=\"flex items-start gap-3\">\n {item.avatar ?? <WorkspaceInitial name={item.name} size=\"lg\" />}\n <div className=\"min-w-0 flex-1 pt-0.5\">\n <Link\n href={item.href}\n to={item.href}\n title={item.name}\n className=\"line-clamp-2 break-words text-sm font-semibold text-foreground after:absolute after:inset-0 after:content-[''] focus-visible:outline-none focus-visible:after:rounded-xl focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring\"\n >\n {item.name}\n </Link>\n {detail && <p className=\"mt-0.5 truncate text-sm text-muted-foreground\" title={detail}>{detail}</p>}\n </div>\n {menu.length > 0 && <ItemMenu item={item} entries={menu} />}\n </div>\n <div className=\"mt-auto flex items-end justify-between gap-3 pt-4\">\n {shownFields.length > 0 ? (\n <dl className=\"flex min-w-0 flex-wrap gap-x-4 gap-y-1 text-sm\">\n {shownFields.map((field) => (\n <div key={field.id} className=\"flex min-w-0 gap-1\">\n <dt className=\"text-muted-foreground\">{field.label}</dt>\n <dd className=\"truncate font-medium text-foreground\">{item.values?.[field.id]}</dd>\n </div>\n ))}\n </dl>\n ) : <span />}\n <UpdatedAt value={item.updatedAt} formatDate={formatDate} />\n </div>\n </li>\n )\n}\n\nfunction ItemMenu({ item, entries }: { item: WorkspaceListItem; entries: MenuEntry[] }) {\n const [open, setOpen] = useState(false)\n const panelId = useId()\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen)\n return (\n <div ref={containerRef} className=\"relative z-10 shrink-0\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-label={`Actions for ${item.name}`}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen(!open)}\n // Hidden until hover only where hover exists; a touch screen of any width shows it.\n className=\"flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11 transition hover:bg-muted hover:text-foreground focus-visible:opacity-100 aria-expanded:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover:opacity-100\"\n >\n <svg aria-hidden className=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <circle cx=\"5\" cy=\"12\" r=\"1.6\" /><circle cx=\"12\" cy=\"12\" r=\"1.6\" /><circle cx=\"19\" cy=\"12\" r=\"1.6\" />\n </svg>\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"menu\"\n aria-label={`Actions for ${item.name}`}\n side=\"below\"\n align=\"end\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n className={`w-44 overflow-hidden rounded-md border border-card-edge bg-popover py-1 ${OVERLAY_SHADOW}`}\n >\n {entries.map((entry, index) => (\n <button\n key={entry.id}\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n setOpen(false)\n // The dialog this opens returns focus to whatever had it — the trigger, not <body>.\n triggerRef.current?.focus()\n entry.onSelect()\n }}\n className={`block w-full px-3 py-1.5 text-left text-sm transition ${\n entry.destructive ? 'text-destructive hover:bg-destructive/10' : 'text-foreground hover:bg-accent'\n } ${entry.destructive && index > 0 ? 'mt-1 border-t border-border pt-2' : ''}`}\n >\n {entry.label}\n </button>\n ))}\n </PopoverSurface>\n </div>\n )\n}\n\nfunction CreateButton({\n create,\n label,\n Link,\n}: {\n create: NonNullable<WorkspaceListProps['create']>\n label: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- router-agnostic link slot\n Link: ComponentType<any>\n}) {\n const className = 'inline-flex h-9 shrink-0 items-center gap-1.5 rounded-md bg-primary px-3.5 text-sm font-medium text-primary-foreground transition hover:opacity-90 active:scale-[0.98]'\n const icon = (\n <svg aria-hidden className=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n )\n if (create.href) {\n return (\n <Link href={create.href} to={create.href} className={className}>\n {icon}\n {label}\n </Link>\n )\n }\n return (\n <button type=\"button\" onClick={create.onSelect} className={className}>\n {icon}\n {label}\n </button>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAyE;;;ACAlF,SAAS,aAAa,gBAAoD;AA+D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AAA,IACb,UAAU,cAAc,IAAI,CAAC,EAAE,IAAI,OAAO,MAAM,MAAM,SAAS,OAAO,EAAE,IAAI,OAAO,MAAM,MAAa,SAAS,EAAE;AAAA,IACjH,cAAc,gBAAgB,CAAC,aAAa,IAAI;AAAA,EAClD,IACA;AACJ,QAAM,oBAA4C;AAAA,IAChD,GAAG;AAAA,IACH,GAAI,aAAa,CAAC,UAAU,IAAI,CAAC;AAAA,IACjC,GAAI,WAAW,CAAC,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,aAAa,CAAC,UAAU,IAAI,CAAC;AAAA,EACnC;AAEA,QAAM,YAAY,aAAa,aAAa;AAC5C,QAAM,gBAAgB,UAClB;AAAA,IACE,MAAM,QAAQ;AAAA,IACd,UAAU,QAAQ;AAAA,IAClB,mBACE,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA,eAAe,aAAa;AAAA;AAAA,IAC9B;AAAA,EAEJ,IACA,CAAC;AACL,QAAM,cAAc;AAAA,IAClB;AAAA,IACA,YAAY;AAAA,IACZ,GAAG;AAAA,IACH,GAAG;AAAA,EACL;AAEA,SACE,gBAAAA,KAAC,wBAAwB,UAAxB,EAAiC,OAAO,UAAU,gBAAgB,MACjE,0BAAAA;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,UAAU,cAAc,UAAU,KAAK;AAAA,MAEtC;AAAA;AAAA,EACH,GACF;AAEJ;","names":["useCallback","useState","jsx","jsxs","AgentWorkspaceCompanion","useState","Fragment","jsx","jsxs","SEARCH_THRESHOLD","DefaultLink","capitalize","useState","jsx"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-store/parts.ts"],"sourcesContent":["/**\n * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox\n * SDK's authoritative plan lifecycle.\n * - `work_product`: the persisted work-product anchor card in\n * `/work-product`'s contract (`workProductToPersistedPart` /\n * `persistedPartToWorkProduct`) — SYSTEM-authored on the ready transition\n * and updated on a reviewer verdict; no prompt teaches an agent to author\n * one.\n * - `mention`: an `@`-picked reference to a file that already lives in the\n * workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus\n * the image/file discriminant). Neither transport lane produces it — the\n * turn route persists it from the request's `mentions` field — but it is a\n * part a product persists into a transcript, so it belongs in this\n * vocabulary rather than in a parallel one.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswers,\n NoticeKind,\n} from '../web-react/chat-interactions'\nimport { persistedPartToInteraction } from '../interactions/contract'\nimport {\n persistedPartToWorkProduct,\n type WorkProductPersistedPart,\n} from '../work-product/types'\nimport {\n persistedPartToPlan,\n planToPersistedPart,\n type ChatPlanPersistedPart,\n} from '../plans/index'\n// `./wire` is import-free by construction, so this edge costs the store\n// nothing and keeps ONE image-extension table for the whole mention layer.\nimport {\n mentionKindForPath,\n type ChatAttachmentInput,\n type ChatAttachmentKind,\n type ChatMentionKind,\n type FileMention,\n} from '../chat-routes/wire'\n\nexport type { ChatMentionKind, ChatAttachmentKind }\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\n/** Define a reasoning part of a chat with text content and optional metadata fields */\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\n/** Describe the current state and data of a chat tool including status, input, output, and metadata */\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\n/** Define a chat component representing a tool with its state and optional call identifier */\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. `name` is the\n * attachment-flavored display label an uploaded/promoted file carries (see\n * {@link ChatAttachmentPart}) — absent on a harness-emitted file part, which\n * uses `filename`. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\n/** Define properties for an image part within a chat message including optional metadata fields */\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Define a subtask part of a chat with prompt, description, agent, and optional identifier */\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\n/** Define a chat step finish part indicating completion with optional reason, tokens, and cost */\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n answers?: InteractionAnswers\n cancelReason?: string\n}\n\n/** Resolve a chat plan part by aliasing it to the persisted chat plan part type */\nexport type ChatPlanPart = ChatPlanPersistedPart\n\n/** Persisted work-product anchor card — byte-matches\n * `workProductToPersistedPart` in `/work-product`'s contract. Written by the\n * PLATFORM on the ready transition (and updated on a verdict); never\n * authored by a prompt. */\nexport type ChatWorkProductPart = WorkProductPersistedPart\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n /** Typed reason for an `error` notice, e.g. the sandbox or upstream error code. */\n code?: string\n /** The failure's redacted cause chain, for operators and support. Kept with the transcript; not rendered. */\n detail?: string\n}\n\n/**\n * A file the user `@`-mentioned on this turn: a workspace-relative path into\n * the sandbox, never bytes. `type: 'mention'` is its own discriminant\n * precisely so it does NOT collide with the `file`/`image` attachment parts —\n * an attachment carries content the product uploaded, a mention points at\n * something the box already has, and a transcript renders them differently\n * (an inline pill, not an attachment card).\n *\n * `path` is the identity: mentioning one file twice in a turn folds to one\n * part. `turnId` is optional and set by products that rebuild a turn's\n * mentions on retry.\n */\nexport interface ChatMentionPart {\n type: 'mention'\n mentionKind: ChatMentionKind\n path: string\n name: string\n size?: number\n turnId?: string\n}\n\n/** Represent parts of a chat message including text, reasoning, tools, files, images, subtasks, steps, interactions, notices, plans, and mentions */\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n | ChatPlanPart\n | ChatWorkProductPart\n | ChatMentionPart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\n/**\n * The typed projection at the `/stream` → `/chat-store` boundary. The stream\n * normalizers (`normalizePersistedPart`/`mergePersistedPart`/\n * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they\n * normalize wire shapes and do not own the stored vocabulary. THIS module\n * owns it, so this is where rows gain the `ChatMessagePart` type: each entry\n * is validated against its kind's required fields and narrowed, junk is\n * dropped, and — enforced by the exhaustiveness check below — no storable\n * kind can silently fall out (the step-finish/interaction trap).\n */\nexport function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[] {\n const out: ChatMessagePart[] = []\n for (const part of parts) {\n const typed = toChatMessagePart(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\nconst str = (value: unknown): value is string => typeof value === 'string'\n\nfunction toChatMessagePart(part: Record<string, unknown>): ChatMessagePart | null {\n if (!part || typeof part !== 'object') return null\n const type = part.type as ChatMessagePart['type'] | undefined\n switch (type) {\n case 'text':\n case 'reasoning':\n return str(part.text) ? (part as unknown as ChatTextPart | ChatReasoningPart) : null\n case 'tool':\n return str(part.id) && str(part.tool) && part.state && typeof part.state === 'object'\n ? (part as unknown as ChatToolPart)\n : null\n case 'file':\n case 'image':\n return part as unknown as ChatFilePart | ChatImagePart\n case 'subtask':\n return str(part.prompt) && str(part.description) && str(part.agent)\n ? (part as unknown as ChatSubtaskPart)\n : null\n case 'step-start':\n return { type: 'step-start' }\n case 'step-finish':\n return part as unknown as ChatStepFinishPart\n case 'interaction':\n return persistedPartToInteraction(part) ? (part as unknown as ChatInteractionPart) : null\n case 'notice':\n return str(part.id) && str(part.noticeKind) && str(part.text)\n ? (part as unknown as ChatNoticePart)\n : null\n case 'plan': {\n const plan = persistedPartToPlan(part)\n return plan ? ({ ...part, ...planToPersistedPart(plan) } as ChatPlanPart) : null\n }\n case 'work_product':\n // Validate via the codec but keep the original row (extra fields the\n // product persisted round-trip, matching the interaction case).\n return persistedPartToWorkProduct(part) ? (part as unknown as ChatWorkProductPart) : null\n case 'mention':\n return isChatMentionPart(part) ? part : null\n case undefined:\n return null\n default: {\n // Compile-time exhaustiveness: a new ChatMessagePart kind that is not\n // handled above makes `type` non-never here and this line fails.\n const _exhaustive: never = type\n void _exhaustive\n return null\n }\n }\n}\n/** Resolve whether a ChatMessagePart is a ChatInteractionPart based on its type property */\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n/** Widened to `unknown` — unlike its siblings this guard also runs over raw\n * untyped stored rows (a transcript renderer reads `message.parts` before the\n * typed projection), which is exactly what {@link mentionPartsFromMessageParts}\n * needs. `path` and `name` carry the pill; a row missing either is unrenderable.\n *\n * Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,\n * then {@link mentionInputToPart}): a blank `name` is rejected there and so is\n * rejected here, and `size` — optional, but typed `number` once present — is\n * type-checked so `'12'` or `null` cannot ride through the guard wearing a\n * type it does not have. Negative sizes are NOT re-rejected: the wire screens\n * them, `mentionInputToPart` trusts its input, and a read guard stricter than\n * what the writer can emit would drop rows it produced itself. */\nexport function isChatMentionPart(part: unknown): part is ChatMentionPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n if (record.size !== undefined && (typeof record.size !== 'number' || !Number.isFinite(record.size))) {\n return false\n }\n return (\n record.type === 'mention' &&\n typeof record.path === 'string' &&\n record.path.length > 0 &&\n typeof record.name === 'string' &&\n record.name.trim().length > 0 &&\n (record.mentionKind === 'image' || record.mentionKind === 'file')\n )\n}\n\n/** Every mention part on one message, in stored order. The projection a\n * transcript renderer runs before deciding which mentions the message text\n * already shows inline (see `segmentMentionContent` in `/web-react`). */\nexport function mentionPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined,\n): ChatMentionPart[] {\n if (!parts) return []\n return (parts as ReadonlyArray<unknown>).filter(isChatMentionPart)\n}\n\n/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the\n * part the turn route persists. An absent/non-finite `size` is DROPPED rather\n * than stored as `undefined`, so a stored row never carries a key that means\n * nothing. */\nexport function mentionInputToPart(input: FileMention): ChatMentionPart {\n const part: ChatMentionPart = {\n type: 'mention',\n mentionKind: mentionKindForPath(input.path),\n path: input.path,\n name: input.name,\n }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n return part\n}\n\n// ── attachments ──────────────────────────────────────────────────────────\n//\n// An attachment is a file the product uploaded into its own store (vault /\n// object-store) ahead of the turn — content the box did not already have,\n// unlike a `@`-mention. It persists NOT as a new `ChatMessagePart` union\n// member but as an attachment-flavored `file`/`image` part: `type` is the\n// existing `image`/`file` discriminant, with `path` + `name` load-bearing.\n// That reuse is deliberate — a transcript already renders `file`/`image`\n// parts, and `toChatMessagePart` passes them through by cast (fields survive),\n// so an attachment slots into the same stored `parts` array without a parallel\n// vocabulary. These helpers own the input→part projection, the path-keyed\n// stream key, and the agent-facing prompt block, all byte-identical to the gtm\n// source they were lifted from (gtm-agent#618 adoption reproduces its rows and\n// dispatched prompt bytes through them).\n\n/** `image` for any `image/*` mime, `file` for everything else (including an\n * absent/empty mime) — the same split the composer and the persisted-part\n * discriminant both key on. */\nexport function attachmentKindForMime(mime?: string): ChatAttachmentKind {\n return mime?.startsWith('image/') ? 'image' : 'file'\n}\n\n/** Stream/transcript part key for an attachment — ONE declaration, owned by\n * `/stream`'s normalizer (whose `getPartKey` routes path-bearing file/image\n * parts through it). Re-exported here (not redefined) so the root barrel's\n * star-exports of both modules resolve to the same symbol instead of\n * colliding (TS2308 in the dts build). */\nexport { attachmentPartKey } from '../stream/stream-normalizer'\n\n/**\n * Persisted attachment part: structurally an attachment-flavored `ChatFilePart`\n * / `ChatImagePart` (`path` + `name` promoted to required) rather than a\n * separate union member — see the section note above. The index signature keeps\n * it a `Record<string, unknown>` so it drops into the same untyped `parts`\n * arrays every other stored part rides in, and lets the `type`-driven\n * constructors below build it without union-discriminant gymnastics.\n */\nexport interface ChatAttachmentPart {\n type: ChatAttachmentKind\n path: string\n name: string\n size?: number\n mediaType?: string\n turnId?: string\n [key: string]: unknown\n}\n\n/** True for any `image`/`file` part carrying a non-empty string `path`.\n * DELIBERATELY also matches a sidecar path-bearing file part (a mention-style\n * `file` part with only `path`) — the guard is a structural attachment shape,\n * not proof of provenance; a caller that needs to exclude those filters\n * upstream. The `path.length > 0` check diverges from gtm's original guard\n * (which only checked `typeof`), mirroring sibling {@link isChatMentionPart}:\n * read-side robustness against a stored `{type:'file', path:''}` row — which\n * would otherwise render a malformed `(vault: )` pointer line — justifies the\n * small divergence from byte-for-byte gtm parity here; no legitimate write\n * path ever produces an empty `path`. */\nexport function isChatAttachmentPart(part: unknown): part is ChatAttachmentPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n return (\n (record.type === 'image' || record.type === 'file') &&\n typeof record.path === 'string' &&\n record.path.length > 0\n )\n}\n\n/** Drop absent/empty optional fields rather than persisting `undefined`/`''`\n * — keeps stored parts minimal. */\nexport function attachmentInputToPart(input: ChatAttachmentInput): ChatAttachmentPart {\n const part: ChatAttachmentPart = { type: input.kind, path: input.path, name: input.name }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n if (input.mediaType) part.mediaType = input.mediaType\n return part\n}\n\n/** Every attachment part on one message's stored `parts`, in stored order. */\nexport function attachmentPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | null | undefined,\n): ChatAttachmentPart[] {\n if (!parts) return []\n return parts.filter(isChatAttachmentPart)\n}\n\n/** Attachment carry-forward in first-seen path order. Current-turn paths\n * are excluded; a later history row replaces a path's value without moving\n * the Map entry, matching the existing product dispatches. */\nexport function historyAttachmentsFromMessages(\n currentAttachments: ReadonlyArray<Pick<ChatAttachmentPart, 'path'>>,\n priorMessages: ReadonlyArray<{ parts?: ReadonlyArray<Record<string, unknown>> | null }>,\n): ChatAttachmentPart[] {\n const currentPaths = new Set(currentAttachments.map((part) => part.path))\n const historyByPath = new Map<string, ChatAttachmentPart>()\n for (const message of priorMessages) {\n for (const part of attachmentPartsFromMessageParts(message.parts)) {\n if (!currentPaths.has(part.path)) historyByPath.set(part.path, part)\n }\n }\n return [...historyByPath.values()]\n}\n\n/** gtm's exact default header for {@link buildAttachmentPromptBlock} — kept\n * byte-identical because it feeds dispatched prompts (gtm-agent#618\n * reproduces the prompt bytes through this module). Override only with intent. */\nexport const DEFAULT_ATTACHMENT_PROMPT_HEADER =\n 'Attached files (already saved to the workspace vault — read them from these paths):'\n\n/** Same C0-control/DEL sweep as `/chat-routes`'s `resolve-attachments.ts`\n * (kept as a separate literal rather than a shared import — this module is\n * the read side and must stay usable over PERSISTED rows the wire validator\n * never saw). Replaced with a single space, not stripped or collapsed: this\n * is defense-in-depth for legacy/corrupt stored rows that bypassed wire\n * validation, not the primary control — a name/path a `resolveChatAttachments`\n * call validated today never contains one, so this is a no-op on legitimate\n * input and gtm byte-compat holds. */\nconst PROMPT_BLOCK_CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/g\n\n/**\n * The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in `message.content`. Empty array → `''` so callers can append\n * unconditionally. The sole producer of this text: both the current turn's\n * dispatch and history projection ({@link historyContentWithAttachments}) build\n * it from here, so the two can never drift. `header` overrides the first line\n * ({@link DEFAULT_ATTACHMENT_PROMPT_HEADER}); the per-file line format is fixed.\n *\n * Every interpolated `name`/`path` is swept for control characters first\n * (newline/carriage-return/tab included) and each one replaced with a single\n * space — a single-line-per-file guarantee. Without it, a control character\n * riding through on a PERSISTED row (`historyContentWithAttachments` reads\n * whatever is already stored; a legacy or hand-edited row was never re-checked\n * against `resolveChatAttachments`) could inject extra lines — fabricated\n * pointer entries or instructions — into a prompt the agent trusts verbatim.\n * The wire-side validator is the primary control; this is the backstop for\n * rows it never saw.\n */\nexport function buildAttachmentPromptBlock(\n atts: ReadonlyArray<Pick<ChatAttachmentPart, 'name' | 'path'>>,\n header: string = DEFAULT_ATTACHMENT_PROMPT_HEADER,\n): string {\n if (atts.length === 0) return ''\n const clean = (value: string) => value.replace(PROMPT_BLOCK_CONTROL_CHARS, ' ')\n const lines = atts.map((a) => `- ${clean(a.name)} (vault: ${clean(a.path)})`)\n return `\\n\\n${header}\\n${lines.join('\\n')}`\n}\n\n/**\n * History projection for a persisted message: `content` unchanged when it\n * carries no attachment parts, else the block is appended once. The\n * no-double-annotation guarantee holds under the invariant that the block is\n * never persisted INTO `message.content` — it is appended only at read time,\n * by this function and the current turn's dispatch, both sourcing from\n * `attachmentPartsFromMessageParts` — never by content inspection. This\n * function does not (and cannot) detect an already-embedded block by scanning\n * `content` for its text: a message whose stored `content` happens to already\n * contain the block's bytes, alongside attachment parts, still gets the block\n * appended a second time. See the pinned test for that boundary.\n */\nexport function historyContentWithAttachments(\n message: {\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n },\n header?: string,\n): string {\n const attachmentParts = attachmentPartsFromMessageParts(message.parts)\n if (attachmentParts.length === 0) return message.content\n return `${message.content}${buildAttachmentPromptBlock(attachmentParts, header)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0RO,SAAS,mBAAmB,OAA0D;AAC3F,QAAM,MAAyB,CAAC;AAChC,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,kBAAkB,IAAI;AACpC,QAAI,MAAO,KAAI,KAAK,KAAK;AAAA,EAC3B;AACA,SAAO;AACT;AAEA,IAAM,MAAM,CAAC,UAAoC,OAAO,UAAU;AAElE,SAAS,kBAAkB,MAAuD;AAChF,MAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,QAAM,OAAO,KAAK;AAClB,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AACH,aAAO,IAAI,KAAK,IAAI,IAAK,OAAuD;AAAA,IAClF,KAAK;AACH,aAAO,IAAI,KAAK,EAAE,KAAK,IAAI,KAAK,IAAI,KAAK,KAAK,SAAS,OAAO,KAAK,UAAU,WACxE,OACD;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,KAAK,IAC7D,OACD;AAAA,IACN,KAAK;AACH,aAAO,EA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