Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

Enhance scheduling features in trueforge-ui (#533)

Govinda Vashishtha0cc59f87678a
diff --git a/.changeset/google-sans-default-font.md b/.changeset/google-sans-default-font.md
new file mode 100644
index 000000000..f323f1262
--- /dev/null
+++ b/.changeset/google-sans-default-font.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-ui": patch
+---
+
+Use Google Sans as the default `trueforge` theme font and load it from Google Fonts when styles are injected.
diff --git a/.changeset/schedule-runs-ui.md b/.changeset/schedule-runs-ui.md
new file mode 100644
index 000000000..772881f52
--- /dev/null
+++ b/.changeset/schedule-runs-ui.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-ui": minor
+---
+
+Wire schedule test runs and show last five run status chips on the schedules table. Bump `@truefoundry/assistant-ui-runtime` to `0.1.25`.
diff --git a/.changeset/schedules-side-drawer.md b/.changeset/schedules-side-drawer.md
new file mode 100644
index 000000000..bca28f0e8
--- /dev/null
+++ b/.changeset/schedules-side-drawer.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-ui": minor
+---
+
+Add global Schedules page at `/schedules` with listing, popover-based filters, and create/edit drawer wired to the schedule API. New schedules save as paused, open a Test Schedule review with MCP connect status, and support Activate Anyway. List schedules uses server token pagination and multi-agent filters. Agents Library shows a Schedules count column (warning when any are paused) loaded via a batched list for on-screen agents. Add Table primitives with client-side and token pagination plus portal DropdownMenu so row actions are not clipped by overflow. Export a reusable popover select with single- and multi-select modes.
diff --git a/.gitignore b/.gitignore
index 6ba4f9250..a90e1c82d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
node_modules/
dist/
*.tgz
+!vendor/*.tgz
.DS_Store
*.log
coverage/
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index d250f424d..b4b9a7ff7 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -26,7 +26,7 @@
"@assistant-ui/core": "0.2.22",
"@assistant-ui/react": "0.14.27",
"@assistant-ui/store": "0.2.21",
- "@truefoundry/assistant-ui-runtime": "0.1.23",
+ "@truefoundry/assistant-ui-runtime": "0.1.25",
"@truefoundry/trueforge-sdk": "workspace:*",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
diff --git a/packages/trueforge-ui/docs/compatibility.md b/packages/trueforge-ui/docs/compatibility.md
index 7703150d2..935e92210 100644
--- a/packages/trueforge-ui/docs/compatibility.md
+++ b/packages/trueforge-ui/docs/compatibility.md
@@ -21,7 +21,7 @@ Install once at the app root.
| ----------------------------------- | ---------- |
| `@assistant-ui/core` | `^0.2.22` |
| `@assistant-ui/react` | `^0.14.24` |
-| `@truefoundry/assistant-ui-runtime` | `0.1.22` |
+| `@truefoundry/assistant-ui-runtime` | `0.1.25` |
| `truefoundry-gateway-sdk` | `^0.4.0` |
| `lucide-react` | `^0.562.0` |
diff --git a/packages/trueforge-ui/package.json b/packages/trueforge-ui/package.json
index 0b6fe2d1f..a5f8c9592 100644
--- a/packages/trueforge-ui/package.json
+++ b/packages/trueforge-ui/package.json
@@ -95,7 +95,7 @@
"@openuidev/react-headless": "^0.9.4",
"@openuidev/react-lang": "^0.2.9",
"@openuidev/react-ui": "^0.13.2",
- "@truefoundry/assistant-ui-runtime": "0.1.23",
+ "@truefoundry/assistant-ui-runtime": "0.1.25",
"@truefoundry/trueforge-sdk": "workspace:*",
"chart.js": "^4.5.1",
"clsx": "^2.1.1",
diff --git a/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx b/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx
index bf86cf759..36d91b551 100644
--- a/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx
+++ b/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx
@@ -9,17 +9,13 @@ import { libraryAgentId, useOptionalShellMode } from '../server/ShellModeContext
import { auiButtonClass } from './lib/buttonClasses.js';
import { cn } from './lib/cn.js';
import { useCompactLayout } from './lib/CompactLayoutContext.js';
+import { themePortalRoot } from './lib/themePortalRoot.js';
import { useIsMobile } from './lib/useIsMobile.js';
import { useSearchAgentsList } from './lib/useSearchAgentsList.js';
import { BottomSheet } from './primitives/BottomSheet.js';
import { DropdownMenuItem } from './primitives/DropdownMenu.js';
import SearchInput from './primitives/SearchInput.js';
-/** Keep portaled chrome under ThemeProvider so preset/custom CSS vars still apply. */
-function themePortalRoot(from: HTMLElement | null): HTMLElement {
- return from?.closest('.aui-theme-root') ?? document.body;
-}
-
/**
* Funnel popover for filtering chat history by agent id.
* Desktop: fixed menu to the right of the funnel. Mobile/compact: bottom sheet.
diff --git a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx
index 299bde754..8364d5e82 100644
--- a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx
+++ b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx
@@ -4,24 +4,36 @@ import { useCallback, useEffect, useState } from 'react';
import { useSessionShareSearch } from '../hooks/useSessionShareSearch.js';
import { Icon } from '../icons/Icon.js';
-import { useOptionalAgentSessionsServer } from '../server/ServerContext.js';
+import { useOptionalAgentSessionsServer, useOptionalScheduleServer } from '../server/ServerContext.js';
import { libraryAgentId, useShellMode } from '../server/ShellModeContext.js';
-import type { AgentLibraryEntry, AgentSpec } from '../server/types.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 { 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';
import { Tooltip } from './primitives/Tooltip.js';
export type AgentsLibraryProps = {
onSelectAgent?: (agentName: string) => void;
};
+export type AgentScheduleSummary = {
+ count: number;
+ hasPaused: boolean;
+};
+
export type AgentLibraryRowProps = {
agent: AgentLibraryEntry;
showEdit: boolean;
+ scheduleSummary?: AgentScheduleSummary | null;
+ onOpenSchedules?: () => void;
onOpen?: () => void;
onTry: () => void;
onEdit: () => void;
@@ -33,113 +45,229 @@ function displayModelLabel(modelName: string): string {
return slash >= 0 ? modelName.slice(slash + 1) : modelName;
}
-export function AgentLibraryRow({ agent, showEdit, onOpen, onTry, onEdit }: AgentLibraryRowProps) {
+function AgentSchedulesEmptyState({ agentName, onOpen }: { agentName: string; onOpen?: () => void }) {
+ return (
+ <button
+ type="button"
+ aria-label={`Add schedule for ${agentName}`}
+ className="text-text-secondary hover:text-primary-button-bg cursor-pointer text-sm font-medium"
+ onClick={onOpen}
+ >
+ <span aria-hidden className="md:group-hover:hidden">
+ -
+ </span>
+ <span aria-hidden className="hidden items-center gap-1 md:group-hover:inline-flex">
+ <Icon name="plus" className="size-3.5 shrink-0" />
+ Schedule
+ </span>
+ </button>
+ );
+}
+
+function AgentSchedulesBadge({
+ summary,
+ agentName,
+ onOpen,
+}: {
+ summary: AgentScheduleSummary;
+ agentName: string;
+ onOpen?: () => void;
+}) {
+ const warning = summary.hasPaused;
+ return (
+ <button
+ type="button"
+ aria-label={`${String(summary.count)} schedules for ${agentName}${warning ? ' (has paused)' : ''}`}
+ className={cn(
+ 'inline-flex cursor-pointer items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium',
+ warning
+ ? 'border-amber-600/30 bg-amber-500/10 text-amber-800 dark:text-amber-300'
+ : 'border-border bg-secondary-bg text-text-secondary',
+ )}
+ onClick={onOpen}
+ >
+ <Icon name="calendar-clock" className="size-3.5 shrink-0" />
+ <span>{summary.count}</span>
+ {warning ? <Icon name="triangle-exclamation" className="size-3.5 shrink-0" /> : null}
+ </button>
+ );
+}
+
+export function AgentLibraryRow({
+ agent,
+ showEdit,
+ scheduleSummary,
+ onOpenSchedules,
+ onOpen,
+ onTry,
+ onEdit,
+}: AgentLibraryRowProps) {
const spec = agent.agentSpec;
const modelName = spec?.model.name;
const skillsCount = spec?.skills?.length ?? 0;
const mcpCount = spec?.mcpServers?.length ?? 0;
- const skillNames = (spec?.skills ?? []).map(s => (s as { name?: string }).name).filter(Boolean);
- const mcpNames = (spec?.mcpServers ?? []).map(m => (m as { name?: string }).name).filter(Boolean);
+ const skillNames = (spec?.skills ?? []).map(mountName).filter((name: string | null): name is string => name != null);
+ 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 hasNoSchedules = scheduleSummary != null && scheduleSummary.count === 0;
+
return (
- <div
- role="menuitem"
- tabIndex={onOpen == null ? undefined : 0}
- aria-label={onOpen == null ? undefined : `Open ${agent.name}`}
- className={cn(
- 'flex w-full items-center gap-2.5 rounded-md border border-transparent px-2.5 py-2 transition-colors',
- 'hover:border-border hover:bg-ghost-button-hover',
- 'focus-within:border-border focus-within:bg-ghost-button-hover',
- onOpen != null &&
- 'cursor-pointer focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-focus-ring',
- )}
- onClick={onOpen}
- onKeyDown={event => {
- if (onOpen == null || event.target !== event.currentTarget || (event.key !== 'Enter' && event.key !== ' ')) {
- return;
- }
- event.preventDefault();
- onOpen();
- }}
- >
- <span className="bg-primary-bg text-text-secondary inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-border">
- <Icon name="robot" className="size-4" />
- </span>
- <span className="text-text-primary min-w-0 flex-1 truncate text-left text-sm font-medium leading-tight">
- {agent.name}
- </span>
- {spec != null ? (
- <span className="text-text-secondary flex shrink-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}
- <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>
- <Tooltip content={skillsTitle}>
- <span className="inline-flex items-center gap-1 text-xs" aria-label={skillsTitle}>
- <Icon name="lightbulb" className="size-3.5" />
- {skillsCount}
+ <TableRow className={hasNoSchedules ? 'group' : undefined}>
+ <TableCell className="text-text-primary font-medium">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <span className="bg-primary-bg text-text-secondary inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-border">
+ <Icon name="robot" className="size-4" />
+ </span>
+ <div className="min-w-0">
+ {onOpen == null ? (
+ <span className="block truncate">{agent.name}</span>
+ ) : (
+ <button
+ type="button"
+ className="hover:text-primary-button-bg block max-w-full cursor-pointer truncate text-left hover:underline"
+ aria-label={`Open ${agent.name}`}
+ onClick={onOpen}
+ >
+ {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>
+ {scheduleSummary !== undefined ? (
+ <TableCell>
+ {scheduleSummary != null && scheduleSummary.count > 0 ? (
+ <AgentSchedulesBadge summary={scheduleSummary} agentName={agent.name} onOpen={onOpenSchedules} />
+ ) : scheduleSummary != null ? (
+ <AgentSchedulesEmptyState agentName={agent.name} onOpen={onOpenSchedules} />
+ ) : (
+ <span className="text-text-secondary text-sm" aria-label={`Schedule count unavailable for ${agent.name}`}>
+ —
</span>
- </Tooltip>
- </span>
+ )}
+ </TableCell>
) : null}
- <span className="flex shrink-0 items-center gap-1.5">
- {showEdit ? (
+ <TableCell className="w-px">
+ <div className="flex items-center justify-end gap-1.5">
<button
type="button"
- aria-label={`Edit agent ${agent.name}`}
+ aria-label={`Try agent ${agent.name}`}
className={auiButtonClass({
- variant: 'ghost',
+ variant: 'outline',
size: 'sm',
})}
- onClick={event => {
- event.stopPropagation();
- onEdit();
- }}
+ onClick={onTry}
>
- <Icon name="pencil" className="size-3.5" />
- Edit
+ <Icon name="play" className="size-3.5" />
+ Try
</button>
- ) : null}
- <button
- type="button"
- aria-label={`Try agent ${agent.name}`}
- className={auiButtonClass({
- variant: 'outline',
- size: 'sm',
- })}
- onClick={event => {
- event.stopPropagation();
- onTry();
- }}
- >
- <Icon name="play" className="size-3.5" />
- Try
- </button>
- </span>
- </div>
+ {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}
+ </div>
+ </TableCell>
+ </TableRow>
);
}
+function summarizeSchedulesByAgent(schedules: readonly Schedule[]): Map<string, AgentScheduleSummary> {
+ const map = new Map<string, AgentScheduleSummary>();
+ for (const schedule of schedules) {
+ const id = schedule.agentId;
+ const prev = map.get(id) ?? { count: 0, hasPaused: false };
+ const next = {
+ count: prev.count + 1,
+ hasPaused: prev.hasPaused || schedule.status === 'paused',
+ };
+ map.set(id, next);
+ if (schedule.agentName != null && schedule.agentName !== '' && schedule.agentName !== id) {
+ map.set(schedule.agentName, next);
+ }
+ }
+ return map;
+}
+
+async function listAllSchedulesForAgents({
+ listSchedules,
+ agentIds,
+}: {
+ listSchedules: NonNullable<ReturnType<typeof useOptionalScheduleServer>>['listSchedules'];
+ agentIds: string[];
+}): Promise<Schedule[]> {
+ if (agentIds.length === 0) return [];
+ const rows: Schedule[] = [];
+ let pageToken: string | undefined;
+ do {
+ const page = await listSchedules({
+ agentIds,
+ limit: 25,
+ ...(pageToken === undefined ? {} : { pageToken }),
+ });
+ rows.push(...page.data);
+ pageToken = page.nextPageToken;
+ } while (pageToken != null && pageToken !== '');
+ return rows;
+}
+
export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {
const shell = useShellMode();
const { updateShareSearch } = useSessionShareSearch();
const sessionsServer = useOptionalAgentSessionsServer();
+ const scheduleServer = useOptionalScheduleServer();
const SlottedAgentLibraryRow = useSlot('AgentLibraryRow');
const [query, setQuery] = useState('');
+ const [scheduleByAgent, setScheduleByAgent] = useState<Map<string, AgentScheduleSummary> | null>(null);
const open = shell.libraryOpen;
const canEdit = shell.isComposerEnabled === true;
const agentsListEpoch = shell.agentsListEpoch;
+ const showSchedulesColumn = scheduleServer != null;
useEffect(() => {
if (!open) setQuery('');
@@ -168,6 +296,41 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {
refreshKey: agentsListEpoch,
});
+ useEffect(() => {
+ if (!open || scheduleServer == null || agents.length === 0) {
+ setScheduleByAgent(null);
+ return;
+ }
+ let cancelled = false;
+ setScheduleByAgent(null);
+ const agentIds = agents.map(libraryAgentId);
+ void listAllSchedulesForAgents({ listSchedules: scheduleServer.listSchedules, agentIds })
+ .then(rows => {
+ if (!cancelled) setScheduleByAgent(summarizeSchedulesByAgent(rows));
+ })
+ .catch(() => {
+ if (!cancelled) setScheduleByAgent(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [agents, open, scheduleServer, agentsListEpoch]);
+
+ const openSchedulesForAgent = (agentId: string) => {
+ 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 });
+ window.history.replaceState(window.history.state, '', url);
+ shell.setLibraryOpen(false);
+ shell.setSchedulesOpen(true);
+ };
+
const handleTry = (agent: AgentLibraryEntry) => {
closeLibrary();
onSelectAgent?.(agent.name);
@@ -193,34 +356,23 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {
return (
<div className="flex h-full min-h-0 w-full flex-col bg-primary-bg">
- <header className="flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5">
- <button
- type="button"
- aria-label="Back"
- title="Back"
- className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
- onClick={closeLibrary}
- >
- <Icon name="arrow-left" />
- </button>
- <h1 className="text-lg font-semibold tracking-tight text-text-primary">Agents Library</h1>
- </header>
-
- <div className="bg-secondary-bg/40 flex min-h-0 flex-1 flex-col">
- <div className="shrink-0 border-b border-border px-4 py-3">
+ <header className="flex shrink-0 flex-wrap items-center gap-2 border-b border-border px-4 py-2.5 md:px-6">
+ <div className="flex min-w-0 items-center gap-2">
+ <Icon name="bot" className="text-text-primary size-4" />
+ <h1 className="text-text-primary truncate text-md font-semibold">Agents Library</h1>
+ </div>
+ <div className="ml-auto w-56 shrink-0">
<SearchInput query={query} setQuery={setQuery} placeholder="Search agents" />
{isSearching ? (
- <p className="text-text-secondary mt-1.5 text-xs" role="status">
+ <p className="sr-only" role="status">
Searching…
</p>
) : null}
</div>
- <div
- ref={listRef}
- className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2"
- role="menu"
- aria-label="Agents"
- >
+ </header>
+
+ <div className="bg-secondary-bg/40 flex min-h-0 flex-1 flex-col">
+ <div ref={listRef} className="flex min-h-0 flex-1 flex-col overflow-y-auto p-4" aria-label="Agents">
{isInitialLoading ? (
<div className="flex flex-col gap-2 p-1" role="status" aria-label="Loading agents">
{Array.from({ length: 6 }, (_, i) => (
@@ -237,36 +389,63 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {
</p>
) : (
<>
- {agents.map(agent => {
- const agentSpec = agent.agentSpec;
- const agentId = agent.agentId;
- const showEdit = canEdit && agentSpec != null;
- return (
- <SlottedAgentLibraryRow
- key={libraryAgentId(agent)}
- agent={agent}
- showEdit={showEdit}
- {...(sessionsServer != null && agentId != null
- ? {
- onOpen: () => {
- updateShareSearch({
- agentId,
- tab: 'overview',
- sessionId: null,
- view: null,
- timeRange: null,
- });
- shell.openLibraryAgent(agentId);
- },
- }
- : {})}
- onTry={() => handleTry(agent)}
- onEdit={() => {
- if (agentSpec != null) handleEdit(agent, agentSpec);
- }}
- />
- );
- })}
+ <div className="overflow-hidden rounded-lg border border-border">
+ <Table>
+ <TableHeader>
+ <TableRow className="hover:bg-transparent">
+ <TableHead>Agent name</TableHead>
+ {showSchedulesColumn ? <TableHead className="w-[8rem]">Schedules</TableHead> : null}
+ <TableHead className="w-px">
+ <span className="sr-only">Actions</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {agents.map(agent => {
+ 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) ??
+ (scheduleByAgent == null ? null : { count: 0, hasPaused: false }))
+ : undefined;
+ return (
+ <SlottedAgentLibraryRow
+ key={id}
+ agent={agent}
+ showEdit={showEdit}
+ {...(summary !== undefined ? { scheduleSummary: summary } : {})}
+ {...(showSchedulesColumn
+ ? {
+ onOpenSchedules: () => openSchedulesForAgent(id),
+ }
+ : {})}
+ {...(sessionsServer != null && agentId != null
+ ? {
+ onOpen: () => {
+ updateShareSearch({
+ agentId,
+ tab: 'overview',
+ sessionId: null,
+ view: null,
+ timeRange: null,
+ });
+ shell.openLibraryAgent(agentId);
+ },
+ }
+ : {})}
+ onTry={() => handleTry(agent)}
+ onEdit={() => {
+ if (agentSpec != null) handleEdit(agent, agentSpec);
+ }}
+ />
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
{hasMore ? (
<div ref={sentinelRef} className="flex h-8 shrink-0 items-center justify-center" aria-hidden>
{loadingMore ? (
diff --git a/packages/trueforge-ui/src/atoms/AgentsLibraryButton.tsx b/packages/trueforge-ui/src/atoms/AgentsLibraryButton.tsx
index 77ee2f9ec..72a105cae 100644
--- a/packages/trueforge-ui/src/atoms/AgentsLibraryButton.tsx
+++ b/packages/trueforge-ui/src/atoms/AgentsLibraryButton.tsx
@@ -60,7 +60,7 @@ export function AgentsLibraryButton({ className, compact = false }: AgentsLibrar
})}
onClick={() => shell?.setLibraryOpen(true)}
>
- <Icon name="robot" />
+ <Icon name="bot" />
{!compact ? (
<>
<span className="truncate">
diff --git a/packages/trueforge-ui/src/atoms/SchedulesButton.tsx b/packages/trueforge-ui/src/atoms/SchedulesButton.tsx
new file mode 100644
index 000000000..d89cf651d
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/SchedulesButton.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { Icon } from '../icons/Icon.js';
+import { useOptionalScheduleServer } from '../server/ServerContext.js';
+import { useOptionalShellMode } from '../server/ShellModeContext.js';
+import { auiButtonClass } from './lib/buttonClasses.js';
+import { cn } from './lib/cn.js';
+
+export type SchedulesButtonProps = {
+ className?: string;
+ compact?: boolean;
+};
+
+export function SchedulesButton({ className, compact = false }: SchedulesButtonProps) {
+ const shell = useOptionalShellMode();
+ const scheduleServer = useOptionalScheduleServer();
+
+ const enabled = scheduleServer != null && shell != null;
+ const open = shell?.schedulesOpen === true;
+
+ if (!enabled) return null;
+
+ return (
+ <div className={cn('relative min-w-0', compact ? 'w-8' : 'w-full', className)}>
+ <button
+ type="button"
+ aria-label={compact ? 'Schedules' : undefined}
+ title={compact ? 'Schedules' : undefined}
+ aria-current={open ? 'page' : undefined}
+ className={auiButtonClass({
+ variant: 'ghost',
+ className: cn(
+ 'h-8 rounded-md text-sm font-medium text-text-primary shadow-none hover:bg-ghost-button-hover hover:text-ghost-button-text',
+ compact ? 'w-8 !justify-center p-0' : 'w-full !justify-start px-2.5',
+ open && 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text',
+ ),
+ })}
+ onClick={() => shell.setSchedulesOpen(!open)}
+ >
+ <Icon name="calendar-clock" />
+ {!compact ? (
+ <>
+ <span className="truncate">Schedules</span>
+ <Icon name="chevron-right" className="ml-auto size-3.5 shrink-0 opacity-60" />
+ </>
+ ) : null}
+ </button>
+ </div>
+ );
+}
+
+declare module '../theme/SlotsProvider.js' {
+ interface AtomSlots {
+ SchedulesButton: typeof SchedulesButton;
+ }
+}
diff --git a/packages/trueforge-ui/src/atoms/SessionsBrowserButton.tsx b/packages/trueforge-ui/src/atoms/SessionsBrowserButton.tsx
index 64be5ea56..c6c527b4b 100644
--- a/packages/trueforge-ui/src/atoms/SessionsBrowserButton.tsx
+++ b/packages/trueforge-ui/src/atoms/SessionsBrowserButton.tsx
@@ -49,7 +49,7 @@ export function SessionsBrowserButton({ className, compact = false }: SessionsBr
shell.setSessionsOpen(true);
}}
>
- <Icon name="clock-rotate-left" />
+ <Icon name="message-square-text" />
{!compact ? (
<>
<span className="truncate">Sessions</span>
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx
index 440f67dad..940b33f97 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx
@@ -2,9 +2,10 @@
import { useEffect, useRef, useState } from 'react';
+import { Icon } from '../../icons/Icon.js';
import { useOptionalServer } from '../../server/ServerContext.js';
import { useOptionalShellMode } from '../../server/ShellModeContext.js';
-import type { AgentBuilderServer, AgentLibraryEntry } from '../../server/types.js';
+import type { AgentLibraryEntry } from '../../server/types.js';
import { SESSION_CUSTOM_RANGE_MAX_DAYS, type SessionTimeRange } from '../../utils/sessionShareUrl.js';
import {
formatSessionTimePresetLabel,
@@ -13,17 +14,12 @@ import {
SESSION_TIME_PRESETS,
toDateTimeLocalValue,
} from '../../utils/sessionTimePresets.js';
+import { auiButtonClass } from '../lib/buttonClasses.js';
import { cn } from '../lib/cn.js';
-import { SEARCH_AGENTS_PAGE_SIZE } from '../lib/useSearchAgentsList.js';
-
-async function searchAllAgents(
- server: Pick<AgentBuilderServer, 'searchAgents'>,
- offset = 0,
-): Promise<AgentLibraryEntry[]> {
- const rows = await server.searchAgents({ limit: SEARCH_AGENTS_PAGE_SIZE, offset });
- if (rows.length < SEARCH_AGENTS_PAGE_SIZE) return rows;
- return [...rows, ...(await searchAllAgents(server, offset + rows.length))];
-}
+import { auiInputClass } from '../lib/inputClasses.js';
+import { auiSelectMenuClass, auiSelectOptionClass, auiSelectTriggerClass } from '../lib/selectClasses.js';
+import { searchAllAgents } from '../lib/useSearchAgentsList.js';
+import { PopoverSelect } from '../primitives/PopoverSelect.js';
export type AgentSessionsFiltersProps = {
agentId: string | null;
@@ -111,32 +107,24 @@ export function AgentSessionsFilters({
return (
<div className="flex min-w-0 items-center gap-2">
{showAgentFilter ? (
- <label className="flex items-center gap-1 text-xs text-text-secondary">
- Agents
- <select
- aria-label="Filter sessions by agent"
- className="h-8 max-w-36 rounded-md border border-border bg-primary-bg px-2 text-xs text-text-primary"
- value={agentId ?? ''}
- onChange={event => onAgentChange(event.target.value.length === 0 ? null : event.target.value)}
- >
- <option value="">All</option>
- {agents.map(agent => {
- const id = agent.agentId ?? agent.name;
- return (
- <option key={id} value={id}>
- {agent.name}
- </option>
- );
- })}
- </select>
- </label>
+ <PopoverSelect
+ aria-label="Filter sessions by agent"
+ prefix="Agents"
+ className="min-w-[12rem]"
+ value={agentId ?? ''}
+ options={[
+ { value: '', label: 'All' },
+ ...agents.map(agent => ({ value: agent.agentId ?? agent.name, label: agent.name })),
+ ]}
+ onValueChange={value => onAgentChange(value.length === 0 ? null : value)}
+ />
) : null}
<div className="relative" ref={popoverRef}>
<button
type="button"
aria-expanded={menuOpen}
aria-haspopup="listbox"
- className="h-8 min-w-36 rounded-md border border-border bg-primary-bg px-2 text-left text-xs text-text-primary"
+ className={auiSelectTriggerClass('min-w-36')}
onClick={() => {
setMenuOpen(open => {
if (open) setCustomPickerOpen(false);
@@ -144,10 +132,11 @@ export function AgentSessionsFilters({
});
}}
>
- {timeLabel}
+ <span className="truncate">{timeLabel}</span>
+ <Icon name="chevron-down" className="size-4 shrink-0" />
</button>
{menuOpen ? (
- <div className="absolute right-0 z-20 mt-1 flex overflow-hidden rounded-md border border-border bg-card-bg shadow-md">
+ <div className={auiSelectMenuClass('right-0 flex max-h-none overflow-y-visible p-0')}>
{customPickerOpen ? (
<div className="flex w-64 min-w-0 flex-col gap-2 border-r border-border p-3">
<div className="text-sm font-medium text-text-primary">Select Time Range</div>
@@ -157,7 +146,7 @@ export function AgentSessionsFilters({
<input
type="datetime-local"
step="1"
- className="h-8 rounded-md border border-border bg-primary-bg px-2 text-xs text-text-primary"
+ className={auiInputClass('h-9')}
value={fromValue}
onChange={event => setFromValue(event.target.value)}
/>
@@ -167,7 +156,7 @@ export function AgentSessionsFilters({
<input
type="datetime-local"
step="1"
- className="h-8 rounded-md border border-border bg-primary-bg px-2 text-xs text-text-primary"
+ className={auiInputClass('h-9')}
value={toValue}
onChange={event => setToValue(event.target.value)}
/>
@@ -175,54 +164,58 @@ export function AgentSessionsFilters({
<p className="text-xs text-text-secondary">
Timezone: <span className="font-medium text-text-primary">{formatTimezoneOffsetLabel()}</span>
</p>
- <button
- type="button"
- className="mt-auto h-8 rounded-md bg-primary-button-bg px-3 text-xs font-medium text-primary-button-text"
- onClick={applyCustom}
- >
+ <button type="button" className={auiButtonClass({ className: 'mt-auto' })} onClick={applyCustom}>
Apply
</button>
</div>
) : null}
- <div className="flex max-h-80 w-44 shrink-0 flex-col overflow-y-auto py-1" role="listbox">
+ <div className="flex max-h-80 w-44 shrink-0 flex-col overflow-y-auto p-1" role="listbox">
{showCustomTimeRange ? (
<button
type="button"
- className={cn(
- 'px-3 py-2 text-left text-xs',
- timeRange.timeWindowMs == null
- ? 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text'
- : 'text-text-primary hover:bg-ghost-button-hover',
- )}
+ role="option"
+ aria-selected={timeRange.timeWindowMs == null}
+ className={auiSelectOptionClass()}
onClick={() => setCustomPickerOpen(true)}
>
- Custom Time Range
+ <span className="min-w-0 flex-1 truncate">Custom Time Range</span>
+ <Icon
+ name="check"
+ className={cn(
+ 'ml-auto size-4 shrink-0',
+ timeRange.timeWindowMs == null ? 'opacity-100' : 'opacity-0',
+ )}
+ />
</button>
) : null}
- {SESSION_TIME_PRESETS.map(preset => (
- <button
- key={preset.windowMs}
- type="button"
- className={cn(
- 'px-3 py-2 text-left text-xs',
- timeRange.timeWindowMs === preset.windowMs
- ? 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text'
- : 'text-text-primary hover:bg-ghost-button-hover',
- )}
- onClick={() => {
- const endTs = Date.now();
- onTimeRangeChange({
- startTs: endTs - preset.windowMs,
- endTs,
- timeWindowMs: preset.windowMs,
- });
- setMenuOpen(false);
- setCustomPickerOpen(false);
- }}
- >
- {preset.label}
- </button>
- ))}
+ {SESSION_TIME_PRESETS.map(preset => {
+ const selected = timeRange.timeWindowMs === preset.windowMs;
+ return (
+ <button
+ key={preset.windowMs}
+ type="button"
+ role="option"
+ aria-selected={selected}
+ className={auiSelectOptionClass()}
+ onClick={() => {
+ const endTs = Date.now();
+ onTimeRangeChange({
+ startTs: endTs - preset.windowMs,
+ endTs,
+ timeWindowMs: preset.windowMs,
+ });
+ setMenuOpen(false);
+ setCustomPickerOpen(false);
+ }}
+ >
+ <span className="min-w-0 flex-1 truncate">{preset.label}</span>
+ <Icon
+ name="check"
+ className={cn('ml-auto size-4 shrink-0', selected ? 'opacity-100' : 'opacity-0')}
+ />
+ </button>
+ );
+ })}
</div>
</div>
) : null}
diff --git a/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx b/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx
index 5837eaa9c..32fc479a2 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx
@@ -3,6 +3,7 @@
import { Suspense, useEffect, useMemo, useState } from 'react';
import { useSessionShareSearch } from '../../hooks/useSessionShareSearch.js';
+import { Icon } from '../../icons/Icon.js';
import { useOptionalAgentSessionsServer } from '../../server/ServerContext.js';
import { useSlot } from '../../theme/SlotsProvider.js';
import {
@@ -52,20 +53,25 @@ export function SessionsPage() {
return (
<div className="flex h-full min-h-0 w-full flex-col bg-primary-bg">
- <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3">
- <h1 className="text-lg font-semibold tracking-tight text-text-primary">Agent Sessions</h1>
- <AgentSessionsFilters
- agentId={agentFilter}
- timeRange={timeRange}
- onAgentChange={nextAgentId => {
- setAgentFilter(nextAgentId);
- updateShareSearch({ agentId: nextAgentId, sessionId: null, view: 'sessions' });
- }}
- onTimeRangeChange={nextRange => {
- setTimeRange(nextRange);
- updateShareSearch({ timeRange: nextRange, sessionId: null, view: 'sessions' });
- }}
- />
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-border px-4 py-2.5 md:px-6">
+ <div className="flex min-w-0 items-center gap-2">
+ <Icon name="message-square-text" className="text-text-primary size-4" />
+ <h1 className="text-text-primary truncate text-md font-semibold">Agent Sessions</h1>
+ </div>
+ <div className="ml-auto">
+ <AgentSessionsFilters
+ agentId={agentFilter}
+ timeRange={timeRange}
+ onAgentChange={nextAgentId => {
+ setAgentFilter(nextAgentId);
+ updateShareSearch({ agentId: nextAgentId, sessionId: null, view: 'sessions' });
+ }}
+ onTimeRangeChange={nextRange => {
+ setTimeRange(nextRange);
+ updateShareSearch({ timeRange: nextRange, sessionId: null, view: 'sessions' });
+ }}
+ />
+ </div>
</div>
<div className="min-h-0 flex-1">
{sessionsServer == null ? (
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
index 74dd0eac8..20fdf47a2 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
@@ -7,14 +7,10 @@ import { withCapabilitiesSandbox } from '../../server/draftSpecPreferences.js';
import { useServerCapabilities } from '../../server/ServerContext.js';
import { useShellMode } from '../../server/ShellModeContext.js';
import type { AgentSkill, AgentSpec, ConnectorState, ModelSelection } from '../../server/types.js';
+import { mountName } from '../lib/mountName.js';
import { useDraftCatalog } from './DraftCatalogProvider.js';
import { modelPatchWithReasoningEffort } from './reasoningEffort.js';
-function mountName(mount: object): string | null {
- const name = Reflect.get(mount, 'name');
- return typeof name === 'string' ? name : null;
-}
-
function filterMounts<T extends object>(mounts: T[] | undefined, availableNames: Set<string>): T[] | undefined {
if (mounts === undefined) return undefined;
const filtered = mounts.filter(mount => {
diff --git a/packages/trueforge-ui/src/atoms/lib/mountName.ts b/packages/trueforge-ui/src/atoms/lib/mountName.ts
new file mode 100644
index 000000000..d65457db6
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/lib/mountName.ts
@@ -0,0 +1,3 @@
+export function mountName(mount: object): string | null {
+ return 'name' in mount && typeof mount.name === 'string' ? mount.name : null;
+}
diff --git a/packages/trueforge-ui/src/atoms/lib/selectClasses.ts b/packages/trueforge-ui/src/atoms/lib/selectClasses.ts
new file mode 100644
index 000000000..ae392c4af
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/lib/selectClasses.ts
@@ -0,0 +1,36 @@
+import { cn } from './cn.js';
+import { auiInputClass } from './inputClasses.js';
+
+/**
+ * Shared dropdown chrome. Every select-like surface (PopoverSelect, the session
+ * time-range popover) composes these so triggers, menus, and option rows stay
+ * visually identical; callers pass `className` for width and placement only.
+ */
+export function auiSelectTriggerClass(className?: string): string {
+ return auiInputClass(cn('flex h-9 cursor-pointer items-center justify-between gap-2 pr-2 text-left', className));
+}
+
+/** Prefixed chip trigger: static label | selected chip + chevron. */
+export function auiSelectPrefixTriggerClass(className?: string): string {
+ return cn(
+ 'inline-flex h-9 w-full cursor-pointer items-center rounded-md border border-border bg-input-box-bg text-left text-sm text-text-primary outline-none',
+ 'focus-visible:ring-2 focus-visible:ring-focus-ring/40 disabled:cursor-not-allowed disabled:opacity-50',
+ className,
+ );
+}
+
+export function auiSelectMenuClass(className?: string): string {
+ return cn(
+ 'bg-card-bg text-text-primary absolute top-full z-50 mt-1 max-h-64 overflow-y-auto rounded-md border border-border p-1 shadow-md',
+ className,
+ );
+}
+
+export function auiSelectOptionClass(className?: string): string {
+ return cn(
+ 'text-text-primary flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none transition-colors',
+ 'hover:bg-ghost-button-hover focus:bg-dropdown-selected-item-bg focus:text-dropdown-selected-item-text',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ className,
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/lib/themePortalRoot.ts b/packages/trueforge-ui/src/atoms/lib/themePortalRoot.ts
new file mode 100644
index 000000000..dd386dc48
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/lib/themePortalRoot.ts
@@ -0,0 +1,6 @@
+/** Keep portaled chrome inside the active dialog/theme boundary. */
+export function themePortalRoot(from: HTMLElement | null): HTMLElement {
+ const dialog = from?.closest('dialog');
+ if (dialog instanceof HTMLElement) return dialog;
+ return from?.closest('.aui-theme-root') ?? document.body;
+}
diff --git a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts
index acda757f1..acc0e70ca 100644
--- a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts
+++ b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useOptionalServer } from '../../server/ServerContext.js';
-import type { AgentLibraryEntry } from '../../server/types.js';
+import type { AgentBuilderServer, AgentLibraryEntry } from '../../server/types.js';
import { getErrorMessage } from '../../utils/getErrorMessage.js';
import { useDebouncedValue } from './useDebouncedValue.js';
@@ -11,6 +11,16 @@ export const SEARCH_AGENTS_PAGE_SIZE = 50;
const DEFAULT_DEBOUNCE_MS = 300;
const LOAD_MORE_ROOT_MARGIN = '48px';
+/** Drain every `searchAgents` page (offset pagination). */
+export async function searchAllAgents(
+ server: Pick<AgentBuilderServer, 'searchAgents'>,
+ offset = 0,
+): Promise<AgentLibraryEntry[]> {
+ const rows = await server.searchAgents({ limit: SEARCH_AGENTS_PAGE_SIZE, offset });
+ if (rows.length < SEARCH_AGENTS_PAGE_SIZE) return rows;
+ return [...rows, ...(await searchAllAgents(server, offset + rows.length))];
+}
+
export type UseSearchAgentsListOptions = {
/** When false, no fetches run. */
enabled: boolean;
diff --git a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx
index 5a77fb39f..c26569c85 100644
--- a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx
+++ b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx
@@ -1,6 +1,10 @@
-import React, { useEffect, useId, useRef, useState } from 'react';
+'use client';
+
+import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
import { cn } from '../lib/cn.js';
+import { themePortalRoot } from '../lib/themePortalRoot.js';
export type DropdownMenuProps = {
trigger: React.ReactNode;
@@ -11,26 +15,61 @@ export type DropdownMenuProps = {
export function DropdownMenu({ trigger, children, align = 'end', className }: DropdownMenuProps) {
const [open, setOpen] = useState(false);
+ const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
+ const focusedOpenRef = useRef(false);
const menuId = useId();
+ useLayoutEffect(() => {
+ if (!open) {
+ setPos(null);
+ return;
+ }
+
+ const update = () => {
+ const el = containerRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ setPos({
+ top: rect.bottom + 4,
+ left: align === 'end' ? rect.right : rect.left,
+ });
+ };
+
+ update();
+ window.addEventListener('scroll', update, true);
+ window.addEventListener('resize', update);
+ return () => {
+ window.removeEventListener('scroll', update, true);
+ window.removeEventListener('resize', update);
+ };
+ }, [open, align]);
+
useEffect(() => {
if (!open) return;
const handler = (e: MouseEvent) => {
- if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
- setOpen(false);
- }
+ const target = e.target;
+ if (!(target instanceof Node)) return;
+ if (containerRef.current?.contains(target)) return;
+ if (menuRef.current?.contains(target)) return;
+ setOpen(false);
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [open]);
+ // Menu mounts only after `pos` is set; focus once per open, not on every scroll/resize pos rewrite.
useEffect(() => {
- if (!open) return;
+ if (!open) {
+ focusedOpenRef.current = false;
+ return;
+ }
+ if (pos == null || focusedOpenRef.current) return;
const first = menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]:not([disabled])');
first?.focus();
- }, [open]);
+ focusedOpenRef.current = true;
+ }, [open, pos]);
useEffect(() => {
if (!open) return;
@@ -82,25 +121,35 @@ export function DropdownMenu({ trigger, children, align = 'end', className }: Dr
})
: trigger;
+ const menu =
+ open && pos != null
+ ? createPortal(
+ <div
+ ref={menuRef}
+ id={menuId}
+ role="menu"
+ style={{
+ top: pos.top,
+ left: pos.left,
+ transform: align === 'end' ? 'translateX(-100%)' : undefined,
+ }}
+ className={cn(
+ 'fixed z-[200] min-w-[8rem] rounded-md border border-border bg-card-bg p-1',
+ 'text-text-primary shadow-md',
+ className,
+ )}
+ onClick={() => setOpen(false)}
+ >
+ {children}
+ </div>,
+ themePortalRoot(containerRef.current),
+ )
+ : null;
+
return (
<div ref={containerRef} className="relative inline-flex">
<div onClick={() => setOpen(v => !v)}>{triggerEl}</div>
- {open && (
- <div
- ref={menuRef}
- id={menuId}
- role="menu"
- className={cn(
- 'absolute top-full z-50 mt-1 min-w-[8rem] rounded-md border border-border bg-card-bg p-1',
- 'text-text-primary shadow-md',
- align === 'end' ? 'right-0' : 'left-0',
- className,
- )}
- onClick={() => setOpen(false)}
- >
- {children}
- </div>
- )}
+ {menu}
</div>
);
}
diff --git a/packages/trueforge-ui/src/atoms/primitives/PopoverSelect.tsx b/packages/trueforge-ui/src/atoms/primitives/PopoverSelect.tsx
new file mode 100644
index 000000000..99c875b40
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/primitives/PopoverSelect.tsx
@@ -0,0 +1,201 @@
+'use client';
+
+import { useEffect, useId, useRef, useState } from 'react';
+
+import { Icon } from '../../icons/Icon.js';
+import { cn } from '../lib/cn.js';
+import {
+ auiSelectMenuClass,
+ auiSelectOptionClass,
+ auiSelectPrefixTriggerClass,
+ auiSelectTriggerClass,
+} from '../lib/selectClasses.js';
+
+export type PopoverSelectOption<T extends string> = {
+ value: T;
+ label: string;
+ disabled?: boolean;
+};
+
+type CommonPopoverSelectProps<T extends string> = {
+ options: readonly PopoverSelectOption<T>[];
+ placeholder?: string;
+ disabled?: boolean;
+ className?: string;
+ /** Which edge of the trigger the menu opens toward. Default `bottom`. */
+ menuPlacement?: 'top' | 'bottom';
+ /** When set, renders a labeled chip trigger (label | value chip + chevron). */
+ prefix?: string;
+ 'aria-label': string;
+};
+
+export type PopoverSelectProps<T extends string> = CommonPopoverSelectProps<T> &
+ (
+ | {
+ multiple?: false;
+ value: T;
+ onValueChange: (value: T) => void;
+ }
+ | {
+ multiple: true;
+ value: readonly T[];
+ onValueChange: (value: T[]) => void;
+ }
+ );
+
+export function PopoverSelect<T extends string>(props: PopoverSelectProps<T>) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const listboxRef = useRef<HTMLDivElement>(null);
+ const listboxId = useId();
+
+ useEffect(() => {
+ if (!open) return;
+
+ const handlePointerDown = (event: MouseEvent) => {
+ if (event.target instanceof Node && !rootRef.current?.contains(event.target)) setOpen(false);
+ };
+ document.addEventListener('mousedown', handlePointerDown);
+ return () => document.removeEventListener('mousedown', handlePointerDown);
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+ const selected = listboxRef.current?.querySelector<HTMLElement>('[role="option"][aria-selected="true"]');
+ const first = listboxRef.current?.querySelector<HTMLElement>('[role="option"]:not([aria-disabled="true"])');
+ (selected ?? first)?.focus();
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ setOpen(false);
+ triggerRef.current?.focus();
+ return;
+ }
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
+
+ const items = Array.from(
+ listboxRef.current?.querySelectorAll<HTMLElement>('[role="option"]:not([aria-disabled="true"])') ?? [],
+ );
+ if (items.length === 0) return;
+
+ event.preventDefault();
+ const currentIndex = items.findIndex(item => item === document.activeElement);
+ const nextIndex =
+ event.key === 'Home'
+ ? 0
+ : event.key === 'End'
+ ? items.length - 1
+ : event.key === 'ArrowDown'
+ ? (currentIndex + 1) % items.length
+ : (currentIndex - 1 + items.length) % items.length;
+ items[nextIndex]?.focus();
+ };
+ document.addEventListener('keydown', handleKeyDown);
+ return () => document.removeEventListener('keydown', handleKeyDown);
+ }, [open]);
+
+ const isSelected = (value: T) => (props.multiple ? props.value.includes(value) : props.value === value);
+
+ const selectedLabels = props.options.filter(option => isSelected(option.value)).map(option => option.label);
+ const triggerLabel =
+ selectedLabels.length === 0
+ ? (props.placeholder ?? 'Select')
+ : props.multiple && selectedLabels.length > 1
+ ? `${selectedLabels.length} selected`
+ : selectedLabels[0];
+
+ const select = (option: PopoverSelectOption<T>) => {
+ if (option.disabled) return;
+ if (props.multiple) {
+ props.onValueChange(
+ props.value.includes(option.value)
+ ? props.value.filter(value => value !== option.value)
+ : [...props.value, option.value],
+ );
+ return;
+ }
+ props.onValueChange(option.value);
+ setOpen(false);
+ triggerRef.current?.focus();
+ };
+
+ const menuPlacement = props.menuPlacement ?? 'bottom';
+
+ return (
+ <div ref={rootRef} className={cn('relative', props.className)}>
+ <button
+ ref={triggerRef}
+ type="button"
+ disabled={props.disabled}
+ aria-label={props['aria-label']}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={open ? listboxId : undefined}
+ className={props.prefix != null ? auiSelectPrefixTriggerClass() : auiSelectTriggerClass()}
+ onClick={() => setOpen(value => !value)}
+ onKeyDown={event => {
+ if (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setOpen(true);
+ }
+ }}
+ >
+ {props.prefix != null ? (
+ <>
+ <span className="text-text-primary shrink-0 border-r border-border px-3 font-semibold">{props.prefix}</span>
+ <span className="flex min-w-0 flex-1 items-center justify-between gap-2 px-2">
+ <span className="bg-primary-button-bg/10 text-text-primary truncate rounded px-2 py-0.5 text-sm">
+ {triggerLabel}
+ </span>
+ <Icon name="chevron-down" className="text-text-secondary size-4 shrink-0" />
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="truncate">{triggerLabel}</span>
+ <Icon name="chevron-down" className="size-4 shrink-0" />
+ </>
+ )}
+ </button>
+
+ {open ? (
+ <div
+ ref={listboxRef}
+ id={listboxId}
+ role="listbox"
+ aria-label={props['aria-label']}
+ aria-multiselectable={props.multiple || undefined}
+ className={cn(
+ auiSelectMenuClass('left-0 min-w-full'),
+ menuPlacement === 'top' && 'top-auto bottom-full mt-0 mb-1',
+ )}
+ >
+ {props.options.map(option => {
+ const selected = isSelected(option.value);
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="option"
+ aria-selected={selected}
+ aria-disabled={option.disabled || undefined}
+ disabled={option.disabled}
+ className={auiSelectOptionClass()}
+ onClick={() => select(option)}
+ >
+ <span className="min-w-0 flex-1 whitespace-nowrap">{option.label}</span>
+ <Icon name="check" className={cn('ml-auto size-4 shrink-0', selected ? 'opacity-100' : 'opacity-0')} />
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/primitives/SideDrawer.tsx b/packages/trueforge-ui/src/atoms/primitives/SideDrawer.tsx
new file mode 100644
index 000000000..21d885629
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/primitives/SideDrawer.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { useEffect, useId, useRef, type ReactNode } from 'react';
+
+import { Icon } from '../../icons/Icon.js';
+import { auiButtonClass } from '../lib/buttonClasses.js';
+import { cn } from '../lib/cn.js';
+import { useCompactLayout } from '../lib/CompactLayoutContext.js';
+import { useCompactOverlayStyle } from '../lib/useCompactOverlayStyle.js';
+
+export type SideDrawerAnchor = 'left' | 'right';
+export type SideDrawerSize = 'sm' | 'md' | 'lg' | 'xl';
+
+export type SideDrawerProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description?: string;
+ headerIcon?: ReactNode;
+ children: ReactNode;
+ footer?: ReactNode;
+ /** Desktop side; ignored when compact / below `md` (falls back to bottom sheet). */
+ anchor?: SideDrawerAnchor;
+ /** Desktop width. Defaults to `md`. */
+ size?: SideDrawerSize;
+ className?: string;
+ 'aria-label'?: string;
+};
+
+const SIZE_WIDTH: Record<SideDrawerSize, string> = {
+ sm: 'md:w-80',
+ md: 'md:w-[28rem]',
+ lg: 'md:w-[36rem]',
+ xl: 'md:w-[42rem]',
+};
+
+/**
+ * Responsive overlay chrome: side drawer on `md+`, bottom sheet below `md`
+ * (and always when compact dock/widget layout is active).
+ */
+export function SideDrawer({
+ open,
+ onOpenChange,
+ title,
+ description,
+ headerIcon,
+ children,
+ footer,
+ anchor = 'right',
+ size = 'md',
+ className,
+ 'aria-label': ariaLabel,
+}: SideDrawerProps) {
+ const ref = useRef<HTMLDialogElement>(null);
+ const titleId = useId();
+ const descriptionId = useId();
+ const compact = useCompactLayout();
+ const compactStyle = useCompactOverlayStyle(ref, compact);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ if (open && !el.open) el.showModal();
+ else if (!open && el.open) el.close();
+ }, [open]);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const handler = () => onOpenChange(false);
+ el.addEventListener('close', handler);
+ return () => el.removeEventListener('close', handler);
+ }, [onOpenChange]);
+
+ return (
+ <dialog
+ ref={ref}
+ aria-label={ariaLabel ?? title}
+ aria-labelledby={titleId}
+ aria-describedby={description ? descriptionId : undefined}
+ // Escape still closes via cancel; backdrop click must not (no light-dismiss).
+ closedby="closerequest"
+ onCancel={event => {
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenChange(false);
+ }}
+ style={compactStyle}
+ className={cn(
+ 'bg-card-bg text-text-primary border-border open:flex open:flex-col overflow-hidden rounded-none p-0 shadow-xl',
+ 'backdrop:bg-black/50 backdrop:backdrop-blur-[2px] dark:backdrop:bg-black/70',
+ compact
+ ? 'm-0 mt-auto h-[min(85dvh,40rem)] w-full max-w-none border-t pb-[env(safe-area-inset-bottom)]'
+ : cn(
+ // Mobile / narrow: bottom sheet
+ 'm-0 mt-auto h-[min(85dvh,40rem)] w-full max-w-none border-t pb-[env(safe-area-inset-bottom)]',
+ // Desktop: side drawer
+ 'md:mt-0 md:h-dvh md:max-h-none md:border md:pb-0',
+ SIZE_WIDTH[size],
+ anchor === 'right'
+ ? 'md:ml-auto md:mr-0 md:border-y-0 md:border-r-0'
+ : 'md:mr-auto md:ml-0 md:border-y-0 md:border-l-0',
+ ),
+ className,
+ )}
+ >
+ <header className="bg-topbar-bg flex shrink-0 items-center gap-3 border-b border-border px-5 py-4">
+ {headerIcon}
+ <div className="min-w-0 flex-1">
+ <h2 id={titleId} className="text-text-primary text-lg font-semibold tracking-tight">
+ {title}
+ </h2>
+ {description ? (
+ <p id={descriptionId} className="text-text-secondary mt-1 text-sm">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ aria-label="Close"
+ title="Close"
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ onClick={() => onOpenChange(false)}
+ >
+ <Icon name="xmark" />
+ </button>
+ </header>
+ <div className="flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto">{children}</div>
+ {footer ? <div className="shrink-0 border-t border-border px-5 py-3">{footer}</div> : null}
+ </dialog>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/primitives/Table.tsx b/packages/trueforge-ui/src/atoms/primitives/Table.tsx
new file mode 100644
index 000000000..6b5a76877
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/primitives/Table.tsx
@@ -0,0 +1,223 @@
+'use client';
+
+import React from 'react';
+
+import { Icon } from '../../icons/Icon.js';
+import { auiButtonClass } from '../lib/buttonClasses.js';
+import { cn } from '../lib/cn.js';
+import { PopoverSelect } from './PopoverSelect.js';
+
+export const DEFAULT_TABLE_PAGE_SIZE = 10;
+export const TABLE_PAGE_SIZE_OPTIONS = [10, 25, 50] as const;
+
+export type TableProps = React.HTMLAttributes<HTMLTableElement> & {
+ /** Extra classes on the horizontal scroll wrapper. */
+ containerClassName?: string;
+};
+
+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} />
+ </div>
+ );
+}
+
+export type TableHeaderProps = React.HTMLAttributes<HTMLTableSectionElement>;
+
+export function TableHeader({ className, ...props }: TableHeaderProps) {
+ return <thead className={cn('bg-secondary-bg/60', className)} {...props} />;
+}
+
+export type TableBodyProps = React.HTMLAttributes<HTMLTableSectionElement>;
+
+export function TableBody({ className, ...props }: TableBodyProps) {
+ return <tbody className={cn(className)} {...props} />;
+}
+
+export type TableRowProps = React.HTMLAttributes<HTMLTableRowElement>;
+
+export function TableRow({ className, ...props }: TableRowProps) {
+ return (
+ <tr className={cn('border-b border-border last:border-b-0 hover:bg-ghost-button-hover/40', className)} {...props} />
+ );
+}
+
+export type TableHeadProps = React.ThHTMLAttributes<HTMLTableCellElement>;
+
+export function TableHead({ className, ...props }: TableHeadProps) {
+ return (
+ <th
+ className={cn(
+ 'text-text-secondary border-b border-border px-3 py-2.5 text-left text-xs font-semibold tracking-wide uppercase',
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export type TableCellProps = React.TdHTMLAttributes<HTMLTableCellElement>;
+
+export function TableCell({ className, ...props }: TableCellProps) {
+ return <td className={cn('text-text-secondary px-3 py-3', className)} {...props} />;
+}
+
+export type TablePaginationProps = {
+ page: number;
+ pageSize: number;
+ total: number;
+ onPageChange: (page: number) => void;
+ onPageSizeChange: (pageSize: number) => void;
+ pageSizeOptions?: readonly number[];
+ className?: string;
+};
+
+export function TablePagination({
+ page,
+ pageSize,
+ total,
+ onPageChange,
+ onPageSizeChange,
+ pageSizeOptions = TABLE_PAGE_SIZE_OPTIONS,
+ className,
+}: TablePaginationProps) {
+ const pageCount = Math.max(1, Math.ceil(total / pageSize));
+ const safePage = Math.min(page, pageCount - 1);
+ const from = total === 0 ? 0 : safePage * pageSize + 1;
+ const to = Math.min(total, (safePage + 1) * pageSize);
+ const canPrev = safePage > 0;
+ const canNext = safePage < pageCount - 1;
+
+ const sizeOptions = pageSizeOptions.map(size => ({
+ value: String(size),
+ label: String(size),
+ }));
+
+ return (
+ <div
+ className={cn(
+ 'text-text-secondary flex flex-wrap items-center justify-between gap-3 border-t border-border px-3 py-2 text-sm',
+ className,
+ )}
+ >
+ <p className="tabular-nums" aria-live="polite">
+ {total === 0 ? 'Showing 0 of 0' : `Showing ${String(from)}–${String(to)} of ${String(total)}`}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-2">
+ <span className="whitespace-nowrap">Rows per page</span>
+ <PopoverSelect
+ aria-label="Rows per page"
+ className="w-[4.5rem]"
+ value={String(pageSize)}
+ options={sizeOptions}
+ onValueChange={value => {
+ onPageSizeChange(Number(value));
+ }}
+ />
+ </label>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ aria-label="Previous page"
+ disabled={!canPrev}
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ onClick={() => onPageChange(safePage - 1)}
+ >
+ <Icon name="chevron-left" className="size-4" />
+ </button>
+ <span className="min-w-[4.5rem] text-center tabular-nums">
+ {String(safePage + 1)} / {String(pageCount)}
+ </span>
+ <button
+ type="button"
+ aria-label="Next page"
+ disabled={!canNext}
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ onClick={() => onPageChange(safePage + 1)}
+ >
+ <Icon name="chevron-right" className="size-4" />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** Cursor / token pagination when the API has no total count. */
+export type TableTokenPaginationProps = {
+ pageSize: number;
+ rowCount: number;
+ canPrev: boolean;
+ canNext: boolean;
+ onPrev: () => void;
+ onNext: () => void;
+ onPageSizeChange: (pageSize: number) => void;
+ pageSizeOptions?: readonly number[];
+ className?: string;
+};
+
+export function TableTokenPagination({
+ pageSize,
+ rowCount,
+ canPrev,
+ canNext,
+ onPrev,
+ onNext,
+ onPageSizeChange,
+ pageSizeOptions = TABLE_PAGE_SIZE_OPTIONS,
+ className,
+}: TableTokenPaginationProps) {
+ const sizeOptions = pageSizeOptions.map(size => ({
+ value: String(size),
+ label: String(size),
+ }));
+
+ return (
+ <div
+ className={cn(
+ 'text-text-secondary flex flex-wrap items-center justify-between gap-3 border-t border-border px-3 py-2 text-sm',
+ className,
+ )}
+ >
+ <p className="tabular-nums" aria-live="polite">
+ {rowCount === 0 ? 'Showing 0' : `Showing ${String(rowCount)}`}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-2">
+ <span className="whitespace-nowrap">Rows per page</span>
+ <PopoverSelect
+ aria-label="Rows per page"
+ className="w-[4.5rem]"
+ value={String(pageSize)}
+ options={sizeOptions}
+ onValueChange={value => {
+ onPageSizeChange(Number(value));
+ }}
+ />
+ </label>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ aria-label="Previous page"
+ disabled={!canPrev}
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ onClick={onPrev}
+ >
+ <Icon name="chevron-left" className="size-4" />
+ </button>
+ <button
+ type="button"
+ aria-label="Next page"
+ disabled={!canNext}
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ onClick={onNext}
+ >
+ <Icon name="chevron-right" className="size-4" />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
index a8c8cc864..f51b48de0 100644
--- a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
+++ b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
@@ -4,6 +4,7 @@ import React, { cloneElement, isValidElement, useLayoutEffect, useRef, useState
import { createPortal } from 'react-dom';
import { cn } from '../lib/cn.js';
+import { themePortalRoot } from '../lib/themePortalRoot.js';
const TOOLTIP_VIEWPORT_PAD = 8;
@@ -47,16 +48,6 @@ export function clampCenteredTooltip({
return { top: nextTop, left: nextLeft };
}
-// Keep portaled chrome under ThemeProvider so preset/custom CSS vars still apply.
-function themePortalRoot(from: HTMLElement | null): HTMLElement {
- // A native <dialog> opened with showModal() renders in the top layer, above any
- // z-index. When the trigger lives inside one, portal into the dialog so the
- // tooltip joins the top layer instead of rendering behind the modal.
- const dialog = from?.closest('dialog');
- if (dialog instanceof HTMLElement) return dialog;
- return from?.closest('.aui-theme-root') ?? document.body;
-}
-
function hasTooltipContent(content: React.ReactNode): boolean {
if (content == null || content === false) return false;
if (typeof content === 'string') return content.trim().length > 0;
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx
new file mode 100644
index 000000000..bd9d0b9d5
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx
@@ -0,0 +1,320 @@
+'use client';
+
+import { useEffect, useMemo, useState, type FormEvent, type ReactNode } from 'react';
+
+import { useToasterOptional } from '../../containers/ToasterContainer.js';
+import { Icon } from '../../icons/Icon.js';
+import { useScheduleServer, useServer } from '../../server/ServerContext.js';
+import { libraryAgentId } from '../../server/ShellModeContext.js';
+import type { AgentLibraryEntry, Schedule } from '../../server/types.js';
+import { DraftCatalogProvider } from '../draft/DraftCatalogProvider.js';
+import { mountName } from '../lib/mountName.js';
+import { searchAllAgents } from '../lib/useSearchAgentsList.js';
+import { Button } from '../primitives/Button.js';
+import { SideDrawer } from '../primitives/SideDrawer.js';
+import {
+ cronToFormValues,
+ defaultScheduleFormValues,
+ formatCadenceSummary,
+ valuesToCron,
+ type ScheduleFormValues,
+} from './cadence.js';
+import { ScheduleFormFields } from './ScheduleFormFields.js';
+import { TestScheduleScreen } from './TestScheduleScreen.js';
+
+export type ScheduleFormDrawerProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ mode: 'create' | 'edit';
+ schedule?: Schedule;
+ initialAgentId?: string;
+ onSaved?: () => void;
+};
+
+type DrawerView = { kind: 'form'; saved?: Schedule } | { kind: 'test'; schedule: Schedule };
+
+function ScheduleFormDrawerBody({
+ open,
+ onOpenChange,
+ mode,
+ schedule,
+ initialAgentId = '',
+ onSaved,
+}: ScheduleFormDrawerProps) {
+ const scheduleServer = useScheduleServer();
+ const server = useServer();
+ const toaster = useToasterOptional();
+ const [form, setForm] = useState<ScheduleFormValues>(defaultScheduleFormValues);
+ const [agentId, setAgentId] = useState(initialAgentId);
+ const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);
+ const [view, setView] = useState<DrawerView>({ kind: 'form' });
+ const [saving, setSaving] = useState(false);
+ const [activating, setActivating] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const savedFromCreate = view.kind === 'form' ? view.saved : view.schedule;
+ const isExternalEdit = mode === 'edit' && view.kind === 'form' && view.saved == null && schedule != null;
+ const isCreatedEdit = view.kind === 'form' && view.saved != null;
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ void searchAllAgents(server)
+ .then(rows => {
+ if (cancelled) return;
+ setAgents(rows);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [open, server]);
+
+ useEffect(() => {
+ if (!open) {
+ setForm(defaultScheduleFormValues());
+ setAgentId(initialAgentId);
+ setError(null);
+ setView({ kind: 'form' });
+ setActivating(false);
+ return;
+ }
+ if (mode === 'edit' && schedule != null) {
+ setForm(
+ cronToFormValues({
+ name: schedule.name,
+ task: schedule.task,
+ cron: schedule.cron,
+ timezone: schedule.timezone,
+ }),
+ );
+ setAgentId(schedule.agentId);
+ setView({ kind: 'form' });
+ return;
+ }
+ setForm(defaultScheduleFormValues());
+ setAgentId(initialAgentId);
+ setView({ kind: 'form' });
+ }, [open, mode, schedule, initialAgentId]);
+
+ const agentOptions = useMemo(
+ () => agents.map(agent => ({ agentId: libraryAgentId(agent), name: agent.name })),
+ [agents],
+ );
+
+ const selectedAgent = useMemo(
+ () => agents.find(agent => libraryAgentId(agent) === agentId) ?? null,
+ [agents, agentId],
+ );
+
+ const agentLabel =
+ selectedAgent?.name ??
+ savedFromCreate?.agentName ??
+ schedule?.agentName ??
+ agentOptions.find(option => option.agentId === agentId)?.name ??
+ agentId;
+
+ const mcpMounts = useMemo(() => {
+ const mounts = selectedAgent?.agentSpec?.mcpServers ?? [];
+ return mounts
+ .map(mountName)
+ .filter((name: string | null): name is string => name != null)
+ .map(name => ({ name }));
+ }, [selectedAgent]);
+
+ const canSubmit = useMemo(() => {
+ const cron = valuesToCron(form);
+ return form.name.trim().length > 0 && form.task.trim().length > 0 && cron.length > 0 && agentId.length > 0;
+ }, [form, agentId]);
+
+ const enterTestView = (saved: Schedule) => {
+ setView({ kind: 'test', schedule: saved });
+ setForm(
+ cronToFormValues({
+ name: saved.name,
+ task: saved.task,
+ cron: saved.cron,
+ timezone: saved.timezone,
+ }),
+ );
+ setAgentId(saved.agentId);
+ };
+
+ const handleSave = async (event: FormEvent) => {
+ event.preventDefault();
+ if (!canSubmit) return;
+ const cron = valuesToCron(form);
+ setSaving(true);
+ setError(null);
+ try {
+ if (isExternalEdit && schedule != null) {
+ await scheduleServer.updateSchedule({
+ id: schedule.id,
+ name: form.name.trim(),
+ task: form.task.trim(),
+ cron,
+ timezone: form.timezone,
+ status: schedule.status,
+ });
+ onSaved?.();
+ onOpenChange(false);
+ return;
+ }
+
+ if (isCreatedEdit && view.kind === 'form' && view.saved != null) {
+ const saved = await scheduleServer.updateSchedule({
+ id: view.saved.id,
+ name: form.name.trim(),
+ task: form.task.trim(),
+ cron,
+ timezone: form.timezone,
+ status: 'paused',
+ });
+ onSaved?.();
+ enterTestView(saved);
+ toaster?.showSuccess({
+ title: 'Schedule saved as paused',
+ description: formatCadenceSummary({ cron: saved.cron, timezone: saved.timezone }),
+ });
+ return;
+ }
+
+ const saved = await scheduleServer.createSchedule({
+ agentId,
+ name: form.name.trim(),
+ task: form.task.trim(),
+ cron,
+ timezone: form.timezone,
+ status: 'paused',
+ });
+ onSaved?.();
+ enterTestView(saved);
+ toaster?.showSuccess({
+ title: 'Schedule saved as paused',
+ description: formatCadenceSummary({ cron: saved.cron, timezone: saved.timezone }),
+ });
+ } catch (caught) {
+ const message = caught instanceof Error ? caught.message : 'Failed to save schedule';
+ setError(message);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleActivate = async () => {
+ if (view.kind !== 'test') return;
+ setActivating(true);
+ setError(null);
+ try {
+ await scheduleServer.updateSchedule({
+ id: view.schedule.id,
+ name: view.schedule.name,
+ task: view.schedule.task,
+ cron: view.schedule.cron,
+ timezone: view.schedule.timezone,
+ status: 'active',
+ });
+ onSaved?.();
+ toaster?.showSuccess({ title: 'Schedule activated' });
+ onOpenChange(false);
+ } catch (caught) {
+ const message = caught instanceof Error ? caught.message : 'Failed to activate schedule';
+ setError(message);
+ toaster?.showError(caught);
+ } finally {
+ setActivating(false);
+ }
+ };
+
+ const title =
+ view.kind === 'test' ? 'Test Schedule' : isExternalEdit || isCreatedEdit ? 'Edit Schedule' : 'New Schedule';
+ const description =
+ view.kind === 'test'
+ ? `Recurring unattended runs of ${agentLabel}.`
+ : isExternalEdit || isCreatedEdit
+ ? 'Update cadence and task for this schedule.'
+ : 'Create a recurring unattended run for an agent.';
+
+ let footer: ReactNode;
+ if (view.kind === 'test') {
+ footer = (
+ <div className="flex flex-col gap-2">
+ {error != null ? <p className="text-failure-bg text-sm">{error}</p> : null}
+ <Button
+ type="button"
+ variant="secondary"
+ className="w-full"
+ disabled={activating}
+ onClick={() => void handleActivate()}
+ >
+ Activate Anyway
+ </Button>
+ </div>
+ );
+ } else {
+ footer = (
+ <div className="flex flex-col gap-2">
+ {error != null ? <p className="text-failure-bg text-sm">{error}</p> : null}
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
+ Cancel
+ </Button>
+ <Button type="submit" form="schedule-form" disabled={!canSubmit || saving}>
+ Save
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <SideDrawer
+ open={open}
+ onOpenChange={onOpenChange}
+ title={title}
+ description={description}
+ anchor="right"
+ size="lg"
+ headerIcon={
+ <span className="text-primary-button-bg inline-flex size-8 items-center justify-center">
+ <Icon
+ name={view.kind === 'test' || isExternalEdit || isCreatedEdit ? 'calendar' : 'calendar-plus'}
+ className="size-5"
+ />
+ </span>
+ }
+ footer={footer}
+ >
+ {view.kind === 'test' ? (
+ <TestScheduleScreen
+ schedule={view.schedule}
+ agentName={agentLabel}
+ mcpMounts={mcpMounts}
+ onEditConfiguration={() => {
+ setError(null);
+ setView({ kind: 'form', saved: view.schedule });
+ }}
+ />
+ ) : (
+ <form id="schedule-form" onSubmit={event => void handleSave(event)}>
+ <ScheduleFormFields
+ values={form}
+ onChange={setForm}
+ agentId={agentId}
+ onAgentIdChange={isExternalEdit || isCreatedEdit ? undefined : setAgentId}
+ agentOptions={agentOptions}
+ agentPickerDisabled={isExternalEdit || isCreatedEdit}
+ />
+ </form>
+ )}
+ </SideDrawer>
+ );
+}
+
+export function ScheduleFormDrawer(props: ScheduleFormDrawerProps) {
+ return (
+ <DraftCatalogProvider>
+ <ScheduleFormDrawerBody {...props} />
+ </DraftCatalogProvider>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx
new file mode 100644
index 000000000..97a70fec8
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx
@@ -0,0 +1,221 @@
+'use client';
+
+import { cn } from '../lib/cn.js';
+import { auiInputClass } from '../lib/inputClasses.js';
+import { PopoverSelect } from '../primitives/PopoverSelect.js';
+import {
+ TIMEZONE_OPTIONS,
+ WEEKDAY_OPTIONS,
+ formatCadenceSummary,
+ valuesToCron,
+ type RecurrenceKind,
+ type ScheduleFormValues,
+} from './cadence.js';
+
+export const RECURRENCE_OPTIONS: Array<{ value: RecurrenceKind; label: string }> = [
+ { value: 'hourly', label: 'Hourly' },
+ { value: 'daily', label: 'Daily' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'custom', label: 'Custom' },
+];
+
+const HOUR_OPTIONS = Array.from({ length: 24 }, (_, hour) => ({
+ value: String(hour),
+ label: hour.toString().padStart(2, '0'),
+}));
+const MINUTE_OPTIONS = [0, 15, 30, 45].map(minute => ({
+ value: String(minute),
+ label: `:${minute.toString().padStart(2, '0')}`,
+}));
+
+export type ScheduleFormFieldsProps = {
+ values: ScheduleFormValues;
+ onChange: (next: ScheduleFormValues) => void;
+ agentId: string;
+ onAgentIdChange?: (agentId: string) => void;
+ agentOptions: Array<{ agentId: string; name: string }>;
+ agentPickerDisabled?: boolean;
+};
+
+export function ScheduleFormFields({
+ values,
+ onChange,
+ agentId,
+ onAgentIdChange,
+ agentOptions,
+ agentPickerDisabled = false,
+}: ScheduleFormFieldsProps) {
+ const cron = valuesToCron(values);
+ const cadence = formatCadenceSummary({ cron, timezone: values.timezone });
+
+ const set = <K extends keyof ScheduleFormValues>(key: K, value: ScheduleFormValues[K]) => {
+ onChange({ ...values, [key]: value });
+ };
+
+ const toggleWeekday = (day: number) => {
+ const has = values.weekdays.includes(day);
+ const weekdays = has ? values.weekdays.filter(d => d !== day) : [...values.weekdays, day];
+ onChange({ ...values, weekdays: weekdays.length > 0 ? weekdays : [day] });
+ };
+
+ return (
+ <div className="flex flex-col gap-4 px-5 py-4">
+ <div className="block">
+ <span className="mb-1.5 block text-sm font-medium">Agent</span>
+ <PopoverSelect
+ aria-label="Agent"
+ placeholder="Select an agent"
+ value={agentId}
+ options={agentOptions.map(agent => ({ value: agent.agentId, label: agent.name }))}
+ onValueChange={value => onAgentIdChange?.(value)}
+ disabled={agentPickerDisabled || onAgentIdChange == null}
+ />
+ </div>
+
+ <label className="block">
+ <span className="mb-1.5 block text-sm font-medium">Name</span>
+ <input
+ value={values.name}
+ onChange={e => set('name', e.target.value)}
+ placeholder="harness-daily-digest"
+ className={auiInputClass('h-9')}
+ required
+ />
+ </label>
+
+ <label className="block">
+ <span className="mb-1.5 block text-sm font-medium">Task</span>
+ <textarea
+ value={values.task}
+ onChange={e => set('task', e.target.value)}
+ rows={3}
+ placeholder="Summarise yesterday's harness runs and post the digest…"
+ className={auiInputClass('resize-y py-2')}
+ required
+ />
+ </label>
+
+ <fieldset>
+ <legend className="mb-1.5 text-sm font-medium">Recurrence</legend>
+ <div className="grid grid-cols-4 gap-1 rounded-lg border border-border p-1">
+ {RECURRENCE_OPTIONS.map(opt => {
+ const selected = values.recurrence === opt.value;
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ className={cn(
+ 'rounded-md px-2 py-1.5 text-xs font-medium transition-colors',
+ selected
+ ? 'border border-primary-button-bg/40 bg-primary-button-bg/10 text-primary-button-bg'
+ : 'text-text-secondary hover:bg-ghost-button-hover border border-transparent',
+ )}
+ aria-pressed={selected}
+ onClick={() => set('recurrence', opt.value)}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ </fieldset>
+
+ {values.recurrence === 'hourly' ? (
+ <div className="block max-w-[8rem]">
+ <span className="mb-1.5 block text-sm font-medium">Minute</span>
+ <PopoverSelect
+ aria-label="Minute"
+ value={String(values.minute)}
+ options={MINUTE_OPTIONS}
+ onValueChange={value => set('minute', Number(value))}
+ />
+ </div>
+ ) : null}
+
+ {values.recurrence === 'daily' || values.recurrence === 'weekly' ? (
+ <div className="flex flex-wrap gap-3">
+ <div className="block min-w-[7rem] flex-1">
+ <span className="mb-1.5 block text-sm font-medium">Hour</span>
+ <PopoverSelect
+ aria-label="Hour"
+ value={String(values.hour)}
+ options={HOUR_OPTIONS}
+ onValueChange={value => set('hour', Number(value))}
+ />
+ </div>
+ <div className="block min-w-[7rem] flex-1">
+ <span className="mb-1.5 block text-sm font-medium">Minute</span>
+ <PopoverSelect
+ aria-label="Minute"
+ value={String(values.minute)}
+ options={MINUTE_OPTIONS}
+ onValueChange={value => set('minute', Number(value))}
+ />
+ </div>
+ </div>
+ ) : null}
+
+ {values.recurrence === 'weekly' ? (
+ <fieldset>
+ <legend className="mb-1.5 text-sm font-medium">Days</legend>
+ <div className="flex flex-wrap gap-1.5">
+ {WEEKDAY_OPTIONS.map(day => {
+ const selected = values.weekdays.includes(day.value);
+ return (
+ <button
+ key={day.value}
+ type="button"
+ className={cn(
+ 'rounded-md border px-2.5 py-1 text-xs font-medium',
+ selected
+ ? 'border-primary-button-bg/40 bg-primary-button-bg/10 text-primary-button-bg'
+ : 'border-border text-text-secondary hover:bg-ghost-button-hover',
+ )}
+ aria-pressed={selected}
+ onClick={() => toggleWeekday(day.value)}
+ >
+ {day.label}
+ </button>
+ );
+ })}
+ </div>
+ </fieldset>
+ ) : null}
+
+ {values.recurrence === 'custom' ? (
+ <label className="block">
+ <span className="mb-1.5 block text-sm font-medium">Cron expression</span>
+ <input
+ value={values.customCron}
+ onChange={e => set('customCron', e.target.value)}
+ placeholder="0 9 * * 1-5"
+ className={auiInputClass('h-9 font-mono')}
+ required
+ />
+ <span className="text-text-secondary mt-1 block text-xs">
+ Standard 5-field cron: minute hour day-of-month month day-of-week
+ </span>
+ </label>
+ ) : null}
+
+ <div className="block">
+ <span className="mb-1.5 block text-sm font-medium">Timezone</span>
+ <PopoverSelect
+ aria-label="Timezone"
+ value={values.timezone}
+ options={TIMEZONE_OPTIONS}
+ onValueChange={value => set('timezone', value)}
+ menuPlacement="top"
+ />
+ </div>
+
+ <div className="rounded-lg border border-border bg-secondary-bg/40 px-3 py-3">
+ <div className="flex items-start justify-between gap-3">
+ <span className="text-text-secondary text-[10px] font-semibold tracking-wide uppercase">Cadence</span>
+ <code className="text-text-secondary font-mono text-xs">{cron || '—'}</code>
+ </div>
+ <p className="text-text-primary mt-1 text-sm font-semibold">{cadence || '—'}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleLastRunsCell.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleLastRunsCell.tsx
new file mode 100644
index 000000000..681f20d1f
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleLastRunsCell.tsx
@@ -0,0 +1,19 @@
+'use client';
+
+import type { ScheduleRun } from '../../server/types.js';
+import { ScheduleRunChip } from './ScheduleRunChip.js';
+import { lastHistoricalRuns } from './scheduleRuns.js';
+
+export function ScheduleLastRunsCell({ runs }: { runs: readonly ScheduleRun[] }) {
+ const history = lastHistoricalRuns(runs);
+ if (history.length === 0) {
+ return <span className="text-text-secondary text-sm">—</span>;
+ }
+ return (
+ <div className="flex items-center gap-1">
+ {history.map(run => (
+ <ScheduleRunChip key={run.id} run={run} />
+ ))}
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleRunChip.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleRunChip.tsx
new file mode 100644
index 000000000..fd9c1acdb
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleRunChip.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Icon } from '../../icons/Icon.js';
+import type { ScheduleRun } from '../../server/types.js';
+import { cn } from '../lib/cn.js';
+import { Tooltip } from '../primitives/Tooltip.js';
+import { formatScheduleRunInstant, runChipKind, runStatusLabel } from './scheduleRuns.js';
+import { ScheduleRunTooltip } from './ScheduleRunTooltip.js';
+
+const CHIP_STYLES = {
+ success:
+ 'border-emerald-600/30 bg-emerald-500/10 text-emerald-700 dark:border-emerald-400/35 dark:bg-emerald-500/15 dark:text-emerald-300',
+ failed: 'border-red-600/30 bg-red-500/10 text-red-700 dark:border-red-400/35 dark:bg-red-500/15 dark:text-red-300',
+} as const;
+
+export function ScheduleRunChip({ run }: { run: ScheduleRun }) {
+ const kind = runChipKind(run.status);
+ const when = formatScheduleRunInstant(run.triggeredAt ?? run.scheduledFor);
+ return (
+ <Tooltip content={<ScheduleRunTooltip run={run} />} side="top">
+ <span
+ className={cn('inline-flex size-6 shrink-0 items-center justify-center rounded-md border', CHIP_STYLES[kind])}
+ aria-label={`${runStatusLabel(run.status)} run at ${when}`}
+ >
+ <Icon name={kind === 'failed' ? 'triangle-exclamation' : 'check'} className="size-3.5" />
+ </span>
+ </Tooltip>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleRunTooltip.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleRunTooltip.tsx
new file mode 100644
index 000000000..2aee776e8
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleRunTooltip.tsx
@@ -0,0 +1,18 @@
+'use client';
+
+import type { ScheduleRun } from '../../server/types.js';
+import { formatScheduleRunInstant, runStatusLabel, runTypeLabel } from './scheduleRuns.js';
+
+export function ScheduleRunTooltip({ run }: { run: ScheduleRun }) {
+ return (
+ <div className="flex flex-col gap-1 text-left text-xs">
+ <p className="text-text-primary font-medium">{runStatusLabel(run.status)}</p>
+ <p className="text-text-secondary">{runTypeLabel(run.name)}</p>
+ <p className="text-text-secondary">Scheduled for: {formatScheduleRunInstant(run.scheduledFor)}</p>
+ {run.triggeredAt != null ? (
+ <p className="text-text-secondary">Triggered at: {formatScheduleRunInstant(run.triggeredAt)}</p>
+ ) : null}
+ <p className="text-text-secondary">Triggered by: {run.triggeredBy}</p>
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleStatusBadge.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleStatusBadge.tsx
new file mode 100644
index 000000000..cf19cbcd5
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleStatusBadge.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import type { ScheduleStatus } from '../../server/types.js';
+import { cn } from '../lib/cn.js';
+
+export function ScheduleStatusBadge({ status }: { status: ScheduleStatus }) {
+ const active = status === 'active';
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium',
+ active
+ ? 'border-emerald-600/30 bg-emerald-500/10 text-emerald-700 dark:border-emerald-400/35 dark:bg-emerald-500/15 dark:text-emerald-300'
+ : 'border-border bg-secondary-bg text-text-secondary',
+ )}
+ >
+ <span
+ className={cn(
+ 'size-1.5 shrink-0 rounded-full',
+ active ? 'bg-emerald-600 dark:bg-emerald-400' : 'bg-text-secondary',
+ )}
+ aria-hidden
+ />
+ {active ? 'Active' : 'Paused'}
+ </span>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx
new file mode 100644
index 000000000..2d59b6f7a
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx
@@ -0,0 +1,526 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import { useToasterOptional } from '../../containers/ToasterContainer.js';
+import { Icon } from '../../icons/Icon.js';
+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 { auiButtonClass } from '../lib/buttonClasses.js';
+import { cn } from '../lib/cn.js';
+import { searchAllAgents } from '../lib/useSearchAgentsList.js';
+import { Button } from '../primitives/Button.js';
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '../primitives/Dialog.js';
+import { DropdownMenu, DropdownMenuItem } from '../primitives/DropdownMenu.js';
+import { PopoverSelect } from '../primitives/PopoverSelect.js';
+import SearchInput from '../primitives/SearchInput.js';
+import { Skeleton } from '../primitives/Skeleton.js';
+import {
+ DEFAULT_TABLE_PAGE_SIZE,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ TableTokenPagination,
+} from '../primitives/Table.js';
+import { formatCadenceSummary } from './cadence.js';
+import { ScheduleFormDrawer } from './ScheduleFormDrawer.js';
+import { ScheduleLastRunsCell } from './ScheduleLastRunsCell.js';
+import { ScheduleStatusBadge } from './ScheduleStatusBadge.js';
+
+type AgentOption = { agentId: string; name: string };
+
+type DrawerState = { kind: 'closed' } | { kind: 'create'; agentId?: string } | { kind: 'edit'; schedule: Schedule };
+
+const STATUS_FILTER_OPTIONS: Array<{ value: 'all' | ScheduleStatus; label: string }> = [
+ { value: 'all', label: 'All statuses' },
+ { value: 'active', label: 'Active' },
+ { value: 'paused', label: 'Paused' },
+];
+
+/** API max page size for schedules list. */
+const SCHEDULES_PAGE_SIZE_OPTIONS = [10, 25] as const;
+
+function clampPageSize(size: number): number {
+ return Math.min(Math.max(size, 1), 25);
+}
+
+function filtersFromSearch(search: string): {
+ nameQuery: string;
+ statusFilter: 'all' | ScheduleStatus;
+ agentFilter: string;
+} {
+ const share = readScheduleShareSearch(search);
+ return {
+ nameQuery: share.q ?? '',
+ statusFilter: share.status ?? 'all',
+ agentFilter: share.agent ?? 'all',
+ };
+}
+
+function ScheduleRowActions({
+ schedule,
+ running,
+ onRunNow,
+ onEdit,
+ onTogglePause,
+ onDelete,
+}: {
+ schedule: Schedule;
+ running: boolean;
+ onRunNow: () => void;
+ onEdit: () => void;
+ onTogglePause: () => void;
+ onDelete: () => void;
+}) {
+ return (
+ <div className="inline-flex items-center justify-end gap-1.5">
+ <button
+ type="button"
+ disabled={running}
+ aria-label={`Run now ${schedule.name}`}
+ className={auiButtonClass({ variant: 'outline', size: 'sm' })}
+ onClick={onRunNow}
+ >
+ <Icon name={running ? 'loader' : 'play'} className={cn('size-3.5', running && 'animate-spin')} />
+ Run now
+ </button>
+ <DropdownMenu
+ align="end"
+ trigger={
+ <button
+ type="button"
+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}
+ aria-label={`Actions for ${schedule.name}`}
+ >
+ <Icon name="ellipsis" className="size-4" />
+ </button>
+ }
+ >
+ <DropdownMenuItem onClick={onEdit}>
+ <Icon name="pencil" className="size-3.5" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={onTogglePause}>
+ <Icon name={schedule.status === 'active' ? 'pause' : 'play'} className="size-3.5" />
+ {schedule.status === 'active' ? 'Pause' : 'Resume'}
+ </DropdownMenuItem>
+ <DropdownMenuItem className="text-failure-bg focus:text-failure-bg" onClick={onDelete}>
+ <Icon name="trash" className="size-3.5" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenu>
+ </div>
+ );
+}
+
+export function SchedulesPage() {
+ const scheduleServer = useScheduleServer();
+ const server = useServer();
+ const toaster = useToasterOptional();
+
+ const [schedules, setSchedules] = useState<Schedule[]>([]);
+ const [runsByScheduleId, setRunsByScheduleId] = useState<Record<string, ScheduleRun[]>>({});
+ const [runsLoading, setRunsLoading] = useState(false);
+ const [runningScheduleIds, setRunningScheduleIds] = useState<ReadonlySet<string>>(() => new Set());
+ const [agentOptions, setAgentOptions] = useState<AgentOption[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [nameQuery, setNameQuery] = useState(() => filtersFromSearch(window.location.search).nameQuery);
+ const [statusFilter, setStatusFilter] = useState<'all' | ScheduleStatus>(
+ () => filtersFromSearch(window.location.search).statusFilter,
+ );
+ const [agentFilter, setAgentFilter] = useState(() => filtersFromSearch(window.location.search).agentFilter);
+ const [drawer, setDrawer] = useState<DrawerState>({ kind: 'closed' });
+ const [pendingDelete, setPendingDelete] = useState<Schedule | null>(null);
+ const [pageSize, setPageSize] = useState(() => clampPageSize(DEFAULT_TABLE_PAGE_SIZE));
+ const [pageToken, setPageToken] = useState<string | undefined>(undefined);
+ const [nextPageToken, setNextPageToken] = useState<string | undefined>(undefined);
+ const [prevTokenStack, setPrevTokenStack] = useState<string[]>([]);
+ const loadGenRef = useRef(0);
+
+ const loadRunsForSchedules = useCallback(
+ async ({ rows, gen }: { rows: Schedule[]; gen: number }) => {
+ if (rows.length === 0) {
+ if (gen === loadGenRef.current) setRunsByScheduleId({});
+ return;
+ }
+ setRunsLoading(true);
+ try {
+ const results = await Promise.allSettled(
+ rows.map(schedule => scheduleServer.listScheduleRuns({ scheduleId: schedule.id })),
+ );
+ if (gen !== loadGenRef.current) return;
+ setRunsByScheduleId(
+ Object.fromEntries(
+ rows.map((schedule, index) => {
+ const result = results[index];
+ const runs = result?.status === 'fulfilled' ? result.value : [];
+ return [schedule.id, runs] as const;
+ }),
+ ),
+ );
+ } finally {
+ if (gen === loadGenRef.current) setRunsLoading(false);
+ }
+ },
+ [scheduleServer],
+ );
+
+ const loadSchedules = useCallback(
+ async ({ token, size, agentId }: { token: string | undefined; size: number; agentId: string }) => {
+ const gen = ++loadGenRef.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const page = await scheduleServer.listSchedules({
+ limit: clampPageSize(size),
+ ...(token === undefined || token === '' ? {} : { pageToken: token }),
+ ...(agentId === 'all' ? {} : { agentIds: [agentId] }),
+ });
+ if (gen !== loadGenRef.current) return;
+ setSchedules(page.data);
+ setNextPageToken(page.nextPageToken);
+ void loadRunsForSchedules({ rows: page.data, gen });
+ } catch (caught) {
+ if (gen !== loadGenRef.current) return;
+ const message = caught instanceof Error ? caught.message : 'Failed to load schedules';
+ setError(message);
+ setSchedules([]);
+ setRunsByScheduleId({});
+ setNextPageToken(undefined);
+ } finally {
+ if (gen === loadGenRef.current) setLoading(false);
+ }
+ },
+ [scheduleServer, loadRunsForSchedules],
+ );
+
+ const resetToFirstPage = useCallback(
+ (next?: { size?: number; agentId?: string }) => {
+ const size = next?.size ?? pageSize;
+ const agentId = next?.agentId ?? agentFilter;
+ setPageToken(undefined);
+ setPrevTokenStack([]);
+ void loadSchedules({ token: undefined, size, agentId });
+ },
+ [agentFilter, loadSchedules, pageSize],
+ );
+
+ // Keep filters in the URL so deep links and Agents Library → Schedules work.
+ useEffect(() => {
+ replaceScheduleShareSearch({
+ agent: agentFilter === 'all' ? null : agentFilter,
+ status: statusFilter === 'all' ? null : statusFilter,
+ q: nameQuery.trim().length === 0 ? null : nameQuery,
+ });
+ }, [agentFilter, statusFilter, nameQuery]);
+
+ useEffect(() => {
+ const syncFromUrl = () => {
+ const next = filtersFromSearch(window.location.search);
+ setNameQuery(next.nameQuery);
+ setStatusFilter(next.statusFilter);
+ setAgentFilter(current => {
+ if (current === next.agentFilter) return current;
+ setPageToken(undefined);
+ setPrevTokenStack([]);
+ return next.agentFilter;
+ });
+ };
+ window.addEventListener('popstate', syncFromUrl);
+ return () => {
+ window.removeEventListener('popstate', syncFromUrl);
+ };
+ }, []);
+
+ useEffect(() => {
+ void loadSchedules({ token: pageToken, size: pageSize, agentId: agentFilter });
+ }, [agentFilter, pageSize, pageToken, loadSchedules]);
+
+ useEffect(() => {
+ let cancelled = false;
+ void searchAllAgents(server)
+ .then(rows => {
+ if (cancelled) return;
+ setAgentOptions(rows.map(agent => ({ agentId: libraryAgentId(agent), name: agent.name })));
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [server]);
+
+ const agentNameById = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const agent of agentOptions) {
+ map.set(agent.agentId, agent.name);
+ }
+ return map;
+ }, [agentOptions]);
+
+ // Name + status are client-side on the current server page only.
+ const filtered = useMemo(() => {
+ const q = nameQuery.trim().toLowerCase();
+ return schedules.filter(schedule => {
+ if (statusFilter !== 'all' && schedule.status !== statusFilter) return false;
+ if (q.length > 0 && !schedule.name.toLowerCase().includes(q)) return false;
+ return true;
+ });
+ }, [schedules, nameQuery, statusFilter]);
+
+ const hasPageNav = prevTokenStack.length > 0 || nextPageToken != null;
+
+ const handleTogglePause = async (schedule: Schedule) => {
+ const nextStatus: ScheduleStatus = schedule.status === 'active' ? 'paused' : 'active';
+ try {
+ await scheduleServer.updateSchedule({ ...schedule, status: nextStatus });
+ await loadSchedules({ token: pageToken, size: pageSize, agentId: agentFilter });
+ } catch (caught) {
+ toaster?.showError(caught);
+ }
+ };
+
+ const handleRunNow = async (schedule: Schedule) => {
+ setRunningScheduleIds(prev => new Set(prev).add(schedule.id));
+ try {
+ await scheduleServer.createScheduleRun({ scheduleId: schedule.id });
+ toaster?.showSuccess({ title: 'Run started' });
+ const runs = await scheduleServer.listScheduleRuns({ scheduleId: schedule.id });
+ setRunsByScheduleId(prev => ({ ...prev, [schedule.id]: runs }));
+ } catch (caught) {
+ toaster?.showError(caught);
+ } finally {
+ setRunningScheduleIds(prev => {
+ const next = new Set(prev);
+ next.delete(schedule.id);
+ return next;
+ });
+ }
+ };
+
+ const handleDelete = async (schedule: Schedule) => {
+ setPendingDelete(null);
+ try {
+ await scheduleServer.deleteSchedule({ id: schedule.id });
+ resetToFirstPage();
+ } catch (caught) {
+ toaster?.showError(caught);
+ }
+ };
+
+ const goNext = () => {
+ if (nextPageToken == null) return;
+ setPrevTokenStack(stack => [...stack, pageToken ?? '']);
+ setPageToken(nextPageToken);
+ };
+
+ const goPrev = () => {
+ if (prevTokenStack.length === 0) return;
+ const stack = [...prevTokenStack];
+ const prev = stack.pop();
+ setPrevTokenStack(stack);
+ setPageToken(prev === '' ? undefined : prev);
+ };
+
+ return (
+ <div className="flex h-full min-h-0 flex-col bg-primary-bg">
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-border px-4 py-2.5 md:px-6">
+ <div className="flex min-w-0 items-center gap-2">
+ <Icon name="calendar-clock" className="text-text-primary size-4" />
+ <h1 className="text-text-primary truncate text-md font-semibold">Scheduled Agents</h1>
+ </div>
+
+ <div className="ml-auto flex flex-wrap items-center gap-2">
+ <div className="w-full sm:w-56">
+ <SearchInput query={nameQuery} setQuery={setNameQuery} placeholder="Search schedules by name" />
+ </div>
+ <PopoverSelect
+ value={statusFilter}
+ onValueChange={setStatusFilter}
+ options={STATUS_FILTER_OPTIONS}
+ className="sm:w-40"
+ aria-label="Filter by status"
+ />
+ <PopoverSelect
+ value={agentFilter}
+ onValueChange={value => {
+ setAgentFilter(value);
+ setPageToken(undefined);
+ setPrevTokenStack([]);
+ }}
+ options={[
+ { value: 'all', label: 'All agents' },
+ ...agentOptions.map(agent => ({ value: agent.agentId, label: agent.name })),
+ ]}
+ className="sm:w-40"
+ aria-label="Filter by agent"
+ />
+ <Button
+ type="button"
+ onClick={() =>
+ setDrawer({
+ kind: 'create',
+ agentId: agentFilter !== 'all' ? agentFilter : undefined,
+ })
+ }
+ >
+ <Icon name="plus" className="size-3.5" />
+ Create Schedule
+ </Button>
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-auto px-4 py-4 md:px-6">
+ {loading ? (
+ <div className="flex flex-col gap-2" role="status" aria-label="Loading schedules">
+ {Array.from({ length: 5 }, (_, i) => (
+ <Skeleton key={i} className="h-12 w-full rounded-md" />
+ ))}
+ </div>
+ ) : 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.
+ </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>
+ )}
+ {(filtered.length > 0 || hasPageNav) && (
+ <TableTokenPagination
+ pageSize={pageSize}
+ rowCount={filtered.length}
+ 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([]);
+ }}
+ />
+ )}
+ </div>
+ )}
+ </div>
+
+ {drawer.kind === 'create' ? (
+ <ScheduleFormDrawer
+ open
+ mode="create"
+ initialAgentId={drawer.agentId ?? ''}
+ onOpenChange={open => {
+ if (!open) setDrawer({ kind: 'closed' });
+ }}
+ onSaved={() => resetToFirstPage()}
+ />
+ ) : null}
+ {drawer.kind === 'edit' ? (
+ <ScheduleFormDrawer
+ open
+ mode="edit"
+ schedule={drawer.schedule}
+ onOpenChange={open => {
+ if (!open) setDrawer({ kind: 'closed' });
+ }}
+ onSaved={() => void loadSchedules({ token: pageToken, size: pageSize, agentId: agentFilter })}
+ />
+ ) : null}
+ {pendingDelete != null ? (
+ <Dialog
+ open
+ onOpenChange={open => {
+ if (!open) setPendingDelete(null);
+ }}
+ aria-label="Delete schedule"
+ className="max-w-md"
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Delete schedule</DialogTitle>
+ <p className="text-text-secondary text-sm">
+ “{pendingDelete.name}” will stop running. This cannot be undone.
+ </p>
+ </DialogHeader>
+ </DialogContent>
+ <DialogFooter>
+ <Button type="button" variant="secondary" onClick={() => setPendingDelete(null)}>
+ Cancel
+ </Button>
+ <Button type="button" variant="destructive" onClick={() => void handleDelete(pendingDelete)}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </Dialog>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/TestScheduleScreen.tsx b/packages/trueforge-ui/src/atoms/schedules/TestScheduleScreen.tsx
new file mode 100644
index 000000000..1bab76a91
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/TestScheduleScreen.tsx
@@ -0,0 +1,182 @@
+'use client';
+
+import { useEffect, useState, type ReactNode } from 'react';
+
+import { useToasterOptional } from '../../containers/ToasterContainer.js';
+import { Icon } from '../../icons/Icon.js';
+import { useOptionalCatalogServer, useScheduleServer } from '../../server/ServerContext.js';
+import type { ConnectorState, Schedule, ScheduleRun } from '../../server/types.js';
+import { useDraftCatalog } from '../draft/DraftCatalogProvider.js';
+import { ConnectorConnectButton } from '../draft/DraftCompositeSelector.js';
+import { auiButtonClass } from '../lib/buttonClasses.js';
+import { cn } from '../lib/cn.js';
+import { Button } from '../primitives/Button.js';
+import { formatCadenceSummary, formatRelativeTime } from './cadence.js';
+import { ScheduleRunChip } from './ScheduleRunChip.js';
+import { runTypeLabel } from './scheduleRuns.js';
+import { ScheduleStatusBadge } from './ScheduleStatusBadge.js';
+
+export type ScheduleMcpMount = {
+ name: string;
+};
+
+export type TestScheduleScreenProps = {
+ schedule: Schedule;
+ agentName: string;
+ mcpMounts: readonly ScheduleMcpMount[];
+ onEditConfiguration: () => void;
+};
+
+function mountConnector(connectors: ConnectorState[], name: string): ConnectorState | null {
+ return connectors.find(connector => connector.name === name || connector.id === name) ?? null;
+}
+
+function ScheduleMcpConnect({
+ connector,
+ onConnected,
+}: {
+ connector: ConnectorState;
+ onConnected: () => Promise<void>;
+}) {
+ const catalog = useOptionalCatalogServer();
+ if (catalog == null) return null;
+ return <ConnectorConnectButton connector={connector} onConnected={onConnected} />;
+}
+
+function DetailRow({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="flex items-start justify-between gap-3 border-b border-border px-3 py-2.5 last:border-b-0">
+ <span className="text-text-secondary shrink-0 text-[10px] font-semibold tracking-wide uppercase">{label}</span>
+ <div className="min-w-0 text-right text-sm text-text-primary">{children}</div>
+ </div>
+ );
+}
+
+export function TestScheduleScreen({ schedule, agentName, mcpMounts, onEditConfiguration }: TestScheduleScreenProps) {
+ const scheduleServer = useScheduleServer();
+ const toaster = useToasterOptional();
+ const { connectors, ensureLoaded, refreshConnectors, loading, error } = useDraftCatalog();
+ const [running, setRunning] = useState(false);
+ const [lastTestRun, setLastTestRun] = useState<ScheduleRun | null>(null);
+ const cadence = formatCadenceSummary({ cron: schedule.cron, timezone: schedule.timezone });
+
+ const handleRunTest = async () => {
+ setRunning(true);
+ try {
+ const run = await scheduleServer.createScheduleRun({ scheduleId: schedule.id });
+ setLastTestRun(run);
+ toaster?.showSuccess({ title: 'Test run started' });
+ } catch (caught) {
+ toaster?.showError(caught);
+ } finally {
+ setRunning(false);
+ }
+ };
+
+ useEffect(() => {
+ ensureLoaded();
+ }, [ensureLoaded]);
+
+ useEffect(() => {
+ if (error != null) toaster?.showError(error);
+ }, [error, toaster]);
+
+ return (
+ <div className="flex flex-col gap-4 px-5 py-4">
+ <section className="overflow-hidden rounded-lg border border-border bg-card-bg">
+ <DetailRow label="Agent">{agentName}</DetailRow>
+ <DetailRow label="Name">{schedule.name}</DetailRow>
+ <DetailRow label="Task">
+ <span className="whitespace-pre-wrap break-words">{schedule.task}</span>
+ </DetailRow>
+ <DetailRow label="Cadence">
+ <div className="flex flex-wrap items-center justify-end gap-1.5">
+ <span>{cadence}</span>
+ <code className="text-text-secondary font-mono text-xs">{schedule.cron}</code>
+ </div>
+ </DetailRow>
+ <DetailRow label="Status">
+ <ScheduleStatusBadge status={schedule.status} />
+ </DetailRow>
+ <div className="flex justify-end px-3 py-2.5">
+ <Button type="button" variant="outline" size="sm" onClick={onEditConfiguration}>
+ <Icon name="pencil" className="size-3.5" />
+ Edit Configuration
+ </Button>
+ </div>
+ </section>
+
+ <section className="overflow-hidden rounded-lg border border-border bg-card-bg">
+ <div className="border-b border-border px-3 py-2">
+ <h3 className="text-text-secondary text-[10px] font-semibold tracking-wide uppercase">Tool Authorization</h3>
+ </div>
+ {mcpMounts.length === 0 ? (
+ <p className="text-text-secondary px-3 py-3 text-sm">No MCP connectors configured for this agent.</p>
+ ) : (
+ <ul className="divide-y divide-border">
+ {mcpMounts.map(mount => {
+ const connector = mountConnector(connectors, mount.name);
+ const authenticated = connector?.authenticated === true;
+ const unavailable = connector == null && !loading;
+ return (
+ <li key={mount.name} className="flex items-center gap-2 px-3 py-2.5">
+ <span
+ className={cn(
+ 'inline-flex size-4 shrink-0 items-center justify-center rounded-full border',
+ authenticated
+ ? 'border-emerald-600/40 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300'
+ : 'border-border text-transparent',
+ )}
+ aria-hidden
+ >
+ {authenticated ? <Icon name="check" className="size-3" /> : null}
+ </span>
+ <span className="text-text-primary min-w-0 flex-1 truncate text-sm">{mount.name}</span>
+ {authenticated ? (
+ <span className="text-success-bg text-xs font-medium">Connected</span>
+ ) : unavailable ? (
+ <span className="text-text-secondary text-xs">Unavailable</span>
+ ) : connector != null && connector.authenticated === false ? (
+ <ScheduleMcpConnect connector={connector} onConnected={refreshConnectors} />
+ ) : loading ? (
+ <span className="text-text-secondary text-xs">Loading…</span>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+
+ <section className="overflow-hidden rounded-lg border border-border bg-card-bg">
+ <div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
+ <h3 className="text-text-secondary text-[10px] font-semibold tracking-wide uppercase">Test Run</h3>
+ <button
+ type="button"
+ disabled={running}
+ onClick={() => void handleRunTest()}
+ className={auiButtonClass({ variant: 'default', size: 'sm' })}
+ >
+ <Icon name={running ? 'loader' : 'play'} className={cn('size-3.5', running && 'animate-spin')} />
+ Run Test
+ </button>
+ </div>
+ {lastTestRun == null ? (
+ <p className="text-text-secondary px-3 py-3 text-sm">
+ Run a one-off test using the schedule task. This does not change the cron pending run.
+ </p>
+ ) : (
+ <div className="flex items-center gap-3 px-3 py-3">
+ <ScheduleRunChip run={lastTestRun} />
+ <div className="min-w-0 text-sm">
+ <p className="text-text-primary font-medium">{runTypeLabel(lastTestRun.name)}</p>
+ <p className="text-text-secondary">
+ {formatRelativeTime(lastTestRun.triggeredAt ?? lastTestRun.scheduledFor)}
+ </p>
+ </div>
+ </div>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/cadence.ts b/packages/trueforge-ui/src/atoms/schedules/cadence.ts
new file mode 100644
index 000000000..7a2ce4ca4
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/cadence.ts
@@ -0,0 +1,247 @@
+export type RecurrenceKind = 'hourly' | 'daily' | 'weekly' | 'custom';
+
+export type ScheduleFormValues = {
+ name: string;
+ task: string;
+ recurrence: RecurrenceKind;
+ hour: number;
+ minute: number;
+ /** Cron DOW: 0=Sun … 6=Sat. Used when recurrence is weekly. */
+ weekdays: number[];
+ customCron: string;
+ timezone: string;
+};
+
+export const TIMEZONE_OPTIONS = [
+ { value: 'America/New_York', label: 'America/New_York (ET)' },
+ { value: 'America/Chicago', label: 'America/Chicago (CT)' },
+ { value: 'America/Denver', label: 'America/Denver (MT)' },
+ { value: 'America/Los_Angeles', label: 'America/Los_Angeles (PT)' },
+ { value: 'UTC', label: 'UTC' },
+ { value: 'Europe/London', label: 'Europe/London (GMT/BST)' },
+ { value: 'Europe/Berlin', label: 'Europe/Berlin (CET)' },
+ { value: 'Asia/Kolkata', label: 'Asia/Kolkata (IST)' },
+ { value: 'Asia/Tokyo', label: 'Asia/Tokyo (JST)' },
+] as const;
+
+export const WEEKDAY_OPTIONS = [
+ { value: 1, label: 'Mon' },
+ { value: 2, label: 'Tue' },
+ { value: 3, label: 'Wed' },
+ { value: 4, label: 'Thu' },
+ { value: 5, label: 'Fri' },
+ { value: 6, label: 'Sat' },
+ { value: 0, label: 'Sun' },
+] as const;
+
+const TZ_ABBR: Record<string, string> = {
+ 'America/New_York': 'ET',
+ 'America/Chicago': 'CT',
+ 'America/Denver': 'MT',
+ 'America/Los_Angeles': 'PT',
+ UTC: 'UTC',
+ 'Europe/London': 'GMT',
+ 'Europe/Berlin': 'CET',
+ 'Asia/Kolkata': 'IST',
+ 'Asia/Tokyo': 'JST',
+};
+
+export function defaultScheduleFormValues(): ScheduleFormValues {
+ return {
+ name: '',
+ task: '',
+ recurrence: 'daily',
+ hour: 9,
+ minute: 0,
+ weekdays: [1],
+ customCron: '0 9 * * *',
+ timezone: 'America/New_York',
+ };
+}
+
+export function timezoneAbbrev(timezone: string): string {
+ return TZ_ABBR[timezone] ?? timezone.split('/').pop() ?? timezone;
+}
+
+function pad2(n: number): string {
+ return n.toString().padStart(2, '0');
+}
+
+function formatClock({ hour, minute }: { hour: number; minute: number }): string {
+ const period = hour >= 12 ? 'PM' : 'AM';
+ const h12 = hour % 12 === 0 ? 12 : hour % 12;
+ return `${String(h12)}:${pad2(minute)} ${period}`;
+}
+
+export function valuesToCron(values: ScheduleFormValues): string {
+ const minute = values.minute;
+ const hour = values.hour;
+ switch (values.recurrence) {
+ case 'hourly':
+ return `${String(minute)} * * * *`;
+ case 'daily':
+ return `${String(minute)} ${String(hour)} * * *`;
+ case 'weekly': {
+ const days = [...values.weekdays].sort((a, b) => a - b);
+ const dow = days.length > 0 ? days.join(',') : '*';
+ return `${String(minute)} ${String(hour)} * * ${dow}`;
+ }
+ case 'custom':
+ return values.customCron.trim();
+ }
+}
+
+export function formatCadenceSummary(input: { cron: string; timezone: string }): string {
+ const abbr = timezoneAbbrev(input.timezone);
+ const parts = input.cron.trim().split(/\s+/);
+ if (parts.length !== 5) return input.cron;
+
+ const [minuteRaw, hourRaw, dayOfMonthRaw, monthRaw, dowRaw] = parts;
+ if (dayOfMonthRaw !== '*' || monthRaw !== '*') return input.cron;
+
+ const minute = Number(minuteRaw);
+ const hour = Number(hourRaw);
+
+ if (hourRaw === '*' && dowRaw === '*' && minuteRaw !== undefined && !Number.isNaN(minute)) {
+ return `Hourly at :${pad2(minute)} ${abbr}`;
+ }
+
+ if (
+ dowRaw === '*' &&
+ hourRaw !== undefined &&
+ minuteRaw !== undefined &&
+ !Number.isNaN(hour) &&
+ !Number.isNaN(minute)
+ ) {
+ return `Daily ${formatClock({ hour, minute })} ${abbr}`;
+ }
+
+ if (
+ dowRaw === '1-5' &&
+ hourRaw !== undefined &&
+ minuteRaw !== undefined &&
+ !Number.isNaN(hour) &&
+ !Number.isNaN(minute)
+ ) {
+ return `Weekdays ${formatClock({ hour, minute })} ${abbr}`;
+ }
+
+ if (
+ dowRaw != null &&
+ /^\d(?:,\d)*$/.test(dowRaw) &&
+ hourRaw !== undefined &&
+ minuteRaw !== undefined &&
+ !Number.isNaN(hour) &&
+ !Number.isNaN(minute)
+ ) {
+ const labels = dowRaw.split(',').map(d => WEEKDAY_OPTIONS.find(w => w.value === Number(d))?.label ?? d);
+ if (labels.length === 1) {
+ const day = labels[0] === 'Mon' ? 'Monday' : labels[0];
+ return `Every ${day} ${formatClock({ hour, minute })} ${abbr}`;
+ }
+ return `${labels.join(', ')} ${formatClock({ hour, minute })} ${abbr}`;
+ }
+
+ return input.cron;
+}
+
+/** Best-effort parse of known patterns into form values for edit. */
+export function cronToFormValues(input: {
+ name: string;
+ task: string;
+ cron: string;
+ timezone: string;
+}): ScheduleFormValues {
+ const base = defaultScheduleFormValues();
+ const parts = input.cron.trim().split(/\s+/);
+ if (parts.length !== 5) {
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'custom',
+ customCron: input.cron,
+ };
+ }
+
+ const [minuteRaw, hourRaw, dom, month, dowRaw] = parts;
+ const minute = Number(minuteRaw);
+ const hour = Number(hourRaw);
+
+ if (dom !== '*' || month !== '*') {
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'custom',
+ customCron: input.cron,
+ };
+ }
+
+ if (hourRaw === '*' && dowRaw === '*' && !Number.isNaN(minute)) {
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'hourly',
+ minute,
+ customCron: input.cron,
+ };
+ }
+
+ if (dowRaw === '*' && !Number.isNaN(hour) && !Number.isNaN(minute)) {
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'daily',
+ hour,
+ minute,
+ customCron: input.cron,
+ };
+ }
+
+ if (dowRaw != null && /^\d(?:,\d)*$/.test(dowRaw) && !Number.isNaN(hour) && !Number.isNaN(minute)) {
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'weekly',
+ hour,
+ minute,
+ weekdays: dowRaw.split(',').map(Number),
+ customCron: input.cron,
+ };
+ }
+
+ // Weekdays 1-5 → treat as custom so the cron string is preserved on save.
+ return {
+ ...base,
+ name: input.name,
+ task: input.task,
+ timezone: input.timezone,
+ recurrence: 'custom',
+ customCron: input.cron,
+ hour: Number.isNaN(hour) ? base.hour : hour,
+ minute: Number.isNaN(minute) ? base.minute : minute,
+ };
+}
+
+export function formatRelativeTime(iso: string | null, nowMs = Date.now()): string {
+ if (iso == null) return 'Never';
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return 'Never';
+ const deltaSec = Math.round((nowMs - then) / 1000);
+ if (deltaSec < 60) return 'just now';
+ const mins = Math.round(deltaSec / 60);
+ if (mins < 60) return `${String(mins)} min ago`;
+ const hours = Math.round(mins / 60);
+ if (hours < 48) return `${String(hours)} hour${hours === 1 ? '' : 's'} ago`;
+ const days = Math.round(hours / 24);
+ return `${String(days)} day${days === 1 ? '' : 's'} ago`;
+}
diff --git a/packages/trueforge-ui/src/atoms/schedules/scheduleRuns.ts b/packages/trueforge-ui/src/atoms/schedules/scheduleRuns.ts
new file mode 100644
index 000000000..04dc35e97
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/schedules/scheduleRuns.ts
@@ -0,0 +1,40 @@
+import type { ScheduleRun, ScheduleRunStatus } from '../../server/types.js';
+
+export function isManualRun(name: string): boolean {
+ return name.startsWith('manual-');
+}
+
+export function runChipKind(status: ScheduleRunStatus): 'success' | 'failed' {
+ if (status === 'failed') return 'failed';
+ return 'success';
+}
+
+export function runStatusLabel(status: ScheduleRunStatus): string {
+ if (status === 'failed') return 'Failed';
+ if (status === 'triggered') return 'Triggered';
+ return 'Scheduled';
+}
+
+export function runTypeLabel(name: string): string {
+ return isManualRun(name) ? 'Manual test' : 'Cron';
+}
+
+/** Newest-first API rows → up to `limit` historical runs, oldest on the left. */
+export function lastHistoricalRuns(runs: readonly ScheduleRun[], limit = 5): ScheduleRun[] {
+ const historical = runs.filter(run => run.status !== 'scheduled');
+ return historical.slice(0, limit).reverse();
+}
+
+export function formatScheduleRunInstant(iso: string | null): string {
+ if (iso == null) return '—';
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return '—';
+ return new Intl.DateTimeFormat(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ hour12: true,
+ }).format(date);
+}
diff --git a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx b/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
index 5b7923871..82ae36059 100644
--- a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
+++ b/packages/trueforge-ui/src/containers/ThreadListContainer.tsx
@@ -132,12 +132,13 @@ function ThreadListItemRow({
const mainThreadId = useAuiState(s => s.threads.mainThreadId);
const agentName = readThreadAgentName(custom);
const showDelete = canDeleteSession && remoteId != null;
+ const sidebarNavOpen = shell?.libraryOpen === true || shell?.sessionsOpen === true || shell?.schedulesOpen === true;
return (
<ThreadListItemPrimitive.Root className="min-w-0">
<ThreadListRow
title={title ?? 'New Chat'}
- active={id === mainThreadId}
+ active={id === mainThreadId && !sidebarNavOpen}
agentName={agentName}
lastMessageAt={lastMessageAt}
onSelect={() => {
@@ -145,6 +146,7 @@ function ThreadListItemRow({
shell?.setSettingsOpen(false);
shell?.setLibraryOpen(false);
shell?.setSessionsOpen(false);
+ shell?.setSchedulesOpen(false);
// Prefer custom.isMutable (session wire); agentName-only is a legacy fallback.
const sessionMutable = threadListItemIsMutable(custom);
@@ -269,6 +271,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
const ThreadListNewButton = useSlot('ThreadListNewButton');
const AgentsLibraryButton = useSlot('AgentsLibraryButton');
const SessionsBrowserButton = useSlot('SessionsBrowserButton');
+ const SchedulesButton = useSlot('SchedulesButton');
const ThreadListRowSkeleton = useSlot('ThreadListRowSkeleton');
const ThreadListEmptyState = useSlot('ThreadListEmptyState');
@@ -331,6 +334,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
return;
}
shell?.setSettingsOpen(false);
+ shell?.setSchedulesOpen(false);
void Promise.resolve(aui.threads().switchToNewThread()).catch(() => undefined);
};
@@ -356,6 +360,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =
{showNewChat ? <ThreadListNewButton onClick={handleNewChat} /> : null}
<AgentsLibraryButton />
<SessionsBrowserButton />
+ <SchedulesButton />
</div>
}
>
diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx
index 0ce6efa9b..9dee342a8 100644
--- a/packages/trueforge-ui/src/icons/IconRegistry.tsx
+++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx
@@ -7,6 +7,9 @@ import {
Bot,
Box,
Brain,
+ Calendar,
+ CalendarClock,
+ CalendarPlus,
Check,
ChevronDown,
ChevronLeft,
@@ -36,11 +39,13 @@ import {
LogOut,
Maximize2,
Menu,
+ MessageSquareText,
Minimize2,
Moon,
PanelLeftClose,
PanelLeftOpen,
Paperclip,
+ Pause,
Pencil,
Play,
Plug,
@@ -116,6 +121,10 @@ const defaults: Record<string, IconEntry> = {
check: Check,
pencil: Pencil,
play: Play,
+ pause: Pause,
+ calendar: Calendar,
+ 'calendar-clock': CalendarClock,
+ 'calendar-plus': CalendarPlus,
'square-pen': SquarePen,
'rotate-right': RotateCw,
broom: Broom,
@@ -150,6 +159,8 @@ const defaults: Record<string, IconEntry> = {
'oauth-loading': Loader2,
'welcome-sparkle': Sparkle,
robot: Bot,
+ bot: Bot,
+ 'message-square-text': MessageSquareText,
'book-open': BookOpen,
funnel: ListFilter,
plug: Plug,
diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts
index 6f97b8f51..e94fb39db 100644
--- a/packages/trueforge-ui/src/index.ts
+++ b/packages/trueforge-ui/src/index.ts
@@ -36,8 +36,46 @@ export type { ButtonProps, ButtonSize, ButtonVariant } from './atoms/primitives/
export { CenteredModal } from './atoms/primitives/CenteredModal.js';
export type { CenteredModalProps } from './atoms/primitives/CenteredModal.js';
export type { IconButtonProps } from './atoms/primitives/IconButton.js';
+export { PopoverSelect } from './atoms/primitives/PopoverSelect.js';
+export type { PopoverSelectOption, PopoverSelectProps } from './atoms/primitives/PopoverSelect.js';
+export { SideDrawer } from './atoms/primitives/SideDrawer.js';
+export type { SideDrawerAnchor, SideDrawerProps, SideDrawerSize } from './atoms/primitives/SideDrawer.js';
export { Switch } from './atoms/primitives/Switch.js';
export type { SwitchProps, SwitchSize } from './atoms/primitives/Switch.js';
+export {
+ DEFAULT_TABLE_PAGE_SIZE,
+ TABLE_PAGE_SIZE_OPTIONS,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TablePagination,
+ TableRow,
+ TableTokenPagination,
+} from './atoms/primitives/Table.js';
+export type {
+ TableBodyProps,
+ TableCellProps,
+ TableHeadProps,
+ TableHeaderProps,
+ TablePaginationProps,
+ TableProps,
+ TableRowProps,
+ TableTokenPaginationProps,
+} from './atoms/primitives/Table.js';
+export { ScheduleFormDrawer } from './atoms/schedules/ScheduleFormDrawer.js';
+export type { ScheduleFormDrawerProps } from './atoms/schedules/ScheduleFormDrawer.js';
+export { ScheduleFormFields } from './atoms/schedules/ScheduleFormFields.js';
+export type { ScheduleFormFieldsProps } from './atoms/schedules/ScheduleFormFields.js';
+export { ScheduleLastRunsCell } from './atoms/schedules/ScheduleLastRunsCell.js';
+export { ScheduleRunChip } from './atoms/schedules/ScheduleRunChip.js';
+export { SchedulesPage } from './atoms/schedules/SchedulesPage.js';
+export { ScheduleStatusBadge } from './atoms/schedules/ScheduleStatusBadge.js';
+export { TestScheduleScreen } from './atoms/schedules/TestScheduleScreen.js';
+export type { ScheduleMcpMount, TestScheduleScreenProps } from './atoms/schedules/TestScheduleScreen.js';
+export { SchedulesButton } from './atoms/SchedulesButton.js';
+export type { SchedulesButtonProps } from './atoms/SchedulesButton.js';
export { Icon } from './icons/Icon.js';
export type { IconProps } from './icons/Icon.js';
@@ -245,7 +283,9 @@ export {
useOptionalAgentMetricsServer,
useOptionalAgentSessionsServer,
useOptionalCatalogServer,
+ useOptionalScheduleServer,
useOptionalServer,
+ useScheduleServer,
useServer,
useServerCapabilities,
} from './server/ServerContext.js';
diff --git a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx
index 1d7e6b519..95f501a3d 100644
--- a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx
+++ b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx
@@ -15,6 +15,9 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js';
import { useSlot } from '../theme/SlotsProvider.js';
const TruefoundrySettingsBuilder = lazy(() => import('../containers/SettingsBuilder/index.js'));
+const SchedulesPage = lazy(() =>
+ import('../atoms/schedules/SchedulesPage.js').then(m => ({ default: m.SchedulesPage })),
+);
export function DrawerLayout({ className }: { className?: string }) {
const aui = useAui();
@@ -34,11 +37,12 @@ export function DrawerLayout({ className }: { className?: string }) {
const settingsOpen = shell?.settingsOpen === true;
const libraryOpen = shell?.libraryOpen === true;
const sessionsOpen = shell?.sessionsOpen === true;
- const overlayOpen = settingsOpen || libraryOpen || sessionsOpen;
+ const schedulesOpen = shell?.schedulesOpen === true;
+ const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen;
useEffect(() => {
- if (libraryOpen || sessionsOpen) setThreadsOpen(false);
- }, [libraryOpen, sessionsOpen]);
+ if (libraryOpen || sessionsOpen || schedulesOpen) setThreadsOpen(false);
+ }, [libraryOpen, sessionsOpen, schedulesOpen]);
useEffect(() => {
if (!threadsOpen) return;
@@ -71,6 +75,7 @@ export function DrawerLayout({ className }: { className?: string }) {
shell.openDraft();
} else {
shell?.setSettingsOpen(false);
+ shell?.setSchedulesOpen(false);
aui.threads().switchToNewThread();
}
setThreadsOpen(false);
@@ -87,6 +92,21 @@ export function DrawerLayout({ className }: { className?: string }) {
<ClearChatButton />
<SaveAgentButton />
</>
+ ) : libraryOpen || schedulesOpen ? (
+ <>
+ <button
+ type="button"
+ className={auiButtonClass({ variant: 'ghost', size: 'sm' })}
+ onClick={() => {
+ shell?.setLibraryOpen(false);
+ shell?.setSchedulesOpen(false);
+ }}
+ >
+ <Icon name="arrow-left" />
+ Back to chat
+ </button>
+ <span className="min-w-0 flex-1" />
+ </>
) : (
<span className="min-w-0 flex-1" />
)}
@@ -140,6 +160,22 @@ export function DrawerLayout({ className }: { className?: string }) {
<AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />
) : libraryOpen ? (
<AgentsLibrary onSelectAgent={() => setThreadsOpen(false)} />
+ ) : schedulesOpen ? (
+ <Suspense
+ fallback={
+ <div
+ className="flex h-full items-center justify-center"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ }
+ >
+ <SchedulesPage />
+ </Suspense>
) : isIdle ? (
<SelectAgentEmptyState />
) : (
diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
index 672f912c2..15984b2e1 100644
--- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
+++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx
@@ -18,6 +18,9 @@ import { useSlot } from '../theme/SlotsProvider.js';
import { useBrand } from '../theme/ThemeProvider.js';
const TruefoundrySettingsBuilder = lazy(() => import('../containers/SettingsBuilder/index.js'));
+const SchedulesPage = lazy(() =>
+ import('../atoms/schedules/SchedulesPage.js').then(m => ({ default: m.SchedulesPage })),
+);
// Survives ChatProvider remounts when openDraft / selectAgent bumps runtimeKey.
let desktopCollapsed = false;
@@ -36,6 +39,7 @@ export function SidebarLayout({ className }: { className?: string }) {
const AgentsLibraryButton = useSlot('AgentsLibraryButton');
const SessionsBrowserButton = useSlot('SessionsBrowserButton');
const SessionsPage = useSlot('SessionsPage');
+ const SchedulesButton = useSlot('SchedulesButton');
const ClearChatButton = useSlot('ClearChatButton');
const SaveAgentButton = useSlot('SaveAgentButton');
const SelectAgentEmptyState = useSlot('SelectAgentEmptyState');
@@ -56,7 +60,8 @@ export function SidebarLayout({ className }: { className?: string }) {
const settingsOpen = shell?.settingsOpen === true;
const libraryOpen = shell?.libraryOpen === true;
const sessionsOpen = shell?.sessionsOpen === true;
- const overlayOpen = settingsOpen || libraryOpen || sessionsOpen;
+ const schedulesOpen = shell?.schedulesOpen === true;
+ const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen;
const hasChatHeaderContent = useChatHeaderContentVisible();
useEffect(() => {
@@ -91,6 +96,7 @@ export function SidebarLayout({ className }: { className?: string }) {
return;
}
shell?.setSettingsOpen(false);
+ shell?.setSchedulesOpen(false);
void Promise.resolve(aui.threads().switchToNewThread()).catch(() => undefined);
};
@@ -142,6 +148,7 @@ export function SidebarLayout({ className }: { className?: string }) {
) : null}
<AgentsLibraryButton compact />
<SessionsBrowserButton compact />
+ <SchedulesButton compact />
</nav>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden" hidden={collapsed}>
<ThreadListContainer />
@@ -216,6 +223,22 @@ export function SidebarLayout({ className }: { className?: string }) {
<AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />
) : libraryOpen ? (
<AgentsLibrary onSelectAgent={() => setMobileNavOpen(false)} />
+ ) : schedulesOpen ? (
+ <Suspense
+ fallback={
+ <div
+ className="flex h-full items-center justify-center"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ }
+ >
+ <SchedulesPage />
+ </Suspense>
) : isIdle ? (
<SelectAgentEmptyState />
) : (
diff --git a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx
index e638633dd..7b9d1202f 100644
--- a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx
+++ b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx
@@ -15,6 +15,9 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js';
import { useSlot } from '../theme/SlotsProvider.js';
const TruefoundrySettingsBuilder = lazy(() => import('../containers/SettingsBuilder/index.js'));
+const SchedulesPage = lazy(() =>
+ import('../atoms/schedules/SchedulesPage.js').then(m => ({ default: m.SchedulesPage })),
+);
export type StackChatPanelProps = {
className?: string;
@@ -40,6 +43,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
const settingsOpen = shell?.settingsOpen === true;
const libraryOpen = shell?.libraryOpen === true;
const sessionsOpen = shell?.sessionsOpen === true;
+ const schedulesOpen = shell?.schedulesOpen === true;
useEffect(() => {
if (isIdle) return;
@@ -78,6 +82,24 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
<div className="min-h-0 flex-1">
<AgentsLibrary onSelectAgent={() => setView('thread')} />
</div>
+ ) : schedulesOpen ? (
+ <div className="min-h-0 flex-1">
+ <Suspense
+ fallback={
+ <div
+ className="flex h-full items-center justify-center"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ }
+ >
+ <SchedulesPage />
+ </Suspense>
+ </div>
) : view === 'list' ? (
<ThreadListContainer onThreadOpen={() => setView('thread')} />
) : (
@@ -102,7 +124,23 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
</>
)}
{/* Stable mount: only ShellActions needs to survive Settings / list / thread; host end chrome stays in the thread header. */}
- <footer className="flex shrink-0 justify-end border-t border-border px-2 py-1.5">
+ <footer className="flex shrink-0 items-center justify-between border-t border-border px-2 py-1.5">
+ {libraryOpen || schedulesOpen ? (
+ <button
+ type="button"
+ className={auiButtonClass({ variant: 'ghost', size: 'sm' })}
+ onClick={() => {
+ shell?.setLibraryOpen(false);
+ shell?.setSchedulesOpen(false);
+ setView('thread');
+ }}
+ >
+ <Icon name="arrow-left" />
+ Back to chat
+ </button>
+ ) : (
+ <span />
+ )}
<ShellActions key="shell-actions" />
</footer>
</div>
diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts
index 47406fea1..6dfa11ee2 100644
--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts
+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts
@@ -12,6 +12,7 @@ import { createSandboxProviderCatalog } from './catalogs/sandboxProviderCatalog.
import { createSkillCatalog } from './catalogs/skillCatalog.js';
import { createHarnessChatServer } from './chatServer.js';
import { createTrueForgeClient, type CreateTrueForgeClientOptions } from './client.js';
+import { createScheduleServer } from './schedules/scheduleServer.js';
import type { HarnessAgentSpec } from './types.js';
export { createHarnessAgentMetricsServer, type CreateHarnessAgentMetricsServerOptions } from './agentMetricsServer.js';
@@ -56,6 +57,7 @@ export {
export { createTrueForgeClient } from './client.js';
export type { CreateTrueForgeClientOptions } from './client.js';
export { getCapabilities, listConfiguredMcpServers, listModels, listSkills } from './lists.js';
+export { createScheduleServer } from './schedules/scheduleServer.js';
export type { HarnessAgentSpec, HarnessMcpServerMount, HarnessSkillMount } from './types.js';
export type CreateTrueForgeAgentUIServerOptions = CreateTrueForgeClientOptions & {
@@ -84,5 +86,6 @@ export function createTrueForgeAgentUIServer(options: CreateTrueForgeAgentUIServ
catalog,
sessions: createHarnessAgentSessionsServer({ ...clientOptions, client }),
metrics: createHarnessAgentMetricsServer({ ...clientOptions, client }),
+ schedules: createScheduleServer({ client }),
});
}
diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts
new file mode 100644
index 000000000..895e28a9e
--- /dev/null
+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts
@@ -0,0 +1,162 @@
+/**
+ * Harness ScheduleServer adapter — maps flat runtime DTOs to SDK wire (manifest + agentName).
+ */
+import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';
+import type {
+ CreateScheduleRequest,
+ CreateScheduleRunRequest,
+ ListResult,
+ ListSchedulesParams,
+ Schedule,
+ ScheduleRun,
+ ScheduleServer,
+ ScheduleStatus,
+ UpdateScheduleRequest,
+} from '../../../server/types.js';
+import { toListResult } from '../chatServer.js';
+
+/** Matches API PAGE_LIMIT for schedules list. */
+const SCHEDULES_PAGE_LIMIT = 25;
+
+type AgentIndex = {
+ idToName: ReadonlyMap<string, string>;
+ nameToId: ReadonlyMap<string, string>;
+};
+
+async function loadAgentIndex(client: TrueForge): Promise<AgentIndex> {
+ const { data } = await client.agents.list();
+ const idToName = new Map<string, string>();
+ const nameToId = new Map<string, string>();
+ for (const agent of data) {
+ idToName.set(agent.id, agent.name);
+ nameToId.set(agent.name, agent.id);
+ }
+ return { idToName, nameToId };
+}
+
+function resolveAgentName(agentId: string, index: AgentIndex): string {
+ const byId = index.idToName.get(agentId);
+ if (byId != null) return byId;
+ if (index.nameToId.has(agentId)) return agentId;
+ throw new Error(`Unknown agent: ${agentId}`);
+}
+
+function collectAgentIds(req?: ListSchedulesParams): string[] {
+ const ids: string[] = [];
+ if (req?.agentIds != null) {
+ for (const id of req.agentIds) {
+ if (id !== '') ids.push(id);
+ }
+ }
+ if (req?.agentId != null && req.agentId !== '') ids.push(req.agentId);
+ return [...new Set(ids)];
+}
+
+function wireStatus(manifest: TrueForgeApi.ScheduleManifest): ScheduleStatus {
+ return manifest.status ?? 'active';
+}
+
+function toUiSchedule(wire: TrueForgeApi.Schedule, index: AgentIndex): Schedule {
+ const agentId = index.nameToId.get(wire.agentName) ?? wire.agentName;
+ return {
+ id: wire.id,
+ name: wire.name,
+ agentId,
+ agentName: wire.agentName,
+ task: wire.manifest.task,
+ cron: wire.manifest.cron,
+ timezone: wire.manifest.timezone ?? 'UTC',
+ status: wireStatus(wire.manifest),
+ lastRunAt: null,
+ };
+}
+
+function toWireManifest(input: {
+ task: string;
+ cron: string;
+ timezone?: string;
+ status?: ScheduleStatus;
+}): TrueForgeApi.ScheduleManifest {
+ return {
+ task: input.task,
+ cron: input.cron,
+ timezone: input.timezone ?? 'UTC',
+ status: input.status ?? 'active',
+ };
+}
+
+function toIsoInstant(value: Date | string): string {
+ if (value instanceof Date) return value.toISOString();
+ return value;
+}
+
+function toUiScheduleRun(wire: TrueForgeApi.ScheduleRun): ScheduleRun {
+ return {
+ id: wire.id,
+ scheduleId: wire.scheduleId,
+ name: wire.name,
+ scheduledFor: toIsoInstant(wire.scheduledFor),
+ status: wire.status,
+ triggeredAt: wire.triggeredAt == null ? null : toIsoInstant(wire.triggeredAt),
+ triggeredBy: wire.triggeredBy,
+ };
+}
+
+export function createScheduleServer(options: { client: TrueForge }): ScheduleServer {
+ const { client } = options;
+
+ return {
+ async listSchedules(req?: ListSchedulesParams): Promise<ListResult<Schedule>> {
+ const index = await loadAgentIndex(client);
+ const agentIds = collectAgentIds(req);
+ const agentNames = agentIds.length === 0 ? undefined : agentIds.map(id => resolveAgentName(id, index)).join(',');
+ const limit = Math.min(Math.max(req?.limit ?? SCHEDULES_PAGE_LIMIT, 1), SCHEDULES_PAGE_LIMIT);
+ const page = await client.schedules.list({
+ limit,
+ ...(req?.pageToken === undefined || req.pageToken === '' ? {} : { pageToken: req.pageToken }),
+ ...(agentNames === undefined ? {} : { agentNames }),
+ });
+ return toListResult(page, row => toUiSchedule(row, index));
+ },
+
+ async getSchedule({ id }): Promise<Schedule> {
+ const index = await loadAgentIndex(client);
+ const { data } = await client.schedules.get(id);
+ return toUiSchedule(data, index);
+ },
+
+ async createSchedule(req: CreateScheduleRequest): Promise<Schedule> {
+ const index = await loadAgentIndex(client);
+ const agentName = resolveAgentName(req.agentId, index);
+ const { data } = await client.schedules.create({
+ agentName,
+ name: req.name,
+ manifest: toWireManifest(req),
+ });
+ return toUiSchedule(data, index);
+ },
+
+ async updateSchedule(req: UpdateScheduleRequest): Promise<Schedule> {
+ const index = await loadAgentIndex(client);
+ const { data } = await client.schedules.update(req.id, {
+ name: req.name,
+ manifest: toWireManifest(req),
+ });
+ return toUiSchedule(data, index);
+ },
+
+ async deleteSchedule({ id }): Promise<void> {
+ await client.schedules.delete(id);
+ },
+
+ async listScheduleRuns({ scheduleId }): Promise<ScheduleRun[]> {
+ const { data } = await client.schedules.listRuns(scheduleId);
+ return data.map(toUiScheduleRun);
+ },
+
+ async createScheduleRun(req: CreateScheduleRunRequest): Promise<ScheduleRun> {
+ const { data } = await client.schedules.createRun({ scheduleId: req.scheduleId });
+ return toUiScheduleRun(data);
+ },
+ };
+}
diff --git a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx
index 1d7f87864..1577159ec 100644
--- a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx
+++ b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx
@@ -32,6 +32,7 @@ export function ShellRouteSync({
libraryOpen: shell.libraryOpen,
sessionsOpen: shell.sessionsOpen,
libraryAgentId: shell.libraryAgentId,
+ schedulesOpen: shell.schedulesOpen,
pendingSessionId: shell.pendingSessionId,
activeRemoteId,
mode: shell.mode,
@@ -99,6 +100,9 @@ export function ShellRouteSync({
case 'libraryAgent':
shell.openLibraryAgent(target.agentId);
return;
+ case 'schedules':
+ shell.setSchedulesOpen(true);
+ return;
case 'session':
shell.setLibraryOpen(false);
if (shell.pendingSessionId === target.sessionId || activeRemoteId === target.sessionId) return;
@@ -111,6 +115,7 @@ export function ShellRouteSync({
case 'root':
shell.setSettingsOpen(false);
shell.setLibraryOpen(false);
+ shell.setSchedulesOpen(false);
switch (shell.agentConfigMode) {
case 'AgentLibrary':
shell.openLibraryHome();
@@ -149,6 +154,8 @@ export function ShellRouteSync({
shell.setSessionsOpen(true);
} else if (urlPlace.type === 'libraryAgent') {
shell.openLibraryAgent(urlPlace.agentId);
+ } else if (urlPlace.type === 'schedules') {
+ shell.setSchedulesOpen(true);
} else {
const chatPlace = deriveChatPlace(snapshot);
if (!placesEqual(chatPlace, urlPlace)) applyPlace(urlPlace);
@@ -232,6 +239,10 @@ export function ShellRouteSync({
if (urlPlace.type !== 'sessionsBrowser' && shell.sessionsOpen) {
shell.setSessionsOpen(false);
}
+ if (urlPlace.type !== 'schedules' && shell.schedulesOpen) {
+ // Leaving schedules via Back to a chat place.
+ shell.setSchedulesOpen(false);
+ }
applyPlace(urlPlace);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.pathname]);
diff --git a/packages/trueforge-ui/src/routing/derivePlace.ts b/packages/trueforge-ui/src/routing/derivePlace.ts
index 59dbf4b6b..cb0d3b87d 100644
--- a/packages/trueforge-ui/src/routing/derivePlace.ts
+++ b/packages/trueforge-ui/src/routing/derivePlace.ts
@@ -1,7 +1,8 @@
import type { RoutePlace, ShellSnapshot } from './types.js';
/**
- * The chat place implied by shell state, ignoring overlay routes (settings, library).
+ * The chat place implied by shell state, ignoring settings, schedules,
+ * sessions-browser, and library overlays.
* SingleAgent canonicalizes to `root` so `/` and `/agents/{name}` alias.
*/
export function deriveChatPlace(snapshot: ShellSnapshot): RoutePlace {
@@ -19,9 +20,10 @@ export function deriveChatPlace(snapshot: ShellSnapshot): RoutePlace {
return { type: 'root' };
}
-/** Full place including overlay routes, which win over the chat place. */
+/** Full place with overlay priority: settings, schedules, sessions, library, chat. */
export function derivePlace(snapshot: ShellSnapshot): RoutePlace {
if (snapshot.settingsOpen) return { type: 'settings' };
+ if (snapshot.schedulesOpen) return { type: 'schedules' };
if (snapshot.sessionsOpen) return { type: 'sessionsBrowser' };
if (snapshot.libraryOpen && snapshot.libraryAgentId != null) {
return { type: 'libraryAgent', agentId: snapshot.libraryAgentId };
diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.ts
index 5c1010b7e..1daee3c34 100644
--- a/packages/trueforge-ui/src/routing/paths.ts
+++ b/packages/trueforge-ui/src/routing/paths.ts
@@ -1,3 +1,4 @@
+import { clearScheduleShareSearch } from '../utils/scheduleShareUrl.js';
import { readSessionShareSearch, writeSessionShareSearch } from '../utils/sessionShareUrl.js';
import type { ResolvedRoutes, RoutePlace, RoutesConfig } from './types.js';
@@ -6,6 +7,7 @@ const DEFAULTS = {
settings: '/settings',
library: '/library',
libraryAgent: '/library/:agentId',
+ schedules: '/schedules',
agent: '/agents/:agentName',
session: '/sessions/:sessionId',
sessionsBrowser: '/sessions',
@@ -31,6 +33,7 @@ export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes {
settings: resolveOptional(paths?.settings, DEFAULTS.settings),
library: resolveOptional(paths?.library, DEFAULTS.library),
libraryAgent: resolveOptional(paths?.libraryAgent, DEFAULTS.libraryAgent),
+ schedules: resolveOptional(paths?.schedules, DEFAULTS.schedules),
agent: resolveOptional(paths?.agent, DEFAULTS.agent),
session: resolveOptional(paths?.session, DEFAULTS.session),
sessionsBrowser: resolveOptional(paths?.sessionsBrowser, DEFAULTS.sessionsBrowser),
@@ -62,6 +65,8 @@ export function buildPath(place: RoutePlace, routes: ResolvedRoutes): string | n
return routes.library;
case 'libraryAgent':
return routes.libraryAgent == null ? null : fillTemplate(routes.libraryAgent, place.agentId);
+ case 'schedules':
+ return routes.schedules;
case 'agent':
return routes.agent == null ? null : fillTemplate(routes.agent, place.agentName);
case 'session':
@@ -81,6 +86,7 @@ export function sanitizeSearchForPlace(place: RoutePlace, search: string): strin
const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
if (place.type === 'sessionsBrowser') {
writeSessionShareSearch(params, { tab: null });
+ clearScheduleShareSearch(params);
} else if (place.type === 'libraryAgent') {
const share = readSessionShareSearch(search);
writeSessionShareSearch(params, {
@@ -88,6 +94,16 @@ export function sanitizeSearchForPlace(place: RoutePlace, search: string): strin
timeRange: null,
...(share.sessionId != null && share.agentId !== place.agentId ? { sessionId: null, agentId: null } : {}),
});
+ clearScheduleShareSearch(params);
+ } else if (place.type === 'schedules') {
+ writeSessionShareSearch(params, {
+ sessionId: null,
+ agentId: null,
+ tab: null,
+ view: null,
+ timeRange: null,
+ });
+ // Keep `agent` / `status` / `q` — owned by the schedules place.
} else {
writeSessionShareSearch(params, {
sessionId: null,
@@ -96,6 +112,7 @@ export function sanitizeSearchForPlace(place: RoutePlace, search: string): strin
view: null,
timeRange: null,
});
+ clearScheduleShareSearch(params);
}
const next = params.toString();
return next.length > 0 ? `?${next}` : '';
@@ -148,6 +165,9 @@ export function matchPath(pathname: string, routes: ResolvedRoutes): RoutePlace
const agentId = matchTemplate(routes.libraryAgent, segments);
if (agentId != null) return { type: 'libraryAgent', agentId };
}
+ if (routes.schedules != null && normalized === routes.schedules) {
+ return { type: 'schedules' };
+ }
if (routes.agent != null) {
const agentName = matchTemplate(routes.agent, segments);
if (agentName != null) return { type: 'agent', agentName };
diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.ts
index 0d1e01a0b..655ab387e 100644
--- a/packages/trueforge-ui/src/routing/types.ts
+++ b/packages/trueforge-ui/src/routing/types.ts
@@ -11,7 +11,8 @@ export type RoutePlace =
| { type: 'settings' }
| { type: 'library' }
| { type: 'libraryAgent'; agentId: string }
- | { type: 'sessionsBrowser' };
+ | { type: 'sessionsBrowser' }
+ | { type: 'schedules' };
/**
* Host-facing route path customization. Only honored when `withRouter`.
@@ -30,6 +31,8 @@ export type RoutesConfig = {
library?: string | false;
/** Agent detail under the library. Default `'/library/:agentId'`. */
libraryAgent?: string | false;
+ /** Schedules page. `false` keeps schedules overlay-only (no URL). Default `'/schedules'`. */
+ schedules?: string | false;
/** Immutable "Try" agent. `false` disables. Default `'/agents/:agentName'`. */
agent?: string | false;
/** Session deep link. `false` disables. Default `'/sessions/:sessionId'`. */
@@ -46,6 +49,7 @@ export type ResolvedRoutes = {
settings: string | null;
library: string | null;
libraryAgent: string | null;
+ schedules: string | null;
agent: string | null;
session: string | null;
sessionsBrowser: string | null;
@@ -57,6 +61,7 @@ export type ShellSnapshot = {
libraryOpen: boolean;
sessionsOpen: boolean;
libraryAgentId: string | null;
+ schedulesOpen: boolean;
pendingSessionId?: string;
/** Remote id of the active thread once a fresh chat is persisted. */
activeRemoteId?: string;
diff --git a/packages/trueforge-ui/src/server/ServerContext.tsx b/packages/trueforge-ui/src/server/ServerContext.tsx
index 5e8110b2c..8326e9440 100644
--- a/packages/trueforge-ui/src/server/ServerContext.tsx
+++ b/packages/trueforge-ui/src/server/ServerContext.tsx
@@ -8,6 +8,7 @@ import type {
AgentSessionsServer,
AgentUIServer,
CatalogServer,
+ ScheduleServer,
} from './types.js';
const ServerContext = createContext<AgentUIServer | null>(null);
@@ -110,3 +111,15 @@ export function useAgentMetricsServer(): AgentMetricsServer {
export function useOptionalAgentMetricsServer(): AgentMetricsServer | null {
return useOptionalServer()?.metrics ?? null;
}
+
+export function useScheduleServer(): ScheduleServer {
+ const server = useServer();
+ if (server.schedules == null) {
+ throw new Error('useScheduleServer requires AgentUIServer.schedules. Pass schedules to createTrueFoundryServer.');
+ }
+ return server.schedules;
+}
+
+export function useOptionalScheduleServer(): ScheduleServer | null {
+ return useOptionalServer()?.schedules ?? null;
+}
diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsx
index 16ba02196..db189b423 100644
--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx
+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx
@@ -9,7 +9,11 @@ import {
withCapabilitiesSandbox,
writeDraftSpecPreferences,
} from './draftSpecPreferences.js';
-import { useOptionalRefreshServerCapabilities, useServerCapabilities } from './ServerContext.js';
+import {
+ useOptionalRefreshServerCapabilities,
+ useOptionalScheduleServer,
+ useServerCapabilities,
+} from './ServerContext.js';
import type { AgentLibraryEntry, AgentSpec } from './types.js';
/** Host-facing shell configuration for agent / library / composer chrome. */
@@ -74,6 +78,8 @@ type ShellModeContextValue = {
setSessionsOpen: (open: boolean) => void;
openLibraryAgent: (agentId: string) => void;
closeLibraryAgent: () => void;
+ schedulesOpen: boolean;
+ setSchedulesOpen: (open: boolean) => void;
/**
* Bind from the Agents Library (Try = immutable, Edit = mutable + agentSpec).
* Prefer this over `selectAgent` / `openDraft` when both fields are available.
@@ -173,6 +179,7 @@ export function ShellModeProvider({
}) {
const capabilities = useServerCapabilities();
const refreshCapabilities = useOptionalRefreshServerCapabilities();
+ const scheduleServer = useOptionalScheduleServer();
const rememberedSpecRef = useRef<AgentSpec | null>(readDraftSpecPreferences());
const mutableSeedRef = useRef(rememberedSpecRef.current ?? mutableSeedFromConfig(agentConfig));
if (
@@ -198,10 +205,13 @@ export function ShellModeProvider({
const [libraryOpenState, setLibraryOpenState] = useState(false);
const [sessionsOpenState, setSessionsOpenState] = useState(false);
const [libraryAgentId, setLibraryAgentId] = useState<string | null>(null);
+ 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 settingsOpen = settingsEnabled && settingsOpenState;
+ const schedulesEnabled = scheduleServer != null;
+ const schedulesOpen = schedulesEnabled && schedulesOpenState;
const libraryOpen = isLibraryEnabled && libraryOpenState;
const sessionsOpen = sessionsOpenState;
const setSessionsOpen = useCallback((open: boolean) => {
@@ -209,6 +219,7 @@ export function ShellModeProvider({
setSettingsOpenState(false);
setLibraryOpenState(false);
setLibraryAgentId(null);
+ setSchedulesOpenState(false);
} else {
replaceSessionShareSearch({ view: null });
}
@@ -220,6 +231,7 @@ export function ShellModeProvider({
if (open) {
setSettingsOpenState(false);
setSessionsOpen(false);
+ setSchedulesOpenState(false);
}
setLibraryAgentId(null);
setLibraryOpenState(open);
@@ -231,6 +243,7 @@ export function ShellModeProvider({
if (!isLibraryEnabled) return;
setSettingsOpenState(false);
setSessionsOpen(false);
+ setSchedulesOpenState(false);
setLibraryOpenState(true);
setLibraryAgentId(agentId);
},
@@ -248,11 +261,24 @@ export function ShellModeProvider({
setLibraryOpenState(false);
setLibraryAgentId(null);
setSessionsOpen(false);
+ setSchedulesOpenState(false);
}
setSettingsOpenState(settingsEnabled && open);
},
[setSessionsOpen, settingsEnabled],
);
+ const setSchedulesOpen = useCallback(
+ (open: boolean) => {
+ if (open) {
+ setSettingsOpenState(false);
+ setLibraryOpenState(false);
+ setLibraryAgentId(null);
+ setSessionsOpen(false);
+ }
+ setSchedulesOpenState(schedulesEnabled && open);
+ },
+ [schedulesEnabled, setSessionsOpen],
+ );
useEffect(() => {
if (!settingsEnabled) {
@@ -260,6 +286,12 @@ export function ShellModeProvider({
}
}, [settingsEnabled]);
+ useEffect(() => {
+ if (!schedulesEnabled) {
+ setSchedulesOpenState(false);
+ }
+ }, [schedulesEnabled]);
+
const invalidateAgentsList = useCallback(() => {
setAgentsListEpoch(n => n + 1);
}, []);
@@ -295,6 +327,7 @@ export function ShellModeProvider({
setLibraryOpenState(false);
setLibraryAgentId(null);
setSessionsOpen(false);
+ setSchedulesOpen(false);
setPendingSessionId(undefined);
setMode({
status: 'active',
@@ -314,6 +347,7 @@ export function ShellModeProvider({
setLibraryOpenState(false);
setLibraryAgentId(null);
setSessionsOpen(false);
+ setSchedulesOpen(false);
setPendingSessionId(undefined);
setMode({
status: 'active',
@@ -324,7 +358,7 @@ export function ShellModeProvider({
});
bumpEpoch(false);
},
- [isComposerEnabled, isLibraryEnabled, bumpEpoch, setSettingsOpen, setSessionsOpen],
+ [isComposerEnabled, isLibraryEnabled, bumpEpoch, setSettingsOpen, setSessionsOpen, setSchedulesOpen],
);
const bindMutableAgent = useCallback(
@@ -383,6 +417,7 @@ export function ShellModeProvider({
setLibraryOpenState(false);
setLibraryAgentId(null);
setSessionsOpen(false);
+ setSchedulesOpen(false);
setPendingSessionId(sessionId);
const isMutable = isMutableOpt ?? agentName == null;
if (isMutable) {
@@ -410,7 +445,16 @@ export function ShellModeProvider({
});
bumpEpoch(false);
},
- [isLibraryEnabled, isComposerEnabled, locked, lockedAgentName, bumpEpoch, setSettingsOpen, setSessionsOpen],
+ [
+ isLibraryEnabled,
+ isComposerEnabled,
+ locked,
+ lockedAgentName,
+ bumpEpoch,
+ setSettingsOpen,
+ setSessionsOpen,
+ setSchedulesOpen,
+ ],
);
const clearChat = useCallback(() => {
@@ -439,9 +483,10 @@ export function ShellModeProvider({
setSettingsOpen(false);
setLibraryOpenState(false);
setLibraryAgentId(null);
+ setSchedulesOpen(false);
setMode({ status: 'idle' });
bumpEpoch(false);
- }, [isLibraryEnabled, isComposerEnabled, setSettingsOpen, bumpEpoch]);
+ }, [isLibraryEnabled, isComposerEnabled, setSettingsOpen, setSchedulesOpen, bumpEpoch]);
// Mutable remounts are driven only by mutableEpoch (library Edit / New Chat / Clear).
// Agent id and model must not be in the key — saveAgent binds those onto the same draft.
@@ -472,6 +517,8 @@ export function ShellModeProvider({
setSessionsOpen,
openLibraryAgent,
closeLibraryAgent,
+ schedulesOpen,
+ setSchedulesOpen,
selectLibraryAgent,
bindMutableAgent,
selectAgent,
@@ -504,6 +551,8 @@ export function ShellModeProvider({
setSessionsOpen,
openLibraryAgent,
closeLibraryAgent,
+ schedulesOpen,
+ setSchedulesOpen,
selectLibraryAgent,
bindMutableAgent,
selectAgent,
diff --git a/packages/trueforge-ui/src/server/createTrueFoundryServer.ts b/packages/trueforge-ui/src/server/createTrueFoundryServer.ts
index ed342ba73..d73b31f48 100644
--- a/packages/trueforge-ui/src/server/createTrueFoundryServer.ts
+++ b/packages/trueforge-ui/src/server/createTrueFoundryServer.ts
@@ -12,6 +12,7 @@ import type {
ModelSelection,
SaveAgentRequest,
SaveAgentResult,
+ ScheduleServer,
SearchAgentsParams,
} from './types.js';
@@ -26,6 +27,7 @@ export type CreateTrueFoundryServerOptions<
TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,
TSessions extends AgentSessionsServer<TSpec> = AgentSessionsServer<TSpec>,
TMetrics extends AgentMetricsServer = AgentMetricsServer,
+ TSchedules extends ScheduleServer = ScheduleServer,
> = {
/** Chat port — e.g. from `@truefoundry/agent-server-adapter`. */
chatServer: AgentChatServer<TSpec>;
@@ -42,6 +44,8 @@ export type CreateTrueFoundryServerOptions<
sessions?: TSessions;
/** Optional aggregate metrics + chart port. */
metrics?: TMetrics;
+ /** Schedules listing + CRUD. Optional. */
+ schedules?: TSchedules;
};
export type TrueFoundryServer<
@@ -55,11 +59,13 @@ export type TrueFoundryServer<
TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,
TSessions extends AgentSessionsServer<TSpec> = AgentSessionsServer<TSpec>,
TMetrics extends AgentMetricsServer = AgentMetricsServer,
+ TSchedules extends ScheduleServer = ScheduleServer,
> = AgentChatServer<TSpec> &
AgentBuilderServer<TSpec, TModel, TSkill, TMcp, TAgent, TSave, TCapabilities> & {
catalog?: TCatalog;
sessions?: TSessions;
metrics?: TMetrics;
+ schedules?: TSchedules;
};
/**
@@ -78,6 +84,7 @@ export function createTrueFoundryServer<
TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,
TSessions extends AgentSessionsServer<TSpec> = AgentSessionsServer<TSpec>,
TMetrics extends AgentMetricsServer = AgentMetricsServer,
+ TSchedules extends ScheduleServer = ScheduleServer,
>(
opts: CreateTrueFoundryServerOptions<
TSpec,
@@ -89,9 +96,22 @@ export function createTrueFoundryServer<
TCatalog,
TCapabilities,
TSessions,
- TMetrics
+ TMetrics,
+ TSchedules
>,
-): TrueFoundryServer<TSpec, TModel, TSkill, TMcp, TAgent, TSave, TCatalog, TCapabilities, TSessions, TMetrics> {
+): TrueFoundryServer<
+ TSpec,
+ TModel,
+ TSkill,
+ TMcp,
+ TAgent,
+ TSave,
+ TCatalog,
+ TCapabilities,
+ TSessions,
+ TMetrics,
+ TSchedules
+> {
const builder: AgentBuilderServer<TSpec, TModel, TSkill, TMcp, TAgent, TSave, TCapabilities> = {
getCapabilities: opts.getCapabilities,
getModels: opts.getModels,
@@ -118,13 +138,15 @@ export function createTrueFoundryServer<
TCatalog,
TCapabilities,
TSessions,
- TMetrics
+ TMetrics,
+ TSchedules
> = {
...opts.chatServer,
...builder,
...(opts.catalog != null ? { catalog: opts.catalog } : {}),
...(opts.sessions != null ? { sessions: opts.sessions } : {}),
...(opts.metrics != null ? { metrics: opts.metrics } : {}),
+ ...(opts.schedules != null ? { schedules: opts.schedules } : {}),
};
return server;
}
diff --git a/packages/trueforge-ui/src/server/types.ts b/packages/trueforge-ui/src/server/types.ts
index 334a3f7ec..556b32b05 100644
--- a/packages/trueforge-ui/src/server/types.ts
+++ b/packages/trueforge-ui/src/server/types.ts
@@ -52,6 +52,8 @@ export type {
CreateConnectorRequest,
CreateModelProviderRequest,
CreateSandboxProviderRequest,
+ CreateScheduleRequest,
+ CreateScheduleRunRequest,
CreateSessionRequest,
CreateSkillRequest,
CreateSkillRequestBase,
@@ -59,6 +61,7 @@ export type {
GithubSkill,
ImportGithubSkillRequest,
ListResult,
+ ListSchedulesParams,
ListSessionEventsParams,
ListSessionsOrder,
ListSessionsParams,
@@ -86,6 +89,11 @@ export type {
SandboxSnapshotSyncStatus,
SaveAgentRequest,
SaveAgentResult,
+ Schedule,
+ ScheduleRun,
+ ScheduleRunStatus,
+ ScheduleServer,
+ ScheduleStatus,
SearchAgentsParams,
SelectRegistrySkillRequest,
Session,
@@ -107,6 +115,7 @@ export type {
UpdateConnectorRequest,
UpdateModelProviderRequest,
UpdateSandboxProviderRequest,
+ UpdateScheduleRequest,
UpdateSessionRequest,
UserMessage,
UserMessageContent,
diff --git a/packages/trueforge-ui/src/styles.css b/packages/trueforge-ui/src/styles.css
index 24fb446fe..621d3a10a 100644
--- a/packages/trueforge-ui/src/styles.css
+++ b/packages/trueforge-ui/src/styles.css
@@ -156,14 +156,15 @@
* brand names and sidebars), while `.aui-root` covers standalone thread
* shells and consumer slot overrides. `.font-sans-flex` remains available
* for explicitly portaled surfaces. All three override `--font-sans`.
- * Override `--font-agent-ui` in host CSS to brand the font (the SDK
- * stylesheet does not load webfonts from a CDN).
+ * Override `--font-agent-ui` in host CSS to brand the font. Default face is
+ * Google Sans (loaded once via `ensureStyles`).
*/
.aui-theme-root,
.aui-root,
.font-sans-flex {
--font-sans: var(
--font-agent-ui,
+ 'Google Sans',
ui-sans-serif,
system-ui,
-apple-system,
@@ -175,6 +176,7 @@
);
font-family: var(
--font-agent-ui,
+ 'Google Sans',
ui-sans-serif,
system-ui,
-apple-system,
@@ -310,6 +312,9 @@
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
+ /* Between text-sm (0.875rem) and text-lg (1.125rem); Tailwind has no default text-md. */
+ --text-md: 1rem;
+ --text-md--line-height: 1.5rem;
}
/* Monaco embeds: blend into surrounding cards (transparent editor chrome). */
diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.ts
index df5a1859d..d1d8e3518 100644
--- a/packages/trueforge-ui/src/theme/defaultSlots.ts
+++ b/packages/trueforge-ui/src/theme/defaultSlots.ts
@@ -55,6 +55,7 @@ import { OpenUiFenceBlock } from '../atoms/OpenUiFenceBlock.js';
import { SandboxArtifactDownload } from '../atoms/SandboxArtifactDownload.js';
import { SandboxToolCallCard } from '../atoms/SandboxToolCallCard.js';
import { SaveAgentButton } from '../atoms/SaveAgentButton.js';
+import { SchedulesButton } from '../atoms/SchedulesButton.js';
import { ScrollToBottomButton } from '../atoms/ScrollToBottomButton.js';
import { SelectAgentEmptyState } from '../atoms/SelectAgentEmptyState.js';
import { SessionsBrowserButton } from '../atoms/SessionsBrowserButton.js';
@@ -187,6 +188,7 @@ export const defaultSlots = {
AgentSessions,
AgentCodeSnippets,
AgentCodeBlock,
+ SchedulesButton,
SaveAgentButton,
SelectAgentEmptyState,
ClearChatButton,
diff --git a/packages/trueforge-ui/src/theme/ensureStyles.ts b/packages/trueforge-ui/src/theme/ensureStyles.ts
index cedcf1aa3..c85309395 100644
--- a/packages/trueforge-ui/src/theme/ensureStyles.ts
+++ b/packages/trueforge-ui/src/theme/ensureStyles.ts
@@ -1,14 +1,30 @@
import { EMBEDDED_STYLES } from './embeddedStyles.js';
export const TRUEFORGE_UI_STYLE_ID = 'trueforge-ui-styles';
+export const TRUEFORGE_UI_FONTS_ID = 'trueforge-ui-fonts';
+
+/** Default UI face — https://fonts.google.com/specimen/Google+Sans */
+const GOOGLE_SANS_STYLESHEET =
+ 'https://fonts.googleapis.com/css2?family=Google+Sans:ital,opsz,wght@0,17..18,400..700;1,17..18,400..700&display=swap';
+
+function ensureGoogleSans(): void {
+ if (document.getElementById(TRUEFORGE_UI_FONTS_ID) != null) return;
+ const link = document.createElement('link');
+ link.id = TRUEFORGE_UI_FONTS_ID;
+ link.rel = 'stylesheet';
+ link.href = GOOGLE_SANS_STYLESHEET;
+ document.head.appendChild(link);
+}
/**
- * Injects the published SDK stylesheet once into `document.head`.
+ * Injects the published SDK stylesheet once into `document.head`, and loads
+ * Google Sans for the default `trueforge` preset.
* No-ops when a host already loaded styles (same id) or when CSS was not
* embedded (dev without a prior CSS build).
*/
export function ensureStyles(css: string = EMBEDDED_STYLES): void {
if (typeof document === 'undefined') return;
+ ensureGoogleSans();
if (document.getElementById(TRUEFORGE_UI_STYLE_ID) != null) return;
if (css.length === 0) return;
diff --git a/packages/trueforge-ui/src/theme/presets/index.ts b/packages/trueforge-ui/src/theme/presets/index.ts
index 02ab44ca3..8ead73c7d 100644
--- a/packages/trueforge-ui/src/theme/presets/index.ts
+++ b/packages/trueforge-ui/src/theme/presets/index.ts
@@ -12,7 +12,7 @@ const trueforge: PresetTokens = {
primaryBg: '#FFFFFF',
secondaryBg: '#F4F4F5',
border: '#E4E4E7',
- fontFamily: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
+ fontFamily: '"Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
inputBoxBg: '#FAFAFA',
inputBorder: '#E4E4E7',
textPrimary: '#18181B',
@@ -52,7 +52,7 @@ const trueforge: PresetTokens = {
primaryBg: '#1F1F22',
secondaryBg: '#27272A',
border: '#343439',
- fontFamily: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
+ fontFamily: '"Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
inputBoxBg: '#27272A',
inputBorder: '#343439',
textPrimary: '#FDFDFD',
diff --git a/packages/trueforge-ui/src/utils/scheduleShareUrl.ts b/packages/trueforge-ui/src/utils/scheduleShareUrl.ts
new file mode 100644
index 000000000..ddc9e13dc
--- /dev/null
+++ b/packages/trueforge-ui/src/utils/scheduleShareUrl.ts
@@ -0,0 +1,64 @@
+import type { ScheduleStatus } from '../server/types.js';
+
+export const SCHEDULE_AGENT_QUERY = 'agent';
+export const SCHEDULE_STATUS_QUERY = 'status';
+export const SCHEDULE_NAME_QUERY = 'q';
+
+export const SCHEDULE_SHARE_CHANGE_EVENT = 'trueforge-schedule-share';
+
+export type ScheduleShareSearch = {
+ /** Agent id filter; `null` means all agents. */
+ agent: string | null;
+ /** Status filter; `null` means all statuses. */
+ status: ScheduleStatus | null;
+ /** Name search; `null` when empty. */
+ q: string | null;
+};
+
+export type ScheduleShareWrite = {
+ agent?: string | null;
+ status?: ScheduleStatus | null;
+ q?: string | null;
+};
+
+function nonEmpty(value: string | null): string | null {
+ return value != null && value.length > 0 ? value : null;
+}
+
+function parseStatus(value: string | null): ScheduleStatus | null {
+ if (value === 'active' || value === 'paused') return value;
+ return null;
+}
+
+export function readScheduleShareSearch(search: string): ScheduleShareSearch {
+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
+ return {
+ agent: nonEmpty(params.get(SCHEDULE_AGENT_QUERY)),
+ status: parseStatus(params.get(SCHEDULE_STATUS_QUERY)),
+ q: nonEmpty(params.get(SCHEDULE_NAME_QUERY)),
+ };
+}
+
+export function writeScheduleShareSearch(params: URLSearchParams, next: ScheduleShareWrite): void {
+ if (next.agent === null) params.delete(SCHEDULE_AGENT_QUERY);
+ else if (next.agent != null) params.set(SCHEDULE_AGENT_QUERY, next.agent);
+ if (next.status === null) params.delete(SCHEDULE_STATUS_QUERY);
+ else if (next.status != null) params.set(SCHEDULE_STATUS_QUERY, next.status);
+ if (next.q === null) params.delete(SCHEDULE_NAME_QUERY);
+ else if (next.q != null) params.set(SCHEDULE_NAME_QUERY, next.q);
+}
+
+/** Drop all schedules-owned query keys (used when leaving the schedules place). */
+export function clearScheduleShareSearch(params: URLSearchParams): void {
+ params.delete(SCHEDULE_AGENT_QUERY);
+ params.delete(SCHEDULE_STATUS_QUERY);
+ params.delete(SCHEDULE_NAME_QUERY);
+}
+
+export function replaceScheduleShareSearch(next: ScheduleShareWrite): string {
+ const url = new URL(window.location.href);
+ writeScheduleShareSearch(url.searchParams, next);
+ window.history.replaceState(window.history.state, '', url);
+ window.dispatchEvent(new Event(SCHEDULE_SHARE_CHANGE_EVENT));
+ return url.search;
+}
diff --git a/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx
index 652c3b01e..0b9612f13 100644
--- a/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx
+++ b/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx
@@ -26,6 +26,8 @@ describe('AgentSessionsFilters', () => {
</ServerProvider>,
);
+ fireEvent.click(await screen.findByRole('button', { name: 'Filter sessions by agent' }));
+
await waitFor(() => expect(screen.getByRole('option', { name: 'Agent 51' })).toBeInTheDocument());
expect(searchAgents).toHaveBeenNthCalledWith(1, { limit: 50, offset: 0 });
expect(searchAgents).toHaveBeenNthCalledWith(2, { limit: 50, offset: 50 });
diff --git a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx
index 0b5e0ed79..5b8d27d45 100644
--- a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx
+++ b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx
@@ -33,6 +33,7 @@ function mockServer(
agentId: string;
agentSpec?: {
model: { name: string };
+ description?: string;
skills?: Array<{ id: string; name: string }>;
mcpServers?: Array<{ id: string; name: string }>;
};
@@ -122,7 +123,7 @@ describe('AgentsLibrary', () => {
renderLibrary(<LibraryHarness />, { server });
fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
- fireEvent.click(await screen.findByRole('menuitem', { name: 'Open alpha-agent' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Open alpha-agent' }));
expect(screen.getByTestId('library-agent-id')).toHaveTextContent('agent-1');
const params = new URL(window.location.href).searchParams;
expect(params.get('theme')).toBe('dark');
@@ -173,10 +174,10 @@ describe('AgentsLibrary', () => {
fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
- await waitFor(() => {
- expect(screen.getByRole('button', { name: 'Edit agent writer' })).toBeInTheDocument();
- });
- expect(screen.queryByRole('button', { name: 'Edit agent try-only' })).not.toBeInTheDocument();
+ 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('button', { name: 'Try agent try-only' })).toBeInTheDocument();
});
@@ -229,7 +230,7 @@ describe('AgentsLibrary', () => {
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Try agent writer' })).toBeInTheDocument();
});
- expect(screen.queryByRole('button', { name: 'Edit agent writer' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Actions for writer' })).not.toBeInTheDocument();
});
it('shows create-one guidance when there are no agents yet', async () => {
@@ -259,13 +260,13 @@ describe('AgentsLibrary', () => {
expect(screen.queryByText('No agents yet. Build one in a chat, then save it as an agent.')).not.toBeInTheDocument();
});
- it('closes via the back button', () => {
+ it('closes via Escape', () => {
renderLibrary(<LibraryHarness />);
fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
expect(screen.getByRole('heading', { name: 'Agents Library' })).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Back' }));
+ fireEvent.keyDown(window, { key: 'Escape' });
expect(screen.queryByRole('heading', { name: 'Agents Library' })).not.toBeInTheDocument();
});
});
@@ -352,4 +353,113 @@ describe('AgentsLibraryButton', () => {
expect(screen.getByRole('button', { name: 'Agents Library' })).toBeInTheDocument();
expect(searchAgents).not.toHaveBeenCalled();
});
+
+ it('shows a schedules count badge for visible agents and opens schedules on click', async () => {
+ const listSchedules = vi.fn(async () => ({
+ data: [
+ {
+ id: 's1',
+ name: 'job-a',
+ agentId: 'alpha-agent',
+ agentName: 'alpha-agent',
+ task: 't',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'paused' as const,
+ lastRunAt: null,
+ },
+ {
+ id: 's2',
+ name: 'job-b',
+ agentId: 'alpha-agent',
+ agentName: 'alpha-agent',
+ task: 't',
+ cron: '0 10 * * *',
+ timezone: 'UTC',
+ status: 'active' as const,
+ lastRunAt: null,
+ },
+ ],
+ }));
+ const server = createMockAgentUIServer({
+ searchAgents: vi.fn(async () => [
+ { name: 'alpha-agent', agentId: 'alpha-agent' },
+ { name: 'beta-agent', agentId: 'beta-agent' },
+ ]),
+ schedules: {
+ listSchedules,
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(),
+ updateSchedule: vi.fn(),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(),
+ },
+ });
+
+ function SchedulesOpenProbe() {
+ const shell = useShellMode();
+ return <output data-testid="schedules-open">{shell.schedulesOpen ? 'yes' : 'no'}</output>;
+ }
+
+ renderLibrary(
+ <LibraryHarness>
+ <SchedulesOpenProbe />
+ </LibraryHarness>,
+ { server },
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
+
+ await waitFor(() => {
+ expect(listSchedules).toHaveBeenCalledWith(
+ expect.objectContaining({ agentIds: ['alpha-agent', 'beta-agent'], limit: 25 }),
+ );
+ });
+
+ const badge = await screen.findByRole('button', { name: /2 schedules for alpha-agent/ });
+ expect(badge).toHaveTextContent('2');
+ const addSchedule = screen.getByRole('button', { name: 'Add schedule for beta-agent' });
+ expect(addSchedule).toHaveTextContent('-');
+
+ fireEvent.click(addSchedule);
+ expect(screen.getByTestId('schedules-open')).toHaveTextContent('yes');
+ expect(new URL(window.location.href).searchParams.get('agent')).toBe('beta-agent');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
+ await screen.findByRole('button', { name: /2 schedules for alpha-agent/ });
+ fireEvent.click(screen.getByRole('button', { name: /2 schedules for alpha-agent/ }));
+ expect(new URL(window.location.href).searchParams.get('agent')).toBe('alpha-agent');
+ });
+
+ it('does not show an empty-schedules action before schedule counts load', async () => {
+ let resolveSchedules: (value: { data: [] }) => void = () => undefined;
+ const listSchedules = vi.fn(
+ () =>
+ new Promise<{ data: [] }>(resolve => {
+ resolveSchedules = resolve;
+ }),
+ );
+ const server = createMockAgentUIServer({
+ searchAgents: vi.fn(async () => [{ name: 'alpha-agent', agentId: 'alpha-agent' }]),
+ schedules: {
+ listSchedules,
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(),
+ updateSchedule: vi.fn(),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(),
+ },
+ });
+
+ renderLibrary(<LibraryHarness />, { server });
+ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));
+
+ await screen.findByRole('button', { name: 'Try agent alpha-agent' });
+ expect(screen.getByLabelText('Schedule count unavailable for alpha-agent')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Add schedule for alpha-agent' })).not.toBeInTheDocument();
+
+ resolveSchedules({ data: [] });
+ expect(await screen.findByRole('button', { name: 'Add schedule for alpha-agent' })).toBeInTheDocument();
+ });
});
diff --git a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx
index 9d035de45..9e5691217 100644
--- a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx
+++ b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx
@@ -112,10 +112,10 @@ describe('SessionsPage', () => {
renderPage();
const timeButton = await screen.findByRole('button', { name: 'Last 30 days' });
fireEvent.click(timeButton);
- expect(screen.getByRole('button', { name: 'Custom Time Range' })).toBeInTheDocument();
+ expect(screen.getByRole('option', { name: 'Custom Time Range' })).toBeInTheDocument();
expect(screen.queryByText('Select Time Range')).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Custom Time Range' }));
+ fireEvent.click(screen.getByRole('option', { name: 'Custom Time Range' }));
expect(screen.getByText('Select Time Range')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Apply' })).toBeInTheDocument();
});
@@ -125,7 +125,7 @@ describe('SessionsPage', () => {
const listSessions = vi.fn(async () => ({ data: [namedRow, draftRow] }));
renderPage({ listSessions });
fireEvent.click(await screen.findByRole('button', { name: 'Last 30 days' }));
- fireEvent.click(screen.getByRole('button', { name: 'Custom Time Range' }));
+ fireEvent.click(screen.getByRole('option', { name: 'Custom Time Range' }));
fireEvent.change(screen.getByLabelText('From'), {
target: { value: toDateTimeLocalValue(Date.parse('2026-05-01T00:00:00.000Z')) },
});
diff --git a/packages/trueforge-ui/test/atoms/primitives/DropdownMenu.test.tsx b/packages/trueforge-ui/test/atoms/primitives/DropdownMenu.test.tsx
index 99e580eb1..48959c529 100644
--- a/packages/trueforge-ui/test/atoms/primitives/DropdownMenu.test.tsx
+++ b/packages/trueforge-ui/test/atoms/primitives/DropdownMenu.test.tsx
@@ -115,4 +115,23 @@ describe('DropdownMenu', () => {
expect(screen.getByRole('menuitem', { name: 'Rename item' })).toHaveAttribute('name', 'rename');
expect(screen.getByRole('separator', { name: 'More actions' })).toHaveAttribute('data-divider', 'actions');
});
+
+ it('portals the menu outside an overflow-hidden ancestor', () => {
+ render(
+ <div data-testid="clipped" style={{ overflow: 'hidden', height: 24 }}>
+ <DropdownMenu trigger={<button>Actions</button>}>
+ <DropdownMenuItem>Edit</DropdownMenuItem>
+ <DropdownMenuItem>Resume</DropdownMenuItem>
+ <DropdownMenuItem>Delete</DropdownMenuItem>
+ </DropdownMenu>
+ </div>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Actions' }));
+
+ const menu = screen.getByRole('menu');
+ expect(menu).toBeInTheDocument();
+ expect(screen.getByTestId('clipped').contains(menu)).toBe(false);
+ expect(menu.className).toContain('fixed');
+ });
});
diff --git a/packages/trueforge-ui/test/atoms/primitives/PopoverSelect.test.tsx b/packages/trueforge-ui/test/atoms/primitives/PopoverSelect.test.tsx
new file mode 100644
index 000000000..29dfe233b
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/primitives/PopoverSelect.test.tsx
@@ -0,0 +1,89 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { useState } from 'react';
+import { describe, expect, it } from 'vitest';
+
+import { PopoverSelect } from '@/atoms/primitives/PopoverSelect.js';
+
+const options = [
+ { value: 'active', label: 'Active' },
+ { value: 'paused', label: 'Paused' },
+] as const;
+
+function SingleSelect() {
+ const [value, setValue] = useState<'active' | 'paused'>('active');
+ return <PopoverSelect aria-label="Status" options={options} value={value} onValueChange={setValue} />;
+}
+
+function MultiSelect() {
+ const [value, setValue] = useState<Array<'active' | 'paused'>>([]);
+ return <PopoverSelect multiple aria-label="Statuses" options={options} value={value} onValueChange={setValue} />;
+}
+
+describe('PopoverSelect', () => {
+ it('selects one option and closes the popover', () => {
+ render(<SingleSelect />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Status' }));
+ fireEvent.click(screen.getByRole('option', { name: 'Paused' }));
+
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Status' })).toHaveTextContent('Paused');
+ });
+
+ it('keeps the popover open while toggling multiple options', () => {
+ render(<MultiSelect />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Statuses' }));
+ fireEvent.click(screen.getByRole('option', { name: 'Active' }));
+
+ expect(screen.getByRole('listbox')).toHaveAttribute('aria-multiselectable', 'true');
+ expect(screen.getByRole('option', { name: 'Active' })).toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByRole('button', { name: 'Statuses' })).toHaveTextContent('Active');
+ });
+
+ it('closes on Escape and returns focus to the trigger', () => {
+ render(<SingleSelect />);
+ const trigger = screen.getByRole('button', { name: 'Status' });
+
+ fireEvent.click(trigger);
+ fireEvent.keyDown(document, { key: 'Escape' });
+
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ expect(trigger).toHaveFocus();
+ });
+
+ it('renders a prefixed chip trigger', () => {
+ render(
+ <PopoverSelect
+ aria-label="Filter by agent"
+ prefix="Agents"
+ options={[{ value: 'a', label: 'alpha' }]}
+ value="a"
+ onValueChange={() => undefined}
+ />,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Filter by agent' });
+ expect(trigger).toHaveTextContent('Agents');
+ expect(trigger).toHaveTextContent('alpha');
+ expect(trigger.querySelector('.border-r')).not.toBeNull();
+ });
+
+ it('opens the menu above the trigger when menuPlacement is top', () => {
+ render(
+ <PopoverSelect
+ aria-label="Timezone"
+ menuPlacement="top"
+ options={[{ value: 'UTC', label: 'UTC' }]}
+ value="UTC"
+ onValueChange={() => undefined}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Timezone' }));
+
+ expect(screen.getByRole('listbox').className).toContain('bottom-full');
+ expect(screen.getByRole('listbox').className).toContain('mb-1');
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/primitives/SideDrawer.test.tsx b/packages/trueforge-ui/test/atoms/primitives/SideDrawer.test.tsx
new file mode 100644
index 000000000..e897df104
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/primitives/SideDrawer.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SideDrawer } from '@/atoms/primitives/SideDrawer.js';
+
+const originalShowModal = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'showModal');
+const originalClose = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'close');
+const showModal = vi.fn(function showModal(this: HTMLDialogElement) {
+ this.open = true;
+});
+const close = vi.fn(function close(this: HTMLDialogElement) {
+ this.open = false;
+ this.dispatchEvent(new Event('close'));
+});
+
+beforeEach(() => {
+ showModal.mockClear();
+ close.mockClear();
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {
+ configurable: true,
+ value: showModal,
+ });
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', {
+ configurable: true,
+ value: close,
+ });
+});
+
+afterEach(() => {
+ if (originalShowModal === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', originalShowModal);
+ }
+ if (originalClose === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'close');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', originalClose);
+ }
+});
+
+describe('SideDrawer', () => {
+ it('opens with right-anchored md width classes', () => {
+ render(
+ <SideDrawer open onOpenChange={() => undefined} title="Drawer" anchor="right" size="md">
+ <p>body</p>
+ </SideDrawer>,
+ );
+
+ const dialog = screen.getByRole('dialog', { name: 'Drawer' });
+ expect(dialog).toHaveAttribute('open');
+ expect(dialog.className).toContain('md:ml-auto');
+ expect(dialog.className).toContain('md:w-[28rem]');
+ expect(dialog.className).toContain('rounded-none');
+ expect(dialog.className).not.toContain('rounded-l-xl');
+ expect(dialog).toHaveAttribute('closedby', 'closerequest');
+ expect(screen.getByText('body')).toBeInTheDocument();
+ });
+
+ it('does not close when the dialog backdrop surface is clicked', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <SideDrawer open onOpenChange={onOpenChange} title="Drawer">
+ <p>body</p>
+ </SideDrawer>,
+ );
+
+ fireEvent.click(screen.getByRole('dialog', { name: 'Drawer' }));
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('supports left anchor and xl size', () => {
+ render(
+ <SideDrawer open onOpenChange={() => undefined} title="Left" anchor="left" size="xl">
+ <p>left body</p>
+ </SideDrawer>,
+ );
+
+ const dialog = screen.getByRole('dialog', { name: 'Left' });
+ expect(dialog.className).toContain('md:mr-auto');
+ expect(dialog.className).toContain('md:w-[42rem]');
+ });
+
+ it('closes via the close button', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <SideDrawer open onOpenChange={onOpenChange} title="Drawer">
+ <p>body</p>
+ </SideDrawer>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('renders a sticky footer when provided', () => {
+ render(
+ <SideDrawer open onOpenChange={() => undefined} title="Drawer" footer={<button type="button">Save</button>}>
+ <p>body</p>
+ </SideDrawer>,
+ );
+
+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/primitives/Table.test.tsx b/packages/trueforge-ui/test/atoms/primitives/Table.test.tsx
new file mode 100644
index 000000000..8d173b0ce
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/primitives/Table.test.tsx
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { useState } from 'react';
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_TABLE_PAGE_SIZE,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TablePagination,
+ TableRow,
+} from '@/atoms/primitives/Table.js';
+
+function PaginatedDemo({ rows }: { rows: string[] }) {
+ const [page, setPage] = useState(0);
+ const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE);
+ const pageRows = rows.slice(page * pageSize, page * pageSize + pageSize);
+
+ return (
+ <div>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {pageRows.map(name => (
+ <TableRow key={name}>
+ <TableCell>{name}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ <TablePagination
+ page={page}
+ pageSize={pageSize}
+ total={rows.length}
+ onPageChange={setPage}
+ onPageSizeChange={size => {
+ setPageSize(size);
+ setPage(0);
+ }}
+ />
+ </div>
+ );
+}
+
+describe('Table', () => {
+ it('does not force narrow tables to desktop width', () => {
+ render(
+ <Table aria-label="Compact table">
+ <TableBody />
+ </Table>,
+ );
+
+ const table = screen.getByRole('table', { name: 'Compact table' });
+ expect(table).toHaveClass('min-w-full');
+ expect(table).not.toHaveClass('min-w-[48rem]');
+ });
+
+ it('renders header and body cells', () => {
+ render(
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow>
+ <TableCell>alpha</TableCell>
+ </TableRow>
+ </TableBody>
+ </Table>,
+ );
+
+ expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument();
+ expect(screen.getByRole('cell', { name: 'alpha' })).toBeInTheDocument();
+ });
+
+ it('paginates rows and changes page size', () => {
+ const rows = Array.from({ length: 12 }, (_, i) => `row-${String(i + 1)}`);
+ render(<PaginatedDemo rows={rows} />);
+
+ expect(screen.getByText('Showing 1–10 of 12')).toBeInTheDocument();
+ expect(screen.getByText('row-1')).toBeInTheDocument();
+ expect(screen.getByText('row-10')).toBeInTheDocument();
+ expect(screen.queryByText('row-11')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Next page' }));
+ expect(screen.getByText('Showing 11–12 of 12')).toBeInTheDocument();
+ expect(screen.getByText('row-11')).toBeInTheDocument();
+ expect(screen.queryByText('row-1')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Rows per page' }));
+ fireEvent.click(screen.getByRole('option', { name: '25' }));
+ expect(screen.getByText('Showing 1–12 of 12')).toBeInTheDocument();
+ expect(screen.getByText('row-1')).toBeInTheDocument();
+ expect(screen.getByText('row-12')).toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx
new file mode 100644
index 000000000..b6257e6d8
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx
@@ -0,0 +1,340 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ComponentProps } from 'react';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { ScheduleFormDrawer } from '@/atoms/schedules/ScheduleFormDrawer.js';
+import { ToasterProvider } from '@/containers/ToasterContainer.js';
+import { ServerProvider } from '@/server/ServerContext.js';
+import type { AgentUIServer, ConnectorBase, Schedule, ScheduleServer } from '@/server/types.js';
+import { SlotsProvider } from '@/theme/SlotsProvider.js';
+import { createMockAgentUIServer, createMockCatalog } 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 slackMcp = {
+ id: 'Slack 1234',
+ name: 'Slack 1234',
+ authenticated: false as boolean,
+};
+
+const slackCatalogConnector: ConnectorBase = {
+ id: 'Slack 1234',
+ name: 'Slack 1234',
+ description: '',
+ url: 'https://example.com',
+ auth: { type: 'dcr' },
+ requiresAuth: true,
+ authenticated: false,
+};
+
+function pausedSchedule(overrides: Partial<Schedule> = {}): Schedule {
+ return {
+ id: 'new',
+ name: 'digest',
+ agentId: 'demo-agent',
+ agentName: 'demo-agent',
+ task: 'summarize',
+ cron: '0 9 * * *',
+ timezone: 'America/New_York',
+ status: 'paused',
+ lastRunAt: null,
+ ...overrides,
+ };
+}
+
+function mockScheduleServer(overrides: Partial<ScheduleServer> = {}): ScheduleServer {
+ return {
+ listSchedules: vi.fn(async () => ({ data: [] })),
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(async () => pausedSchedule()),
+ updateSchedule: vi.fn(async req =>
+ pausedSchedule({ ...req, agentId: 'demo-agent', agentName: 'demo-agent', lastRunAt: null }),
+ ),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(async () => ({
+ id: 'run-1',
+ scheduleId: 'new',
+ name: 'manual-test',
+ scheduledFor: '2024-06-01T12:00:00.000Z',
+ status: 'triggered' as const,
+ triggeredAt: '2024-06-01T12:00:01.000Z',
+ triggeredBy: 'alice',
+ })),
+ ...overrides,
+ };
+}
+
+function renderDrawer({
+ server,
+ scheduleServer,
+ ...props
+}: Partial<ComponentProps<typeof ScheduleFormDrawer>> & {
+ server?: AgentUIServer;
+ scheduleServer?: ScheduleServer;
+}) {
+ const agentServer =
+ server ??
+ createMockAgentUIServer({
+ searchAgents: vi.fn(async () => [
+ {
+ name: 'demo-agent',
+ agentId: 'demo-agent',
+ agentSpec: {
+ model: { name: 'openai/gpt-4.1' },
+ mcpServers: [{ name: 'Slack 1234' }],
+ },
+ },
+ ]),
+ getMcp: vi.fn(async () => [slackMcp]),
+ catalog: createMockCatalog({
+ connectorCatalog: {
+ getConnectorCatalog: async () => [],
+ listConnectors: async () => [slackCatalogConnector],
+ getConnector: async () => slackCatalogConnector,
+ getToolsByConnectorId: async () => [],
+ createConnector: vi.fn(),
+ updateConnector: vi.fn(),
+ authenticateConnector: vi.fn(async () => ({ status: 'AUTHENTICATED' })),
+ disconnectConnector: vi.fn(),
+ },
+ }),
+ });
+ const schedules = scheduleServer ?? mockScheduleServer();
+ return {
+ schedules,
+ ...render(
+ <SlotsProvider>
+ <ToasterProvider>
+ <ServerProvider server={{ ...agentServer, schedules }}>
+ <ScheduleFormDrawer open mode="create" onOpenChange={() => undefined} {...props} />
+ </ServerProvider>
+ </ToasterProvider>
+ </SlotsProvider>,
+ ),
+ };
+}
+
+async function saveCreateForm() {
+ fireEvent.change(await screen.findByLabelText('Name'), { target: { value: 'digest' } });
+ fireEvent.change(screen.getByLabelText('Task'), { target: { value: 'summarize' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+}
+
+describe('ScheduleFormDrawer', () => {
+ it('shows agent picker on create', async () => {
+ renderDrawer({});
+ const picker = await screen.findByLabelText('Agent');
+ expect(picker).toBeInTheDocument();
+
+ fireEvent.click(picker);
+ await waitFor(() => {
+ expect(screen.getByRole('option', { name: 'demo-agent' })).toBeInTheDocument();
+ });
+ });
+
+ it('disables agent picker on edit', async () => {
+ renderDrawer({ mode: 'edit', schedule: pausedSchedule({ status: 'active' }) });
+ expect(await screen.findByLabelText('Agent')).toBeDisabled();
+ });
+
+ it('creates a paused schedule, stays open on the test screen, and toasts', async () => {
+ const createSchedule = vi.fn(async () => pausedSchedule());
+ const onOpenChange = vi.fn();
+ renderDrawer({
+ scheduleServer: mockScheduleServer({ createSchedule }),
+ onOpenChange,
+ initialAgentId: 'demo-agent',
+ });
+
+ await saveCreateForm();
+
+ await waitFor(() => {
+ expect(createSchedule).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'demo-agent',
+ name: 'digest',
+ task: 'summarize',
+ status: 'paused',
+ }),
+ );
+ });
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(await screen.findByRole('heading', { name: 'Test Schedule' })).toBeInTheDocument();
+ expect(screen.getByText('Schedule saved as paused')).toBeInTheDocument();
+ expect(screen.getByText('Slack 1234')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Run Test' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Activate Anyway' })).toBeInTheDocument();
+ });
+
+ it('starts a test run from the test screen', async () => {
+ const createScheduleRun = vi.fn(async () => ({
+ id: 'run-1',
+ scheduleId: 'new',
+ name: 'manual-test',
+ scheduledFor: '2024-06-01T12:00:00.000Z',
+ status: 'triggered' as const,
+ triggeredAt: '2024-06-01T12:00:01.000Z',
+ triggeredBy: 'alice',
+ }));
+ renderDrawer({
+ scheduleServer: mockScheduleServer({ createScheduleRun }),
+ initialAgentId: 'demo-agent',
+ });
+
+ await saveCreateForm();
+ fireEvent.click(await screen.findByRole('button', { name: 'Run Test' }));
+
+ await waitFor(() => {
+ expect(createScheduleRun).toHaveBeenCalledWith({ scheduleId: 'new' });
+ });
+ expect(screen.getByText('Test run started')).toBeInTheDocument();
+ expect(screen.getByText('Manual test')).toBeInTheDocument();
+ });
+
+ it('edits a created schedule without creating a duplicate', async () => {
+ const createSchedule = vi.fn(async () => pausedSchedule());
+ const updateSchedule = vi.fn(async req =>
+ pausedSchedule({
+ id: req.id,
+ name: req.name,
+ task: req.task,
+ cron: req.cron,
+ timezone: req.timezone,
+ status: req.status,
+ }),
+ );
+ renderDrawer({
+ scheduleServer: mockScheduleServer({ createSchedule, updateSchedule }),
+ initialAgentId: 'demo-agent',
+ });
+
+ await saveCreateForm();
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit Configuration' }));
+ fireEvent.change(await screen.findByLabelText('Name'), { target: { value: 'digest-v2' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => {
+ expect(updateSchedule).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'new',
+ name: 'digest-v2',
+ status: 'paused',
+ }),
+ );
+ });
+ expect(createSchedule).toHaveBeenCalledTimes(1);
+ expect(await screen.findByRole('heading', { name: 'Test Schedule' })).toBeInTheDocument();
+ expect(screen.getByText('digest-v2')).toBeInTheDocument();
+ });
+
+ it('connects an MCP and refreshes its status', async () => {
+ const authenticateConnector = vi.fn(async () => ({ status: 'AUTHENTICATED' }));
+ let authenticated = false;
+ const getMcp = vi.fn(async () => [{ ...slackMcp, authenticated }]);
+ renderDrawer({
+ server: createMockAgentUIServer({
+ searchAgents: vi.fn(async () => [
+ {
+ name: 'demo-agent',
+ agentId: 'demo-agent',
+ agentSpec: {
+ model: { name: 'openai/gpt-4.1' },
+ mcpServers: [{ name: 'Slack 1234' }],
+ },
+ },
+ ]),
+ getMcp,
+ catalog: createMockCatalog({
+ connectorCatalog: {
+ getConnectorCatalog: async () => [],
+ listConnectors: async () => [{ ...slackCatalogConnector, authenticated }],
+ getConnector: async () => ({ ...slackCatalogConnector, authenticated }),
+ getToolsByConnectorId: async () => [],
+ createConnector: vi.fn(),
+ updateConnector: vi.fn(),
+ authenticateConnector,
+ disconnectConnector: vi.fn(),
+ },
+ }),
+ }),
+ initialAgentId: 'demo-agent',
+ });
+
+ await saveCreateForm();
+ const connect = await screen.findByRole('button', { name: 'Connect Slack 1234' });
+ authenticated = true;
+ fireEvent.click(connect);
+
+ await waitFor(() => {
+ expect(authenticateConnector).toHaveBeenCalled();
+ expect(screen.getByText('Connected')).toBeInTheDocument();
+ });
+ });
+
+ it('activates the schedule and closes the drawer', async () => {
+ const updateSchedule = vi.fn(async req =>
+ pausedSchedule({ ...req, status: 'active', lastRunAt: null, agentId: 'demo-agent', agentName: 'demo-agent' }),
+ );
+ const onOpenChange = vi.fn();
+ const onSaved = vi.fn();
+ renderDrawer({
+ scheduleServer: mockScheduleServer({ updateSchedule }),
+ onOpenChange,
+ onSaved,
+ initialAgentId: 'demo-agent',
+ });
+
+ await saveCreateForm();
+ fireEvent.click(await screen.findByRole('button', { name: 'Activate Anyway' }));
+
+ await waitFor(() => {
+ expect(updateSchedule).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'new',
+ status: 'active',
+ }),
+ );
+ });
+ expect(onSaved).toHaveBeenCalled();
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('closes after an external edit save', async () => {
+ const updateSchedule = vi.fn(async req =>
+ pausedSchedule({
+ id: req.id,
+ name: req.name,
+ task: req.task,
+ cron: req.cron,
+ timezone: req.timezone,
+ status: req.status,
+ }),
+ );
+ const onOpenChange = vi.fn();
+ renderDrawer({
+ mode: 'edit',
+ schedule: pausedSchedule({ status: 'active' }),
+ scheduleServer: mockScheduleServer({ updateSchedule }),
+ onOpenChange,
+ });
+
+ fireEvent.change(await screen.findByLabelText('Name'), { target: { value: 'renamed' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => {
+ expect(updateSchedule).toHaveBeenCalledWith(expect.objectContaining({ name: 'renamed', status: 'active' }));
+ });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(screen.queryByRole('heading', { name: 'Test Schedule' })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx
new file mode 100644
index 000000000..6678af6b4
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx
@@ -0,0 +1,369 @@
+// @vitest-environment jsdom
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SchedulesPage } from '@/atoms/schedules/SchedulesPage.js';
+import { ToasterProvider } from '@/containers/ToasterContainer.js';
+import { ServerProvider } from '@/server/ServerContext.js';
+import type { AgentUIServer, Schedule, ScheduleRun, ScheduleServer } from '@/server/types.js';
+import { createMockAgentUIServer } from '../../server/mockServer.js';
+
+const sampleSchedules: Schedule[] = [
+ {
+ id: 's1',
+ name: 'daily-digest',
+ agentId: 'demo-agent',
+ agentName: 'demo-agent',
+ task: 'summarize',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'active',
+ lastRunAt: null,
+ },
+];
+
+const originalShowModal = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'showModal');
+const originalClose = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'close');
+
+beforeEach(() => {
+ window.history.replaceState(null, '', '/schedules');
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {
+ configurable: true,
+ value: function showModal(this: HTMLDialogElement) {
+ this.open = true;
+ },
+ });
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', {
+ configurable: true,
+ value: function close(this: HTMLDialogElement) {
+ this.open = false;
+ this.dispatchEvent(new Event('close'));
+ },
+ });
+});
+
+afterEach(() => {
+ window.history.replaceState(null, '', '/');
+ if (originalShowModal === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', originalShowModal);
+ }
+ if (originalClose === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'close');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', originalClose);
+ }
+});
+
+function renderPage(
+ schedules: Schedule[] = sampleSchedules,
+ overrides: Partial<ScheduleServer> = {},
+ listImpl?: ScheduleServer['listSchedules'],
+ searchAgents?: AgentUIServer['searchAgents'],
+) {
+ const scheduleServer: ScheduleServer = {
+ listSchedules: vi.fn(
+ listImpl ??
+ (async () => ({
+ data: schedules,
+ })),
+ ),
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(),
+ updateSchedule: vi.fn(),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(),
+ ...overrides,
+ };
+ const server = createMockAgentUIServer({
+ searchAgents: searchAgents ?? vi.fn(async () => [{ name: 'demo-agent', agentId: 'demo-agent' }]),
+ schedules: scheduleServer,
+ });
+ render(
+ <ServerProvider server={server}>
+ <ToasterProvider>
+ <SchedulesPage />
+ </ToasterProvider>
+ </ServerProvider>,
+ );
+ return { scheduleServer };
+}
+
+describe('SchedulesPage', () => {
+ it('lists schedules in the table', async () => {
+ const { scheduleServer } = renderPage();
+ expect(await screen.findByRole('heading', { name: 'Scheduled Agents' })).toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'daily-digest' })).toBeInTheDocument();
+ });
+ expect(screen.getAllByText('demo-agent').length).toBeGreaterThan(0);
+ expect(screen.getByText('—')).toBeInTheDocument();
+ expect(screen.getByText('Showing 1')).toBeInTheDocument();
+ expect(scheduleServer.listSchedules).toHaveBeenCalledWith(expect.objectContaining({ limit: 10 }));
+ });
+
+ it('shows empty state when there are no schedules', async () => {
+ renderPage([]);
+ expect(await screen.findByText('No schedules yet. Create one to get started.')).toBeInTheDocument();
+ });
+
+ it('requests the next page token when Next is clicked', async () => {
+ const listSchedules = vi
+ .fn()
+ .mockResolvedValueOnce({ data: sampleSchedules, nextPageToken: 'page-2' })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ ...sampleSchedules[0],
+ id: 's2',
+ name: 'weekly-digest',
+ },
+ ],
+ });
+ renderPage(sampleSchedules, {}, listSchedules);
+
+ expect(await screen.findByRole('button', { name: 'daily-digest' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Next page' }));
+
+ await waitFor(() => {
+ expect(listSchedules).toHaveBeenLastCalledWith(expect.objectContaining({ pageToken: 'page-2', limit: 10 }));
+ });
+ expect(await screen.findByRole('button', { name: 'weekly-digest' })).toBeInTheDocument();
+ });
+
+ it('ignores run history returned for a stale schedules page', async () => {
+ let resolveFirstRuns: (runs: ScheduleRun[]) => void = () => undefined;
+ const listSchedules = vi
+ .fn()
+ .mockResolvedValueOnce({ data: sampleSchedules, nextPageToken: 'page-2' })
+ .mockResolvedValueOnce({
+ data: [{ ...sampleSchedules[0], id: 's2', name: 'weekly-digest' }],
+ });
+ const listScheduleRuns = vi.fn(({ scheduleId }: { scheduleId: string }) => {
+ if (scheduleId !== 's1') return Promise.resolve([]);
+ return new Promise<ScheduleRun[]>(resolve => {
+ resolveFirstRuns = resolve;
+ });
+ });
+ renderPage(sampleSchedules, { listScheduleRuns }, listSchedules);
+
+ await screen.findByRole('button', { name: 'daily-digest' });
+ fireEvent.click(screen.getByRole('button', { name: 'Next page' }));
+ expect(await screen.findByRole('button', { name: 'weekly-digest' })).toBeInTheDocument();
+
+ await act(async () => {
+ resolveFirstRuns([
+ {
+ id: 'stale-run',
+ scheduleId: 's1',
+ name: 'manual-stale',
+ scheduledFor: '2024-06-01T10:00:00.000Z',
+ status: 'failed',
+ triggeredAt: '2024-06-01T10:00:01.000Z',
+ triggeredBy: 'alice',
+ },
+ ]);
+ });
+ expect(screen.queryByLabelText(/Failed run at/i)).not.toBeInTheDocument();
+ });
+
+ it('filters by agent via agentIds', async () => {
+ const { scheduleServer } = renderPage();
+ await screen.findByRole('button', { name: 'daily-digest' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Filter by agent' }));
+ fireEvent.click(screen.getByRole('option', { name: 'demo-agent' }));
+
+ await waitFor(() => {
+ expect(scheduleServer.listSchedules).toHaveBeenCalledWith(
+ expect.objectContaining({ agentIds: ['demo-agent'], limit: 10 }),
+ );
+ });
+ expect(new URL(window.location.href).searchParams.get('agent')).toBe('demo-agent');
+ });
+
+ it('seeds filters from the URL and writes status and search to the query', async () => {
+ window.history.replaceState(null, '', '/schedules?agent=demo-agent&status=paused&q=daily');
+ const { scheduleServer } = renderPage([
+ {
+ id: 's1',
+ name: 'daily-digest',
+ agentId: 'demo-agent',
+ agentName: 'demo-agent',
+ task: 'summarize',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'paused',
+ lastRunAt: null,
+ },
+ ]);
+
+ await waitFor(() => {
+ expect(scheduleServer.listSchedules).toHaveBeenCalledWith(
+ expect.objectContaining({ agentIds: ['demo-agent'], limit: 10 }),
+ );
+ });
+ expect(screen.getByPlaceholderText('Search schedules by name')).toHaveValue('daily');
+ expect(screen.getByRole('button', { name: 'Filter by status' })).toHaveTextContent('Paused');
+
+ fireEvent.change(screen.getByPlaceholderText('Search schedules by name'), {
+ target: { value: 'digest' },
+ });
+ await waitFor(() => {
+ expect(new URL(window.location.href).searchParams.get('q')).toBe('digest');
+ });
+ expect(new URL(window.location.href).searchParams.get('status')).toBe('paused');
+ expect(new URL(window.location.href).searchParams.get('agent')).toBe('demo-agent');
+ });
+
+ it('shows run history chips with tooltip labels', async () => {
+ renderPage(sampleSchedules, {
+ listScheduleRuns: vi.fn(async (): Promise<ScheduleRun[]> => [
+ {
+ id: 'run-failed',
+ scheduleId: 's1',
+ name: 'sched-123',
+ scheduledFor: '2024-06-01T10:00:00.000Z',
+ status: 'failed',
+ triggeredAt: '2024-06-01T10:00:01.000Z',
+ triggeredBy: 'alice',
+ },
+ {
+ id: 'run-ok',
+ scheduleId: 's1',
+ name: 'manual-abc',
+ scheduledFor: '2024-06-02T10:00:00.000Z',
+ status: 'triggered',
+ triggeredAt: '2024-06-02T10:00:01.000Z',
+ triggeredBy: 'alice',
+ },
+ {
+ id: 'run-pending',
+ scheduleId: 's1',
+ name: 'sched-999',
+ scheduledFor: '2024-12-31T10:00:00.000Z',
+ status: 'scheduled',
+ triggeredAt: null,
+ triggeredBy: 'alice',
+ },
+ ]),
+ });
+
+ await waitFor(() => {
+ expect(screen.getByLabelText(/Failed run at/i)).toBeInTheDocument();
+ expect(screen.getByLabelText(/Triggered run at/i)).toBeInTheDocument();
+ });
+ });
+
+ it('runs a schedule now from the table actions', async () => {
+ const createScheduleRun = vi.fn(async () => ({
+ id: 'run-manual',
+ scheduleId: 's1',
+ name: 'manual-abc',
+ scheduledFor: '2024-06-02T10:00:00.000Z',
+ status: 'triggered' as const,
+ triggeredAt: '2024-06-02T10:00:01.000Z',
+ triggeredBy: 'alice',
+ }));
+ const listScheduleRuns = vi
+ .fn()
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([
+ {
+ id: 'run-manual',
+ scheduleId: 's1',
+ name: 'manual-abc',
+ scheduledFor: '2024-06-02T10:00:00.000Z',
+ status: 'triggered' as const,
+ triggeredAt: '2024-06-02T10:00:01.000Z',
+ triggeredBy: 'alice',
+ },
+ ]);
+ const { scheduleServer } = renderPage(sampleSchedules, { createScheduleRun, listScheduleRuns });
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Run now daily-digest' }));
+
+ await waitFor(() => {
+ expect(createScheduleRun).toHaveBeenCalledWith({ scheduleId: 's1' });
+ });
+ await waitFor(() => {
+ expect(listScheduleRuns).toHaveBeenCalledTimes(2);
+ });
+ expect(scheduleServer.createScheduleRun).toHaveBeenCalledWith({ scheduleId: 's1' });
+ });
+
+ it('deletes only after the confirmation dialog is accepted', async () => {
+ const { scheduleServer } = renderPage();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Actions for daily-digest' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));
+
+ expect(screen.getByRole('dialog', { name: 'Delete schedule' })).toBeInTheDocument();
+ expect(scheduleServer.deleteSchedule).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('dialog', { name: 'Delete schedule' })).not.toBeInTheDocument();
+ expect(scheduleServer.deleteSchedule).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Actions for daily-digest' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+
+ await waitFor(() => {
+ expect(scheduleServer.deleteSchedule).toHaveBeenCalledWith({ id: 's1' });
+ });
+ });
+
+ it('toasts when pause or delete fails', async () => {
+ const updateSchedule = vi.fn(async () => {
+ throw new Error('pause failed');
+ });
+ const deleteSchedule = vi.fn(async () => {
+ throw new Error('delete failed');
+ });
+ renderPage(sampleSchedules, { updateSchedule, deleteSchedule });
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Actions for daily-digest' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Pause' }));
+
+ expect(await screen.findByText('pause failed')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Actions for daily-digest' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+
+ expect(await screen.findByText('delete failed')).toBeInTheDocument();
+ });
+
+ it('keeps pagination when name filter matches nothing on the current page', async () => {
+ renderPage(sampleSchedules, {}, async () => ({
+ data: sampleSchedules,
+ nextPageToken: 'page-2',
+ }));
+
+ await screen.findByRole('button', { name: 'daily-digest' });
+ fireEvent.change(screen.getByPlaceholderText('Search schedules by name'), {
+ target: { value: 'nope' },
+ });
+
+ expect(await screen.findByText('No schedules match your filters.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled();
+ });
+
+ it('loads every page of agents for the filter', async () => {
+ const agents = Array.from({ length: 51 }, (_, index) => ({
+ agentId: `agent-${String(index + 1)}`,
+ name: `Agent ${String(index + 1)}`,
+ }));
+ const searchAgents = vi.fn(async ({ limit = 50, offset = 0 } = {}) => agents.slice(offset, offset + limit));
+ renderPage(sampleSchedules, {}, undefined, searchAgents);
+
+ await waitFor(() => {
+ expect(searchAgents).toHaveBeenCalledTimes(2);
+ });
+ fireEvent.click(await screen.findByRole('button', { name: 'Filter by agent' }));
+ expect(screen.getByRole('option', { name: 'Agent 51' })).toBeInTheDocument();
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/schedules/cadence.test.ts b/packages/trueforge-ui/test/atoms/schedules/cadence.test.ts
new file mode 100644
index 000000000..499461529
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/schedules/cadence.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { cronToFormValues, formatCadenceSummary } from '@/atoms/schedules/cadence.js';
+
+describe('formatCadenceSummary', () => {
+ it('formats supported hourly, daily, and weekly patterns', () => {
+ expect(formatCadenceSummary({ cron: '15 * * * *', timezone: 'UTC' })).toBe('Hourly at :15 UTC');
+ expect(formatCadenceSummary({ cron: '30 9 * * *', timezone: 'UTC' })).toBe('Daily 9:30 AM UTC');
+ expect(formatCadenceSummary({ cron: '0 14 * * 1-5', timezone: 'UTC' })).toBe('Weekdays 2:00 PM UTC');
+ });
+
+ it('keeps custom monthly and yearly expressions verbatim', () => {
+ expect(formatCadenceSummary({ cron: '0 9 1 * *', timezone: 'UTC' })).toBe('0 9 1 * *');
+ expect(formatCadenceSummary({ cron: '0 9 1 1 *', timezone: 'UTC' })).toBe('0 9 1 1 *');
+ });
+
+ it('keeps weekday-constrained hourly expressions custom', () => {
+ const cron = '15 * * * 1';
+ expect(formatCadenceSummary({ cron, timezone: 'UTC' })).toBe(cron);
+ expect(
+ cronToFormValues({
+ name: 'monday-hourly',
+ task: 'run',
+ cron,
+ timezone: 'UTC',
+ }).recurrence,
+ ).toBe('custom');
+ });
+});
diff --git a/packages/trueforge-ui/test/atoms/schedules/scheduleRuns.test.ts b/packages/trueforge-ui/test/atoms/schedules/scheduleRuns.test.ts
new file mode 100644
index 000000000..ff4c1dc98
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/schedules/scheduleRuns.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { isManualRun, lastHistoricalRuns, runChipKind, runStatusLabel } from '@/atoms/schedules/scheduleRuns.js';
+import type { ScheduleRun } from '@/server/types.js';
+
+const run = (overrides: Partial<ScheduleRun>): ScheduleRun => ({
+ id: overrides.id ?? 'run',
+ scheduleId: 's1',
+ name: overrides.name ?? 'sched-1',
+ scheduledFor: overrides.scheduledFor ?? '2024-06-01T10:00:00.000Z',
+ status: overrides.status ?? 'triggered',
+ triggeredAt: overrides.triggeredAt ?? '2024-06-01T10:00:01.000Z',
+ triggeredBy: 'alice',
+});
+
+describe('scheduleRuns helpers', () => {
+ it('detects manual runs by name prefix', () => {
+ expect(isManualRun('manual-abc')).toBe(true);
+ expect(isManualRun('sched-123')).toBe(false);
+ });
+
+ it('maps chip kinds from run status', () => {
+ expect(runChipKind('failed')).toBe('failed');
+ expect(runChipKind('triggered')).toBe('success');
+ expect(runChipKind('scheduled')).toBe('success');
+ expect(runStatusLabel('triggered')).toBe('Triggered');
+ });
+
+ it('returns up to five historical runs oldest-first', () => {
+ const runs = [
+ run({ id: 'newest', scheduledFor: '2024-06-03T10:00:00.000Z' }),
+ run({ id: 'middle', scheduledFor: '2024-06-02T10:00:00.000Z' }),
+ run({ id: 'oldest', scheduledFor: '2024-06-01T10:00:00.000Z' }),
+ run({ id: 'pending', status: 'scheduled', triggeredAt: null, scheduledFor: '2024-12-31T10:00:00.000Z' }),
+ ];
+ expect(lastHistoricalRuns(runs).map(row => row.id)).toEqual(['oldest', 'middle', 'newest']);
+ });
+});
diff --git a/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx b/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
index e84e4bf32..bf1110f1a 100644
--- a/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
+++ b/packages/trueforge-ui/test/containers/ThreadListContainer.pagination.test.tsx
@@ -5,8 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
-const { loadMore, setSessionsOpen } = vi.hoisted(() => ({
+const { loadMore, setSchedulesOpen, setSessionsOpen } = vi.hoisted(() => ({
loadMore: vi.fn().mockResolvedValue(undefined),
+ setSchedulesOpen: vi.fn(),
setSessionsOpen: vi.fn(),
}));
@@ -76,6 +77,7 @@ vi.mock('@assistant-ui/react', () => ({
vi.mock('@/server/ServerContext.js', () => ({
useOptionalServer: () => undefined,
useOptionalAgentSessionsServer: () => null,
+ useOptionalScheduleServer: () => null,
}));
vi.mock('@/server/ShellModeContext.js', () => ({
@@ -86,6 +88,7 @@ vi.mock('@/server/ShellModeContext.js', () => ({
mode: { status: 'active', isMutable: false, agentName: 'agent', agentId: 'agent', locked: false },
setSettingsOpen: vi.fn(),
setLibraryOpen: vi.fn(),
+ setSchedulesOpen,
setSessionsOpen,
selectLibraryAgent: vi.fn(),
openDraft: vi.fn(),
diff --git a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
index f38c6d4df..0406f62dc 100644
--- a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx
@@ -13,6 +13,7 @@ import type { ThreadListRowProps } from '@/atoms/ThreadListRow.js';
import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js';
import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
import { ServerProvider } from '@/server/ServerContext.js';
+import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
import { createMockAgentUIServer } from '../server/mockServer.js';
@@ -183,4 +184,57 @@ describe('ThreadListContainer', () => {
expect(onDelete).toHaveBeenCalledWith('thread-1');
});
});
+
+ it('clears chat selection highlight while a sidebar top nav tab is open', () => {
+ function OpenSchedulesButton() {
+ const shell = useShellMode();
+ return (
+ <button type="button" onClick={() => shell.setSchedulesOpen(true)}>
+ Open schedules tab
+ </button>
+ );
+ }
+
+ const server = createMockAgentUIServer({
+ schedules: {
+ listSchedules: vi.fn(async () => ({ data: [] })),
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(),
+ updateSchedule: vi.fn(),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(),
+ },
+ });
+
+ render(
+ <ServerProvider server={server}>
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>
+ <SlotsProvider overrides={{ ThreadListRow: ThreadListRowOverride }}>
+ <ThreadListRuntimeHarness
+ threadList={{
+ threadId: 'thread-1',
+ threads: [
+ {
+ status: 'regular',
+ id: 'thread-1',
+ title: 'Current session',
+ },
+ ],
+ }}
+ >
+ <CompactLayoutProvider>
+ <OpenSchedulesButton />
+ <ThreadListContainer />
+ </CompactLayoutProvider>
+ </ThreadListRuntimeHarness>
+ </SlotsProvider>
+ </ShellModeProvider>
+ </ServerProvider>,
+ );
+
+ expect(screen.getByTestId('thread-row-Current session')).toHaveAttribute('data-active', 'true');
+ fireEvent.click(screen.getByRole('button', { name: 'Open schedules tab' }));
+ expect(screen.getByTestId('thread-row-Current session')).toHaveAttribute('data-active', 'false');
+ });
});
diff --git a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
index a020840e6..dfecd6cc7 100644
--- a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
+++ b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx
@@ -60,7 +60,7 @@ import { SidebarLayout } from '@/layouts/SidebarLayout.js';
import { StackChatPanel } from '@/layouts/StackChatPanel.js';
import { WidgetLayout } from '@/layouts/WidgetLayout.js';
import { ServerProvider } from '@/server/ServerContext.js';
-import { ShellModeProvider } from '@/server/ShellModeContext.js';
+import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
import { RuntimeHarness } from './RuntimeHarness.js';
@@ -299,6 +299,55 @@ describe('StackChatPanel', () => {
expect(screen.getByRole('button', { name: 'Start new chat' })).toBeInTheDocument();
expect(screen.queryByLabelText('Sessions')).not.toBeInTheDocument();
});
+
+ it.each([
+ ['dock/widget', StackChatPanel],
+ ['drawer', DrawerLayout],
+ ] as const)('%s can return to chat after opening schedules', async (_name, Layout) => {
+ const server = createMockAgentUIServer({
+ schedules: {
+ listSchedules: vi.fn(async () => ({ data: [] })),
+ getSchedule: vi.fn(),
+ createSchedule: vi.fn(),
+ updateSchedule: vi.fn(),
+ deleteSchedule: vi.fn(),
+ listScheduleRuns: vi.fn(async () => []),
+ createScheduleRun: vi.fn(),
+ },
+ });
+
+ function OpenSchedules() {
+ const shell = useShellMode();
+ return (
+ <button type="button" onClick={() => shell.setSchedulesOpen(true)}>
+ Open schedules
+ </button>
+ );
+ }
+
+ render(
+ <SlotsProvider>
+ <ServerProvider server={server}>
+ <ShellModeProvider agentConfig={{ mode: 'SingleAgent', name: 'a' }}>
+ <RuntimeHarness messages={[]}>
+ <OpenSchedules />
+ <div className="h-96">
+ <Layout />
+ </div>
+ </RuntimeHarness>
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open schedules' }));
+ expect(await screen.findByRole('heading', { name: 'Scheduled Agents' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Back to chat' }));
+ await waitFor(() => {
+ expect(screen.queryByRole('heading', { name: 'Scheduled Agents' })).not.toBeInTheDocument();
+ });
+ });
});
describe('SidebarLayout', () => {
diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts
new file mode 100644
index 000000000..f2530f9e8
--- /dev/null
+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createScheduleServer } from '@/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.js';
+import type { TrueForge } from '@truefoundry/trueforge-sdk';
+
+function mockClient(
+ overrides: {
+ agents?: Array<{ id: string; name: string }>;
+ list?: ReturnType<typeof vi.fn>;
+ listRuns?: ReturnType<typeof vi.fn>;
+ createRun?: ReturnType<typeof vi.fn>;
+ } = {},
+): TrueForge {
+ const agents = overrides.agents ?? [
+ { id: 'a1', name: 'alpha' },
+ { id: 'a2', name: 'beta' },
+ ];
+ const list =
+ overrides.list ??
+ vi.fn(async () => ({
+ data: [
+ {
+ id: 's1',
+ name: 'job',
+ agentName: 'alpha',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ updatedAt: new Date('2024-01-01T00:00:00.000Z'),
+ manifest: {
+ task: 'do thing',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'paused' as const,
+ },
+ },
+ ],
+ response: { pagination: { limit: 25, nextPageToken: 'next-1' } },
+ hasNextPage: () => true,
+ getNextPage: async () => undefined,
+ }));
+
+ return {
+ agents: {
+ list: vi.fn(async () => ({ data: agents })),
+ },
+ schedules: {
+ list,
+ get: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ listRuns: overrides.listRuns ?? vi.fn(),
+ createRun: overrides.createRun ?? vi.fn(),
+ },
+ } as unknown as TrueForge;
+}
+
+describe('createScheduleServer.listSchedules', () => {
+ it('maps agentIds to agentNames CSV and returns ListResult pagination', async () => {
+ const list = vi.fn(async () => ({
+ data: [
+ {
+ id: 's1',
+ name: 'job',
+ agentName: 'alpha',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ updatedAt: new Date('2024-01-01T00:00:00.000Z'),
+ manifest: {
+ task: 'do thing',
+ cron: '0 9 * * *',
+ timezone: 'UTC',
+ status: 'paused' as const,
+ },
+ },
+ ],
+ response: { pagination: { limit: 10, nextPageToken: 'tok' } },
+ hasNextPage: () => true,
+ getNextPage: async () => undefined,
+ }));
+ const server = createScheduleServer({ client: mockClient({ list }) });
+
+ const page = await server.listSchedules({ agentIds: ['a1', 'a2'], limit: 10, pageToken: 'prev' });
+
+ expect(list).toHaveBeenCalledWith({
+ limit: 10,
+ pageToken: 'prev',
+ agentNames: 'alpha,beta',
+ });
+ expect(page.data).toHaveLength(1);
+ expect(page.data[0]?.agentId).toBe('a1');
+ expect(page.data[0]?.status).toBe('paused');
+ expect(page.nextPageToken).toBe('tok');
+ });
+
+ it('caps limit at 25', async () => {
+ const list = vi.fn(async () => ({
+ data: [],
+ response: { pagination: { limit: 25 } },
+ hasNextPage: () => false,
+ getNextPage: async () => undefined,
+ }));
+ const server = createScheduleServer({ client: mockClient({ list }) });
+ await server.listSchedules({ limit: 100 });
+ expect(list).toHaveBeenCalledWith({ limit: 25 });
+ });
+});
+
+describe('createScheduleServer schedule runs', () => {
+ const wireRun = {
+ id: 'run-1',
+ scheduleId: 's1',
+ name: 'manual-abc',
+ scheduledFor: new Date('2024-06-01T12:00:00.000Z'),
+ status: 'triggered' as const,
+ triggeredAt: new Date('2024-06-01T12:00:01.000Z'),
+ triggeredBy: 'alice',
+ createdAt: new Date('2024-06-01T12:00:00.000Z'),
+ updatedAt: new Date('2024-06-01T12:00:01.000Z'),
+ };
+
+ it('maps listScheduleRuns from SDK listRuns', async () => {
+ const listRuns = vi.fn(async () => ({ data: [wireRun] }));
+ const server = createScheduleServer({ client: mockClient({ listRuns }) });
+ const runs = await server.listScheduleRuns({ scheduleId: 's1' });
+ expect(listRuns).toHaveBeenCalledWith('s1');
+ expect(runs).toEqual([
+ {
+ id: 'run-1',
+ scheduleId: 's1',
+ name: 'manual-abc',
+ scheduledFor: '2024-06-01T12:00:00.000Z',
+ status: 'triggered',
+ triggeredAt: '2024-06-01T12:00:01.000Z',
+ triggeredBy: 'alice',
+ },
+ ]);
+ });
+
+ it('maps createScheduleRun from SDK createRun', async () => {
+ const createRun = vi.fn(async () => ({ data: wireRun }));
+ const server = createScheduleServer({ client: mockClient({ createRun }) });
+ const run = await server.createScheduleRun({ scheduleId: 's1' });
+ expect(createRun).toHaveBeenCalledWith({ scheduleId: 's1' });
+ expect(run.id).toBe('run-1');
+ expect(run.triggeredAt).toBe('2024-06-01T12:00:01.000Z');
+ });
+});
diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.ts
index 1599884da..e131cdd2b 100644
--- a/packages/trueforge-ui/test/publicUiExports.test.ts
+++ b/packages/trueforge-ui/test/publicUiExports.test.ts
@@ -46,6 +46,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'CustomActionContainer',
'CustomActionRenderersProvider',
'DEFAULT_AGENT_CONFIG',
+ 'DEFAULT_TABLE_PAGE_SIZE',
'DraftCatalogProvider',
'DraftComposerLeftSection',
'DraftComposerRightSection',
@@ -56,6 +57,14 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'HistoryLoaderContainer',
'Icon',
'MCP_AUTH_POPUP_CHANNEL',
+ 'ScheduleFormDrawer',
+ 'ScheduleFormFields',
+ 'ScheduleLastRunsCell',
+ 'ScheduleRunChip',
+ 'ScheduleStatusBadge',
+ 'TestScheduleScreen',
+ 'SchedulesButton',
+ 'SchedulesPage',
'Markdown',
'McpAuthContainer',
'MessageActionBar',
@@ -68,6 +77,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'MonacoEditorCore',
'OpenUiFenceBlock',
'PRESETS',
+ 'PopoverSelect',
'PostMcpOauthScreen',
'ReasoningContainer',
'ResumeUnavailableContainer',
@@ -82,10 +92,20 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'SessionsPage',
'ShellActionsActionSlot',
'ShellModeProvider',
+ 'SideDrawer',
'SlotsProvider',
'SubAgentCard',
'Switch',
'SyntaxHighlighter',
+ 'TABLE_PAGE_SIZE_OPTIONS',
+ 'Table',
+ 'TableBody',
+ 'TableCell',
+ 'TableHead',
+ 'TableHeader',
+ 'TablePagination',
+ 'TableTokenPagination',
+ 'TableRow',
'ThemeProvider',
'Thread',
'ThreadComposerAreaShell',
@@ -148,8 +168,10 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'useOptionalCatalogServer',
'useOptionalContentClassNames',
'useOptionalCustomActionRenderers',
+ 'useOptionalScheduleServer',
'useOptionalServer',
'useOptionalShellMode',
+ 'useScheduleServer',
'useServer',
'useServerCapabilities',
'useShellMode',
diff --git a/packages/trueforge-ui/test/routing/derivePlace.test.ts b/packages/trueforge-ui/test/routing/derivePlace.test.ts
index efe8cd4d6..15f090889 100644
--- a/packages/trueforge-ui/test/routing/derivePlace.test.ts
+++ b/packages/trueforge-ui/test/routing/derivePlace.test.ts
@@ -9,6 +9,7 @@ function snap(partial: Partial<ShellSnapshot>): ShellSnapshot {
libraryOpen: false,
sessionsOpen: false,
libraryAgentId: null,
+ schedulesOpen: false,
mode: { status: 'idle' },
agentConfigMode: 'AgentLibraryWithComposer',
...partial,
@@ -39,6 +40,14 @@ describe('derivePlace', () => {
expect(derivePlace(snap({ settingsOpen: true, libraryOpen: true }))).toEqual({ type: 'settings' });
});
+ it('schedules overlay wins over chat when settings is closed', () => {
+ expect(derivePlace(snap({ schedulesOpen: true, pendingSessionId: 'abc' }))).toEqual({ type: 'schedules' });
+ });
+
+ it('settings wins over schedules when both are open', () => {
+ expect(derivePlace(snap({ settingsOpen: true, schedulesOpen: true }))).toEqual({ type: 'settings' });
+ });
+
it('pendingSessionId maps to a session while no thread has reported yet', () => {
expect(derivePlace(snap({ pendingSessionId: 'abc' }))).toEqual({ type: 'session', sessionId: 'abc' });
});
diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.ts
index 78c005ff5..e12394218 100644
--- a/packages/trueforge-ui/test/routing/paths.test.ts
+++ b/packages/trueforge-ui/test/routing/paths.test.ts
@@ -17,6 +17,7 @@ describe('resolveRoutesConfig', () => {
settings: '/settings',
library: '/library',
libraryAgent: '/library/:agentId',
+ schedules: '/schedules',
agent: '/agents/:agentName',
session: '/sessions/:sessionId',
sessionsBrowser: '/sessions',
@@ -50,6 +51,7 @@ describe('buildPath', () => {
expect(buildPath({ type: 'settings' }, routes)).toBe('/settings');
expect(buildPath({ type: 'library' }, routes)).toBe('/library');
expect(buildPath({ type: 'libraryAgent', agentId: 'agent/id' }, routes)).toBe('/library/agent%2Fid');
+ expect(buildPath({ type: 'schedules' }, routes)).toBe('/schedules');
expect(buildPath({ type: 'agent', agentName: 'code-helper' }, routes)).toBe('/agents/code-helper');
expect(buildPath({ type: 'session', sessionId: 'abc123' }, routes)).toBe('/sessions/abc123');
expect(buildPath({ type: 'sessionsBrowser' }, routes)).toBe('/sessions');
@@ -91,6 +93,14 @@ describe('sanitizeSearchForPlace', () => {
);
expect(sanitizeSearchForPlace({ type: 'settings' }, sessionSearch)).toBe(sessionSearch);
});
+
+ it('keeps schedules filters on the schedules place and clears them elsewhere', () => {
+ const scheduleSearch = '?theme=dark&agent=alpha&status=paused&q=digest&sessionId=sess-1&agentId=agent-1';
+ expect(sanitizeSearchForPlace({ type: 'schedules' }, scheduleSearch)).toBe(
+ '?theme=dark&agent=alpha&status=paused&q=digest',
+ );
+ expect(sanitizeSearchForPlace({ type: 'library' }, scheduleSearch)).toBe('?theme=dark');
+ });
});
describe('matchPath', () => {
@@ -101,6 +111,7 @@ describe('matchPath', () => {
expect(matchPath('/settings', routes)).toEqual({ type: 'settings' });
expect(matchPath('/library', routes)).toEqual({ type: 'library' });
expect(matchPath('/library/agent%2Fid', routes)).toEqual({ type: 'libraryAgent', agentId: 'agent/id' });
+ expect(matchPath('/schedules', routes)).toEqual({ type: 'schedules' });
expect(matchPath('/agents/a%2Fb', routes)).toEqual({ type: 'agent', agentName: 'a/b' });
expect(matchPath('/sessions', routes)).toEqual({ type: 'sessionsBrowser' });
expect(matchPath('/sessions/xyz', routes)).toEqual({ type: 'session', sessionId: 'xyz' });
@@ -129,6 +140,7 @@ describe('matchPath', () => {
{ type: 'settings' as const },
{ type: 'library' as const },
{ type: 'libraryAgent' as const, agentId: 'agent id/1' },
+ { type: 'schedules' as const },
{ type: 'agent' as const, agentName: 'weird name/1' },
{ type: 'session' as const, sessionId: 'sess 9' },
{ type: 'sessionsBrowser' as const },
diff --git a/packages/trueforge-ui/test/theme/ThemeProvider.test.tsx b/packages/trueforge-ui/test/theme/ThemeProvider.test.tsx
index 089a83cc5..9761864f7 100644
--- a/packages/trueforge-ui/test/theme/ThemeProvider.test.tsx
+++ b/packages/trueforge-ui/test/theme/ThemeProvider.test.tsx
@@ -264,12 +264,15 @@ describe('ThemeProvider', () => {
});
it('preserves the semibold TrueFoundry welcome heading', () => {
- render(
+ const { container } = render(
<ThemeProvider theme={{ preset: 'trueforge', mode: 'light' }}>
<WelcomeScreen />
</ThemeProvider>,
);
+ expect(getThemeRoot(container).style.getPropertyValue('--font-agent-ui')).toBe(
+ '"Google Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
+ );
expect(screen.getByRole('heading', { name: 'How can I help you today?' })).toHaveClass('font-semibold');
});
diff --git a/packages/trueforge-ui/test/theme/ensureStyles.test.ts b/packages/trueforge-ui/test/theme/ensureStyles.test.ts
index 3a6b074f0..2f36f9f3a 100644
--- a/packages/trueforge-ui/test/theme/ensureStyles.test.ts
+++ b/packages/trueforge-ui/test/theme/ensureStyles.test.ts
@@ -1,11 +1,12 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from 'vitest';
-import { ensureStyles, TRUEFORGE_UI_STYLE_ID } from '@/theme/ensureStyles.js';
+import { ensureStyles, TRUEFORGE_UI_FONTS_ID, TRUEFORGE_UI_STYLE_ID } from '@/theme/ensureStyles.js';
describe('ensureStyles', () => {
afterEach(() => {
document.getElementById(TRUEFORGE_UI_STYLE_ID)?.remove();
+ document.getElementById(TRUEFORGE_UI_FONTS_ID)?.remove();
});
it('injects a style tag once', () => {
@@ -17,8 +18,19 @@ describe('ensureStyles', () => {
expect(nodes[0]?.textContent).toBe('.aui-theme-root{color:red}');
});
- it('no-ops when css is empty', () => {
+ it('injects Google Sans stylesheet once', () => {
+ ensureStyles('.aui-theme-root{color:red}');
+ ensureStyles('.aui-theme-root{color:blue}');
+
+ const links = document.querySelectorAll(`#${TRUEFORGE_UI_FONTS_ID}`);
+ expect(links).toHaveLength(1);
+ expect(links[0]?.getAttribute('rel')).toBe('stylesheet');
+ expect(links[0]?.getAttribute('href')).toContain('family=Google+Sans');
+ });
+
+ it('still loads fonts when css is empty', () => {
ensureStyles('');
expect(document.getElementById(TRUEFORGE_UI_STYLE_ID)).toBeNull();
+ expect(document.getElementById(TRUEFORGE_UI_FONTS_ID)).not.toBeNull();
});
});
diff --git a/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts b/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts
new file mode 100644
index 000000000..13038083f
--- /dev/null
+++ b/packages/trueforge-ui/test/utils/scheduleShareUrl.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ clearScheduleShareSearch,
+ readScheduleShareSearch,
+ writeScheduleShareSearch,
+} from '@/utils/scheduleShareUrl.js';
+
+describe('scheduleShareUrl', () => {
+ it('reads agent, status, and q from the search string', () => {
+ expect(readScheduleShareSearch('?agent=alpha&status=paused&q=digest&theme=dark')).toEqual({
+ agent: 'alpha',
+ status: 'paused',
+ q: 'digest',
+ });
+ expect(readScheduleShareSearch('?status=nope&agent=')).toEqual({
+ agent: null,
+ status: null,
+ q: null,
+ });
+ });
+
+ it('writes and clears schedule-owned keys without touching host keys', () => {
+ const params = new URLSearchParams('theme=dark&agent=old&q=x');
+ writeScheduleShareSearch(params, { agent: 'alpha', status: 'active', q: null });
+ expect(params.toString()).toBe('theme=dark&agent=alpha&status=active');
+
+ clearScheduleShareSearch(params);
+ expect(params.toString()).toBe('theme=dark');
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a72690c99..c7f051c11 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -66,8 +66,8 @@ importers:
specifier: 0.2.21
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.23
+ specifier: 0.1.25
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -354,8 +354,8 @@ importers:
specifier: ^0.13.2
'@truefoundry/assistant-ui-runtime':
- specifier: 0.1.23
+ specifier: 0.1.25
'@truefoundry/trueforge-sdk':
specifier: workspace:*
version: link:../trueforge-sdk
@@ -3627,8 +3627,8 @@ packages:
'@types/react-dom':
optional: true
- '@truefoundry/[email protected]':
- resolution: {integrity: sha512-hw0fVLkYA6g4hkuEqpbZ6FAK5QFH/yVoZoJ8uwkXaM93gys6OojeDfnkB7fugrAAIfL6E2IFHyShOJX3BG7s3w==}
+ '@truefoundry/[email protected]':
+ resolution: {integrity: sha512-cJn3Q6FSF3pn0csgJIg2BhF8M/2k21uV7byMdlXPFLkV6v1qdwwJbH3TqxX1c7UzvFdEkDksUqI9DS0V+TNc9g==}
peerDependencies:
'@types/react': '*'
react: ^18 || ^19
@@ -10869,7 +10869,7 @@ snapshots:
'@types/react': 19.2.18
'@types/react-dom': 19.2.5(@types/[email protected])
dependencies:
'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])
@@ -11059,10 +11059,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@eslint-community/regexpp': 4.12.2
'@typescript-eslint/scope-manager': 8.68.0
@@ -15286,7 +15286,7 @@ snapshots:
dependencies:
'@typescript-eslint/typescript-estree': 8.68.0([email protected])([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index c850084b3..e71a1cb60 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -17,7 +17,7 @@ allowBuilds:
# Silence peer mismatches between trueforge-ui peers and the versions we pin.
peerDependencyRules:
allowedVersions:
- '@truefoundry/assistant-ui-runtime': '0.1.23'
+ '@truefoundry/assistant-ui-runtime': '0.1.25'
# One Context module for assistant-ui (avoids "requires an AuiProvider").
overrides: