Skip to content

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

keep Build Agent config on New Chat, confirm before Reset and fix sandbox envirnoment sync issue (#1116)

harshil-2096258f52805b93
diff --git a/.changeset/build-agent-new-chat-reset.md b/.changeset/build-agent-new-chat-reset.md
new file mode 100644
index 000000000..433f5c03d
--- /dev/null
+++ b/.changeset/build-agent-new-chat-reset.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-ui': patch
+---
+
+Keep the Build Agent config when starting a new chat, confirm before Reset, and honor a stored sandbox environment name.
diff --git a/packages/trueforge-ui/src/atoms/ClearChatButton.tsx b/packages/trueforge-ui/src/atoms/ClearChatButton.tsx
index ff5bc5783..dae72e074 100644
--- a/packages/trueforge-ui/src/atoms/ClearChatButton.tsx
+++ b/packages/trueforge-ui/src/atoms/ClearChatButton.tsx
@@ -1,9 +1,11 @@
'use client';
+import { useTrueForgeAgentSpec } from '@truefoundry/trueforge-assistant-ui-runtime';
+
import { useChatChromeActionsVisible } from '../hooks/useChatChromeActionsVisible.js';
import { useActiveSessionCanManage } from '../hooks/useResourcePermissions.js';
import { Icon } from '../icons/Icon.js';
-import { useOptionalShellMode } from '../server/ShellModeContext.js';
+import { shellIsCreateAgent, useOptionalShellMode } from '../server/ShellModeContext.js';
import { useSlot } from '../theme/SlotsProvider.js';
import { auiButtonClass } from './lib/buttonClasses.js';
@@ -11,6 +13,7 @@ import { auiButtonClass } from './lib/buttonClasses.js';
// Hidden while idle and on a fresh chat.
export function ClearChatButton() {
const shell = useOptionalShellMode();
+ const { agentSpec } = useTrueForgeAgentSpec();
const visible = useChatChromeActionsVisible();
const canManageSession = useActiveSessionCanManage();
const PermissionGuard = useSlot('PermissionGuard');
@@ -24,7 +27,8 @@ export function ClearChatButton() {
title="New Chat"
className={auiButtonClass({ variant: 'ghost', size: 'large' })}
onClick={() => {
- if (canManageSession) shell.clearChat();
+ if (!canManageSession) return;
+ shell.clearChat(shellIsCreateAgent(shell.mode) ? (agentSpec ?? undefined) : undefined);
}}
>
<Icon name="square-pen" size="0.875rem" />
diff --git a/packages/trueforge-ui/src/atoms/ResetAgentBuilderButton.tsx b/packages/trueforge-ui/src/atoms/ResetAgentBuilderButton.tsx
index 276ee6046..9d65577a9 100644
--- a/packages/trueforge-ui/src/atoms/ResetAgentBuilderButton.tsx
+++ b/packages/trueforge-ui/src/atoms/ResetAgentBuilderButton.tsx
@@ -1,33 +1,56 @@
'use client';
import { useTrueForgeAgentSpec } from '@truefoundry/trueforge-assistant-ui-runtime';
+import { useState } from 'react';
import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js';
import { AnalyticsEvents } from '../analytics/events.js';
import { Icon } from '../icons/Icon.js';
import { shellIsCreateAgent, useOptionalShellMode } from '../server/ShellModeContext.js';
import { Button } from './primitives/Button.js';
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from './primitives/Dialog.js';
// Build Agent only: remount with a clean config panel (model + runtime toggles).
export function ResetAgentBuilderButton() {
const shell = useOptionalShellMode();
const { agentSpec } = useTrueForgeAgentSpec();
const track = useTrackAnalytics();
+ const [confirmOpen, setConfirmOpen] = useState(false);
if (shell == null || !shellIsCreateAgent(shell.mode)) return null;
return (
- <Button.Secondary
- type="button"
- title="Reset playground"
- onClick={() => {
- track(AnalyticsEvents.Config.RESET);
- shell.resetAgentBuilder(agentSpec ?? undefined);
- }}
- >
- <Icon name="rotate-right" size="0.875rem" />
- Reset
- </Button.Secondary>
+ <>
+ <Button.Ghost type="button" title="Reset playground" onClick={() => setConfirmOpen(true)}>
+ <Icon name="rotate-right" size="0.875rem" />
+ Reset
+ </Button.Ghost>
+ <Dialog open={confirmOpen} onOpenChange={setConfirmOpen} aria-label="Reset agent config">
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Reset agent config</DialogTitle>
+ </DialogHeader>
+ <p className="text-sm text-text-secondary">
+ Instructions, connectors, and skills will be cleared and the chat will restart.
+ </p>
+ <DialogFooter>
+ <Button.Secondary type="button" onClick={() => setConfirmOpen(false)}>
+ Cancel
+ </Button.Secondary>
+ <Button.Primary
+ type="button"
+ onClick={() => {
+ track(AnalyticsEvents.Config.RESET);
+ shell.resetAgentBuilder(agentSpec ?? undefined);
+ setConfirmOpen(false);
+ }}
+ >
+ Reset
+ </Button.Primary>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx b/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
index 5bd27c082..eb5566218 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
@@ -1,8 +1,10 @@
'use client';
+import { useTrueForgeAgentSpec } from '@truefoundry/trueforge-assistant-ui-runtime';
import { useMemo } from 'react';
import { Icon } from '../../icons/Icon.js';
+import { readSandboxEnvironmentName, sandboxWithEnvironmentName } from '../../server/draftSpecPreferences.js';
import { useOptionalShellMode } from '../../server/ShellModeContext.js';
import type { AgentCompactionConfig, AgentRuntimeConfig } from '../../server/types.js';
import { useReadySandboxEnvironments } from '../environments/useReadySandboxEnvironments.js';
@@ -35,6 +37,7 @@ function parsePositiveInteger(raw: string): number | null {
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
+const ENVIRONMENT_LOCKED_HINT = "Can't change the environment after a chat has started";
const NO_SANDBOX_PROVIDER_HINT = 'No sandbox provider yet, add one in Settings → Sandbox';
const DEFAULT_COMPACTION_THRESHOLD_TOKENS = 50_000;
@@ -66,7 +69,10 @@ export function AgentRuntimeConfigFields({
}: AgentRuntimeConfigFieldsProps) {
const shell = useOptionalShellMode();
const { environments: readyEnvironments, refetch: refetchEnvironments } = useReadySandboxEnvironments();
- const selectedEnvironmentName = value.sandbox?.environmentName?.trim() || 'default';
+ const { draftSessionId } = useTrueForgeAgentSpec();
+ // Turns reuse the session sandbox, so the environment is fixed once a chat has started.
+ const environmentLocked = draftSessionId != null;
+ const selectedEnvironmentName = readSandboxEnvironmentName(value.sandbox);
const environmentOptions = useMemo(() => {
const options: Array<{ value: string; label: string; disabled?: boolean }> = readyEnvironments.map(env => ({
@@ -115,6 +121,25 @@ export function AgentRuntimeConfigFields({
},
];
const sandboxEnabled = value.sandbox?.enabled ?? false;
+
+ const environmentSelect = (
+ <PopoverSelect
+ aria-label="Environment"
+ value={selectedEnvironmentName}
+ options={environmentOptions}
+ disabled={disabled || environmentLocked || !sandboxAvailable || !sandboxEnabled}
+ className="w-48"
+ onOpenChange={nextOpen => {
+ if (nextOpen) void refetchEnvironments();
+ }}
+ onValueChange={selected =>
+ onChange({
+ ...value,
+ sandbox: sandboxWithEnvironmentName(value.sandbox, selected === 'default' ? undefined : selected),
+ })
+ }
+ />
+ );
const compactionEnabled = value.contextManagement?.compaction?.enabled ?? true;
const thresholdMode: CompactionThresholdMode =
value.contextManagement?.compaction?.trigger != null ? 'custom' : 'auto';
@@ -281,25 +306,13 @@ export function AgentRuntimeConfigFields({
) : null}
</span>
<div className="flex shrink-0 items-center">
- <PopoverSelect
- aria-label="Environment"
- value={value.sandbox?.environmentName?.trim() || 'default'}
- options={environmentOptions}
- disabled={disabled || !sandboxAvailable || !sandboxEnabled}
- className="w-48"
- onOpenChange={nextOpen => {
- if (nextOpen) void refetchEnvironments();
- }}
- onValueChange={selected =>
- onChange({
- ...value,
- sandbox: {
- ...value.sandbox,
- environmentName: selected === 'default' ? undefined : selected,
- },
- })
- }
- />
+ {environmentLocked ? (
+ <Tooltip content={ENVIRONMENT_LOCKED_HINT}>
+ <span className="inline-flex">{environmentSelect}</span>
+ </Tooltip>
+ ) : (
+ environmentSelect
+ )}
</div>
</div>
{switchField({ field: fileDownloadsField, className: rowClassName })}
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftComposerSections.tsx b/packages/trueforge-ui/src/atoms/draft/DraftComposerSections.tsx
index fa2ade165..f5015abdb 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftComposerSections.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftComposerSections.tsx
@@ -7,6 +7,7 @@ import { Icon } from '../../icons/Icon.js';
import { shellIsCreateAgent, useOptionalShellMode } from '../../server/ShellModeContext.js';
import { useSlot } from '../../theme/SlotsProvider.js';
import type { ComposerLeftSectionProps, ComposerRightSectionProps } from '../ComposerSections.js';
+import { useFallbackMissingSandboxEnvironment } from '../environments/useFallbackMissingSandboxEnvironment.js';
import { auiButtonClass } from '../lib/buttonClasses.js';
import { useCompactLayout } from '../lib/CompactLayoutContext.js';
import { useIsMobile } from '../lib/useIsMobile.js';
@@ -14,6 +15,7 @@ import { Tooltip } from '../primitives/Tooltip.js';
import { DraftReasoningEffortSelector } from './DraftReasoningEffortSelector.js';
export function DraftComposerLeftSection({ disabled, isRunning, onAttach }: ComposerLeftSectionProps) {
+ useFallbackMissingSandboxEnvironment();
const shell = useOptionalShellMode();
const track = useTrackAnalytics();
const DraftCompositeSelector = useSlot('DraftCompositeSelector');
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
index 516863a6e..ba5efb17b 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNod
import { useMCPAuth } from '../../hooks/useMcpAuth.js';
import { Icon } from '../../icons/Icon.js';
+import { readSandboxEnvironmentName, sandboxWithEnvironmentName } from '../../server/draftSpecPreferences.js';
import { useOptionalCatalogServer, useServerCapabilities } from '../../server/ServerContext.js';
import { useOptionalShellMode, type SettingsSection } from '../../server/ShellModeContext.js';
import type { AgentSkill, ConnectorState } from '../../server/types.js';
@@ -585,7 +586,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
shell?.setSettingsOpen(true, section);
};
- const currentEnvName = agentSpec?.config?.sandbox?.environmentName?.trim() || 'default';
+ const currentEnvName = readSandboxEnvironmentName(agentSpec?.config?.sandbox);
const filteredEnvironments = useMemo(() => {
const readyNames = new Set(readyEnvironments.map(e => e.name));
@@ -616,9 +617,8 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
config: {
...agentSpec?.config,
sandbox: {
- ...agentSpec?.config?.sandbox,
+ ...sandboxWithEnvironmentName(agentSpec?.config?.sandbox, isDefault ? undefined : envName),
enabled: isDefault ? agentSpec?.config?.sandbox?.enabled : true,
- environmentName: isDefault ? undefined : envName,
},
},
});
diff --git a/packages/trueforge-ui/src/atoms/environments/useFallbackMissingSandboxEnvironment.ts b/packages/trueforge-ui/src/atoms/environments/useFallbackMissingSandboxEnvironment.ts
new file mode 100644
index 000000000..189d53f89
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/environments/useFallbackMissingSandboxEnvironment.ts
@@ -0,0 +1,36 @@
+'use client';
+
+import { useTrueForgeAgentSpec, useTrueForgeUpdateAgentSpec } from '@truefoundry/trueforge-assistant-ui-runtime';
+import { useEffect } from 'react';
+
+import { readSandboxEnvironmentName, sandboxWithEnvironmentName } from '../../server/draftSpecPreferences.js';
+import { useReadySandboxEnvironments } from './useReadySandboxEnvironments.js';
+
+/**
+ * Resets a remembered sandbox environment that no longer exists to `default` before the first
+ * turn. Mounted with the composer so it runs on page load, not only when the config drawer opens.
+ */
+export function useFallbackMissingSandboxEnvironment(): void {
+ const { agentSpec, draftSessionId } = useTrueForgeAgentSpec();
+ const updateAgentSpec = useTrueForgeUpdateAgentSpec();
+ const { environments, loaded, loading, error } = useReadySandboxEnvironments();
+
+ const sandbox = agentSpec?.config?.sandbox;
+ const name = readSandboxEnvironmentName(sandbox);
+ const missing =
+ draftSessionId == null &&
+ loaded &&
+ !loading &&
+ error === null &&
+ name !== 'default' &&
+ !environments.some(env => env.name === name);
+
+ useEffect(() => {
+ if (!missing) return;
+ updateAgentSpec?.({
+ config: { ...agentSpec?.config, sandbox: sandboxWithEnvironmentName(sandbox, undefined) },
+ });
+ // Only react to the missing-environment transition.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [missing]);
+}
diff --git a/packages/trueforge-ui/src/atoms/environments/useReadySandboxEnvironments.ts b/packages/trueforge-ui/src/atoms/environments/useReadySandboxEnvironments.ts
index caa2ec80c..012d790a4 100644
--- a/packages/trueforge-ui/src/atoms/environments/useReadySandboxEnvironments.ts
+++ b/packages/trueforge-ui/src/atoms/environments/useReadySandboxEnvironments.ts
@@ -11,6 +11,8 @@ import { getErrorMessage } from '../../utils/getErrorMessage.js';
export type UseReadySandboxEnvironmentsResult = {
environments: SandboxEnvironment[];
loading: boolean;
+ /** True once a list request has finished successfully, so an empty list is authoritative. */
+ loaded: boolean;
error: string | null;
refetch: () => Promise<void>;
};
@@ -30,6 +32,7 @@ export function useReadySandboxEnvironments(): UseReadySandboxEnvironmentsResult
const environmentsOpen = shell?.environmentsOpen ?? false;
const [environments, setEnvironments] = useState<SandboxEnvironment[]>([]);
const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const requestGenRef = useRef(0);
const wasEnvironmentsOpenRef = useRef(environmentsOpen);
@@ -37,6 +40,7 @@ export function useReadySandboxEnvironments(): UseReadySandboxEnvironmentsResult
const fetchReadyEnvironments = useCallback(async () => {
if (!environmentServer) {
setEnvironments([]);
+ setLoaded(false);
setLoading(false);
setError(null);
return;
@@ -53,6 +57,7 @@ export function useReadySandboxEnvironments(): UseReadySandboxEnvironmentsResult
if (gen !== requestGenRef.current) return;
const readyOnly = all.filter(env => env.status === 'ready');
setEnvironments(readyOnly);
+ setLoaded(true);
} catch (caught) {
if (gen !== requestGenRef.current) return;
setError(getErrorMessage(caught, 'Failed to load sandbox environments.'));
@@ -78,6 +83,7 @@ export function useReadySandboxEnvironments(): UseReadySandboxEnvironmentsResult
return {
environments,
loading,
+ loaded,
error,
refetch: fetchReadyEnvironments,
};
diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsx
index 24e0b33d3..72a8213e8 100644
--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx
+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx
@@ -161,8 +161,11 @@ type ShellModeContextValue = {
openInaccessibleSession: (req: { sessionId: string; message: string }) => void;
/** Backend/access message when the current pending session could not be opened. */
sessionAccessError: string | null;
- /** Reset current chat; no-op when idle. */
- clearChat: () => void;
+ /**
+ * Reset current chat; no-op when idle.
+ * Builder New Chat passes the live draft so the remount keeps the left panel.
+ */
+ clearChat: (liveSpec?: AgentSpec) => void;
/** Return library-only mode to its idle landing; no-op in other modes. */
openLibraryHome: () => void;
/** Changes only when the chat runtime must reset. */
@@ -802,37 +805,39 @@ export function ShellModeProvider({
[isComposerEnabled, setSettingsOpen, setSessionsOpen, setSchedulesOpen, setEnvironmentsOpen],
);
- const clearChat = useCallback(() => {
- if (effectiveMode.status === 'idle') return;
- setSessionAccessError(null);
- setPendingSessionId(undefined);
- if (effectiveMode.isMutable) {
- // Preserve Edit / builder vs chat intent. New Chat must use the latest
- // chat seed (storage), not the stale mode.agentSpec from draft open —
- // toggles like web search update the seed without rewriting mode.agentSpec.
- const kind: DraftPreferenceKind = effectiveMode.isCreateAgent ? 'agent' : 'chat';
- const agentSpec =
- kind === 'chat'
- ? (readDraftSpecPreferences('chat') ?? chatSeedRef.current)
- : (effectiveMode.agentSpec ?? agentSeedRef.current);
- if (kind === 'chat') {
- chatSeedRef.current = agentSpec;
+ const clearChat = useCallback(
+ (liveSpec?: AgentSpec) => {
+ if (effectiveMode.status === 'idle') return;
+ setSessionAccessError(null);
+ setPendingSessionId(undefined);
+ if (effectiveMode.isMutable) {
+ // Plain New Chat uses the chat seed. Builder New Chat keeps the live draft
+ // so the remount does not replace the left panel with the open/save snapshot.
+ const kind: DraftPreferenceKind = effectiveMode.isCreateAgent ? 'agent' : 'chat';
+ const agentSpec =
+ kind === 'agent'
+ ? (liveSpec ?? effectiveMode.agentSpec ?? agentSeedRef.current)
+ : (readDraftSpecPreferences('chat') ?? chatSeedRef.current);
+ if (kind === 'chat') {
+ chatSeedRef.current = agentSpec;
+ }
+ setMode({
+ status: 'active',
+ isMutable: true,
+ isCreateAgent: effectiveMode.isCreateAgent,
+ agentId: effectiveMode.agentId,
+ agentName: effectiveMode.agentName,
+ agentSpec,
+ locked: false,
+ });
+ setAgentConfigOpenState(effectiveMode.isCreateAgent);
+ bumpEpoch(true);
+ return;
}
- setMode({
- status: 'active',
- isMutable: true,
- isCreateAgent: effectiveMode.isCreateAgent,
- agentId: effectiveMode.agentId,
- agentName: effectiveMode.agentName,
- agentSpec,
- locked: false,
- });
- setAgentConfigOpenState(effectiveMode.isCreateAgent);
- bumpEpoch(true);
- return;
- }
- bumpEpoch(false);
- }, [effectiveMode, bumpEpoch]);
+ bumpEpoch(false);
+ },
+ [effectiveMode, bumpEpoch],
+ );
const openLibraryHome = useCallback(() => {
// Only library-only mode has an idle landing; other modes root via openDraft / clearChat.
diff --git a/packages/trueforge-ui/src/server/draftSpecPreferences.ts b/packages/trueforge-ui/src/server/draftSpecPreferences.ts
index ed7f34f73..207b5999b 100644
--- a/packages/trueforge-ui/src/server/draftSpecPreferences.ts
+++ b/packages/trueforge-ui/src/server/draftSpecPreferences.ts
@@ -1,4 +1,4 @@
-import type { AgentSpec } from './types.js';
+import type { AgentRuntimeConfig, AgentSpec } from './types.js';
/** @deprecated Migrated into chat/agent keys on first read. */
export const DRAFT_SPEC_PREFERENCES_STORAGE_KEY = 'tfy-aui-draft-spec-preferences';
@@ -55,6 +55,56 @@ function readSandboxEnabled(spec: AgentSpec): boolean | undefined {
return typeof enabled === 'boolean' ? enabled : undefined;
}
+function readTrimmedString(value: object, key: string): string {
+ const raw = Reflect.get(value, key);
+ return typeof raw === 'string' ? raw.trim() : '';
+}
+
+type SandboxConfig = NonNullable<AgentRuntimeConfig['sandbox']>;
+
+/** Display name. A leftover wire `environment_name` counts when the client field is empty. */
+export function readSandboxEnvironmentName(sandbox: object | undefined): string {
+ if (!isObject(sandbox)) return 'default';
+ const camelName = readTrimmedString(sandbox, 'environmentName');
+ if (camelName.length > 0) return camelName;
+ const snakeName = readTrimmedString(sandbox, 'environment_name');
+ return snakeName.length > 0 ? snakeName : 'default';
+}
+
+/** Set the client field and drop a leftover wire key so passthrough serialization cannot send it. */
+export function sandboxWithEnvironmentName(
+ sandbox: SandboxConfig | undefined,
+ environmentName: string | undefined,
+): SandboxConfig {
+ const next: SandboxConfig = { ...sandbox, environmentName };
+ Reflect.deleteProperty(next, 'environment_name');
+ return next;
+}
+
+/**
+ * Client field wins. Copy a leftover wire `environment_name` only when the client
+ * field is empty, then drop the wire key.
+ */
+function normalizeSandboxEnvironmentName(spec: AgentSpec): AgentSpec {
+ const sandbox = spec.config?.sandbox;
+ if (sandbox === undefined || !Reflect.has(sandbox, 'environment_name')) return spec;
+
+ const camelName = readTrimmedString(sandbox, 'environmentName');
+ const snakeName = readTrimmedString(sandbox, 'environment_name');
+ const nextSandbox: SandboxConfig = { ...sandbox };
+ Reflect.deleteProperty(nextSandbox, 'environment_name');
+ if (camelName.length === 0 && snakeName.length > 0) {
+ nextSandbox.environmentName = snakeName;
+ }
+ return {
+ ...spec,
+ config: {
+ ...spec.config,
+ sandbox: nextSandbox,
+ },
+ };
+}
+
function readWebSearchEnabled(spec: AgentSpec): boolean | undefined {
if (spec.config?.webSearch === undefined) return undefined;
const enabled = spec.config.webSearch.enabled;
@@ -77,9 +127,10 @@ export function selectChatDraftSpecPreferences(spec: AgentSpec): AgentSpec {
/** New Agent: full composer seed including runtime config (sandbox, ask-user, …). */
export function selectAgentDraftSpecPreferences(spec: AgentSpec): AgentSpec {
+ const normalized = normalizeSandboxEnvironmentName(spec);
return {
- ...selectChatDraftSpecPreferences(spec),
- ...(spec.config !== undefined ? { config: spec.config } : {}),
+ ...selectChatDraftSpecPreferences(normalized),
+ ...(normalized.config !== undefined ? { config: normalized.config } : {}),
};
}
@@ -281,7 +332,7 @@ function migrateLegacyDraftPreferences(): void {
export function readDraftSpecPreferences(kind: DraftPreferenceKind): AgentSpec | null {
migrateLegacyDraftPreferences();
const stored = readStoredSpec(storageKeyForKind(kind));
- return stored == null ? null : selectDraftSpecPreferences(stored, kind);
+ return stored == null ? null : selectDraftSpecPreferences(normalizeSandboxEnvironmentName(stored), kind);
}
export function writeDraftSpecPreferences(kind: DraftPreferenceKind, spec: AgentSpec): void {
diff --git a/packages/trueforge-ui/test/atoms/ResetAgentBuilderButton.test.tsx b/packages/trueforge-ui/test/atoms/ResetAgentBuilderButton.test.tsx
index 2f5b474fa..c1379c04d 100644
--- a/packages/trueforge-ui/test/atoms/ResetAgentBuilderButton.test.tsx
+++ b/packages/trueforge-ui/test/atoms/ResetAgentBuilderButton.test.tsx
@@ -1,12 +1,38 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, within } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ResetAgentBuilderButton } from '@/atoms/ResetAgentBuilderButton.js';
import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
+const originalShowModal = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'showModal');
+const originalClose = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'close');
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = function showModal() {
+ this.open = true;
+ };
+ HTMLDialogElement.prototype.close = function close() {
+ this.open = false;
+ this.dispatchEvent(new Event('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);
+ }
+});
+
vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({
useTrueForgeAgentSpec: () => ({
agentSpec: {
@@ -66,13 +92,26 @@ describe('ResetAgentBuilderButton', () => {
expect(screen.queryByRole('button', { name: 'Reset' })).not.toBeInTheDocument();
});
- it('resets the builder from the chat header control using the live draft', () => {
+ it('asks before resetting the builder from the live draft', () => {
render(wrap(<Harness />));
fireEvent.click(screen.getByRole('button', { name: 'Prep saved builder' }));
- expect(screen.getByRole('button', { name: 'Reset' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
+
+ const dialog = screen.getByRole('dialog', { name: 'Reset agent config' });
+ expect(dialog).toHaveTextContent('Instructions, connectors, and skills will be cleared');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('dialog', { name: 'Reset agent config' })).not.toBeInTheDocument();
+
+ const afterCancel = JSON.parse(screen.getByTestId('mode').textContent ?? '{}') as {
+ agentId: string | null;
+ };
+ expect(afterCancel.agentId).toBe('saved');
fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
+ fireEvent.click(
+ within(screen.getByRole('dialog', { name: 'Reset agent config' })).getByRole('button', { name: 'Reset' }),
+ );
const mode = JSON.parse(screen.getByTestId('mode').textContent ?? '{}') as {
isCreateAgent: boolean;
diff --git a/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx b/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
index 5651412f5..9c3021b27 100644
--- a/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
+++ b/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
@@ -158,4 +158,30 @@ describe('AgentRuntimeConfigFields', () => {
expect(missing).toBeDisabled();
expect(missing).toHaveAttribute('aria-selected', 'true');
});
+
+ it('shows a wire-only sandbox environment name and clears it when default is chosen', async () => {
+ const onChange = vi.fn();
+ const sandbox: NonNullable<AgentRuntimeConfig['sandbox']> = { enabled: true };
+ Reflect.set(sandbox, 'environment_name', 'test');
+ renderRuntimeFields({ value: { sandbox }, onChange });
+
+ const trigger = screen.getByRole('button', { name: 'Environment' });
+ await waitFor(() => {
+ expect(trigger).toHaveTextContent('test');
+ });
+
+ fireEvent.click(trigger);
+ fireEvent.click(await screen.findByRole('option', { name: 'default' }));
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sandbox: expect.objectContaining({ enabled: true, environmentName: undefined }),
+ }),
+ );
+ const update: unknown = onChange.mock.calls[0]?.[0];
+ if (typeof update !== 'object' || update === null || !('sandbox' in update)) {
+ throw new Error('expected sandbox update');
+ }
+ expect(update.sandbox).not.toHaveProperty('environment_name');
+ });
});
diff --git a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
index a3e09b5dc..ecceb52d5 100644
--- a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
+++ b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx
@@ -726,6 +726,42 @@ describe('ShellModeProvider', () => {
expect(result.current.runtimeKey).not.toBe(keyBefore);
});
+ it('clearChat on a builder keeps the live draft instead of the open snapshot', () => {
+ const { result } = renderHook(() => useShellMode(), {
+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
+ });
+ const opened = {
+ model: { name: 'opened/model' },
+ instructions: 'Opened instructions.',
+ };
+ const live = {
+ model: { name: 'live/model' },
+ instructions: 'Keep these instructions.',
+ mcpServers: [{ name: 'exa' }],
+ skills: [{ name: 'research' }],
+ config: { sandbox: { enabled: true } },
+ };
+
+ act(() =>
+ result.current.selectLibraryAgent({
+ isMutable: true,
+ isCreateAgent: true,
+ agentSpec: opened,
+ }),
+ );
+ const keyBefore = result.current.runtimeKey;
+
+ act(() => result.current.clearChat(live));
+
+ expect(result.current.runtimeKey).not.toBe(keyBefore);
+ expect(result.current.mode).toMatchObject({
+ status: 'active',
+ isMutable: true,
+ isCreateAgent: true,
+ agentSpec: live,
+ });
+ });
+
it('listSessionsAgentId follows history filter when library is enabled', () => {
const { result } = renderHook(() => useShellMode(), {
wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
diff --git a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts b/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts
index 960933b98..2096c1ffb 100644
--- a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts
+++ b/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts
@@ -97,6 +97,39 @@ describe('draft preference storage', () => {
});
});
+ it('stores a wire sandbox environment name as environmentName', () => {
+ window.localStorage.setItem(
+ AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,
+ JSON.stringify({
+ version: 1,
+ spec: {
+ model: { name: 'agent/model' },
+ config: { sandbox: { enabled: true, fileDownloads: true, environment_name: 'test' } },
+ },
+ }),
+ );
+
+ expect(readDraftSpecPreferences('agent')).toEqual({
+ model: { name: 'agent/model' },
+ config: { sandbox: { enabled: true, fileDownloads: true, environmentName: 'test' } },
+ });
+
+ const sandbox = { enabled: true, environmentName: 'python-dev' };
+ Reflect.set(sandbox, 'environment_name', 'test');
+ writeDraftSpecPreferences('agent', { model: { name: 'agent/model' }, config: { sandbox } });
+ expect(readDraftSpecPreferences('agent')).toEqual({
+ model: { name: 'agent/model' },
+ config: { sandbox: { enabled: true, environmentName: 'python-dev' } },
+ });
+ expect(JSON.parse(window.localStorage.getItem(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY) ?? 'null')).toEqual({
+ version: 1,
+ spec: {
+ model: { name: 'agent/model' },
+ config: { sandbox: { enabled: true, environmentName: 'python-dev' } },
+ },
+ });
+ });
+
it('persists the chat web-search toggle across read/write', () => {
writeDraftSpecPreferences('chat', {
model: { name: 'chat/model' },