The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Chore/gv/sessions and overview feedbacks (#590)
Govinda Vashishthac4ee138a8ee1
diff --git a/.changeset/agent-overflow-actions.md b/.changeset/agent-overflow-actions.mdnew file mode 100644index 000000000..599086549--- /dev/null+++ b/.changeset/agent-overflow-actions.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Agent list and details overflow menu: Edit, Clone (`{name}-copy` via saveAgent), Manage Schedules, and Delete (wired through harness `deleteAgent`).diff --git a/.changeset/agent-sessions-list-bg.md b/.changeset/agent-sessions-list-bg.mdnew file mode 100644index 000000000..bdc6a0908--- /dev/null+++ b/.changeset/agent-sessions-list-bg.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++AgentSessions list pane uses a quieter surface, and the resize grip stays gray until hover, press, or focus.diff --git a/.changeset/code-editor-copy-secondary.md b/.changeset/code-editor-copy-secondary.mdnew file mode 100644index 000000000..1fd7d95cd--- /dev/null+++ b/.changeset/code-editor-copy-secondary.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Agent Code (`SyntaxHighlighter` / `AgentCodeBlock`) copy control uses the bordered secondary button, and a trailing source newline no longer paints an empty last line while Copy still keeps the exact source.diff --git a/.changeset/empty-screen-states.md b/.changeset/empty-screen-states.mdnew file mode 100644index 000000000..b32f404d1--- /dev/null+++ b/.changeset/empty-screen-states.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Agents, Sessions, and Schedules empty states use a shared centered empty-box screen with title and supporting copy.diff --git a/.changeset/resume-session-new-tab.md b/.changeset/resume-session-new-tab.mdnew file mode 100644index 000000000..b7bd177c1--- /dev/null+++ b/.changeset/resume-session-new-tab.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Resume Chat / Resume Agent building opens in a new tab when routed (`/sessions/:id` + square-arrow-out-up-right); without a router it keeps the in-shell resume fallback.diff --git a/.changeset/settings-route-capability.md b/.changeset/settings-route-capability.mdnew file mode 100644index 000000000..23e248fc9--- /dev/null+++ b/.changeset/settings-route-capability.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Unregister the `/settings` route when Settings chrome is unavailable (no catalog or `capabilities.settings.enabled` is false), matching the sidebar Settings button gate.diff --git a/.changeset/split-draft-preferences.md b/.changeset/split-draft-preferences.mdnew file mode 100644index 000000000..1a74137d9--- /dev/null+++ b/.changeset/split-draft-preferences.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Split New Chat and New Agent draft preference stores. New Chat remembers only model (+ reasoning), skills, and MCP; New Agent keeps the full seed including runtime config.diff --git a/.changeset/turn-token-tooltip.md b/.changeset/turn-token-tooltip.mdnew file mode 100644index 000000000..f237abef9--- /dev/null+++ b/.changeset/turn-token-tooltip.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Per-turn Tokens in Agent Sessions shows a keyboard-accessible Input / Output / Cached tooltip (Input is uncached).diff --git a/packages/trueforge-ui/docs/customization.md b/packages/trueforge-ui/docs/customization.mdindex bafb62448..c365c4caf 100644--- a/packages/trueforge-ui/docs/customization.md+++ b/packages/trueforge-ui/docs/customization.md@@ -143,9 +143,12 @@ Notes on behaviour:- A `/sessions/:sessionId` link is resolved through `getSession` so the chatopens with its own agent binding and mutability rather than as a new draft.- Unrecognized paths (and malformed escapes) normalize to the root place.+- `/settings` is registered only while Settings chrome is available (catalog+ present and `capabilities.settings.enabled !== false`). When that gate is+ off, `/settings` is treated like an unknown path and replaces to root.- A URL naming a place the host cannot honor (e.g. `/agents/x` without the- agent library, or `/settings` when the settings capability is disabled) is- left in the address bar until the next navigation corrects it.+ agent library) is left in the address bar until the next navigation+ corrects it.Hosts serving the SDK must send the app shell for unknown paths (SPAfallback), otherwise deep links 404 before React boots.diff --git a/packages/trueforge-ui/src/atoms/AgentOverflowMenu.tsx b/packages/trueforge-ui/src/atoms/AgentOverflowMenu.tsxnew file mode 100644index 000000000..0bffa7615--- /dev/null+++ b/packages/trueforge-ui/src/atoms/AgentOverflowMenu.tsx@@ -0,0 +1,197 @@+'use client';++import { useState } from 'react';++import { useToasterOptional } from '../containers/ToasterContainer.js';+import { Icon } from '../icons/Icon.js';+import { useOptionalServer } from '../server/ServerContext.js';+import { useOptionalShellMode } from '../server/ShellModeContext.js';+import type { AgentSpec } from '../server/types.js';+import { auiButtonClass } from './lib/buttonClasses.js';+import { Button } from './primitives/Button.js';+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from './primitives/Dialog.js';+import { DropdownMenu, DropdownMenuItem, DropdownMenuSeparator } from './primitives/DropdownMenu.js';++/** Immutable clone name for a library agent (`{name}-copy`). */+export function cloneAgentName(agentName: string): string {+ return `${agentName}-copy`;+}++export type AgentOverflowMenuProps = {+ agentName: string;+ agentSpec?: AgentSpec;+ /** Edit / Clone / Delete when composer is enabled. */+ canMutate: boolean;+ canManageSchedules: boolean;+ onEdit: () => void;+ onManageSchedules?: () => void;+ /** After successful delete (e.g. leave agent details). */+ onDeleted?: () => void;+};++type PendingAction = 'clone' | 'delete' | null;++export function AgentOverflowMenu({+ agentName,+ agentSpec,+ canMutate,+ canManageSchedules,+ onEdit,+ onManageSchedules,+ onDeleted,+}: AgentOverflowMenuProps) {+ const builder = useOptionalServer();+ const shell = useOptionalShellMode();+ const toaster = useToasterOptional();+ const [pending, setPending] = useState<PendingAction>(null);+ const [busy, setBusy] = useState(false);++ const canEditOrClone = canMutate && agentSpec != null;+ const showManageSchedules = canManageSchedules && onManageSchedules != null;+ const showMenu = canEditOrClone || showManageSchedules || canMutate;+ if (!showMenu) return null;++ const clonedName = cloneAgentName(agentName);++ const closePending = () => {+ if (busy) return;+ setPending(null);+ };++ const handleClone = async () => {+ if (builder == null || agentSpec == null) return;+ setBusy(true);+ try {+ await builder.saveAgent({+ agentName: clonedName,+ agentSpec,+ intent: 'create',+ });+ shell?.invalidateAgentsList();+ toaster?.showSuccess({+ title: 'Agent cloned',+ description: `Created “${clonedName}”.`,+ });+ setPending(null);+ } catch (caught) {+ toaster?.showError(caught);+ } finally {+ setBusy(false);+ }+ };++ const handleDelete = async () => {+ if (builder == null || typeof builder.deleteAgent !== 'function') return;+ setBusy(true);+ try {+ await builder.deleteAgent({ agentName });+ shell?.invalidateAgentsList();+ toaster?.showSuccess({+ title: 'Agent deleted',+ description: `“${agentName}” was deleted.`,+ });+ setPending(null);+ onDeleted?.();+ } catch (caught) {+ toaster?.showError(caught);+ } finally {+ setBusy(false);+ }+ };++ return (+ <>+ <DropdownMenu+ align="end"+ className="min-w-48"+ trigger={+ <button+ type="button"+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}+ aria-label={`Actions for ${agentName}`}+ >+ <Icon name="ellipsis-vertical" className="size-4" />+ </button>+ }+ >+ {canEditOrClone ? (+ <DropdownMenuItem className="whitespace-nowrap" onClick={onEdit}>+ <Icon name="pencil" className="size-3.5" />+ Edit+ </DropdownMenuItem>+ ) : null}+ {canEditOrClone ? (+ <DropdownMenuItem className="whitespace-nowrap" onClick={() => setPending('clone')}>+ <Icon name="clone" className="size-3.5" />+ Clone+ </DropdownMenuItem>+ ) : null}+ {showManageSchedules ? (+ <DropdownMenuItem className="whitespace-nowrap" onClick={onManageSchedules}>+ <Icon name="calendar-clock" className="size-3.5" />+ Manage Schedules+ </DropdownMenuItem>+ ) : null}+ {canMutate ? (+ <>+ {canEditOrClone || showManageSchedules ? <DropdownMenuSeparator /> : null}+ <DropdownMenuItem+ className="whitespace-nowrap text-failure-bg focus-visible:text-failure-bg"+ onClick={() => setPending('delete')}+ >+ <Icon name="trash" className="size-3.5" />+ Delete+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenu>++ {pending === 'clone' ? (+ <Dialog open onOpenChange={open => !open && closePending()} aria-label="Clone agent" className="max-w-md">+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Clone agent?</DialogTitle>+ <p className="text-text-secondary text-sm">+ This will create “{clonedName}” with the same configuration as “{agentName}”.+ </p>+ </DialogHeader>+ </DialogContent>+ <DialogFooter>+ <Button type="button" variant="secondary" disabled={busy} onClick={closePending}>+ Cancel+ </Button>+ <Button type="button" disabled={busy || builder == null} onClick={() => void handleClone()}>+ Clone+ </Button>+ </DialogFooter>+ </Dialog>+ ) : null}++ {pending === 'delete' ? (+ <Dialog open onOpenChange={open => !open && closePending()} aria-label="Delete agent" className="max-w-md">+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Delete agent?</DialogTitle>+ <p className="text-text-secondary text-sm">+ “{agentName}” will be permanently deleted. This cannot be undone.+ </p>+ </DialogHeader>+ </DialogContent>+ <DialogFooter>+ <Button type="button" variant="secondary" disabled={busy} onClick={closePending}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ disabled={busy || builder == null || typeof builder.deleteAgent !== 'function'}+ onClick={() => void handleDelete()}+ >+ Delete+ </Button>+ </DialogFooter>+ </Dialog>+ ) : null}+ </>+ );+}diff --git a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsxindex d775dfb1b..35727248c 100644--- a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx+++ b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx@@ -8,13 +8,13 @@ import { useOptionalAgentSessionsServer, useOptionalScheduleServer } from '../seimport { libraryAgentId, useShellMode } from '../server/ShellModeContext.js';import type { AgentLibraryEntry, AgentSpec, Schedule } from '../server/types.js';import { useSlot } from '../theme/SlotsProvider.js';-import { writeScheduleShareSearch } from '../utils/scheduleShareUrl.js';-import { writeSessionShareSearch } from '../utils/sessionShareUrl.js';+import { writeOpenSchedulesForAgentSearch } from '../utils/scheduleShareUrl.js';+import { AgentOverflowMenu } from './AgentOverflowMenu.js';+import { EmptyScreen, EmptyScreenQueryHighlight } from './EmptyScreen.js';import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';import { mountName } from './lib/mountName.js';import { useSearchAgentsList } from './lib/useSearchAgentsList.js';-import { DropdownMenu, DropdownMenuItem } from './primitives/DropdownMenu.js';import SearchInput from './primitives/SearchInput.js';import { Skeleton } from './primitives/Skeleton.js';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './primitives/Table.js';@@ -31,13 +31,15 @@ export type AgentScheduleSummary = {export type AgentLibraryRowProps = {agent: AgentLibraryEntry;- showEdit: boolean;+ canMutate: boolean;+ canManageSchedules: boolean;scheduleSummary?: AgentScheduleSummary | null;onOpenSchedules?: () => void;onCreateSchedule?: () => void;onOpen?: () => void;onTry: () => void;onEdit: () => void;+ onManageSchedules?: () => void;};/** Short label for model fqns like `provider/gpt-4.1` → `gpt-4.1`. */@@ -96,13 +98,15 @@ function AgentSchedulesBadge({export function AgentLibraryRow({agent,- showEdit,+ canMutate,+ canManageSchedules,scheduleSummary,onOpenSchedules,onCreateSchedule,onOpen,onTry,onEdit,+ onManageSchedules,}: AgentLibraryRowProps) {const spec = agent.agentSpec;const modelName = spec?.model.name;@@ -112,8 +116,11 @@ export function AgentLibraryRow({const mcpNames = (spec?.mcpServers ?? []).map(mountName).filter((name: string | null): name is string => name != null);- const connectorsTitle = mcpNames.length ? `Connectors: ${mcpNames.join(', ')}` : `${mcpCount} connectors`;- const skillsTitle = skillNames.length ? `Skills: ${skillNames.join(', ')}` : `${skillsCount} skills`;+ const modelLabel = modelName != null ? displayModelLabel(modelName) : null;+ const modelTitle = modelName ?? '';+ const connectorsTitle = mcpNames.length ? mcpNames.join(', ') : `${mcpCount} connectors`;+ const skillsTitle = skillNames.length ? skillNames.join(', ') : `${skillsCount} skills`;+ const hasConfiguration = modelLabel != null || skillsCount > 0 || mcpCount > 0;const hasNoSchedules = scheduleSummary != null && scheduleSummary.count === 0;@@ -137,35 +144,46 @@ export function AgentLibraryRow({{agent.name}</button>)}- {spec != null ? (- <div className="text-text-secondary mt-1 flex min-w-0 items-center gap-2">- {modelName ? (- <span className="bg-primary-button-bg/10 text-primary-button-bg inline-flex max-w-[8rem] items-center gap-1 truncate rounded-full px-2 py-0.5 text-xs font-medium">- <Icon name="cpu" className="size-3.5 shrink-0" />- <span className="truncate">{displayModelLabel(modelName)}</span>- </span>- ) : null}- {mcpCount > 0 ? (- <Tooltip content={connectorsTitle}>- <span className="inline-flex items-center gap-1 text-xs" aria-label={connectorsTitle}>- <Icon name="plug" className="size-3.5" />- {mcpCount}- </span>- </Tooltip>- ) : null}- {skillsCount > 0 ? (- <Tooltip content={skillsTitle}>- <span className="inline-flex items-center gap-1 text-xs" aria-label={skillsTitle}>- <Icon name="lightbulb" className="size-3.5" />- {skillsCount}- </span>- </Tooltip>- ) : null}- </div>- ) : null}</div></div></TableCell>+ <TableCell>+ {hasConfiguration ? (+ <div className="text-text-secondary flex min-w-0 items-center gap-2">+ {modelLabel != null ? (+ <Tooltip content={modelTitle}>+ <span+ className="bg-primary-button-bg/10 text-primary-button-bg inline-flex max-w-[10rem] items-center gap-1 truncate rounded-full px-2 py-0.5 text-xs font-medium"+ aria-label={modelTitle}+ >+ <Icon name="cpu" className="size-3.5 shrink-0" />+ <span className="truncate">{modelLabel}</span>+ </span>+ </Tooltip>+ ) : null}+ {skillsCount > 0 ? (+ <Tooltip content={skillsTitle}>+ <span className="inline-flex items-center gap-1 text-xs" aria-label={`Skills: ${skillsTitle}`}>+ <Icon name="lightbulb" className="size-3.5 shrink-0" />+ {skillsCount}+ </span>+ </Tooltip>+ ) : null}+ {mcpCount > 0 ? (+ <Tooltip content={connectorsTitle}>+ <span className="inline-flex items-center gap-1 text-xs" aria-label={`Connectors: ${connectorsTitle}`}>+ <Icon name="plug" className="size-3.5 shrink-0" />+ {mcpCount}+ </span>+ </Tooltip>+ ) : null}+ </div>+ ) : (+ <span className="text-text-secondary text-sm" aria-label={`Configuration unavailable for ${agent.name}`}>+ —+ </span>+ )}+ </TableCell>{scheduleSummary !== undefined ? (<TableCell>{scheduleSummary != null && scheduleSummary.count > 0 ? (@@ -193,25 +211,14 @@ export function AgentLibraryRow({<Icon name="play" className="size-3.5" />Try</button>- {showEdit ? (- <DropdownMenu- align="end"- trigger={- <button- type="button"- className={auiButtonClass({ variant: 'ghost', size: 'icon' })}- aria-label={`Actions for ${agent.name}`}- >- <Icon name="ellipsis" className="size-4" />- </button>- }- >- <DropdownMenuItem onClick={onEdit}>- <Icon name="pencil" className="size-3.5" />- Edit- </DropdownMenuItem>- </DropdownMenu>- ) : null}+ <AgentOverflowMenu+ agentName={agent.name}+ {...(spec != null ? { agentSpec: spec } : {})}+ canMutate={canMutate}+ canManageSchedules={canManageSchedules}+ onEdit={onEdit}+ {...(onManageSchedules != null ? { onManageSchedules } : {})}+ /></div></TableCell></TableRow>@@ -267,9 +274,10 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {const [scheduleByAgent, setScheduleByAgent] = useState<Map<string, AgentScheduleSummary> | null>(null);const open = shell.libraryOpen;- const canEdit = shell.isComposerEnabled === true;+ const canMutate = shell.isComposerEnabled === true;const agentsListEpoch = shell.agentsListEpoch;const showSchedulesColumn = scheduleServer != null;+ const canManageSchedules = scheduleServer != null;useEffect(() => {if (!open) setQuery('');@@ -319,22 +327,7 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {}, [agents, open, scheduleServer, agentsListEpoch]);const openSchedulesForAgent = ({ agentId, isNew }: { agentId: string; isNew?: boolean }) => {- const url = new URL(window.location.href);- writeSessionShareSearch(url.searchParams, {- sessionId: null,- agentId: null,- tab: null,- view: null,- timeRange: null,- });- writeScheduleShareSearch(url.searchParams, {- agent: agentId,- status: null,- q: null,- isNew: isNew === true ? true : null,- });- window.history.replaceState(window.history.state, '', url);- shell.setLibraryOpen(false);+ writeOpenSchedulesForAgentSearch({ agentId, ...(isNew === true ? { isNew: true } : {}) });shell.setSchedulesOpen(true);};@@ -390,11 +383,18 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {) : error ? (<p className="text-failure-bg px-3 py-8 text-center text-sm">{error}</p>) : agents.length === 0 ? (- <p className="text-text-secondary px-3 py-8 text-center text-sm">- {query.trim()- ? `No agents match "${query.trim()}".`- : 'No agents yet. Build one in a chat, then save it as an agent.'}- </p>+ <EmptyScreen+ title="No Agents Found"+ description={+ query.trim() ? (+ <>+ No search results found for <EmptyScreenQueryHighlight>{query.trim()}</EmptyScreenQueryHighlight>+ </>+ ) : (+ 'Build one in a chat, then save it as an agent.'+ )+ }+ />) : (<><div className="overflow-hidden rounded-lg border border-border">@@ -402,6 +402,7 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {<TableHeader><TableRow className="hover:bg-transparent"><TableHead>Agent name</TableHead>+ <TableHead>Configuration</TableHead>{showSchedulesColumn ? <TableHead className="w-[8rem]">Schedules</TableHead> : null}<TableHead className="w-px"><span className="sr-only">Actions</span>@@ -413,7 +414,6 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {const agentSpec = agent.agentSpec;const agentId = agent.agentId;const id = libraryAgentId(agent);- const showEdit = canEdit && agentSpec != null;const summary = showSchedulesColumn? (scheduleByAgent?.get(id) ??scheduleByAgent?.get(agent.name) ??@@ -423,12 +423,14 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {<SlottedAgentLibraryRowkey={id}agent={agent}- showEdit={showEdit}+ canMutate={canMutate}+ canManageSchedules={canManageSchedules}{...(summary !== undefined ? { scheduleSummary: summary } : {})}{...(showSchedulesColumn? {onOpenSchedules: () => openSchedulesForAgent({ agentId: id }),onCreateSchedule: () => openSchedulesForAgent({ agentId: id, isNew: true }),+ onManageSchedules: () => openSchedulesForAgent({ agentId: id }),}: {})}{...(sessionsServer != null && agentId != nulldiff --git a/packages/trueforge-ui/src/atoms/CodeEditor.tsx b/packages/trueforge-ui/src/atoms/CodeEditor.tsxindex d2fa65ba7..fd120fd61 100644--- a/packages/trueforge-ui/src/atoms/CodeEditor.tsx+++ b/packages/trueforge-ui/src/atoms/CodeEditor.tsx@@ -4,6 +4,7 @@ import { useCallback, useState } from 'react';import { Icon } from '../icons/Icon.js';import { useSlot } from '../theme/SlotsProvider.js';+import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';import type { MonacoEditorCoreProps } from './MonacoEditorCore.js';@@ -17,22 +18,28 @@ function ToolbarButton({tooltip,icon,active,+ variant = 'ghost',}: {onClick: () => void;tooltip: string;icon: string;active?: boolean;+ variant?: 'ghost' | 'secondary';}) {return (<buttontype="button"onClick={onClick}title={tooltip}- className={cn(- 'flex cursor-pointer items-center justify-center rounded p-1.5 text-xs transition-colors',- 'hover:bg-ghost-button-hover text-text-secondary hover:text-text-primary',- active && 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text',- )}+ className={auiButtonClass({+ variant,+ size: 'icon',+ className: cn(+ 'h-7 w-7 shrink-0',+ variant === 'ghost' && 'text-text-secondary hover:text-text-primary',+ active && 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text',+ ),+ })}aria-label={tooltip}><Icon name={icon} size="0.875em" />@@ -78,6 +85,8 @@ export function CodeEditor({lineNumbers: showLineNumbers ? 'on' : ('off' as const),minimap: { enabled: false },scrollBeyondLastLine: false,+ // Avoid a blank numbered line when the buffer ends with `\n`.+ renderFinalNewline: 'off' as const,wordWrap: 'on' as const,};@@ -105,6 +114,7 @@ export function CodeEditor({onClick={handleCopy}tooltip={copied ? 'Copied!' : 'Copy'}icon={copied ? 'check' : 'copy'}+ variant="secondary"/><ToolbarButton onClick={handleDownload} tooltip="Download" icon="download" /><ToolbarButtondiff --git a/packages/trueforge-ui/src/atoms/EmptyScreen.tsx b/packages/trueforge-ui/src/atoms/EmptyScreen.tsxnew file mode 100644index 000000000..fa713c81d--- /dev/null+++ b/packages/trueforge-ui/src/atoms/EmptyScreen.tsx@@ -0,0 +1,40 @@+'use client';++import type { ReactNode } from 'react';++import { Icon } from '../icons/Icon.js';+import { cn } from './lib/cn.js';++export type EmptyScreenProps = {+ title: string;+ description?: ReactNode;+ className?: string;+};++/** Centered empty surface: `empty` glyph + title + optional supporting copy. */+export function EmptyScreen({ title, description, className }: EmptyScreenProps) {+ return (+ <div+ role="status"+ className={cn(+ 'flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-6 py-16',+ className,+ )}+ >+ <Icon name="empty" size={48} className="shrink-0" aria-hidden />+ <div className="flex max-w-md flex-col items-center gap-1.5 text-center">+ <h2 className="text-base font-semibold text-text-primary">{title}</h2>+ {description != null ? <p className="text-sm text-text-secondary">{description}</p> : null}+ </div>+ </div>+ );+}++/** Inline pill for a search/filter query inside empty-state descriptions. */+export function EmptyScreenQueryHighlight({ children }: { children: string }) {+ return (+ <span className="mx-0.5 inline-flex max-w-full truncate rounded-full bg-secondary-bg px-2 py-0.5 align-middle font-mono text-xs text-text-primary">+ {children}+ </span>+ );+}diff --git a/packages/trueforge-ui/src/atoms/MonacoEditorCore.tsx b/packages/trueforge-ui/src/atoms/MonacoEditorCore.tsxindex 748b4a8f6..357ce21a8 100644--- a/packages/trueforge-ui/src/atoms/MonacoEditorCore.tsx+++ b/packages/trueforge-ui/src/atoms/MonacoEditorCore.tsx@@ -130,6 +130,8 @@ const EMBEDDED_DEFAULTS: Record<string, unknown> = {automaticLayout: true,minimap: { enabled: false },scrollBeyondLastLine: false,+ // Don't paint a blank last line when the buffer ends with `\n`.+ renderFinalNewline: 'off',wordWrap: 'on',fontSize: 12,fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',diff --git a/packages/trueforge-ui/src/atoms/ShellActions.tsx b/packages/trueforge-ui/src/atoms/ShellActions.tsxindex b7906c615..3fb504b9e 100644--- a/packages/trueforge-ui/src/atoms/ShellActions.tsx+++ b/packages/trueforge-ui/src/atoms/ShellActions.tsx@@ -3,6 +3,7 @@import { Icon } from '../icons/Icon.js';import { useOptionalCatalogServer, useServerCapabilities } from '../server/ServerContext.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';+import { isSettingsChromeEnabled } from '../server/settingsChrome.js';import { useSlot } from '../theme/SlotsProvider.js';import { useTheme } from '../theme/ThemeProvider.js';import { auiButtonClass } from './lib/buttonClasses.js';@@ -16,6 +17,7 @@ export function ShellActions({ className, labeled = false }: { className?: strinconst ActionSlot = useSlot('ShellActionsActionSlot');const isDark = mode === 'dark';const themeLabel = isDark ? 'Light' : 'Dark';+ const settingsChromeEnabled = isSettingsChromeEnabled({ catalog, capabilities });const labeledButtonClass ='h-auto w-full flex-col gap-0.5 whitespace-normal px-1 py-1.5 text-[10px] leading-tight !justify-center';@@ -42,7 +44,7 @@ export function ShellActions({ className, labeled = false }: { className?: strin<Icon name={isDark ? 'sun' : 'moon'} size={labeled ? 16 : undefined} />{labeled ? <span className="text-center">{themeLabel}</span> : null}</button>- {shell != null && catalog != null && capabilities?.settings?.enabled !== false ? (+ {shell != null && settingsChromeEnabled ? (<buttontype="button"aria-label="Settings"diff --git a/packages/trueforge-ui/src/atoms/SyntaxHighlighter.tsx b/packages/trueforge-ui/src/atoms/SyntaxHighlighter.tsxindex ad1f30f5f..c09c2cbc1 100644--- a/packages/trueforge-ui/src/atoms/SyntaxHighlighter.tsx+++ b/packages/trueforge-ui/src/atoms/SyntaxHighlighter.tsx@@ -6,6 +6,7 @@ import {isValidElement,memo,useCallback,+ useMemo,useState,type ComponentType,type ReactNode,@@ -15,6 +16,7 @@ import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prisimport { Icon } from '../icons/Icon.js';import { useOptionalContentClassNames } from '../theme/ThemeProvider.js';+import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';export type SyntaxHighlighterProps = {@@ -25,6 +27,11 @@ export type SyntaxHighlighterProps = {showLineNumbers?: boolean;};+/** Drop a single trailing newline so line numbers do not paint an empty last row. */+export function stripTrailingNewline(code: string): string {+ return code.endsWith('\n') ? code.slice(0, -1) : code;+}+function applyLineNumberClassName(children: ReactNode, className: string | undefined): ReactNode {if (!className) return children;@@ -44,6 +51,7 @@ function SyntaxHighlighterImpl({ code, language, darkTheme, className, showLineNconst classNames = useOptionalContentClassNames();const style = darkTheme ? oneDark : oneLight;const [copied, setCopied] = useState(false);+ const displayCode = useMemo(() => stripTrailingNewline(code), [code]);const handleCopy = useCallback(() => {void navigator.clipboard.writeText(code).then(() => {@@ -65,10 +73,11 @@ function SyntaxHighlighterImpl({ code, language, darkTheme, className, showLineNonClick={handleCopy}title={copied ? 'Copied!' : 'Copy'}aria-label={copied ? 'Copied!' : 'Copy'}- className={cn(- 'absolute top-2 right-2 z-10 flex cursor-pointer items-center justify-center rounded p-1.5 text-xs transition-colors',- 'bg-primary-bg/80 text-text-secondary hover:bg-ghost-button-hover hover:text-text-primary',- )}+ className={auiButtonClass({+ variant: 'secondary',+ size: 'icon',+ className: 'absolute top-2 right-2 z-10 h-7 w-7',+ })}><Icon name={copied ? 'check' : 'copy'} size="0.875em" /></button>@@ -99,7 +108,7 @@ function SyntaxHighlighterImpl({ code, language, darkTheme, className, showLineN</code>)}>- {code}+ {displayCode}</PrismHighlighter></div>);diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsHeader.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsHeader.tsxindex 36cb55fcc..7d9524f4c 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsHeader.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsHeader.tsx@@ -1,13 +1,19 @@'use client';import { Icon } from '../../icons/Icon.js';+import { useOptionalScheduleServer, useOptionalServer } from '../../server/ServerContext.js';import { useShellMode } from '../../server/ShellModeContext.js';+import { writeOpenSchedulesForAgentSearch } from '../../utils/scheduleShareUrl.js';+import { AgentOverflowMenu } from '../AgentOverflowMenu.js';import { auiButtonClass } from '../lib/buttonClasses.js';import type { AgentDetailsHeaderProps } from './types.js';export function AgentDetailsHeader({ agentId, detail, onBack }: AgentDetailsHeaderProps) {const shell = useShellMode();- const canEdit = shell.isComposerEnabled && detail != null;+ const scheduleServer = useOptionalScheduleServer();+ const builder = useOptionalServer();+ const canMutate = shell.isComposerEnabled && detail != null && builder != null;+ const canManageSchedules = scheduleServer != null && detail != null;const handleTry = () => {if (detail == null) return;@@ -29,51 +35,53 @@ export function AgentDetailsHeader({ agentId, detail, onBack }: AgentDetailsHead});};+ const handleManageSchedules = () => {+ writeOpenSchedulesForAgentSearch({ agentId });+ shell.setSchedulesOpen(true);+ };+return (- <header className="shrink-0 border-b border-border bg-primary-bg">- <div className="flex min-w-0 flex-wrap items-center gap-2 px-3 py-2">+ <header className="flex shrink-0 flex-wrap items-center gap-2 border-b border-border bg-primary-bg py-2.5 px-2">+ <button+ type="button"+ aria-label="Back to Agents"+ title="Back to Agents"+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}+ onClick={onBack}+ >+ <Icon name="arrow-left" />+ </button>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-1 truncate text-md font-semibold text-text-primary">+ <button type="button" className="cursor-pointer truncate hover:text-text-primary" onClick={onBack}>+ Agents+ </button>+ <Icon name="chevron-right" className="size-3 shrink-0" />+ <span className="truncate">{detail?.name ?? agentId}</span>+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1.5"><buttontype="button"- aria-label="Back to Agents"- title="Back to Agents"- className={auiButtonClass({ variant: 'ghost', size: 'icon' })}- onClick={onBack}+ aria-label="Try agent"+ disabled={detail == null}+ className={auiButtonClass({ variant: 'default', size: 'sm' })}+ onClick={handleTry}>- <Icon name="arrow-left" />+ <Icon name="play" className="size-3.5" />+ Try</button>- <div className="min-w-0 flex-1">- <div className="flex min-w-0 items-center gap-1 text-xs text-text-secondary">- <button type="button" className="cursor-pointer truncate hover:text-text-primary" onClick={onBack}>- Agents- </button>- <Icon name="chevron-right" className="size-3 shrink-0" />- <span className="truncate">{detail?.name ?? agentId}</span>- </div>- <h1 className="truncate text-lg font-semibold tracking-tight text-text-primary">{detail?.name ?? agentId}</h1>- </div>- <div className="flex shrink-0 items-center gap-1.5">- <button- type="button"- aria-label="Try agent"- disabled={detail == null}- className={auiButtonClass({ variant: 'default', size: 'sm' })}- onClick={handleTry}- >- <Icon name="play" className="size-3.5" />- Try- </button>- {canEdit ? (- <button- type="button"- aria-label="Edit agent"- className={auiButtonClass({ variant: 'outline', size: 'sm' })}- onClick={handleEdit}- >- <Icon name="pencil" className="size-3.5" />- Edit- </button>- ) : null}- </div>+ {detail != null ? (+ <AgentOverflowMenu+ agentName={detail.name}+ agentSpec={detail.agentSpec}+ canMutate={canMutate}+ canManageSchedules={canManageSchedules}+ onEdit={handleEdit}+ {...(canManageSchedules ? { onManageSchedules: handleManageSchedules } : {})}+ onDeleted={onBack}+ />+ ) : null}</div></header>);diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsTabs.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsTabs.tsxindex 892d36bae..aad4bfc25 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsTabs.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentDetailsTabs.tsx@@ -6,7 +6,7 @@ import type { AgentDetailsTab, AgentDetailsTabsProps } from './types.js';const tabs: Array<{ id: AgentDetailsTab; label: string; icon: string }> = [{ id: 'overview', label: 'Overview', icon: 'info' },- { id: 'sessions', label: 'Sessions', icon: 'clock-rotate-left' },+ { id: 'sessions', label: 'Sessions', icon: 'message-square-text' },{ id: 'code', label: 'Use In Code', icon: 'code' },{ id: 'metrics', label: 'Metrics', icon: 'chart' },];diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsxindex 8467742d3..952b02e5c 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentOverview.tsx@@ -70,8 +70,8 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {<div className="grid min-h-0 flex-1 gap-3 overflow-auto p-4 md:grid-cols-[minmax(0,1fr)_18rem] md:overflow-hidden"><section className="flex min-h-64 flex-col rounded-lg border border-border bg-card-bg p-4 text-text-primary"><div className="mb-3 flex shrink-0 items-center justify-between gap-2">- <h2 className="flex items-center gap-1.5 text-sm font-semibold">- <Icon name="file" className="size-4 text-text-secondary" />+ <h2 className="flex items-center gap-1.5 text-sm font-semibold text-text-primary">+ <Icon name="book-open" className="size-4 text-text-secondary" />Instructions</h2>{instructions ? (@@ -120,6 +120,32 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {</section><aside className="flex min-h-0 min-w-0 flex-col gap-3 md:overflow-auto">+ <AgentOverviewCard title="Model Configuration" icon="cpu">+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">+ <dt className="text-text-secondary">Model</dt>+ <dd className={cn(valueClassName, 'truncate')} title={spec.model.name}>+ {displayModelName(spec.model.name)}+ </dd>+ {typeof maxTokens === 'number' ? (+ <>+ <dt className="text-text-secondary">Max tokens</dt>+ <dd className={valueClassName}>{maxTokens}</dd>+ </>+ ) : null}+ {spec.model.params?.reasoningEffort !== undefined ? (+ <>+ <dt className="text-text-secondary">Reasoning</dt>+ <dd className={valueClassName}>{spec.model.params.reasoningEffort}</dd>+ </>+ ) : null}+ {typeof temperature === 'number' ? (+ <>+ <dt className="text-text-secondary">Temperature</dt>+ <dd className={valueClassName}>{temperature}</dd>+ </>+ ) : null}+ </dl>+ </AgentOverviewCard><AgentOverviewCard title="MCP Servers" icon="plug" count={connectors.length}>{connectors.length === 0 ? (<p className="text-xs text-text-secondary">No connectors attached.</p>@@ -161,33 +187,6 @@ export default function AgentOverview({ detail }: AgentOverviewProps) {)}</AgentOverviewCard>- <AgentOverviewCard title="Model Configuration" icon="cpu">- <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">- <dt className="text-text-secondary">Model</dt>- <dd className={cn(valueClassName, 'truncate')} title={spec.model.name}>- {displayModelName(spec.model.name)}- </dd>- {typeof maxTokens === 'number' ? (- <>- <dt className="text-text-secondary">Max tokens</dt>- <dd className={valueClassName}>{maxTokens}</dd>- </>- ) : null}- {spec.model.params?.reasoningEffort !== undefined ? (- <>- <dt className="text-text-secondary">Reasoning</dt>- <dd className={valueClassName}>{spec.model.params.reasoningEffort}</dd>- </>- ) : null}- {typeof temperature === 'number' ? (- <>- <dt className="text-text-secondary">Temperature</dt>- <dd className={valueClassName}>{temperature}</dd>- </>- ) : null}- </dl>- </AgentOverviewCard>-{execution.length > 0 ? (<AgentOverviewCard title="Execution" icon="terminal"><dl className="space-y-1 text-xs">diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsxindex 6e22a2b62..6cb1f801c 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx@@ -18,6 +18,7 @@ export function AgentSessionDetailHeader({createdAt,view,onClose,+ resumeHref,onResume,resumeLabel,}: AgentSessionDetailHeaderProps) {@@ -57,7 +58,17 @@ export function AgentSessionDetailHeader({</button></LightTooltip></div>- {onResume != null && resumeLabel != null ? (+ {resumeLabel != null && resumeHref != null ? (+ <a+ href={resumeHref}+ target="_blank"+ rel="noopener noreferrer"+ className={auiButtonClass({ variant: 'outline', size: 'sm' })}+ >+ {resumeLabel}+ <Icon name="square-arrow-out-up-right" size="0.875em" className="shrink-0" />+ </a>+ ) : resumeLabel != null && onResume != null ? (<button type="button" className={auiButtonClass({ variant: 'outline', size: 'sm' })} onClick={onResume}>{resumeLabel}</button>diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTurnHeader.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTurnHeader.tsxindex 5b845f259..fff88699a 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTurnHeader.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTurnHeader.tsx@@ -2,15 +2,67 @@import { Icon } from '../../icons/Icon.js';import { formatCostUsd, formatDurationMs, formatTokenCount } from '../../utils/sessionDisplayFormat.js';+import { LightTooltip } from '../primitives/Tooltip.js';import type { AgentSessionTurnHeaderProps } from './types.js';+function TurnTokenBreakdownTooltip({+ inputTokens,+ outputTokens,+ cachedTokens,+}: {+ inputTokens: number;+ outputTokens: number;+ cachedTokens: number;+}) {+ const rows = [+ { label: 'Input', value: inputTokens },+ { label: 'Output', value: outputTokens },+ { label: 'Cached', value: cachedTokens },+ ] as const;+ return (+ <div className="min-w-28 px-2 py-1.5 text-xs text-text-primary">+ <div className="flex flex-col gap-1">+ {rows.map(row => (+ <div key={row.label} className="flex items-center justify-between gap-4">+ <span className="text-text-secondary">{row.label}</span>+ <span className="tabular-nums font-medium text-text-primary">{formatTokenCount(row.value)}</span>+ </div>+ ))}+ </div>+ </div>+ );+}+export function AgentSessionTurnHeader({turnNumber,totalTokens,+ inputTokens,+ outputTokens,+ cachedTokens,durationMs,totalCostInUsd,}: AgentSessionTurnHeaderProps) {const hasMetrics = totalTokens != null || durationMs != null || totalCostInUsd != null;+ const hasTokenBreakdown = inputTokens != null || outputTokens != null || cachedTokens != null;+ const breakdownInput = inputTokens ?? 0;+ const breakdownOutput = outputTokens ?? 0;+ const breakdownCached = cachedTokens ?? 0;++ const tokensTrigger =+ totalTokens != null ? (+ <button+ type="button"+ className="inline-flex items-center gap-1 rounded-sm text-inherit"+ aria-label={+ hasTokenBreakdown+ ? `Tokens ${formatTokenCount(totalTokens)}. Input ${formatTokenCount(breakdownInput)}, Output ${formatTokenCount(breakdownOutput)}, Cached ${formatTokenCount(breakdownCached)}`+ : `Tokens ${formatTokenCount(totalTokens)}`+ }+ >+ <Icon name="link" className="size-3.5 shrink-0" aria-hidden />+ {`Tokens ${formatTokenCount(totalTokens)}`}+ </button>+ ) : null;return (<div className="flex items-center gap-3 py-1 text-xs text-text-secondary">@@ -18,11 +70,23 @@ export function AgentSessionTurnHeader({<div className="h-px min-w-4 flex-1 bg-border" aria-hidden="true" />{hasMetrics ? (<div className="flex shrink-0 items-center gap-3 tabular-nums">- {totalTokens != null ? (- <span className="inline-flex items-center gap-1">- <Icon name="link" className="size-3.5 shrink-0" />- {`Tokens ${formatTokenCount(totalTokens)}`}- </span>+ {tokensTrigger != null ? (+ hasTokenBreakdown ? (+ <LightTooltip+ title={+ <TurnTokenBreakdownTooltip+ inputTokens={breakdownInput}+ outputTokens={breakdownOutput}+ cachedTokens={breakdownCached}+ />+ }+ side="bottom"+ >+ {tokensTrigger}+ </LightTooltip>+ ) : (+ tokensTrigger+ )) : null}{durationMs != null ? (<span className="inline-flex items-center gap-1">diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsxindex 3fa95c799..80cb278ed 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx@@ -5,12 +5,16 @@ import { Group, Panel, Separator } from 'react-resizable-panels';import { useSessionShareSearch } from '../../hooks/useSessionShareSearch.js';import { Icon } from '../../icons/Icon.js';+import { buildSessionResumeHref } from '../../routing/paths.js';+import { useOptionalResolvedRoutes } from '../../routing/ResolvedRoutesContext.js';import { useAgentSessionsServer, useServer } from '../../server/ServerContext.js';import { useOptionalShellMode } from '../../server/ShellModeContext.js';import type { Session, SessionEventItem, SessionListEntry } from '../../server/types.js';import { useSlot } from '../../theme/SlotsProvider.js';import { drainListPages } from '../../utils/drainListPages.js';import { sessionTimeRangeFromCreatedAt } from '../../utils/sessionShareUrl.js';+import { EmptyScreen } from '../EmptyScreen.js';+import { cn } from '../lib/cn.js';import { sessionIsCreateAgent } from '../lib/sessionCreateAgent.js';import { Skeleton } from '../primitives/Skeleton.js';import type { AgentSessionsProps } from './types.js';@@ -31,6 +35,7 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareViewconst sessionsServer = useAgentSessionsServer();const chatServer = useServer();const shell = useOptionalShellMode();+ const routes = useOptionalResolvedRoutes();const { sessionId: selectedSessionId, updateShareSearch } = useSessionShareSearch();const AgentSessionListRow = useSlot('AgentSessionListRow');@@ -178,6 +183,10 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareViewconst resumeIsMutable =detailSession != null ? detailSession.isMutable : selectedEntry != null ? entryIsMutable(selectedEntry) : true;const resumeLabel = resumeIsCreateAgent ? 'Resume Agent building' : 'Resume Chat';+ const resumeHref =+ selectedSessionId != null && routes != null+ ? buildSessionResumeHref({ sessionId: selectedSessionId, routes })+ : null;const handleResume = () => {if (selectedSessionId == null || shell == null) return;@@ -190,6 +199,26 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareView});};+ const resumeProps =+ resumeHref != null ? { resumeHref, resumeLabel } : shell != null ? { onResume: handleResume, resumeLabel } : {};++ // Full empty only when nothing is selected — keep the detail pane for deep-linked sessionIds+ // (filters/time range can empty the list while share state still points at a session).+ if (+ !listLoading &&+ !listFailed &&+ entries.length === 0 &&+ (selectedSessionId == null || selectedSessionId.length === 0)+ ) {+ return (+ <EmptyScreen+ title="No Sessions Found"+ description="There are no sessions available at the moment."+ className="bg-primary-bg"+ />+ );+ }+return (<Groupid="agent-sessions-split"@@ -198,7 +227,7 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareViewresizeTargetMinimumSize={{ coarse: 24, fine: 11 }}><Panel id="agent-sessions-list" defaultSize="35%" minSize="20%" maxSize="50%">- <aside className="flex h-full min-h-0 w-full flex-col bg-primary-bg">+ <aside className="flex h-full min-h-0 w-full flex-col bg-sidebar-bg"><div className="scrollbar-none min-h-0 flex-1 overflow-y-auto">{listLoading ? (<div className="space-y-2 p-3" role="status" aria-label="Loading sessions">@@ -208,8 +237,6 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareView</div>) : listFailed ? (<p className="px-3 py-6 text-center text-xs text-text-secondary">Sessions could not be loaded.</p>- ) : entries.length === 0 ? (- <p className="px-3 py-6 text-center text-xs text-text-secondary">No sessions are there yet</p>) : (entries.map(entry => (<AgentSessionListRow@@ -249,9 +276,15 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareView<div aria-hidden className="absolute inset-y-0 left-0 w-px bg-border transition-colors" /><divaria-hidden- className="absolute top-1/2 left-0 z-10 flex h-4 w-2 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-xs bg-primary-button-bg shadow-sm"+ className={cn(+ 'absolute top-1/2 left-0 z-10 flex h-4 w-2 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-xs shadow-sm transition-colors',+ 'bg-secondary-button-bg text-text-secondary',+ 'group-hover/resizer:bg-primary-button-bg group-hover/resizer:text-primary-button-text',+ 'group-active/resizer:bg-primary-button-bg group-active/resizer:text-primary-button-text',+ 'group-focus-visible/resizer:bg-primary-button-bg group-focus-visible/resizer:text-primary-button-text',+ )}>- <Icon name="grip-vertical" size={10} className="text-primary-button-text" />+ <Icon name="grip-vertical" size={10} /></div></Separator>@@ -274,7 +307,7 @@ export function AgentSessions({ agentId, startTimestamp, endTimestamp, shareViewcreatedAt={detailSession?.createdAt ?? selectedEntry?.createdAt}view={shareView}onClose={clearSelectedSession}- {...(shell != null ? { onResume: handleResume, resumeLabel } : {})}+ {...resumeProps}/>{detailLoading || detailEvents === undefined ? (<div className="flex flex-1 flex-col p-4" role="status" aria-label="Loading session details">diff --git a/packages/trueforge-ui/src/atoms/agent-details/types.ts b/packages/trueforge-ui/src/atoms/agent-details/types.tsindex 7b1c0b84f..46d307640 100644--- a/packages/trueforge-ui/src/atoms/agent-details/types.ts+++ b/packages/trueforge-ui/src/atoms/agent-details/types.ts@@ -40,7 +40,12 @@ export type AgentSessionDetailHeaderProps = {createdAt?: string;view?: 'sessions' | null;onClose: () => void;- /** When set, shows Resume Chat / Resume Agent building. */+ /**+ * When set with `resumeLabel`, shows Resume Chat / Resume Agent building as a+ * new-tab link (session deep link). Preferred over `onResume` when both are set.+ */+ resumeHref?: string;+ /** In-shell resume fallback when no session deep link is available. */onResume?: () => void;/** Label for the resume action. */resumeLabel?: string;@@ -49,6 +54,9 @@ export type AgentSessionDetailHeaderProps = {export type AgentSessionTurnHeaderProps = {turnNumber: number;totalTokens?: number;+ inputTokens?: number;+ outputTokens?: number;+ cachedTokens?: number;durationMs?: number;totalCostInUsd?: number;};diff --git a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsxindex 20fdf47a2..78554080e 100644--- a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx+++ b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx@@ -81,6 +81,7 @@ export function reconcileDraftSandbox({/*** Mirrors plain-draft composer choices into the shell seed and removes catalog* entries that disappeared since those choices were stored.+ * New Chat and New Agent keep separate seeds; chat never persists runtime config.*/export function DraftSpecPreferenceBridge() {const { mode, pendingSessionId, rememberDraftSpec } = useShellMode();@@ -90,6 +91,7 @@ export function DraftSpecPreferenceBridge() {const sandboxEnabled = capabilities?.sandbox.enabled;const { models, skills, connectors, loaded, error, ensureLoaded } = useDraftCatalog();const isPlainDraft = mode.status === 'active' && mode.isMutable && mode.agentId == null && pendingSessionId == null;+ const preferenceKind = mode.status === 'active' && mode.isMutable && mode.isCreateAgent ? 'agent' : 'chat';useEffect(() => {if (isPlainDraft) ensureLoaded();@@ -97,17 +99,18 @@ export function DraftSpecPreferenceBridge() {useEffect(() => {if (isPlainDraft && agentSpec != null) {- rememberDraftSpec(agentSpec);+ rememberDraftSpec(agentSpec, preferenceKind);}- }, [agentSpec, isPlainDraft, rememberDraftSpec]);+ }, [agentSpec, isPlainDraft, preferenceKind, rememberDraftSpec]);useEffect(() => {- if (!isPlainDraft || agentSpec == null || updateAgentSpec == null) return;+ // Sandbox / runtime config belongs to New Agent only.+ if (!isPlainDraft || preferenceKind !== 'agent' || agentSpec == null || updateAgentSpec == null) return;const update = reconcileDraftSandbox({ agentSpec, sandboxEnabled });if (Object.keys(update).length > 0) {updateAgentSpec(update);}- }, [agentSpec, isPlainDraft, sandboxEnabled, updateAgentSpec]);+ }, [agentSpec, isPlainDraft, preferenceKind, sandboxEnabled, updateAgentSpec]);useEffect(() => {if (!isPlainDraft || agentSpec == null || updateAgentSpec == null || !loaded || error != null) return;diff --git a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsxindex c26569c85..71ef54145 100644--- a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx+++ b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx@@ -163,8 +163,9 @@ export function DropdownMenuItem({ className, ...props }: DropdownMenuItemProps)type="button"className={cn('flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none',+ // focus-visible only: open-menu auto-focus must not look like a stuck hover/selected row.'transition-colors hover:bg-ghost-button-hover',- 'focus:bg-dropdown-selected-item-bg focus:text-dropdown-selected-item-text',+ 'focus-visible:bg-dropdown-selected-item-bg focus-visible:text-dropdown-selected-item-text','aria-selected:bg-dropdown-selected-item-bg aria-selected:text-dropdown-selected-item-text','disabled:pointer-events-none disabled:opacity-50',className,diff --git a/packages/trueforge-ui/src/atoms/primitives/Table.tsx b/packages/trueforge-ui/src/atoms/primitives/Table.tsxindex 6b5a76877..85337a38d 100644--- a/packages/trueforge-ui/src/atoms/primitives/Table.tsx+++ b/packages/trueforge-ui/src/atoms/primitives/Table.tsx@@ -18,7 +18,7 @@ export type TableProps = React.HTMLAttributes<HTMLTableElement> & {export function Table({ className, containerClassName, ...props }: TableProps) {return (<div className={cn('w-full overflow-x-auto', containerClassName)}>- <table className={cn('w-full min-w-full border-collapse text-sm', className)} {...props} />+ <table className={cn('w-full min-w-full border-collapse bg-primary-bg text-sm', className)} {...props} /></div>);}diff --git a/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsxindex 575f48359..50138ad27 100644--- a/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx+++ b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx@@ -8,6 +8,7 @@ import { useScheduleServer, useServer } from '../../server/ServerContext.js';import { libraryAgentId } from '../../server/ShellModeContext.js';import type { Schedule, ScheduleRun, ScheduleStatus } from '../../server/types.js';import { readScheduleShareSearch, replaceScheduleShareSearch } from '../../utils/scheduleShareUrl.js';+import { EmptyScreen } from '../EmptyScreen.js';import { auiButtonClass } from '../lib/buttonClasses.js';import { cn } from '../lib/cn.js';import { searchAllAgents } from '../lib/useSearchAgentsList.js';@@ -399,72 +400,85 @@ export function SchedulesPage() {) : error != null ? (<p className="text-failure-bg px-3 py-8 text-center text-sm">{error}</p>) : schedules.length === 0 ? (- <div className="bg-secondary-bg/50 text-text-secondary flex items-center justify-center rounded-lg border border-border px-4 py-16 text-sm">- No schedules yet. Create one to get started.+ <EmptyScreen title="No Schedules Found" description="Create one to get started." className="min-h-full" />+ ) : filtered.length === 0 ? (+ <div className="flex min-h-full flex-col">+ <EmptyScreen title="No Schedules Found" description="No schedules match your filters." className="flex-1" />+ {hasPageNav ? (+ <TableTokenPagination+ pageSize={pageSize}+ rowCount={0}+ canPrev={prevTokenStack.length > 0}+ canNext={nextPageToken != null}+ onPrev={goPrev}+ onNext={goNext}+ pageSizeOptions={SCHEDULES_PAGE_SIZE_OPTIONS}+ onPageSizeChange={size => {+ const next = clampPageSize(size);+ setPageSize(next);+ setPageToken(undefined);+ setPrevTokenStack([]);+ }}+ />+ ) : null}</div>) : (<div className="rounded-lg border border-border">- {filtered.length === 0 ? (- <div className="bg-secondary-bg/50 text-text-secondary flex items-center justify-center px-4 py-16 text-sm">- No schedules match your filters.- </div>- ) : (- <Table className="min-w-[48rem]">- <TableHeader>- <TableRow className="hover:bg-transparent">- <TableHead>Name</TableHead>- <TableHead>Agent</TableHead>- <TableHead>Cadence</TableHead>- <TableHead>Status</TableHead>- <TableHead>Last 5 runs</TableHead>- <TableHead>- <span className="sr-only">Actions</span>- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {filtered.map(schedule => {- const cadence = formatCadenceSummary({ cron: schedule.cron, timezone: schedule.timezone });- const agentLabel = schedule.agentName ?? agentNameById.get(schedule.agentId) ?? schedule.agentId;- return (- <TableRow key={schedule.id}>- <TableCell className="text-text-primary font-medium">- <button- type="button"- className="text-primary-button-bg hover:underline text-left"- onClick={() => setDrawer({ kind: 'edit', schedule })}- >- {schedule.name}- </button>- </TableCell>- <TableCell>{agentLabel}</TableCell>- <TableCell>{cadence}</TableCell>- <TableCell>- <ScheduleStatusBadge status={schedule.status} />- </TableCell>- <TableCell>- {runsLoading ? (- <span className="text-text-secondary text-sm">…</span>- ) : (- <ScheduleLastRunsCell runs={runsByScheduleId[schedule.id] ?? []} />- )}- </TableCell>- <TableCell className="text-right">- <ScheduleRowActions- schedule={schedule}- running={runningScheduleIds.has(schedule.id)}- onRunNow={() => void handleRunNow(schedule)}- onEdit={() => setDrawer({ kind: 'edit', schedule })}- onTogglePause={() => void handleTogglePause(schedule)}- onDelete={() => setPendingDelete(schedule)}- />- </TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- )}+ <Table className="min-w-[48rem]">+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ <TableHead>Name</TableHead>+ <TableHead>Agent</TableHead>+ <TableHead>Cadence</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Last 5 runs</TableHead>+ <TableHead>+ <span className="sr-only">Actions</span>+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {filtered.map(schedule => {+ const cadence = formatCadenceSummary({ cron: schedule.cron, timezone: schedule.timezone });+ const agentLabel = schedule.agentName ?? agentNameById.get(schedule.agentId) ?? schedule.agentId;+ return (+ <TableRow key={schedule.id}>+ <TableCell className="text-text-primary font-medium">+ <button+ type="button"+ className="text-primary-button-bg hover:underline text-left"+ onClick={() => setDrawer({ kind: 'edit', schedule })}+ >+ {schedule.name}+ </button>+ </TableCell>+ <TableCell>{agentLabel}</TableCell>+ <TableCell>{cadence}</TableCell>+ <TableCell>+ <ScheduleStatusBadge status={schedule.status} />+ </TableCell>+ <TableCell>+ {runsLoading ? (+ <span className="text-text-secondary text-sm">…</span>+ ) : (+ <ScheduleLastRunsCell runs={runsByScheduleId[schedule.id] ?? []} />+ )}+ </TableCell>+ <TableCell className="text-right">+ <ScheduleRowActions+ schedule={schedule}+ running={runningScheduleIds.has(schedule.id)}+ onRunNow={() => void handleRunNow(schedule)}+ onEdit={() => setDrawer({ kind: 'edit', schedule })}+ onTogglePause={() => void handleTogglePause(schedule)}+ onDelete={() => setPendingDelete(schedule)}+ />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>{(filtered.length > 0 || hasPageNav) && (<TableTokenPaginationpageSize={pageSize}diff --git a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsxindex 8b5563019..c95e407f2 100644--- a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx+++ b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx@@ -225,6 +225,9 @@ function SessionTurnSection({AgentSessionTurnHeader: ComponentType<{turnNumber: number;totalTokens?: number;+ inputTokens?: number;+ outputTokens?: number;+ cachedTokens?: number;durationMs?: number;totalCostInUsd?: number;}>;@@ -240,6 +243,9 @@ function SessionTurnSection({<AgentSessionTurnHeaderturnNumber={turn.turnNumber}totalTokens={turn.totalTokens}+ inputTokens={turn.inputTokens}+ outputTokens={turn.outputTokens}+ cachedTokens={turn.cachedTokens}durationMs={turn.durationMs}totalCostInUsd={turn.totalCostInUsd}/>diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsxindex e543bf523..4c1e86043 100644--- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx@@ -10,6 +10,7 @@ import { IS_CREATE_AGENT_METADATA_KEY, isCreateAgentMetadataValue } from '../atoimport { Spinner } from '../atoms/primitives/Spinner.js';import { LibrarySessionShareBoot } from '../routing/LibrarySessionShareBoot.js';import { RemoteIdRouteBridge } from '../routing/RemoteIdRouteBridge.js';+import { ResolvedRoutesProvider } from '../routing/ResolvedRoutesContext.js';import type { ResolvedRoutes, RoutesConfig } from '../routing/types.js';import { CustomActionRenderersProvider, type CustomActionRenderers } from '../server/CustomActionRenderersContext.js';import { ServerProvider } from '../server/ServerContext.js';@@ -274,30 +275,38 @@ export function TrueForgeUIShell(props: TrueForgeUIShellProps) {const server = resolved.server;const layoutTree = <LayoutChildren layout={layout} className={className} />;+ const shellTree = (+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ <LibrarySessionShareBoot />+ {resolvedRoutes != null ? (+ <Suspense fallback={null}>+ <ShellRouteSync+ routes={resolvedRoutes}+ activeRemoteId={activeRemoteId}+ initialSettingsOpen={initialSettingsOpen}+ />+ </Suspense>+ ) : null}+ <ChatProviderFromShell+ server={server}+ onError={onError}+ onRemoteIdChange={resolvedRoutes != null ? handleRemoteIdChange : undefined}+ {...providerRest}+ >+ {layoutTree}+ </ChatProviderFromShell>+ </ShellModeProvider>+ );+return (<SlotsProvider overrides={overrides} theme={theme}><CustomActionRenderersProvider renderers={customActionRenderers}><ServerProvider server={server}>- <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>- <LibrarySessionShareBoot />- {resolvedRoutes != null ? (- <Suspense fallback={null}>- <ShellRouteSync- routes={resolvedRoutes}- activeRemoteId={activeRemoteId}- initialSettingsOpen={initialSettingsOpen}- />- </Suspense>- ) : null}- <ChatProviderFromShell- server={server}- onError={onError}- onRemoteIdChange={resolvedRoutes != null ? handleRemoteIdChange : undefined}- {...providerRest}- >- {layoutTree}- </ChatProviderFromShell>- </ShellModeProvider>+ {resolvedRoutes != null ? (+ <ResolvedRoutesProvider routes={resolvedRoutes}>{shellTree}</ResolvedRoutesProvider>+ ) : (+ shellTree+ )}</ServerProvider></CustomActionRenderersProvider></SlotsProvider>diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsxindex 7a33e253a..43b6669da 100644--- a/packages/trueforge-ui/src/icons/IconRegistry.tsx+++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx@@ -23,6 +23,7 @@ import {Cpu,Download,Ellipsis,+ EllipsisVertical,ExternalLink,File,Github,@@ -58,6 +59,7 @@ import {Settings,SlidersHorizontal,Sparkle,+ SquareArrowOutUpRight,SquarePen,Sun,Terminal,@@ -133,6 +135,7 @@ const defaults: Record<string, IconEntry> = {'rotate-right': RotateCw,broom: Broom,ellipsis: Ellipsis,+ 'ellipsis-vertical': EllipsisVertical,trash: Trash2,'box-archive': Archive,'clock-rotate-left': History,@@ -188,6 +191,7 @@ const defaults: Record<string, IconEntry> = {'expand-alt': Maximize2,compress: Minimize2,'external-link': ExternalLink,+ 'square-arrow-out-up-right': SquareArrowOutUpRight,github: Github,};diff --git a/packages/trueforge-ui/src/icons/empty.svg b/packages/trueforge-ui/src/icons/empty.svgnew file mode 100644index 000000000..f1a89c1ab--- /dev/null+++ b/packages/trueforge-ui/src/icons/empty.svg@@ -0,0 +1 @@+<svg width='22' height='25' viewBox='0 0 22 25' fill='none' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' clip-rule='evenodd' d='M10.4824 12.432L21.0265 6.20004L10.5441 0L0 6.20004L10.4824 12.432Z' fill='#ECF2F9'/><path fill-rule='evenodd' clip-rule='evenodd' d='M10.4729 11.7499L19.75 6.23584L10.5271 0.749939L1.25 6.23584L10.4729 11.7499Z' fill='#FDFEFF'/><path d='M10.5 11.7499V0.749939L19.75 6.24994L10.5 11.7499Z' fill='url(#paint0_linear_10651_178757)'/><path d='M10.5 11.7499V0.749939L1.25 6.24994L10.5 11.7499Z' fill='#0E1623'/><path fill-rule='evenodd' clip-rule='evenodd' d='M0 6.20001V18.686L10.5441 25V12.4319L0 6.20001Z' fill='#CEE0F8'/><path fill-rule='evenodd' clip-rule='evenodd' d='M21.0265 6.20001V18.686L10.4824 25V12.4319L21.0265 6.20001Z' fill='#82A0CE'/><path d='M10.4973 11.7478L4.64099 8.26706V8.95172L10.4973 12.4126L15.8148 9.27748V8.59062L10.4973 11.7478Z' fill='#ECF2F9'/><defs><linearGradient id='paint0_linear_10651_178757' x1='15.0834' y1='2.10412' x2='15.125' y2='11.7499' gradientUnits='userSpaceOnUse'><stop stop-color='#5E7BAA'/><stop offset='1' stop-color='#030407'/></linearGradient></defs></svg>\ No newline at end of filediff --git a/packages/trueforge-ui/src/icons/registerAgentIcons.ts b/packages/trueforge-ui/src/icons/registerAgentIcons.tsindex 00ed0e1ae..abbb00919 100644--- a/packages/trueforge-ui/src/icons/registerAgentIcons.ts+++ b/packages/trueforge-ui/src/icons/registerAgentIcons.ts@@ -6,6 +6,7 @@ import Agent2Icon from './agent-2.svg';import AiIcon from './ai.svg';import BrainRegularIcon from './brain-regular.svg';import CompareIcon from './compare.svg';+import EmptyIcon from './empty.svg';import McpServerIcon from './mcp-server.svg';import SearchGlobeIcon from './search-globe.svg';import TrueForgeLogomarkDarkIcon from './trueforge-logomark-dark.svg';@@ -23,6 +24,7 @@ registerIcons({ai: AiIcon as unknown as SvgIcon,searchGlobe: SearchGlobeIcon as unknown as SvgIcon,'brain-regular': BrainRegularIcon as unknown as SvgIcon,+ empty: EmptyIcon as unknown as SvgIcon,'trueforge-logomark-light': TrueForgeLogomarkLightIcon as unknown as SvgIcon,'trueforge-logomark-dark': TrueForgeLogomarkDarkIcon as unknown as SvgIcon,});diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.tsindex ffa076696..996f56e51 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts@@ -119,5 +119,12 @@ export function createHarnessBuilderServer(const created = await client.agents.create({ name: agentName, manifest });return { agentId: created.data.id };},++ async deleteAgent({ agentName }) {+ const { data } = await client.agents.list();+ const existing = data.find(agent => agent.name === agentName);+ if (!existing) return;+ await client.agents.delete(existing.id);+ },};}diff --git a/packages/trueforge-ui/src/routing/ResolvedRoutesContext.tsx b/packages/trueforge-ui/src/routing/ResolvedRoutesContext.tsxnew file mode 100644index 000000000..d2a7f6d26--- /dev/null+++ b/packages/trueforge-ui/src/routing/ResolvedRoutesContext.tsx@@ -0,0 +1,16 @@+'use client';++import { createContext, useContext, type ReactNode } from 'react';++import type { ResolvedRoutes } from './types.js';++const ResolvedRoutesContext = createContext<ResolvedRoutes | null>(null);++/** Present only when the shell is mounted under `withRouter`. */+export function ResolvedRoutesProvider({ routes, children }: { routes: ResolvedRoutes; children: ReactNode }) {+ return <ResolvedRoutesContext.Provider value={routes}>{children}</ResolvedRoutesContext.Provider>;+}++export function useOptionalResolvedRoutes(): ResolvedRoutes | null {+ return useContext(ResolvedRoutesContext);+}diff --git a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx b/packages/trueforge-ui/src/routing/ShellRouteSync.tsxindex 56492b367..512019367 100644--- a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx+++ b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx@@ -1,11 +1,12 @@'use client';-import { useCallback, useEffect, useRef } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';import { useLocation, useNavigate } from 'react-router-dom';import { sessionIsCreateAgent } from '../atoms/lib/sessionCreateAgent.js';-import { useOptionalServer } from '../server/ServerContext.js';+import { useOptionalCatalogServer, useOptionalServer, useServerCapabilities } from '../server/ServerContext.js';import { useShellMode } from '../server/ShellModeContext.js';+import { isSettingsChromeEnabled } from '../server/settingsChrome.js';import { deriveChatPlace, derivePlace } from './derivePlace.js';import { buildPath, matchLocation, placesEqual, sanitizeSearchForPlace } from './paths.js';import type { ResolvedRoutes, RoutePlace, ShellSnapshot } from './types.js';@@ -25,8 +26,17 @@ export function ShellRouteSync({}) {const shell = useShellMode();const server = useOptionalServer();+ const catalog = useOptionalCatalogServer();+ const capabilities = useServerCapabilities();const navigate = useNavigate();const location = useLocation();+ // Same gate as the Settings sidebar button: no catalog / settings capability+ // off → `/settings` is unregistered (match + build return null).+ const settingsChromeEnabled = isSettingsChromeEnabled({ catalog, capabilities });+ const effectiveRoutes = useMemo(+ () => (settingsChromeEnabled ? routes : { ...routes, settings: null }),+ [routes, settingsChromeEnabled],+ );const snapshot: ShellSnapshot = {settingsOpen: shell.settingsOpen,@@ -144,12 +154,12 @@ export function ShellRouteSync({const urlPlace = matchLocation({pathname: location.pathname,search: location.search,- routes,+ routes: effectiveRoutes,}) ?? { type: 'root' };- const settingsOnBoot = initialSettingsOpen || urlPlace.type === 'settings';+ const settingsOnBoot = settingsChromeEnabled && (initialSettingsOpen || urlPlace.type === 'settings');if (urlPlace.type === 'settings') {- shell.setSettingsOpen(true);+ if (settingsChromeEnabled) shell.setSettingsOpen(true);} else if (urlPlace.type === 'library') {shell.setLibraryOpen(true);} else if (urlPlace.type === 'sessionsBrowser') {@@ -161,11 +171,11 @@ export function ShellRouteSync({} else {const chatPlace = deriveChatPlace(snapshot);if (!placesEqual(chatPlace, urlPlace)) applyPlace(urlPlace);- if (initialSettingsOpen) shell.setSettingsOpen(true);+ if (settingsOnBoot) shell.setSettingsOpen(true);}const desiredPlace: RoutePlace = settingsOnBoot ? { type: 'settings' } : urlPlace;- const desiredPath = buildPath(desiredPlace, routes);+ const desiredPath = buildPath(desiredPlace, effectiveRoutes);const desiredSearch = sanitizeSearchForPlace(desiredPlace, location.search);prevPlaceRef.current = desiredPlace;if (desiredPath != null && (desiredPath !== location.pathname || desiredSearch !== location.search)) {@@ -183,9 +193,11 @@ export function ShellRouteSync({shellSyncStartedRef.current = true;return;}- const target = buildPath(place, routes);+ const target = buildPath(place, effectiveRoutes);if (target == null) return; // place has no configured URL (e.g. settings disabled)- const basename = routes.basename.endsWith('/') ? routes.basename.slice(0, -1) : routes.basename;+ const basename = effectiveRoutes.basename.endsWith('/')+ ? effectiveRoutes.basename.slice(0, -1)+ : effectiveRoutes.basename;const browserPathname = `${basename}${location.pathname}` || '/';const latestSearch = window.location.pathname === browserPathname ? window.location.search : location.search;const targetSearch = sanitizeSearchForPlace(place, latestSearch);@@ -204,7 +216,7 @@ export function ShellRouteSync({navigate({ pathname: target, search: targetSearch, hash: location.hash }, { replace });// location.pathname intentionally excluded: only react to shell-derived place changes.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [placeKey]);+ }, [placeKey, settingsChromeEnabled]);// URL -> shell: apply on genuine location changes (Back/Forward, manual edits).useEffect(() => {@@ -220,11 +232,11 @@ export function ShellRouteSync({const urlPlace = matchLocation({pathname: location.pathname,search: location.search,- routes,+ routes: effectiveRoutes,});if (urlPlace == null) {// Unknown path: normalize to root.- const rootPath = routes.root;+ const rootPath = effectiveRoutes.root;const rootSearch = sanitizeSearchForPlace({ type: 'root' }, location.search);selfNavPathRef.current = rootPath;navigate({ pathname: rootPath, search: rootSearch, hash: location.hash }, { replace: true });diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.tsindex 1daee3c34..cf1336d84 100644--- a/packages/trueforge-ui/src/routing/paths.ts+++ b/packages/trueforge-ui/src/routing/paths.ts@@ -76,6 +76,29 @@ export function buildPath(place: RoutePlace, routes: ResolvedRoutes): string | n}}+/**+ * Absolute href that boots the shell on a history session (`/sessions/:id`).+ * Includes `routes.basename` and clears place-owned share query keys.+ */+export function buildSessionResumeHref({+ sessionId,+ routes,+ href = typeof window === 'undefined' ? 'http://localhost/' : window.location.href,+}: {+ sessionId: string;+ routes: ResolvedRoutes;+ href?: string;+}): string | null {+ const sessionPath = buildPath({ type: 'session', sessionId }, routes);+ if (sessionPath == null) return null;+ const url = new URL(href);+ const basename = routes.basename.endsWith('/') ? routes.basename.slice(0, -1) : routes.basename;+ url.pathname = `${basename}${sessionPath}` || '/';+ url.search = sanitizeSearchForPlace({ type: 'session', sessionId }, url.search);+ url.hash = '';+ return url.toString();+}+/*** Remove query state owned by a different shell place while preserving host* parameters. Settings is an overlay, so it retains the underlying place state.diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsxindex 3e348cd58..6a777ef4b 100644--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx@@ -8,12 +8,15 @@ import {selectDraftSpecPreferences,withCapabilitiesSandbox,writeDraftSpecPreferences,+ type DraftPreferenceKind,} from './draftSpecPreferences.js';import {+ useOptionalCatalogServer,useOptionalRefreshServerCapabilities,useOptionalScheduleServer,useServerCapabilities,} from './ServerContext.js';+import { isSettingsChromeEnabled } from './settingsChrome.js';import type { AgentLibraryEntry, AgentSpec } from './types.js';/** Host-facing shell configuration for agent / library / composer chrome. */@@ -107,8 +110,8 @@ type ShellModeContextValue = {openDraft: () => void;/** Open New Agent builder (mutable + Agent Config drawer). */openAgentBuilder: () => void;- /** Remember plain-draft composer choices as the seed for future new chats. */- rememberDraftSpec: (agentSpec: AgentSpec) => void;+ /** Remember plain-draft composer choices as the seed for future New Chat / New Agent. */+ rememberDraftSpec: (agentSpec: AgentSpec, kind?: DraftPreferenceKind) => void;/*** Open a history session, remounting when mutability/identity changes.* Prefer explicit `isMutable` from the session row; when omitted, agentName@@ -204,25 +207,22 @@ export function ShellModeProvider({children: ReactNode;}) {const capabilities = useServerCapabilities();+ const catalog = useOptionalCatalogServer();const refreshCapabilities = useOptionalRefreshServerCapabilities();const scheduleServer = useOptionalScheduleServer();- const rememberedSpecRef = useRef<AgentSpec | null>(readDraftSpecPreferences());- const mutableSeedRef = useRef(rememberedSpecRef.current ?? mutableSeedFromConfig(agentConfig));- if (- rememberedSpecRef.current == null &&- (agentConfig.mode === 'AgentComposer' || agentConfig.mode === 'AgentLibraryWithComposer') &&- agentConfig.defaultAgentSpec != null- ) {- mutableSeedRef.current = agentConfig.defaultAgentSpec;- }- const mutableSeed = mutableSeedRef.current;+ const chatSeedRef = useRef(+ readDraftSpecPreferences('chat') ?? selectDraftSpecPreferences(mutableSeedFromConfig(agentConfig), 'chat'),+ );+ const agentSeedRef = useRef(+ readDraftSpecPreferences('agent') ?? selectDraftSpecPreferences(mutableSeedFromConfig(agentConfig), 'agent'),+ );const isLibraryEnabled = agentConfig.mode === 'AgentLibrary' || agentConfig.mode === 'AgentLibraryWithComposer';const isComposerEnabled = agentConfig.mode === 'AgentComposer' || agentConfig.mode === 'AgentLibraryWithComposer';const isNewChatEnabled = agentConfig.mode !== 'AgentLibrary';const locked = agentConfig.mode === 'SingleAgent';- const [mode, setMode] = useState<ShellMode>(() => initialMode(agentConfig, mutableSeed));+ const [mode, setMode] = useState<ShellMode>(() => initialMode(agentConfig, chatSeedRef.current));const [mutableEpoch, setMutableEpoch] = useState(0);const [clearEpoch, setClearEpoch] = useState(0);const [agentsListEpoch, setAgentsListEpoch] = useState(0);@@ -235,7 +235,7 @@ export function ShellModeProvider({const [schedulesOpenState, setSchedulesOpenState] = useState(false);const [historyAgentFilter, setHistoryAgentFilter] = useState<string | null>(null);const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);- const settingsEnabled = capabilities?.settings?.enabled !== false;+ const settingsEnabled = isSettingsChromeEnabled({ catalog, capabilities });const settingsOpen = settingsEnabled && settingsOpenState;const schedulesEnabled = scheduleServer != null;const schedulesOpen = schedulesEnabled && schedulesOpenState;@@ -384,13 +384,14 @@ export function ShellModeProvider({setSchedulesOpen(false);setPendingSessionId(undefined);const isCreateAgent = resolveMutableIsCreateAgent(req);+ const kind: DraftPreferenceKind = isCreateAgent ? 'agent' : 'chat';setMode({status: 'active',isMutable: true,isCreateAgent,agentId: req.agentId,agentName: req.agentName,- agentSpec: req.agentSpec ?? mutableSeedRef.current,+ agentSpec: req.agentSpec ?? (kind === 'agent' ? agentSeedRef.current : chatSeedRef.current),locked: false,});setAgentConfigOpenState(isCreateAgent);@@ -449,22 +450,26 @@ export function ShellModeProvider({const openDraft = useCallback(() => {if (!isComposerEnabled) return;refreshCapabilities?.();- selectLibraryAgent({ isMutable: true, isCreateAgent: false, agentSpec: mutableSeedRef.current });+ selectLibraryAgent({ isMutable: true, isCreateAgent: false, agentSpec: chatSeedRef.current });}, [isComposerEnabled, refreshCapabilities, selectLibraryAgent]);const openAgentBuilder = useCallback(() => {if (!isComposerEnabled) return;refreshCapabilities?.();- selectLibraryAgent({ isMutable: true, isCreateAgent: true, agentSpec: mutableSeedRef.current });+ selectLibraryAgent({ isMutable: true, isCreateAgent: true, agentSpec: agentSeedRef.current });}, [isComposerEnabled, refreshCapabilities, selectLibraryAgent]);const sandboxEnabled = capabilities?.sandbox.enabled;const rememberDraftSpec = useCallback(- (agentSpec: AgentSpec) => {- const preferences = withCapabilitiesSandbox(selectDraftSpecPreferences(agentSpec), sandboxEnabled);- rememberedSpecRef.current = preferences;- mutableSeedRef.current = preferences;- writeDraftSpecPreferences(preferences);+ (agentSpec: AgentSpec, kind: DraftPreferenceKind = 'chat') => {+ const selected = selectDraftSpecPreferences(agentSpec, kind);+ const preferences = kind === 'agent' ? withCapabilitiesSandbox(selected, sandboxEnabled) : selected;+ if (kind === 'chat') {+ chatSeedRef.current = preferences;+ } else {+ agentSeedRef.current = preferences;+ }+ writeDraftSpecPreferences(kind, preferences);},[sandboxEnabled],);@@ -495,7 +500,7 @@ export function ShellModeProvider({status: 'active',isMutable: true,isCreateAgent,- agentSpec: mutableSeedRef.current,+ agentSpec: isCreateAgent ? agentSeedRef.current : chatSeedRef.current,locked: false,});setAgentConfigOpenState(isCreateAgent);@@ -535,13 +540,14 @@ export function ShellModeProvider({setPendingSessionId(undefined);if (effectiveMode.isMutable) {// Preserve Edit / builder vs chat intent; blank drafts fall back to host seed.+ const kind: DraftPreferenceKind = effectiveMode.isCreateAgent ? 'agent' : 'chat';setMode({status: 'active',isMutable: true,isCreateAgent: effectiveMode.isCreateAgent,agentId: effectiveMode.agentId,agentName: effectiveMode.agentName,- agentSpec: effectiveMode.agentSpec ?? mutableSeedRef.current,+ agentSpec: effectiveMode.agentSpec ?? (kind === 'agent' ? agentSeedRef.current : chatSeedRef.current),locked: false,});setAgentConfigOpenState(effectiveMode.isCreateAgent);diff --git a/packages/trueforge-ui/src/server/draftSpecPreferences.ts b/packages/trueforge-ui/src/server/draftSpecPreferences.tsindex 8af70ab32..91ef4cfa3 100644--- a/packages/trueforge-ui/src/server/draftSpecPreferences.ts+++ b/packages/trueforge-ui/src/server/draftSpecPreferences.ts@@ -1,6 +1,11 @@import type { AgentSpec } from './types.js';+/** @deprecated Migrated into chat/agent keys on first read. */export const DRAFT_SPEC_PREFERENCES_STORAGE_KEY = 'tfy-aui-draft-spec-preferences';+export const CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY = 'tfy-aui-chat-draft-spec-preferences';+export const AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY = 'tfy-aui-agent-draft-spec-preferences';++export type DraftPreferenceKind = 'chat' | 'agent';type StoredDraftSpecPreferences = {version: 1;@@ -37,16 +42,31 @@ function isStoredDraftSpecPreferences(value: unknown): value is StoredDraftSpecPreturn isObject(value) && Reflect.get(value, 'version') === 1 && isAgentSpec(Reflect.get(value, 'spec'));}-/** Keep only composer choices that should seed future new chats. */-export function selectDraftSpecPreferences(spec: AgentSpec): AgentSpec {+function storageKeyForKind(kind: DraftPreferenceKind): string {+ return kind === 'chat' ? CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY : AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY;+}++/** New Chat: model (+ reasoning params), skills, and MCP only — no runtime config. */+export function selectChatDraftSpecPreferences(spec: AgentSpec): AgentSpec {return {model: spec.model,...(spec.skills !== undefined ? { skills: spec.skills } : {}),...(spec.mcpServers !== undefined ? { mcpServers: spec.mcpServers } : {}),+ };+}++/** New Agent: full composer seed including runtime config (sandbox, ask-user, …). */+export function selectAgentDraftSpecPreferences(spec: AgentSpec): AgentSpec {+ return {+ ...selectChatDraftSpecPreferences(spec),...(spec.config !== undefined ? { config: spec.config } : {}),};}+export function selectDraftSpecPreferences(spec: AgentSpec, kind: DraftPreferenceKind): AgentSpec {+ return kind === 'chat' ? selectChatDraftSpecPreferences(spec) : selectAgentDraftSpecPreferences(spec);+}+function readSandboxEnabled(spec: AgentSpec): boolean | undefined {if (spec.config === undefined) return undefined;// `sandbox` is persisted on draft config but is not part of AgentRuntimeConfig.@@ -69,25 +89,57 @@ export function withCapabilitiesSandbox(spec: AgentSpec, sandboxEnabled: boolean};}-export function readDraftSpecPreferences(): AgentSpec | null {+function readStoredSpec(key: string): AgentSpec | null {if (typeof window === 'undefined') return null;try {- const stored: unknown = JSON.parse(window.localStorage.getItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY) ?? 'null');+ const stored: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null');return isStoredDraftSpecPreferences(stored) ? stored.spec : null;} catch {return null;}}-export function writeDraftSpecPreferences(spec: AgentSpec): void {- if (typeof window === 'undefined') return;+function writeStoredSpec(key: string, spec: AgentSpec): boolean {+ if (typeof window === 'undefined') return false;try {- const stored: StoredDraftSpecPreferences = {- version: 1,- spec: selectDraftSpecPreferences(spec),- };- window.localStorage.setItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY, JSON.stringify(stored));+ const stored: StoredDraftSpecPreferences = { version: 1, spec };+ window.localStorage.setItem(key, JSON.stringify(stored));+ return true;} catch {// Storage can be unavailable or full; in-memory carry-over still works.+ return false;}}++/** One-shot split of the pre-split shared key into chat + agent stores. */+function migrateLegacyDraftPreferences(): void {+ if (typeof window === 'undefined') return;+ const legacy = readStoredSpec(DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ if (legacy == null) return;++ const chatReady =+ readStoredSpec(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY) != null ||+ writeStoredSpec(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY, selectChatDraftSpecPreferences(legacy));+ const agentReady =+ readStoredSpec(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY) != null ||+ writeStoredSpec(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY, selectAgentDraftSpecPreferences(legacy));++ // Keep the legacy key if either destination write failed so a later read can retry.+ if (!chatReady || !agentReady) return;++ try {+ window.localStorage.removeItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ } catch {+ // Ignore quota / private-mode failures; next read still prefers kind keys.+ }+}++export function readDraftSpecPreferences(kind: DraftPreferenceKind): AgentSpec | null {+ migrateLegacyDraftPreferences();+ const stored = readStoredSpec(storageKeyForKind(kind));+ return stored == null ? null : selectDraftSpecPreferences(stored, kind);+}++export function writeDraftSpecPreferences(kind: DraftPreferenceKind, spec: AgentSpec): void {+ writeStoredSpec(storageKeyForKind(kind), selectDraftSpecPreferences(spec, kind));+}diff --git a/packages/trueforge-ui/src/server/settingsChrome.ts b/packages/trueforge-ui/src/server/settingsChrome.tsnew file mode 100644index 000000000..7781184aa--- /dev/null+++ b/packages/trueforge-ui/src/server/settingsChrome.ts@@ -0,0 +1,15 @@+import type { CatalogServer } from './types.js';++/**+ * Whether Settings chrome is available: sidebar button and `/settings` route.+ * Matches the gate in {@link ShellActions}.+ */+export function isSettingsChromeEnabled({+ catalog,+ capabilities,+}: {+ catalog: CatalogServer | null | undefined;+ capabilities: { settings?: { enabled?: boolean } } | null | undefined;+}): boolean {+ return catalog != null && capabilities?.settings?.enabled !== false;+}diff --git a/packages/trueforge-ui/src/utils/buildSessionMetrics.ts b/packages/trueforge-ui/src/utils/buildSessionMetrics.tsindex 6e9969516..e777120ff 100644--- a/packages/trueforge-ui/src/utils/buildSessionMetrics.ts+++ b/packages/trueforge-ui/src/utils/buildSessionMetrics.ts@@ -1,5 +1,4 @@import { getSessionEventColor, type SessionEventTimelineSegment } from './sessionEventTimeline.js';-import { isRecord } from './sessionTimelineEvents.js';import type { SessionTurnView } from './sessionTurnViews.js';export type SessionMetricBarDatum = {@@ -30,33 +29,6 @@ export type SessionListMetricsHint = {totalDurationMs: number;};-function readNumber(record: Record<string, unknown>, camel: string, snake: string): number {- const camelValue = record[camel];- if (typeof camelValue === 'number' && Number.isFinite(camelValue)) return camelValue;- const snakeValue = record[snake];- return typeof snakeValue === 'number' && Number.isFinite(snakeValue) ? snakeValue : 0;-}--function readOptionalNumber({- record,- camel,- snake,-}: {- record: Record<string, unknown>;- camel: string;- snake: string;-}): number | undefined {- const camelValue = record[camel];- if (typeof camelValue === 'number' && Number.isFinite(camelValue)) return camelValue;- const snakeValue = record[snake];- return typeof snakeValue === 'number' && Number.isFinite(snakeValue) ? snakeValue : undefined;-}--function metricsRecord(state: unknown): Record<string, unknown> | undefined {- if (!isRecord(state)) return undefined;- return isRecord(state.metrics) ? state.metrics : undefined;-}-function segmentDurationMs(segment: SessionEventTimelineSegment): number {return Math.max(0, segment.endMs - segment.startMs);}@@ -65,6 +37,16 @@ function hintHasValues(hint?: SessionListMetricsHint): boolean {return hint != null && (hint.totalTurns > 0 || hint.totalCostInUsd != null || hint.totalDurationMs > 0);}+function turnHasMetrics(turn: SessionTurnView): boolean {+ return (+ turn.totalTokens != null ||+ turn.inputTokens != null ||+ turn.outputTokens != null ||+ turn.cachedTokens != null ||+ turn.totalCostInUsd != null+ );+}+export function buildSessionMetrics({turns,segments,@@ -88,25 +70,18 @@ export function buildSessionMetrics({for (const turn of turns) {const label = `T${turn.turnNumber}`;derivedWallTimeMs += turn.durationMs ?? 0;- const metrics = metricsRecord(turn.done?.state);- if (metrics == null) {+ if (!turnHasMetrics(turn)) {costPerTurn.push({ label, value: 0, color: getSessionEventColor('tool_call') });contextByTurn.push({ label, value: contextTokens, color: getSessionEventColor('model') });continue;}- const inputTokens = readNumber(metrics, 'totalInputTokens', 'total_input_tokens');- const outputTokens = readNumber(metrics, 'totalOutputTokens', 'total_output_tokens');- const cachedTokens =- readNumber(metrics, 'totalCacheReadTokens', 'total_cache_read_tokens') +- readNumber(metrics, 'totalCacheWriteTokens', 'total_cache_write_tokens');- const uncachedInputTokens = Math.max(0, inputTokens - cachedTokens);- const turnTotalTokens = readNumber(metrics, 'totalTokens', 'total_tokens') || inputTokens + outputTokens;- const turnCostUsd = readOptionalNumber({- record: metrics,- camel: 'totalCostInUsd',- snake: 'total_cost_in_usd',- });+ // Prefer canonical turn fields from sessionTurnViews (uncached input already).+ const uncachedInputTokens = turn.inputTokens ?? 0;+ const outputTokens = turn.outputTokens ?? 0;+ const cachedTokens = turn.cachedTokens ?? 0;+ const turnTotalTokens = turn.totalTokens ?? uncachedInputTokens + cachedTokens + outputTokens;+ const turnCostUsd = turn.totalCostInUsd;if (turnCostUsd != null) {derivedCostUsd += turnCostUsd;diff --git a/packages/trueforge-ui/src/utils/scheduleShareUrl.ts b/packages/trueforge-ui/src/utils/scheduleShareUrl.tsindex 333f6a4c6..dafe04d82 100644--- a/packages/trueforge-ui/src/utils/scheduleShareUrl.ts+++ b/packages/trueforge-ui/src/utils/scheduleShareUrl.ts@@ -1,4 +1,5 @@import type { ScheduleStatus } from '../server/types.js';+import { writeSessionShareSearch } from './sessionShareUrl.js';export const SCHEDULE_AGENT_QUERY = 'agent';export const SCHEDULE_STATUS_QUERY = 'status';@@ -70,3 +71,25 @@ export function replaceScheduleShareSearch(next: ScheduleShareWrite): string {window.dispatchEvent(new Event(SCHEDULE_SHARE_CHANGE_EVENT));return url.search;}++/**+ * Point the address bar at schedules filtered to `agentId` (clears library agent+ * share keys). Caller still opens the schedules place via shell.+ */+export function writeOpenSchedulesForAgentSearch({ agentId, isNew }: { agentId: string; isNew?: boolean }): void {+ const url = new URL(window.location.href);+ writeSessionShareSearch(url.searchParams, {+ sessionId: null,+ agentId: null,+ tab: null,+ view: null,+ timeRange: null,+ });+ writeScheduleShareSearch(url.searchParams, {+ agent: agentId,+ status: null,+ q: null,+ isNew: isNew === true ? true : null,+ });+ window.history.replaceState(window.history.state, '', url);+}diff --git a/packages/trueforge-ui/src/utils/sessionTurnViews.ts b/packages/trueforge-ui/src/utils/sessionTurnViews.tsindex c96d5a03b..5602cbe0b 100644--- a/packages/trueforge-ui/src/utils/sessionTurnViews.ts+++ b/packages/trueforge-ui/src/utils/sessionTurnViews.ts@@ -12,6 +12,9 @@ export type SessionTurnView = {done?: TurnDoneEvent;events: TurnEvent[];totalTokens?: number;+ inputTokens?: number;+ outputTokens?: number;+ cachedTokens?: number;totalCostInUsd?: number;durationMs?: number;};@@ -39,8 +42,18 @@ function isRenderableTurn(created: TurnCreatedEvent): boolean {});}+function readMetricNumber(metrics: object, camel: string, snake: string): number | undefined {+ const camelValue = Reflect.get(metrics, camel);+ if (typeof camelValue === 'number' && Number.isFinite(camelValue)) return camelValue;+ const snakeValue = Reflect.get(metrics, snake);+ return typeof snakeValue === 'number' && Number.isFinite(snakeValue) ? snakeValue : undefined;+}+function metricsFromTerminalState(state: unknown): {totalTokens?: number;+ inputTokens?: number;+ outputTokens?: number;+ cachedTokens?: number;totalCostInUsd?: number;} {if (typeof state !== 'object' || state == null || !('status' in state)) {@@ -54,11 +67,27 @@ function metricsFromTerminalState(state: unknown): {if (metrics == null || typeof metrics !== 'object') {return {};}- const totalTokens = Reflect.get(metrics, 'totalTokens') ?? Reflect.get(metrics, 'total_tokens');- const totalCostInUsd = Reflect.get(metrics, 'totalCostInUsd') ?? Reflect.get(metrics, 'total_cost_in_usd');+ const explicitTotal = readMetricNumber(metrics, 'totalTokens', 'total_tokens');+ const rawInputTokens = readMetricNumber(metrics, 'totalInputTokens', 'total_input_tokens');+ const outputTokens = readMetricNumber(metrics, 'totalOutputTokens', 'total_output_tokens');+ const cacheRead = readMetricNumber(metrics, 'totalCacheReadTokens', 'total_cache_read_tokens');+ const cacheWrite = readMetricNumber(metrics, 'totalCacheWriteTokens', 'total_cache_write_tokens');+ const totalCostInUsd = readMetricNumber(metrics, 'totalCostInUsd', 'total_cost_in_usd');+ const cachedTokens =+ cacheRead !== undefined || cacheWrite !== undefined ? (cacheRead ?? 0) + (cacheWrite ?? 0) : undefined;+ // Input in UI breakdowns is uncached so Input + Cached + Output does not double-count cache.+ const inputTokens = rawInputTokens !== undefined ? Math.max(0, rawInputTokens - (cachedTokens ?? 0)) : undefined;+ const totalTokens =+ explicitTotal ??+ (rawInputTokens !== undefined || outputTokens !== undefined+ ? (rawInputTokens ?? 0) + (outputTokens ?? 0)+ : undefined);return {- ...(typeof totalTokens === 'number' ? { totalTokens } : {}),- ...(typeof totalCostInUsd === 'number' ? { totalCostInUsd } : {}),+ ...(totalTokens !== undefined ? { totalTokens } : {}),+ ...(inputTokens !== undefined ? { inputTokens } : {}),+ ...(outputTokens !== undefined ? { outputTokens } : {}),+ ...(cachedTokens !== undefined ? { cachedTokens } : {}),+ ...(totalCostInUsd !== undefined ? { totalCostInUsd } : {}),};}diff --git a/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx b/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsxindex 8d89a8426..02c079568 100644--- a/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import { AgentDetailsPage } from '@/atoms/agent-details/AgentDetailsPage.js';import { AgentSessions } from '@/atoms/agent-details/AgentSessions.js';@@ -18,6 +18,16 @@ import type {import { SlotsProvider, type SlotOverrides } from '@/theme/SlotsProvider.js';import { createMockAgentUIServer } from '../server/mockServer.js';+beforeAll(() => {+ HTMLDialogElement.prototype.showModal = function showModal() {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close = function close() {+ this.removeAttribute('open');+ this.dispatchEvent(new Event('close'));+ };+});+const detail: AgentDetail = {agentId: 'agent-1',name: 'release-notes-writer',@@ -77,6 +87,7 @@ function renderPage({metrics,overrides,initialEntries = ['/library/agent-1'],+ serverOverrides,}: {getAgent?: () => Promise<AgentDetail>;getCodeSnippets?: () => Promise<CodeSnippet[]>;@@ -87,11 +98,13 @@ function renderPage({metrics?: AgentMetricsServer;overrides?: SlotOverrides;initialEntries?: string[];+ serverOverrides?: Parameters<typeof createMockAgentUIServer>[0];} = {}) {const server = createMockAgentUIServer({getSession,...(withSessions ? { sessions: { getAgent, getCodeSnippets, listSessions, listSessionEvents } } : {}),...(metrics == null ? {} : { metrics }),+ ...serverOverrides,});render(<MemoryRouter initialEntries={initialEntries}>@@ -104,7 +117,7 @@ function renderPage({</SlotsProvider></MemoryRouter>,);- return { getAgent, getCodeSnippets, listSessions, listSessionEvents, getSession };+ return { getAgent, getCodeSnippets, listSessions, listSessionEvents, getSession, server };}describe('AgentDetailsPage', () => {@@ -115,13 +128,33 @@ describe('AgentDetailsPage', () => {it('loads Overview and renders agent details', async () => {const { getAgent } = renderPage();- expect(await screen.findByRole('heading', { name: 'release-notes-writer' })).toBeInTheDocument();+ expect(await screen.findByText('release-notes-writer')).toBeInTheDocument();expect(await screen.findByText('Write concise release notes.')).toBeInTheDocument();expect(await screen.findByText('github')).toBeInTheDocument();expect(await screen.findByText('release-writing')).toBeInTheDocument();expect(getAgent).toHaveBeenCalledTimes(1);});+ it('shows overflow actions (Edit in menu, not a standalone Edit button) and deletes after confirm', async () => {+ const deleteAgent = vi.fn(async () => {});+ renderPage({ serverOverrides: { deleteAgent } });++ expect(await screen.findByRole('button', { name: 'Try agent' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Edit agent' })).not.toBeInTheDocument();++ fireEvent.click(await screen.findByRole('button', { name: 'Actions for release-notes-writer' }));+ expect(screen.getByRole('menuitem', { name: 'Edit' })).toBeInTheDocument();+ expect(screen.getByRole('menuitem', { name: 'Clone' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));++ expect(screen.getByRole('dialog', { name: 'Delete agent' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));++ await waitFor(() => {+ expect(deleteAgent).toHaveBeenCalledWith({ agentName: 'release-notes-writer' });+ });+ });+it('renders tab bodies through SlotProvider overrides', async () => {renderPage({ overrides: { AgentOverview: () => <div>Custom overview</div> } });expect(await screen.findByText('Custom overview')).toBeInTheDocument();@@ -160,7 +193,7 @@ describe('AgentDetailsPage', () => {it('loads code snippets lazily and retains them across tab changes', async () => {const { getCodeSnippets } = renderPage();- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');expect(getCodeSnippets).not.toHaveBeenCalled();fireEvent.click(screen.getByRole('tab', { name: 'Use In Code' }));@@ -176,7 +209,7 @@ describe('AgentDetailsPage', () => {it('loads the Sessions tab list scoped to the agent', async () => {const { listSessions } = renderPage();- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');fireEvent.click(screen.getByRole('tab', { name: 'Sessions' }));expect(await screen.findByText('Release notes draft')).toBeInTheDocument();expect(screen.getByText('Select a session to view details')).toBeInTheDocument();@@ -185,6 +218,18 @@ describe('AgentDetailsPage', () => {);});+ it('shows a single empty screen when the agent has no sessions', async () => {+ renderPage({+ listSessions: vi.fn(async () => ({ data: [] })),+ });+ await screen.findByText('release-notes-writer');+ fireEvent.click(screen.getByRole('tab', { name: 'Sessions' }));+ expect(await screen.findByText('No Sessions Found')).toBeInTheDocument();+ expect(screen.getByText('There are no sessions available at the moment.')).toBeInTheDocument();+ expect(screen.queryByText('Select a session to view details')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Resize session list')).not.toBeInTheDocument();+ });+it('ignores a stale list response after the agent filter changes', async () => {const first = deferred<{ data: SessionListEntry[] }>();const second = deferred<{ data: SessionListEntry[] }>();@@ -240,7 +285,7 @@ describe('AgentDetailsPage', () => {return { data: sessionRows, nextPageToken: 'next-page' };});renderPage({ listSessions });- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');fireEvent.click(screen.getByRole('tab', { name: 'Sessions' }));expect(await screen.findByText('Release notes draft')).toBeInTheDocument();@@ -293,7 +338,7 @@ describe('AgentDetailsPage', () => {'/?agentId=agent-1&tab=sessions&sessionId=sess-1&view=sessions&s_tw=2592000000',);renderPage({ initialEntries: ['/?agentId=agent-1&tab=sessions&sessionId=sess-1&view=sessions&s_tw=2592000000'] });- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');fireEvent.keyDown(window, { key: 'Escape' });@@ -309,7 +354,7 @@ describe('AgentDetailsPage', () => {const { getSession, listSessionEvents } = renderPage({overrides: { AgentSessionTimelineContainer: () => <div>timeline-body</div> },});- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');fireEvent.click(screen.getByRole('tab', { name: 'Sessions' }));fireEvent.click(await screen.findByText('Release notes draft'));await waitFor(() => {@@ -328,7 +373,7 @@ describe('AgentDetailsPage', () => {),},});- await screen.findByRole('heading', { name: 'release-notes-writer' });+ await screen.findByText('release-notes-writer');fireEvent.click(screen.getByRole('tab', { name: 'Sessions' }));fireEvent.click(await screen.findByText('Release notes draft'));diff --git a/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsxindex f03384a4b..026436b84 100644--- a/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx@@ -58,7 +58,23 @@ describe('AgentSessionDetailHeader', () => {});});- it('shows Resume Chat when onResume is provided', () => {+ it('shows Resume Chat as a new-tab link with an external icon', () => {+ render(+ <AgentSessionDetailHeader+ title="Help me find more details"+ sessionId="sess-1"+ onClose={() => undefined}+ resumeHref="https://app.example/sessions/sess-1"+ resumeLabel="Resume Chat"+ />,+ );+ const resume = screen.getByRole('link', { name: /Resume Chat/i });+ expect(resume).toHaveAttribute('href', 'https://app.example/sessions/sess-1');+ expect(resume).toHaveAttribute('target', '_blank');+ expect(resume).toHaveAttribute('rel', 'noopener noreferrer');+ });++ it('falls back to an in-shell Resume button when only onResume is provided', () => {const onResume = vi.fn();render(<AgentSessionDetailHeader@@ -72,4 +88,20 @@ describe('AgentSessionDetailHeader', () => {fireEvent.click(screen.getByRole('button', { name: 'Resume Chat' }));expect(onResume).toHaveBeenCalledOnce();});++ it('prefers the new-tab link when both resumeHref and onResume are set', () => {+ const onResume = vi.fn();+ render(+ <AgentSessionDetailHeader+ title="Help me find more details"+ sessionId="sess-1"+ onClose={() => undefined}+ resumeHref="https://app.example/sessions/sess-1"+ onResume={onResume}+ resumeLabel="Resume Chat"+ />,+ );+ expect(screen.getByRole('link', { name: /Resume Chat/i })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Resume Chat' })).not.toBeInTheDocument();+ });});diff --git a/packages/trueforge-ui/test/atoms/AgentSessionTurnHeader.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionTurnHeader.test.tsxnew file mode 100644index 000000000..a7f0ea596--- /dev/null+++ b/packages/trueforge-ui/test/atoms/AgentSessionTurnHeader.test.tsx@@ -0,0 +1,47 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { AgentSessionTurnHeader } from '@/atoms/agent-details/AgentSessionTurnHeader.js';++describe('AgentSessionTurnHeader', () => {+ it('shows an Input / Output / Cached tooltip on the turn token count', () => {+ render(+ <AgentSessionTurnHeader+ turnNumber={1}+ totalTokens={8063}+ inputTokens={8000}+ outputTokens={63}+ cachedTokens={0}+ durationMs={1200}+ />,+ );++ const tokens = screen.getByRole('button', { name: /Tokens 8K/i });+ fireEvent.mouseEnter(tokens);+ expect(screen.getByRole('tooltip')).toHaveTextContent('Input');+ expect(screen.getByRole('tooltip')).toHaveTextContent('8K');+ expect(screen.getByRole('tooltip')).toHaveTextContent('Output');+ expect(screen.getByRole('tooltip')).toHaveTextContent('63');+ expect(screen.getByRole('tooltip')).toHaveTextContent('Cached');+ expect(screen.getByRole('tooltip')).toHaveTextContent('0');+ });++ it('exposes the breakdown on a focusable token control', () => {+ render(+ <AgentSessionTurnHeader+ turnNumber={1}+ totalTokens={9000}+ inputTokens={7000}+ outputTokens={1000}+ cachedTokens={1000}+ />,+ );++ const tokens = screen.getByRole('button', {+ name: 'Tokens 9K. Input 7K, Output 1K, Cached 1K',+ });+ fireEvent.focus(tokens);+ expect(screen.getByRole('tooltip')).toBeInTheDocument();+ });+});diff --git a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsxindex 37ca7fcee..9c3a861c1 100644--- a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx@@ -157,7 +157,7 @@ describe('AgentsLibrary', () => {});});- it('shows Edit when composer is enabled and agentSpec is present', async () => {+ it('shows Edit/Clone/Delete when composer is enabled and agentSpec is present', async () => {const server = mockServer([{name: 'writer',@@ -177,11 +177,87 @@ describe('AgentsLibrary', () => {const actions = await screen.findByRole('button', { name: 'Actions for writer' });fireEvent.click(actions);expect(screen.getByRole('menuitem', { name: 'Edit' })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'Actions for try-only' })).not.toBeInTheDocument();+ expect(screen.getByRole('menuitem', { name: 'Clone' })).toBeInTheDocument();+ expect(screen.getByRole('menuitem', { name: 'Delete' })).toBeInTheDocument();+ fireEvent.click(actions); // close without dismissing the library (Escape closes library)++ // No spec → Edit/Clone hidden; Delete still available.+ fireEvent.click(screen.getByRole('button', { name: 'Actions for try-only' }));+ expect(screen.queryByRole('menuitem', { name: 'Edit' })).not.toBeInTheDocument();+ expect(screen.queryByRole('menuitem', { name: 'Clone' })).not.toBeInTheDocument();+ expect(screen.getByRole('menuitem', { name: 'Delete' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Try agent try-only' })).toBeInTheDocument();});- it('shows model name, skills count, and MCP count from agentSpec', async () => {+ it('clones an agent after confirm and stays on the library', async () => {+ const saveAgent = vi.fn(async () => ({ agentId: 'writer-copy-id' }));+ const server = createMockAgentUIServer({+ searchAgents: vi.fn(async () => [+ {+ name: 'writer',+ agentId: 'writer-id',+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },+ },+ ]),+ saveAgent,+ deleteAgent: vi.fn(async () => {}),+ });++ renderLibrary(<LibraryHarness />, {+ server,+ agentConfig: { mode: 'AgentLibraryWithComposer' },+ });++ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Actions for writer' }));+ fireEvent.click(screen.getByRole('menuitem', { name: 'Clone' }));++ expect(screen.getByRole('dialog', { name: 'Clone agent' })).toBeInTheDocument();+ expect(screen.getByText(/This will create “writer-copy”/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Clone' }));++ await waitFor(() => {+ expect(saveAgent).toHaveBeenCalledWith({+ agentName: 'writer-copy',+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },+ intent: 'create',+ });+ });+ expect(screen.getByRole('heading', { name: 'Agents' })).toBeInTheDocument();+ });++ it('deletes an agent after confirm and stays on the library', async () => {+ const deleteAgent = vi.fn(async () => {});+ const server = createMockAgentUIServer({+ searchAgents: vi.fn(async () => [+ {+ name: 'writer',+ agentId: 'writer-id',+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },+ },+ ]),+ deleteAgent,+ });++ renderLibrary(<LibraryHarness />, {+ server,+ agentConfig: { mode: 'AgentLibraryWithComposer' },+ });++ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Actions for writer' }));+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));++ expect(screen.getByRole('dialog', { name: 'Delete agent' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));++ await waitFor(() => {+ expect(deleteAgent).toHaveBeenCalledWith({ agentName: 'writer' });+ });+ expect(screen.getByRole('heading', { name: 'Agents' })).toBeInTheDocument();+ });++ it('shows model, skills, and connector under a Configuration column with tooltips', async () => {const server = mockServer([{name: 'algo-art',@@ -203,12 +279,14 @@ describe('AgentsLibrary', () => {fireEvent.click(screen.getByRole('button', { name: 'Open library' }));await waitFor(() => {- expect(screen.getByText('gpt-5-5')).toBeInTheDocument();+ expect(screen.getByRole('columnheader', { name: 'Configuration' })).toBeInTheDocument();});+ expect(screen.getByLabelText('openai/gpt-5-5')).toBeInTheDocument();+ expect(screen.getByText('gpt-5-5')).toBeInTheDocument();expect(screen.getByLabelText('Connectors: github')).toBeInTheDocument();expect(screen.getByLabelText('Skills: paint')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Try agent bare' })).toBeInTheDocument();- expect(screen.queryByLabelText('0 skills')).not.toBeInTheDocument();+ expect(screen.getByLabelText('Configuration unavailable for bare')).toBeInTheDocument();});it('hides Edit when composer is disabled (AgentLibrary only)', async () => {@@ -241,7 +319,8 @@ describe('AgentsLibrary', () => {fireEvent.click(screen.getByRole('button', { name: 'Open library' }));await waitFor(() => {- expect(screen.getByText('No agents yet. Build one in a chat, then save it as an agent.')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'No Agents Found' })).toBeInTheDocument();+ expect(screen.getByText('Build one in a chat, then save it as an agent.')).toBeInTheDocument();});});@@ -255,9 +334,11 @@ describe('AgentsLibrary', () => {fireEvent.change(screen.getByPlaceholderText('Search agents'), { target: { value: 'zzz' } });await waitFor(() => {- expect(screen.getByText('No agents match "zzz".')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'No Agents Found' })).toBeInTheDocument();+ expect(screen.getByText('zzz')).toBeInTheDocument();+ expect(screen.getByText(/No search results found for/)).toBeInTheDocument();});- expect(screen.queryByText('No agents yet. Build one in a chat, then save it as an agent.')).not.toBeInTheDocument();+ expect(screen.queryByText('Build one in a chat, then save it as an agent.')).not.toBeInTheDocument();});it('closes via Escape', () => {diff --git a/packages/trueforge-ui/test/atoms/CodeEditor.test.tsx b/packages/trueforge-ui/test/atoms/CodeEditor.test.tsxindex e9b8b4509..08cb48af7 100644--- a/packages/trueforge-ui/test/atoms/CodeEditor.test.tsx+++ b/packages/trueforge-ui/test/atoms/CodeEditor.test.tsx@@ -25,6 +25,7 @@ vi.mock('@/atoms/MonacoEditorCore.js', () => ({data-value={value}data-height={String(height)}data-line-numbers={String(options?.lineNumbers)}+ data-render-final-newline={String(options?.renderFinalNewline)}><button type="button" onClick={() => onChange?.('edited')}>Edit@@ -118,8 +119,11 @@ describe('CodeEditor', () => {vi.useFakeTimers();render(<CodeEditor value="copy me" />);+ const copyButton = screen.getByRole('button', { name: 'Copy' });+ expect(copyButton.className).toMatch(/border/);+await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ fireEvent.click(copyButton);await Promise.resolve();});@@ -132,6 +136,11 @@ describe('CodeEditor', () => {expect(screen.getByRole('button', { name: 'Copy' })).toBeInTheDocument();});+ it('disables Monaco final-newline rendering so a trailing \\n is not an empty row', () => {+ render(<CodeEditor value={'line\n'} />);+ expect(screen.getByTestId('monaco-editor')).toHaveAttribute('data-render-final-newline', 'off');+ });+it('expands and collapses the editor while keeping Monaco fill-height', () => {const { container } = render(<CodeEditor value="code" height={240} />);const root = container.querySelector('.aui-code-editor');diff --git a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsxindex 302fbf676..08b7c824d 100644--- a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx@@ -109,6 +109,34 @@ describe('SessionsPage', () => {expect(screen.getByRole('separator', { name: 'Resize session list' })).toHaveClass('w-0');});+ it('shows a single empty screen when there are no sessions', async () => {+ renderPage({ listSessions: vi.fn(async () => ({ data: [] })) });+ expect(await screen.findByRole('heading', { name: 'Agent Sessions' })).toBeInTheDocument();+ expect(await screen.findByText('No Sessions Found')).toBeInTheDocument();+ expect(screen.getByText('There are no sessions available at the moment.')).toBeInTheDocument();+ expect(screen.queryByText('Select a session to view details')).not.toBeInTheDocument();+ expect(screen.queryByRole('separator', { name: 'Resize session list' })).not.toBeInTheDocument();+ });++ it('keeps session detail visible when the list is empty but a sessionId is selected', async () => {+ window.history.replaceState(null, '', '/?view=sessions&sessionId=sess-1');+ const getSession = vi.fn(async (): Promise<Session> => ({+ id: 'sess-1',+ title: 'Pinned session',+ isMutable: false,+ createdAt: namedRow.createdAt,+ updatedAt: namedRow.updatedAt,+ }));+ renderPage({+ listSessions: vi.fn(async () => ({ data: [] })),+ getSession,+ });++ expect(await screen.findByText('Pinned session')).toBeInTheDocument();+ expect(screen.queryByText('No Sessions Found')).not.toBeInTheDocument();+ expect(getSession).toHaveBeenCalledWith({ sessionId: 'sess-1' });+ });+it('shows the custom range picker only after Custom Time Range is clicked', async () => {renderPage();const timeButton = await screen.findByRole('button', { name: 'Last 30 days' });diff --git a/packages/trueforge-ui/test/atoms/SyntaxHighlighter.test.tsx b/packages/trueforge-ui/test/atoms/SyntaxHighlighter.test.tsxindex ac66f1dd0..d82f95c58 100644--- a/packages/trueforge-ui/test/atoms/SyntaxHighlighter.test.tsx+++ b/packages/trueforge-ui/test/atoms/SyntaxHighlighter.test.tsx@@ -106,8 +106,11 @@ describe('SyntaxHighlighter', () => {vi.useFakeTimers();render(<SyntaxHighlighter code="copy me" />);+ const copyButton = screen.getByRole('button', { name: 'Copy' });+ expect(copyButton.className).toMatch(/border/);+await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ fireEvent.click(copyButton);await Promise.resolve();});@@ -120,4 +123,22 @@ describe('SyntaxHighlighter', () => {expect(screen.getByRole('button', { name: 'Copy' })).toBeInTheDocument();vi.useRealTimers();});++ it('strips a trailing newline so line numbers do not show an empty last row', () => {+ render(<SyntaxHighlighter code={'const x = 1;\n'} showLineNumbers />);++ expect(screen.getByTestId('syntax-engine')).toHaveTextContent('const x = 1;');+ expect(screen.getByTestId('syntax-engine').textContent).not.toMatch(/\n$/);+ });++ it('copies the exact source including a trailing newline', async () => {+ render(<SyntaxHighlighter code={'copy me\n'} />);++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ await Promise.resolve();+ });++ expect(writeText).toHaveBeenCalledWith('copy me\n');+ });});diff --git a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsxindex d7adcbb03..c9ecaa15d 100644--- a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx@@ -106,7 +106,8 @@ describe('SchedulesPage', () => {it('shows empty state when there are no schedules', async () => {renderPage([]);- expect(await screen.findByText('No schedules yet. Create one to get started.')).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'No Schedules Found' })).toBeInTheDocument();+ expect(screen.getByText('Create one to get started.')).toBeInTheDocument();});it('requests the next page token when Next is clicked', async () => {@@ -348,7 +349,8 @@ describe('SchedulesPage', () => {target: { value: 'nope' },});- expect(await screen.findByText('No schedules match your filters.')).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'No Schedules Found' })).toBeInTheDocument();+ expect(screen.getByText('No schedules match your filters.')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled();});diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.tsindex 65ccc163e..8b134cf80 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts@@ -332,4 +332,49 @@ describe('harnessBuilderServer', () => {},});});++ it('deleteAgent deletes by name via list + DELETE', async () => {+ const requests: { method: string; url: string }[] = [];+ const fetchMock: typeof fetch = async (input, init) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = init?.method ?? 'GET';+ requests.push({ method, url });+ if (url.endsWith('/api/v1/agents') && method === 'GET') {+ return Response.json({+ data: [{ id: 'agt_1', name: 'writer', manifest: { model: { name: 'test/model' } } }],+ });+ }+ if (url.endsWith('/api/v1/agents/agt_1') && method === 'DELETE') {+ return Response.json({});+ }+ return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });+ };++ const builder = createHarnessBuilderServer({ fetch: fetchMock });+ await builder.deleteAgent?.({ agentName: 'writer' });++ assert.equal(requests.length, 2);+ assert.equal(requests[0]?.method, 'GET');+ assert.equal(requests[1]?.method, 'DELETE');+ assert.ok(requests[1]?.url.endsWith('/api/v1/agents/agt_1'));+ });++ it('deleteAgent is a no-op when the name is missing', async () => {+ const requests: { method: string; url: string }[] = [];+ const fetchMock: typeof fetch = async (input, init) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = init?.method ?? 'GET';+ requests.push({ method, url });+ if (url.endsWith('/api/v1/agents') && method === 'GET') {+ return Response.json({ data: [] });+ }+ return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });+ };++ const builder = createHarnessBuilderServer({ fetch: fetchMock });+ await builder.deleteAgent?.({ agentName: 'missing' });++ assert.equal(requests.length, 1);+ assert.equal(requests[0]?.method, 'GET');+ });});diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsxindex 03605774d..ff1213bfe 100644--- a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx+++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx@@ -1,12 +1,14 @@// @vitest-environment jsdomimport { act, render, waitFor } from '@testing-library/react';-import { useEffect, useState } from 'react';+import { useEffect, useState, type ReactNode } from 'react';import { MemoryRouter, useLocation } from 'react-router-dom';import { describe, expect, it } from 'vitest';import { resolveRoutesConfig } from '@/routing/paths.js';import { ShellRouteSync } from '@/routing/ShellRouteSync.js';+import { ServerProvider } from '@/server/ServerContext.js';import { ShellModeProvider, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';+import { createMockAgentUIServer, createMockCatalog } from '../server/mockServer.js';const routes = resolveRoutesConfig();@@ -33,38 +35,84 @@ function CaptureLocation() {return null;}+function SettingsCatalogProvider({+ children,+ settingsEnabled = true,+ includeCatalog = true,+}: {+ children: ReactNode;+ settingsEnabled?: boolean;+ includeCatalog?: boolean;+}) {+ const server = createMockAgentUIServer({+ ...(includeCatalog ? { catalog: createMockCatalog() } : {}),+ getCapabilities: async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ settings: { enabled: settingsEnabled },+ },+ }),+ getSession: async ({ sessionId }) => ({+ id: sessionId,+ title: 'Session',+ isMutable: true,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ }),+ });+ return <ServerProvider server={server}>{children}</ServerProvider>;+}+function Harness({agentConfig,initialRemoteId,initialSettingsOpen = false,+ settingsEnabled = true,+ includeCatalog = true,}: {agentConfig?: AgentConfig;initialRemoteId?: string;initialSettingsOpen?: boolean;+ settingsEnabled?: boolean;+ includeCatalog?: boolean;}) {const [remoteId, setId] = useState<string | undefined>(initialRemoteId);setRemoteId = setId;return (- <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>- <CaptureShell />- <CaptureLocation />- <ShellRouteSync routes={routes} activeRemoteId={remoteId} initialSettingsOpen={initialSettingsOpen} />- </ShellModeProvider>+ <SettingsCatalogProvider settingsEnabled={settingsEnabled} includeCatalog={includeCatalog}>+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ <CaptureShell />+ <CaptureLocation />+ <ShellRouteSync routes={routes} activeRemoteId={remoteId} initialSettingsOpen={initialSettingsOpen} />+ </ShellModeProvider>+ </SettingsCatalogProvider>);}-function renderSync(opts: { initialEntries?: string[]; agentConfig?: AgentConfig; initialSettingsOpen?: boolean }) {+function renderSync(opts: {+ initialEntries?: string[];+ agentConfig?: AgentConfig;+ initialSettingsOpen?: boolean;+ settingsEnabled?: boolean;+ includeCatalog?: boolean;+}) {return render(<MemoryRouter initialEntries={opts.initialEntries ?? ['/']}>- <Harness agentConfig={opts.agentConfig} initialSettingsOpen={opts.initialSettingsOpen} />+ <Harness+ agentConfig={opts.agentConfig}+ initialSettingsOpen={opts.initialSettingsOpen}+ settingsEnabled={opts.settingsEnabled}+ includeCatalog={opts.includeCatalog}+ /></MemoryRouter>,);}describe('ShellRouteSync', () => {- it('applies a session deep link on boot', () => {+ it('applies a session deep link on boot', async () => {renderSync({ initialEntries: ['/sessions/abc'] });- expect(shell.pendingSessionId).toBe('abc');+ await waitFor(() => expect(shell.pendingSessionId).toBe('abc'));expect(pathname).toBe('/sessions/abc');});@@ -80,10 +128,12 @@ describe('ShellRouteSync', () => {expect(pathname).toBe('/agents/foo');});- it('mirrors settings open/close through history', () => {+ it('mirrors settings open/close through history', async () => {renderSync({ initialEntries: ['/'] });- act(() => shell.setSettingsOpen(true));- expect(pathname).toBe('/settings');+ await waitFor(() => {+ act(() => shell.setSettingsOpen(true));+ expect(pathname).toBe('/settings');+ });act(() => shell.setSettingsOpen(false));expect(pathname).toBe('/');});@@ -125,26 +175,48 @@ describe('ShellRouteSync', () => {expect(pathname).toBe('/sessions/new-session');});- it('opens settings on boot when initialSettingsOpen is set and pushes the URL', () => {+ it('opens settings on boot when initialSettingsOpen is set and pushes the URL', async () => {renderSync({ initialEntries: ['/'], initialSettingsOpen: true });- expect(shell.settingsOpen).toBe(true);- expect(pathname).toBe('/settings');+ await waitFor(() => {+ expect(shell.settingsOpen).toBe(true);+ expect(pathname).toBe('/settings');+ });});// Boot replaces into /settings, so Back would leave the app instead of closing it.- it('returns to the chat place when settings opened on boot is closed', () => {+ it('returns to the chat place when settings opened on boot is closed', async () => {renderSync({ initialEntries: ['/'], initialSettingsOpen: true });+ await waitFor(() => expect(pathname).toBe('/settings'));act(() => shell.setSettingsOpen(false));expect(pathname).toBe('/');});- it('returns to the chat place when a /settings deep link is closed', () => {+ it('returns to the chat place when a /settings deep link is closed', async () => {renderSync({ initialEntries: ['/settings'] });- expect(shell.settingsOpen).toBe(true);+ await waitFor(() => expect(shell.settingsOpen).toBe(true));act(() => shell.setSettingsOpen(false));expect(pathname).toBe('/');});+ it('unregisters /settings when settings capability is disabled', async () => {+ renderSync({ initialEntries: ['/settings'], settingsEnabled: false });+ await waitFor(() => {+ expect(shell.settingsOpen).toBe(false);+ expect(pathname).toBe('/');+ });+ act(() => shell.setSettingsOpen(true));+ expect(shell.settingsOpen).toBe(false);+ expect(pathname).toBe('/');+ });++ it('ignores initialSettingsOpen when Settings chrome has no catalog', async () => {+ renderSync({ initialEntries: ['/'], initialSettingsOpen: true, includeCatalog: false });+ await waitFor(() => {+ expect(shell.settingsOpen).toBe(false);+ expect(pathname).toBe('/');+ });+ });+it('opens library on boot from a /library deep link', () => {renderSync({ initialEntries: ['/library'], agentConfig: { mode: 'AgentLibraryWithComposer' } });expect(shell.libraryOpen).toBe(true);diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.tsindex e12394218..cf052d1a4 100644--- a/packages/trueforge-ui/test/routing/paths.test.ts+++ b/packages/trueforge-ui/test/routing/paths.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {buildPath,+ buildSessionResumeHref,matchLocation,matchPath,placesEqual,@@ -70,6 +71,17 @@ describe('buildPath', () => {expect(buildPath({ type: 'libraryAgent', agentId: 'x' }, disabled)).toBeNull();expect(buildPath({ type: 'agent', agentName: 'x' }, disabled)).toBeNull();});++ it('builds an absolute resume href with basename and cleared share search', () => {+ const withBasename = resolveRoutesConfig({ basename: '/trueforge' });+ expect(+ buildSessionResumeHref({+ sessionId: 'sess-1',+ routes: withBasename,+ href: 'https://app.example/trueforge/library/agent-1?sessionId=old&agentId=agent-1&theme=dark',+ }),+ ).toBe('https://app.example/trueforge/sessions/sess-1?theme=dark');+ });});describe('sanitizeSearchForPlace', () => {diff --git a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui/test/server/ShellModeContext.test.tsxindex 05d6388d6..48048a732 100644--- a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx+++ b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx@@ -3,18 +3,39 @@ import { act, renderHook, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { DRAFT_SPEC_PREFERENCES_STORAGE_KEY, readDraftSpecPreferences } from '@/server/draftSpecPreferences.js';+import {+ AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ readDraftSpecPreferences,+} from '@/server/draftSpecPreferences.js';import { ServerProvider, useServerCapabilities } from '@/server/ServerContext.js';import { ShellModeProvider, useOptionalShellMode, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';import type { AgentUIServer } from '@/server/types.js';-import { createMockAgentUIServer } from './mockServer.js';+import { createMockAgentUIServer, createMockCatalog } from './mockServer.js';function wrap(agentConfig?: AgentConfig, initialSettingsOpen?: boolean) {+ const server = createMockAgentUIServer({ catalog: createMockCatalog() });return function Wrapper({ children }: { children: ReactNode }) {return (- <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>- {children}- </ShellModeProvider>+ <ServerProvider server={server}>+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ {children}+ </ShellModeProvider>+ </ServerProvider>+ );+ };+}++function wrapWithoutCatalog(agentConfig?: AgentConfig, initialSettingsOpen?: boolean) {+ const server = createMockAgentUIServer({ catalog: undefined });+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <ServerProvider server={server}>+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ {children}+ </ShellModeProvider>+ </ServerProvider>);};}@@ -32,6 +53,8 @@ function wrapWithServer(server: AgentUIServer, agentConfig?: AgentConfig) {describe('ShellModeProvider', () => {beforeEach(() => {window.localStorage.removeItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ window.localStorage.removeItem(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ window.localStorage.removeItem(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);});it('requires a provider for useShellMode', () => {@@ -55,6 +78,13 @@ describe('ShellModeProvider', () => {expect(result.current.settingsOpen).toBe(false);});+ it('ignores initialSettingsOpen when Settings chrome has no catalog', () => {+ const { result } = renderHook(() => useShellMode(), { wrapper: wrapWithoutCatalog(undefined, true) });+ expect(result.current.settingsOpen).toBe(false);+ act(() => result.current.setSettingsOpen(true));+ expect(result.current.settingsOpen).toBe(false);+ });+it('opens settings to a requested section', () => {const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });@@ -508,7 +538,7 @@ describe('ShellModeProvider', () => {expect(result.current.mode.status).toBe('idle');});- it('uses remembered plain-draft preferences for the next chat', () => {+ it('uses remembered chat preferences for the next New Chat only', () => {const { result } = renderHook(() => useShellMode(), {wrapper: wrap({mode: 'AgentLibraryWithComposer',@@ -521,15 +551,28 @@ describe('ShellModeProvider', () => {model: { name: 'chosen/model' },skills: [{ name: 'Research' }],mcpServers: [{ name: 'GitHub' }],+ config: { sandbox: { enabled: true } },instructions: 'Do not retain this.',}),);+ act(() =>+ result.current.rememberDraftSpec(+ {+ model: { name: 'agent/model' },+ skills: [{ name: 'Code' }],+ mcpServers: [{ name: 'Linear' }],+ config: { sandbox: { enabled: true } },+ },+ 'agent',+ ),+ );act(() => result.current.selectAgent('saved-agent'));act(() => result.current.openDraft());expect(result.current.mode).toMatchObject({status: 'active',isMutable: true,+ isCreateAgent: false,agentSpec: {model: { name: 'chosen/model' },skills: [{ name: 'Research' }],@@ -538,6 +581,20 @@ describe('ShellModeProvider', () => {});if (result.current.mode.status !== 'active') throw new Error('expected active mode');expect(result.current.mode.agentSpec).not.toHaveProperty('instructions');+ expect(result.current.mode.agentSpec).not.toHaveProperty('config');++ act(() => result.current.openAgentBuilder());+ expect(result.current.mode).toMatchObject({+ status: 'active',+ isMutable: true,+ isCreateAgent: true,+ agentSpec: {+ model: { name: 'agent/model' },+ skills: [{ name: 'Code' }],+ mcpServers: [{ name: 'Linear' }],+ config: { sandbox: { enabled: true } },+ },+ });});it('preserves a host-seeded sandbox while capabilities are unavailable', () => {@@ -546,9 +603,9 @@ describe('ShellModeProvider', () => {wrapper: wrap({ mode: 'AgentComposer', defaultAgentSpec: hostSeed }),});- act(() => result.current.rememberDraftSpec(hostSeed));+ act(() => result.current.rememberDraftSpec(hostSeed, 'agent'));- expect(readDraftSpecPreferences()).toEqual({+ expect(readDraftSpecPreferences('agent')).toEqual({model: { name: 'chosen/model' },config: { sandbox: { enabled: true } },});@@ -571,9 +628,9 @@ describe('ShellModeProvider', () => {);await waitFor(() => expect(result.current.capabilities?.sandbox.enabled).toBe(true));- act(() => result.current.shell.rememberDraftSpec({ model: { name: 'chosen/model' } }));+ act(() => result.current.shell.rememberDraftSpec({ model: { name: 'chosen/model' } }, 'agent'));- expect(readDraftSpecPreferences()).toEqual({+ expect(readDraftSpecPreferences('agent')).toEqual({model: { name: 'chosen/model' },});});@@ -596,15 +653,15 @@ describe('ShellModeProvider', () => {await waitFor(() => expect(result.current.capabilities?.sandbox.enabled).toBe(false));const hostSeed = { model: { name: 'chosen/model' }, config: { sandbox: { enabled: true } } };- act(() => result.current.shell.rememberDraftSpec(hostSeed));+ act(() => result.current.shell.rememberDraftSpec(hostSeed, 'agent'));- expect(readDraftSpecPreferences()).toEqual({+ expect(readDraftSpecPreferences('agent')).toEqual({model: { name: 'chosen/model' },config: { sandbox: { enabled: false } },});});- it('hydrates remembered preferences on first paint', () => {+ it('hydrates remembered chat preferences on first paint and migrates the legacy key', () => {window.localStorage.setItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY,JSON.stringify({@@ -626,7 +683,15 @@ describe('ShellModeProvider', () => {expect(result.current.mode).toMatchObject({status: 'active',isMutable: true,+ isCreateAgent: false,agentSpec: { model: { name: 'remembered/model' } },});+ if (result.current.mode.status !== 'active') throw new Error('expected active mode');+ expect(result.current.mode.agentSpec).not.toHaveProperty('config');+ expect(readDraftSpecPreferences('chat')).toEqual({ model: { name: 'remembered/model' } });+ expect(readDraftSpecPreferences('agent')).toEqual({+ model: { name: 'remembered/model' },+ config: { sandbox: { enabled: true } },+ });});});diff --git a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts b/packages/trueforge-ui/test/server/draftSpecPreferences.test.tsindex ab649d9ba..ff57cbc93 100644--- a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts+++ b/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts@@ -1,7 +1,133 @@// @vitest-environment jsdom-import { describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { withCapabilitiesSandbox } from '@/server/draftSpecPreferences.js';+import {+ AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ readDraftSpecPreferences,+ selectAgentDraftSpecPreferences,+ selectChatDraftSpecPreferences,+ withCapabilitiesSandbox,+ writeDraftSpecPreferences,+} from '@/server/draftSpecPreferences.js';++describe('selectDraftSpecPreferences', () => {+ it('keeps only model, skills, and MCP for chat', () => {+ expect(+ selectChatDraftSpecPreferences({+ model: { name: 'm', params: { reasoningEffort: 'high' } },+ skills: [{ name: 's' }],+ mcpServers: [{ name: 'c' }],+ config: { sandbox: { enabled: true } },+ instructions: 'nope',+ }),+ ).toEqual({+ model: { name: 'm', params: { reasoningEffort: 'high' } },+ skills: [{ name: 's' }],+ mcpServers: [{ name: 'c' }],+ });+ });++ it('keeps runtime config for agent', () => {+ expect(+ selectAgentDraftSpecPreferences({+ model: { name: 'm' },+ config: { sandbox: { enabled: true } },+ instructions: 'nope',+ }),+ ).toEqual({+ model: { name: 'm' },+ config: { sandbox: { enabled: true } },+ });+ });+});++describe('draft preference storage', () => {+ beforeEach(() => {+ window.localStorage.removeItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ window.localStorage.removeItem(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ window.localStorage.removeItem(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ });++ it('stores chat and agent preferences separately', () => {+ writeDraftSpecPreferences('chat', {+ model: { name: 'chat/model' },+ config: { sandbox: { enabled: true } },+ });+ writeDraftSpecPreferences('agent', {+ model: { name: 'agent/model' },+ config: { sandbox: { enabled: true } },+ });++ expect(readDraftSpecPreferences('chat')).toEqual({ model: { name: 'chat/model' } });+ expect(readDraftSpecPreferences('agent')).toEqual({+ model: { name: 'agent/model' },+ config: { sandbox: { enabled: true } },+ });+ });++ it('migrates the legacy shared key into both stores', () => {+ window.localStorage.setItem(+ DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ JSON.stringify({+ version: 1,+ spec: {+ model: { name: 'legacy/model' },+ skills: [{ name: 'Skill' }],+ config: { sandbox: { enabled: true } },+ },+ }),+ );++ expect(readDraftSpecPreferences('chat')).toEqual({+ model: { name: 'legacy/model' },+ skills: [{ name: 'Skill' }],+ });+ expect(readDraftSpecPreferences('agent')).toEqual({+ model: { name: 'legacy/model' },+ skills: [{ name: 'Skill' }],+ config: { sandbox: { enabled: true } },+ });+ expect(window.localStorage.getItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY)).toBeNull();+ });++ it('keeps the legacy key when a destination write fails', () => {+ window.localStorage.setItem(+ DRAFT_SPEC_PREFERENCES_STORAGE_KEY,+ JSON.stringify({+ version: 1,+ spec: {+ model: { name: 'legacy/model' },+ config: { sandbox: { enabled: true } },+ },+ }),+ );++ const originalSetItem = Storage.prototype.setItem;+ const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (+ this: Storage,+ key: string,+ value: string,+ ) {+ if (key === AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY) {+ throw new Error('quota exceeded');+ }+ return originalSetItem.call(this, key, value);+ });++ expect(readDraftSpecPreferences('chat')).toEqual({ model: { name: 'legacy/model' } });+ expect(readDraftSpecPreferences('agent')).toBeNull();+ expect(window.localStorage.getItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY)).not.toBeNull();++ setItemSpy.mockRestore();+ expect(readDraftSpecPreferences('agent')).toEqual({+ model: { name: 'legacy/model' },+ config: { sandbox: { enabled: true } },+ });+ expect(window.localStorage.getItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY)).toBeNull();+ });+});describe('withCapabilitiesSandbox', () => {it('does not enable sandbox merely because it is available', () => {diff --git a/packages/trueforge-ui/test/server/settingsChrome.test.ts b/packages/trueforge-ui/test/server/settingsChrome.test.tsnew file mode 100644index 000000000..ffbcf81b6--- /dev/null+++ b/packages/trueforge-ui/test/server/settingsChrome.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { isSettingsChromeEnabled } from '@/server/settingsChrome.js';+import { createMockCatalog } from './mockServer.js';++describe('isSettingsChromeEnabled', () => {+ const catalog = createMockCatalog();++ it('requires a catalog and treats missing settings capability as enabled', () => {+ expect(isSettingsChromeEnabled({ catalog: null, capabilities: null })).toBe(false);+ expect(isSettingsChromeEnabled({ catalog, capabilities: null })).toBe(true);+ expect(+ isSettingsChromeEnabled({+ catalog,+ capabilities: { settings: { enabled: true } },+ }),+ ).toBe(true);+ });++ it('is false when settings capability is disabled', () => {+ expect(+ isSettingsChromeEnabled({+ catalog,+ capabilities: { settings: { enabled: false } },+ }),+ ).toBe(false);+ });+});diff --git a/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts b/packages/trueforge-ui/test/utils/scheduleShareUrl.test.tsindex 5980134b4..d3ed6f220 100644--- a/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts+++ b/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts@@ -1,8 +1,7 @@-import { describe, expect, it } from 'vitest';-import {clearScheduleShareSearch,readScheduleShareSearch,+ writeOpenSchedulesForAgentSearch,writeScheduleShareSearch,} from '@/utils/scheduleShareUrl.js';@@ -33,4 +32,15 @@ describe('scheduleShareUrl', () => {clearScheduleShareSearch(params);expect(params.toString()).toBe('theme=dark');});++ it('writeOpenSchedulesForAgentSearch clears library share keys and sets agent filter', () => {+ window.history.replaceState(null, '', '/library/old?agentId=old&tab=overview&theme=dark');+ writeOpenSchedulesForAgentSearch({ agentId: 'agt_1', isNew: true });+ const url = new URL(window.location.href);+ expect(url.searchParams.get('agent')).toBe('agt_1');+ expect(url.searchParams.get('isNew')).toBe('true');+ expect(url.searchParams.get('agentId')).toBeNull();+ expect(url.searchParams.get('tab')).toBeNull();+ expect(url.searchParams.get('theme')).toBe('dark');+ });});diff --git a/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts b/packages/trueforge-ui/test/utils/sessionAgentDetails.test.tsindex b40475250..14fc7b616 100644--- a/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts+++ b/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts@@ -94,10 +94,10 @@ describe('buildSessionTurnViews', () => {metrics: {totalTokens: 122_000,totalCostInUsd: 1.4872,- totalInputTokens: 0,- totalOutputTokens: 0,- totalCacheReadTokens: 0,- totalCacheWriteTokens: 0,+ totalInputTokens: 100_000,+ totalOutputTokens: 20_000,+ totalCacheReadTokens: 1_500,+ totalCacheWriteTokens: 500,totalReasoningTokens: 0,},} satisfies TurnDoneEvent['state'] & {@@ -122,14 +122,29 @@ describe('buildSessionTurnViews', () => {const views = buildSessionTurnViews(itemsAsc);assert.deepEqual(- views.map(({ turnId, turnNumber, showHeader, durationMs, totalTokens, totalCostInUsd }) => ({- turnId,- turnNumber,- showHeader,- durationMs,- totalTokens,- totalCostInUsd,- })),+ views.map(+ ({+ turnId,+ turnNumber,+ showHeader,+ durationMs,+ totalTokens,+ inputTokens,+ outputTokens,+ cachedTokens,+ totalCostInUsd,+ }) => ({+ turnId,+ turnNumber,+ showHeader,+ durationMs,+ totalTokens,+ inputTokens,+ outputTokens,+ cachedTokens,+ totalCostInUsd,+ }),+ ),[{turnId: 'turn-1',@@ -137,6 +152,10 @@ describe('buildSessionTurnViews', () => {showHeader: true,durationMs: 60_000,totalTokens: 122_000,+ // Input is uncached: 100_000 total input - 2_000 cached.+ inputTokens: 98_000,+ outputTokens: 20_000,+ cachedTokens: 2_000,totalCostInUsd: 1.4872,},{@@ -145,6 +164,9 @@ describe('buildSessionTurnViews', () => {showHeader: true,durationMs: 60_000,totalTokens: 122_000,+ inputTokens: 98_000,+ outputTokens: 20_000,+ cachedTokens: 2_000,totalCostInUsd: 1.4872,},],