Skip to content

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

bugfix: fix session environment handling in chat history (#1049)

harshil-2096c6ef7d19fb49
diff --git a/.changeset/resume-session-environment-lock.md b/.changeset/resume-session-environment-lock.md
new file mode 100644
index 000000000..ce3b72c7c
--- /dev/null
+++ b/.changeset/resume-session-environment-lock.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge-assistant-ui-runtime': patch
+'@truefoundry/trueforge-ui': patch
+---
+
+Adopt the loaded session agent spec when resuming chat history so New Chat draft edits no longer PATCH over the saved sandbox environment; lock composer environment selection after a session exists; read/write sandbox `environmentName` so resumed chats show the correct environment; and keep showing a deleted environment from the agent spec.
diff --git a/packages/assistant-ui-runtime/src/draft/useDraftAgentSpec.ts b/packages/assistant-ui-runtime/src/draft/useDraftAgentSpec.ts
index 3aed65a25..669f74ba6 100644
--- a/packages/assistant-ui-runtime/src/draft/useDraftAgentSpec.ts
+++ b/packages/assistant-ui-runtime/src/draft/useDraftAgentSpec.ts
@@ -47,7 +47,6 @@ export function useDraftAgentSpec({
const syncTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const syncGenerationRef = useRef(0);
const loadedDraftIdRef = useRef<string | undefined>(undefined);
- const localDirtyRef = useRef(false);
const lastUpdatedAtRef = useRef<string | undefined>(undefined);
const pendingFlushRef = useRef<(() => Promise<void>) | undefined>(undefined);
const inFlightFlushRef = useRef<Promise<void> | undefined>(undefined);
@@ -71,11 +70,6 @@ export function useDraftAgentSpec({
inFlightFlushRef.current = undefined;
lastUpdatedAtRef.current = undefined;
setIsSpecSyncing(false);
- // Dirty edits made against a previous draft must not be replayed onto
- // the new one. Keep them only for lazy creation (undefined -> id).
- if (previousDraftId != null) {
- localDirtyRef.current = false;
- }
}, [draftSessionId]);
useEffect(() => {
@@ -85,7 +79,6 @@ export function useDraftAgentSpec({
if (draftSessionId == null) {
loadedDraftIdRef.current = undefined;
setAgentSpec(defaultAgentSpec);
- localDirtyRef.current = false;
setSpecError(null);
setIsSpecLoading(false);
return;
@@ -105,18 +98,15 @@ export function useDraftAgentSpec({
}
loadedDraftIdRef.current = draftSessionId;
- if (loaded == null) {
- // A session without an agentSpec (e.g. named or immutable session) cannot accept
- // agent spec updates. Clear any unsaved draft edits so we never attempt to sync
- // draft changes against a named session.
- localDirtyRef.current = false;
- } else if (localDirtyRef.current) {
- scheduleSpecSyncRef.current(draftSessionId, agentSpecRef.current);
- localDirtyRef.current = false;
- setSpecError(null);
- setIsSpecLoading(false);
- return;
+ // Adopt the stored session spec; drop any New Chat seed that raced in during load.
+ if (syncTimeoutRef.current != null) {
+ clearTimeout(syncTimeoutRef.current);
+ syncTimeoutRef.current = undefined;
}
+ syncGenerationRef.current++;
+ pendingFlushRef.current = undefined;
+ inFlightFlushRef.current = undefined;
+ setIsSpecSyncing(false);
// If session has no custom draft spec (e.g. non-draft or immutable session),
// keep the default draft spec rather than failing.
@@ -195,9 +185,6 @@ export function useDraftAgentSpec({
[flushSpecSync],
);
- const scheduleSpecSyncRef = useRef(scheduleSpecSync);
- scheduleSpecSyncRef.current = scheduleSpecSync;
-
const flushPendingSpecSyncNow = useCallback(async () => {
if (syncTimeoutRef.current != null) {
clearTimeout(syncTimeoutRef.current);
@@ -223,7 +210,6 @@ export function useDraftAgentSpec({
syncGenerationRef.current++;
pendingFlushRef.current = undefined;
inFlightFlushRef.current = undefined;
- localDirtyRef.current = false;
// Keep the last successful sync timestamp when the caller omits
// updatedAt (e.g. a save that did not return sessionUpdatedAt).
if (updatedAt !== undefined) {
@@ -260,8 +246,9 @@ export function useDraftAgentSpec({
}
const next = mergeAgentSpec(agentSpecRef.current, update);
setAgentSpec(next);
- localDirtyRef.current = true;
- if (draftSessionId != null) {
+ // Wait until the session's stored spec is loaded. Syncing earlier overwrites
+ // a resumed session with the in-memory New Chat seed.
+ if (draftSessionId != null && loadedDraftIdRef.current === draftSessionId) {
scheduleSpecSync(draftSessionId, next);
}
},
diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts
index da9a88f71..333b6d4de 100644
--- a/packages/assistant-ui-runtime/src/server/types.ts
+++ b/packages/assistant-ui-runtime/src/server/types.ts
@@ -123,8 +123,8 @@ export interface AgentCapabilityConfig {
export interface AgentSandboxConfig extends AgentCapabilityConfig {
fileDownloads?: boolean;
- /** Name of a configured sandbox environment. */
- environment_name?: string;
+ /** Name of a configured sandbox environment. Wire JSON is `environment_name`. */
+ environmentName?: string;
}
export interface AgentInputTokensCompactionTrigger {
diff --git a/packages/assistant-ui-runtime/test/draft/useDraftAgentSpec.test.tsx b/packages/assistant-ui-runtime/test/draft/useDraftAgentSpec.test.tsx
index 93b4a42e9..add1f699a 100644
--- a/packages/assistant-ui-runtime/test/draft/useDraftAgentSpec.test.tsx
+++ b/packages/assistant-ui-runtime/test/draft/useDraftAgentSpec.test.tsx
@@ -297,4 +297,111 @@ describe('useDraftAgentSpec', () => {
expect(draftBridge.getDraftAgentSpec).toHaveBeenCalledWith('immutable-session-1');
expect(syncAgentSpec).not.toHaveBeenCalled();
});
+
+ it('adopts a resumed session spec instead of PATCHing dirty New Chat edits onto it', async () => {
+ const resumedSpec = {
+ model: { name: 'openai/gpt-5-6-terra' },
+ config: { sandbox: { enabled: true, environmentName: 'python-dev' } },
+ };
+ const syncAgentSpec = vi.fn().mockResolvedValue('2026-06-30T18:00:00.000Z');
+ const draftBridge: DraftSessionBridge = {
+ getDraftAgentSpec: vi.fn().mockResolvedValue(resumedSpec),
+ syncAgentSpec,
+ };
+ const initialProps: { draftSessionId: string | undefined } = { draftSessionId: undefined };
+ const { result, rerender } = renderHook(
+ ({ draftSessionId }) =>
+ useDraftAgentSpec({
+ draftSessionId,
+ draftBridge,
+ defaultAgentSpec,
+ }),
+ { initialProps },
+ );
+ await flushMicrotasks();
+
+ act(() => {
+ result.current.updateAgentSpec({
+ model: { name: 'openai/gpt-4.1' },
+ config: { sandbox: { enabled: true } },
+ });
+ });
+
+ rerender({ draftSessionId: 'existing-session-1' });
+ await flushMicrotasks();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ await flushMicrotasks();
+
+ expect(draftBridge.getDraftAgentSpec).toHaveBeenCalledWith('existing-session-1');
+ expect(result.current.agentSpec).toEqual(resumedSpec);
+ expect(syncAgentSpec).not.toHaveBeenCalled();
+ });
+
+ it('does not PATCH New Chat seed while a resumed session spec is still loading', async () => {
+ const resumedSpec = {
+ model: { name: 'openai/gpt-5-6-terra' },
+ config: { sandbox: { enabled: true, environmentName: 'python-dev' } },
+ };
+ let resolveLoad: ((spec: typeof resumedSpec) => void) | undefined;
+ const syncAgentSpec = vi.fn().mockResolvedValue('2026-06-30T19:00:00.000Z');
+ const draftBridge: DraftSessionBridge = {
+ getDraftAgentSpec: vi.fn(
+ () =>
+ new Promise<typeof resumedSpec>(resolve => {
+ resolveLoad = resolve;
+ }),
+ ),
+ syncAgentSpec,
+ };
+ const initialProps: { draftSessionId: string | undefined } = { draftSessionId: undefined };
+ const { result, rerender } = renderHook(
+ ({ draftSessionId }) =>
+ useDraftAgentSpec({
+ draftSessionId,
+ draftBridge,
+ defaultAgentSpec,
+ }),
+ { initialProps },
+ );
+ await flushMicrotasks();
+
+ act(() => {
+ result.current.updateAgentSpec({
+ config: { sandbox: { enabled: true }, webSearch: { enabled: true } },
+ });
+ });
+
+ // sameMutable history switch: draftSessionId appears before getDraftAgentSpec resolves.
+ rerender({ draftSessionId: 'existing-session-2' });
+ await flushMicrotasks();
+ expect(result.current.isSpecLoading).toBe(true);
+
+ // Preference bridges call updateAgentSpec while the New Chat seed is still mounted.
+ act(() => {
+ result.current.updateAgentSpec({
+ mcpServers: [],
+ skills: [],
+ });
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ await flushMicrotasks();
+ expect(syncAgentSpec).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveLoad?.(resumedSpec);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ await flushMicrotasks();
+
+ expect(result.current.agentSpec).toEqual(resumedSpec);
+ expect(syncAgentSpec).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx b/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
index a9901b713..5bd27c082 100644
--- a/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/AgentRuntimeConfigFields.tsx
@@ -66,15 +66,23 @@ export function AgentRuntimeConfigFields({
}: AgentRuntimeConfigFieldsProps) {
const shell = useOptionalShellMode();
const { environments: readyEnvironments, refetch: refetchEnvironments } = useReadySandboxEnvironments();
+ const selectedEnvironmentName = value.sandbox?.environmentName?.trim() || 'default';
- const environmentOptions = useMemo(
- () =>
- readyEnvironments.map(env => ({
- value: env.name,
- label: env.name,
- })),
- [readyEnvironments],
- );
+ const environmentOptions = useMemo(() => {
+ const options: Array<{ value: string; label: string; disabled?: boolean }> = readyEnvironments.map(env => ({
+ value: env.name,
+ label: env.name,
+ }));
+ // Keep a deleted session/agent environment visible so the control does not fall back to Select.
+ if (selectedEnvironmentName !== 'default' && !options.some(option => option.value === selectedEnvironmentName)) {
+ options.unshift({
+ value: selectedEnvironmentName,
+ label: selectedEnvironmentName,
+ disabled: true,
+ });
+ }
+ return options;
+ }, [readyEnvironments, selectedEnvironmentName]);
const withCompaction = (compaction: AgentCompactionConfig): AgentRuntimeConfig => ({
...value,
@@ -275,7 +283,7 @@ export function AgentRuntimeConfigFields({
<div className="flex shrink-0 items-center">
<PopoverSelect
aria-label="Environment"
- value={value.sandbox?.environment_name?.trim() || 'default'}
+ value={value.sandbox?.environmentName?.trim() || 'default'}
options={environmentOptions}
disabled={disabled || !sandboxAvailable || !sandboxEnabled}
className="w-48"
@@ -287,7 +295,7 @@ export function AgentRuntimeConfigFields({
...value,
sandbox: {
...value.sandbox,
- environment_name: selected === 'default' ? undefined : selected,
+ environmentName: selected === 'default' ? undefined : selected,
},
})
}
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
index 6658853f1..516863a6e 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx
@@ -60,6 +60,7 @@ const TABS: { id: AttachTab; label: string; icon: string }[] = [
];
const SPEC_FLUSH_MS = 300;
+const ENVIRONMENT_LOCKED_HINT = "Can't change the environment after a chat has started";
export function CatalogRow({
title,
@@ -308,8 +309,10 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
const capabilities = useServerCapabilities();
const settingsCatalog = useOptionalCatalogServer();
const shell = useOptionalShellMode();
- const { agentSpec } = useTrueForgeAgentSpec();
+ const { agentSpec, draftSessionId } = useTrueForgeAgentSpec();
const updateAgentSpec = useTrueForgeUpdateAgentSpec();
+ // Turns reuse the session sandbox; changing environment after create would only update the spec.
+ const environmentLocked = draftSessionId != null;
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<AttachTab>('connectors');
const [query, setQuery] = useState('');
@@ -582,21 +585,32 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
shell?.setSettingsOpen(true, section);
};
- const currentEnvName = agentSpec?.config?.sandbox?.environment_name?.trim() || 'default';
+ const currentEnvName = agentSpec?.config?.sandbox?.environmentName?.trim() || 'default';
const filteredEnvironments = useMemo(() => {
+ const readyNames = new Set(readyEnvironments.map(e => e.name));
const all = readyEnvironments.map(e => ({
name: e.name,
description: e.manifest.description,
+ unavailable: false,
}));
+ // Keep the session's recorded environment visible (and selected) if it left the catalog.
+ if (currentEnvName !== 'default' && !readyNames.has(currentEnvName)) {
+ all.unshift({
+ name: currentEnvName,
+ description: undefined,
+ unavailable: true,
+ });
+ }
const needle = query.trim().toLowerCase();
if (!needle) return all;
return all.filter(
item => item.name.toLowerCase().includes(needle) || (item.description?.toLowerCase().includes(needle) ?? false),
);
- }, [readyEnvironments, query]);
+ }, [readyEnvironments, query, currentEnvName]);
const selectEnvironment = (envName: string) => {
+ if (environmentLocked) return;
const isDefault = envName === 'default';
updateAgentSpec?.({
config: {
@@ -604,7 +618,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
sandbox: {
...agentSpec?.config?.sandbox,
enabled: isDefault ? agentSpec?.config?.sandbox?.enabled : true,
- environment_name: isDefault ? undefined : envName,
+ environmentName: isDefault ? undefined : envName,
},
},
});
@@ -761,8 +775,18 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
</>
) : (
<>
+ {environmentLocked ? (
+ <div
+ role="status"
+ className="border-primary-button-bg/30 bg-primary-button-bg/5 text-text-primary mx-3 mb-2 flex items-center gap-2 rounded-lg border p-3"
+ >
+ <Icon name="lock" className="text-primary-button-bg size-3 shrink-0" />
+ <span className="text-xs leading-none">{ENVIRONMENT_LOCKED_HINT}</span>
+ </div>
+ ) : null}
{filteredEnvironments.map(env => {
const isSelected = currentEnvName === env.name;
+ const rowDisabled = environmentLocked || env.unavailable;
return (
<CatalogRow
key={env.name}
@@ -771,6 +795,8 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC
fallbackIcon="monitor"
selectionControl="radio"
checked={isSelected}
+ disabled={rowDisabled}
+ disabledReason={environmentLocked ? ENVIRONMENT_LOCKED_HINT : undefined}
onToggle={() => selectEnvironment(env.name)}
/>
);
diff --git a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
index f321c2914..9ae92f6f1 100644
--- a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
+++ b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx
@@ -149,7 +149,7 @@ export function reconcileDraftWebSearch({
*/
export function DraftSpecPreferenceBridge() {
const { mode, pendingSessionId, rememberDraftSpec } = useShellMode();
- const { agentSpec } = useTrueForgeAgentSpec();
+ const { agentSpec, isSpecLoading } = useTrueForgeAgentSpec();
const updateAgentSpec = useTrueForgeUpdateAgentSpec();
const capabilities = useServerCapabilities();
const sandboxEnabled = capabilities?.sandbox.enabled;
@@ -158,25 +158,28 @@ export function DraftSpecPreferenceBridge() {
const { models, skills, connectors, loaded, error, ensureLoaded } = useDraftCatalog();
const isMutableDraft = mode.status === 'active' && mode.isMutable && pendingSessionId == null;
const isPlainDraft = isMutableDraft && mode.agentId == null;
+ // While a history session's stored spec is loading, agentSpec is still the New Chat
+ // seed — do not reconcile/PATCH that seed onto the resumed session.
+ const canReconcileLiveSpec = !isSpecLoading;
const preferenceKind = mode.status === 'active' && mode.isMutable && mode.isCreateAgent ? 'agent' : 'chat';
useEffect(() => {
if (isPlainDraft) ensureLoaded();
}, [ensureLoaded, isPlainDraft]);
useEffect(() => {
- if (isPlainDraft && agentSpec != null) {
+ if (isPlainDraft && canReconcileLiveSpec && agentSpec != null) {
rememberDraftSpec(agentSpec, preferenceKind);
}
- }, [agentSpec, isPlainDraft, preferenceKind, rememberDraftSpec]);
+ }, [agentSpec, canReconcileLiveSpec, isPlainDraft, preferenceKind, rememberDraftSpec]);
useEffect(() => {
// New Chat mirrors capabilities onto the live draft; New Agent only disables when unavailable.
- if (!isPlainDraft || agentSpec == null || updateAgentSpec == null) return;
+ if (!isPlainDraft || !canReconcileLiveSpec || agentSpec == null || updateAgentSpec == null) return;
const update = reconcileDraftSandbox({ agentSpec, sandboxEnabled, kind: preferenceKind });
if (Object.keys(update).length > 0) {
updateAgentSpec(update);
}
- }, [agentSpec, isPlainDraft, preferenceKind, sandboxEnabled, updateAgentSpec]);
+ }, [agentSpec, canReconcileLiveSpec, isPlainDraft, preferenceKind, sandboxEnabled, updateAgentSpec]);
useEffect(() => {
// Apply to New Chat / New Agent / edit-existing mutable drafts.
@@ -184,7 +187,7 @@ export function DraftSpecPreferenceBridge() {
// Force-off recovery is only for plain drafts, and only when no choice was stored.
const previousWebSearchEnabled = prevWebSearchEnabledRef.current;
prevWebSearchEnabledRef.current = webSearchEnabled;
- if (!isMutableDraft || agentSpec == null || updateAgentSpec == null) return;
+ if (!isMutableDraft || !canReconcileLiveSpec || agentSpec == null || updateAgentSpec == null) return;
const update = reconcileDraftWebSearch({
agentSpec,
webSearchEnabled,
@@ -195,10 +198,27 @@ export function DraftSpecPreferenceBridge() {
if (Object.keys(update).length > 0) {
updateAgentSpec(update);
}
- }, [agentSpec, isMutableDraft, isPlainDraft, preferenceKind, webSearchEnabled, updateAgentSpec]);
+ }, [
+ agentSpec,
+ canReconcileLiveSpec,
+ isMutableDraft,
+ isPlainDraft,
+ preferenceKind,
+ webSearchEnabled,
+ updateAgentSpec,
+ ]);
useEffect(() => {
- if (!isPlainDraft || agentSpec == null || updateAgentSpec == null || !loaded || error != null) return;
+ if (
+ !isPlainDraft ||
+ !canReconcileLiveSpec ||
+ agentSpec == null ||
+ updateAgentSpec == null ||
+ !loaded ||
+ error != null
+ ) {
+ return;
+ }
const update = reconcileDraftSpecPreferences({
agentSpec,
@@ -212,6 +232,7 @@ export function DraftSpecPreferenceBridge() {
}
}, [
agentSpec,
+ canReconcileLiveSpec,
capabilities?.skill.enabled,
connectors,
error,
diff --git a/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx b/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
index 6e7df1b9f..5651412f5 100644
--- a/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
+++ b/packages/trueforge-ui/test/atoms/draft/AgentRuntimeConfigFields.test.tsx
@@ -136,9 +136,26 @@ describe('AgentRuntimeConfigFields', () => {
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
sandbox: expect.objectContaining({
- environment_name: 'python-dev',
+ environmentName: 'python-dev',
}),
}),
);
});
+
+ it('shows a missing agent-spec environment as the selected option', async () => {
+ renderRuntimeFields({
+ value: { sandbox: { enabled: true, environmentName: 'gone-env' } },
+ });
+
+ const trigger = screen.getByRole('button', { name: 'Environment' });
+ await waitFor(() => {
+ expect(trigger).toHaveTextContent('gone-env');
+ });
+ expect(trigger).not.toHaveTextContent('unavailable');
+
+ fireEvent.click(trigger);
+ const missing = await screen.findByRole('option', { name: 'gone-env' });
+ expect(missing).toBeDisabled();
+ expect(missing).toHaveAttribute('aria-selected', 'true');
+ });
});
diff --git a/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx b/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx
index d55fb463b..355d264b5 100644
--- a/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx
+++ b/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx
@@ -21,6 +21,7 @@ import {
} from '../../server/mockServer.js';
let agentSpec: AgentSpec;
+let draftSessionId: string | undefined;
const updateAgentSpec = vi.fn();
const setSettingsOpen = vi.fn();
const rememberDraftSpec = vi.fn();
@@ -47,7 +48,7 @@ const settingsCatalog = createMockCatalog({ skillCatalog, sandboxCatalog });
const setEnvironmentsOpen = vi.fn();
vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({
- useTrueForgeAgentSpec: () => ({ agentSpec }),
+ useTrueForgeAgentSpec: () => ({ agentSpec, draftSessionId }),
useTrueForgeUpdateAgentSpec: () => updateAgentSpec,
}));
@@ -122,6 +123,7 @@ function renderSelector({
describe('DraftCompositeSelector', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
+ draftSessionId = undefined;
agentSpec = {
model: { name: 'openai/gpt-4.1' },
mcpServers: [{ id: 'slack', name: 'Slack' }],
@@ -457,22 +459,103 @@ describe('DraftCompositeSelector', () => {
config: expect.objectContaining({
sandbox: expect.objectContaining({
enabled: true,
- environment_name: 'python-dev',
+ environmentName: 'python-dev',
}),
}),
});
- // Select default environment clears environment_name
+ // Select default environment clears environmentName
fireEvent.click(screen.getByText('default'));
expect(updateAgentSpec).toHaveBeenCalledWith({
config: expect.objectContaining({
sandbox: expect.objectContaining({
- environment_name: undefined,
+ environmentName: undefined,
}),
}),
});
});
+ it('locks environment selection once a chat session exists', async () => {
+ draftSessionId = 'session-1';
+ agentSpec = {
+ ...agentSpec,
+ config: { sandbox: { enabled: true, environmentName: 'python-dev' } },
+ };
+ const environmentServer = createMockSandboxEnvironmentServer({
+ listEnvironments: async () => ({
+ data: [
+ {
+ id: 'env-default',
+ name: 'default',
+ description: 'Default environment',
+ status: 'ready',
+ statusReason: null,
+ manifest: { name: 'default', description: 'Default environment' },
+ createdBySubject: { subjectId: 'u1', subjectType: 'user', subjectDisplayName: 'user-1' },
+ createdAt: '2026-09-01T10:00:00Z',
+ updatedAt: '2026-09-01T10:00:00Z',
+ },
+ {
+ id: 'env-1',
+ name: 'python-dev',
+ description: 'Python 3.11 environment',
+ status: 'ready',
+ statusReason: null,
+ manifest: { name: 'python-dev', description: 'Python 3.11 environment' },
+ createdBySubject: { subjectId: 'u1', subjectType: 'user', subjectDisplayName: 'user-1' },
+ createdAt: '2026-09-01T10:00:00Z',
+ updatedAt: '2026-09-01T10:00:00Z',
+ },
+ ],
+ }),
+ });
+
+ renderSelector({ environmentServer });
+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));
+ fireEvent.click(screen.getByRole('button', { name: /Environment/ }));
+
+ expect(await screen.findByText("Can't change the environment after a chat has started")).toBeInTheDocument();
+ fireEvent.click(screen.getByText('default'));
+ expect(updateAgentSpec).not.toHaveBeenCalled();
+ });
+
+ it('shows a deleted environment from the agent spec and does not change it', async () => {
+ agentSpec = {
+ ...agentSpec,
+ config: { sandbox: { enabled: true, environmentName: 'gone-env' } },
+ };
+ const environmentServer = createMockSandboxEnvironmentServer({
+ listEnvironments: async () => ({
+ data: [
+ {
+ id: 'env-default',
+ name: 'default',
+ description: 'Default environment',
+ status: 'ready',
+ statusReason: null,
+ manifest: { name: 'default', description: 'Default environment' },
+ createdBySubject: { subjectId: 'u1', subjectType: 'user', subjectDisplayName: 'user-1' },
+ createdAt: '2026-09-01T10:00:00Z',
+ updatedAt: '2026-09-01T10:00:00Z',
+ },
+ ],
+ }),
+ });
+
+ renderSelector({ environmentServer });
+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));
+ fireEvent.click(screen.getByRole('button', { name: /Environment/ }));
+
+ expect(await screen.findByText('gone-env')).toBeInTheDocument();
+ expect(screen.queryByText('This environment is no longer available')).not.toBeInTheDocument();
+ const goneRow = screen.getByRole('menuitemradio', { name: /gone-env/ });
+ expect(goneRow).toHaveAttribute('aria-checked', 'true');
+ expect(goneRow).toHaveAttribute('aria-disabled', 'true');
+
+ fireEvent.click(screen.getByText('gone-env'));
+ expect(updateAgentSpec).not.toHaveBeenCalled();
+ });
+
it('shows Web search under Built-in and toggles draft config when available', async () => {
agentSpec = {
...agentSpec,
diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessServer.test.ts
index e9a4b68cf..6bd78b29f 100644
--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessServer.test.ts
+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessServer.test.ts
@@ -132,6 +132,35 @@ describe('createHarnessChatServer', () => {
});
});
+ it('preserves sandbox environmentName on UI and harness agent specs', () => {
+ const ui = toUiAgentSpec({
+ model: { name: 'test/model' },
+ config: {
+ sandbox: { enabled: true, environmentName: 'python-dev', fileDownloads: true },
+ webSearch: { enabled: true },
+ },
+ });
+ assert.deepEqual(ui.config?.sandbox, {
+ enabled: true,
+ environmentName: 'python-dev',
+ fileDownloads: true,
+ });
+ assert.deepEqual(
+ toHarnessAgentSpec({
+ model: { name: 'test/model' },
+ config: {
+ sandbox: { enabled: true, environmentName: 'python-dev', fileDownloads: true },
+ webSearch: { enabled: true },
+ },
+ }).config?.sandbox,
+ {
+ enabled: true,
+ environmentName: 'python-dev',
+ fileDownloads: true,
+ },
+ );
+ });
+
it('reports pages under the ListResult pagination contract', async () => {
const server = createHarnessChatServer({ fetch: fetchMock });