Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(agent): keep old sandbox conversations writable (#16148)

Lysander Kieselaa0b80fe60d4
diff --git a/packages/shared/src/in-app-agent/constants.ts b/packages/shared/src/in-app-agent/constants.ts
index d8b6881248..2d9cf98d69 100644
--- a/packages/shared/src/in-app-agent/constants.ts
+++ b/packages/shared/src/in-app-agent/constants.ts
@@ -17,9 +17,6 @@ export const IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER =
export const IN_APP_AGENT_LOCAL_SANDBOX_IMAGE =
"langfuse-in-app-agent-sandbox:latest";
-export const IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
- "This conversation has reached the 8-hour limit. Please start a new conversation.";
-
export const IN_APP_AGENT_GENERIC_ERROR_MESSAGE =
"An error occurred. Please try again or start a new conversation.";
diff --git a/packages/shared/src/in-app-agent/server/agent.ts b/packages/shared/src/in-app-agent/server/agent.ts
index 43c4f2ca37..3403c300fa 100644
--- a/packages/shared/src/in-app-agent/server/agent.ts
+++ b/packages/shared/src/in-app-agent/server/agent.ts
@@ -142,6 +142,14 @@ When working in the sandbox filesystem, assume this layout:
`;
}
+/** Run-scoped, not part of the managed prompt: it describes one turn's environment. */
+const SANDBOX_WORKSPACE_RESET_INSTRUCTION = `<sandbox_workspace_reset>
+The sandbox workspace from earlier turns in this conversation expired and has been replaced with an empty one.
+- Any file you created earlier with write, edit, or bash is gone, along with installed packages and all process state.
+- "/workspace/tool_calls" has been restored in full from the conversation history, so results of earlier successful tool calls are still readable there. Failed tool calls were never stored.
+- Do not assume a path exists because you created it earlier in this conversation. Read it first, and recreate what you still need.
+</sandbox_workspace_reset>`;
+
// Adaptive thinking is the default for every Claude model so new generations
// work without maintaining a model list. Older models that only support
// thinking.type.enabled (e.g. haiku 4.5) reject adaptive with a 400 — the
@@ -193,6 +201,8 @@ type CreateAgUiStreamOptions = {
useLocalPrompt: boolean;
langfuseTracing?: InAppAgentTracingConfig;
sandbox?: InAppAgentSandbox;
+ /** Adds a run instruction telling the model its earlier workspace files are gone. */
+ sandboxWorkspaceWasReset?: boolean;
};
export async function createAgUiStream(params: {
@@ -891,6 +901,9 @@ async function createMastraAdapter(params: {
defaultOptions: {
abortSignal: params.signal,
maxSteps: MAX_AGENT_STEPS,
+ ...(params.options.sandboxWorkspaceWasReset
+ ? { system: SANDBOX_WORKSPACE_RESET_INSTRUCTION }
+ : {}),
// Fires once per LLM call with that call's token usage; the AG-UI
// event stream itself never carries usage.
...(params.onStepFinish ? { onStepFinish: params.onStepFinish } : {}),
diff --git a/packages/shared/src/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.ts
index bf1ef0a3bd..5c327f1708 100644
--- a/packages/shared/src/in-app-agent/server/persistence.ts
+++ b/packages/shared/src/in-app-agent/server/persistence.ts
@@ -47,14 +47,12 @@ import { getToolFailureMessage } from "./toolErrors";
export const ACTIVE_RUN_CONFLICT_MESSAGE =
"Assistant is already responding in this conversation";
-const SANDBOX_CONVERSATION_WRITE_WINDOW_MS = 8 * 60 * 60 * 1000;
export type SerializedInAppAgentConversation = {
id: string;
title: string | null;
createdAt: Date;
updatedAt: Date;
- isWriteLocked: boolean;
};
export type PersistedConversationEvent = {
@@ -75,43 +73,15 @@ export function serializeConversation(
InAppAgentConversation,
"id" | "title" | "createdAt" | "updatedAt"
>,
- options?: { isWriteLocked?: boolean },
): SerializedInAppAgentConversation {
return {
id: conversation.id,
title: conversation.title,
createdAt: conversation.createdAt,
updatedAt: conversation.updatedAt,
- isWriteLocked: options?.isWriteLocked ?? false,
};
}
-export function isInAppAgentConversationWriteLocked(params: {
- conversation: Pick<InAppAgentConversation, "createdAt">;
- events: readonly Pick<PersistedConversationEvent, "event">[];
- now?: Date;
-}) {
- const now = params.now ?? new Date();
- const ageMs = now.getTime() - params.conversation.createdAt.getTime();
-
- if (ageMs <= SANDBOX_CONVERSATION_WRITE_WINDOW_MS) {
- return false;
- }
-
- return params.events.some(({ event }) => {
- if (event.type !== EventType.TOOL_CALL_START) {
- return false;
- }
-
- const toolName = getString(event, "toolCallName");
- if (!toolName) {
- return false;
- }
-
- return IN_APP_AGENT_SANDBOX_TOOL_NAMES.has(toolName);
- });
-}
-
export async function getOwnedConversationOrThrow(params: {
prisma: PrismaClient;
projectId: string;
diff --git a/packages/shared/src/in-app-agent/server/sandbox/index.ts b/packages/shared/src/in-app-agent/server/sandbox/index.ts
index 57fe34ab17..b709c76427 100644
--- a/packages/shared/src/in-app-agent/server/sandbox/index.ts
+++ b/packages/shared/src/in-app-agent/server/sandbox/index.ts
@@ -4,6 +4,7 @@ export { createInAppAgentSandbox } from "./service";
export type {
InAppAgentSandbox,
InAppAgentSandboxProviderType,
+ InAppAgentSandboxSessionReplacementReason,
SandboxFile,
SandboxProvider,
SandboxSession,
diff --git a/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts b/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts
index 8c7dd9d4eb..236f2d3cab 100644
--- a/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts
+++ b/packages/shared/src/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts
@@ -13,14 +13,21 @@ import {
import { logger } from "../../../../server";
import { z } from "zod";
-import type { SandboxFile, SandboxProvider, SandboxSession } from "../types";
+import type {
+ InAppAgentSandboxSessionReplacementReason,
+ SandboxFile,
+ SandboxProvider,
+ SandboxSession,
+} from "../types";
const DEFAULT_AUTH_TOKEN_EXPIRATION_MINUTES = 30;
const AUTH_TOKEN_REFRESH_BUFFER_MS = 60_000;
const DEFAULT_SANDBOX_SERVER_PORT = 5000;
const DEFAULT_SUSPEND_AFTER_IDLE_SECONDS = 60;
-const DEFAULT_TERMINATE_AFTER_SUSPEND_SECONDS = 8 * 60 * 60;
-const DEFAULT_MAXIMUM_DURATION_SECONDS = 3_600;
+// Resumable window is min(existence from creation, suspension from last activity),
+// so these two must agree. API maximum for the existence cap is 28,800.
+const DEFAULT_TERMINATE_AFTER_SUSPEND_SECONDS = 4 * 60 * 60;
+const DEFAULT_MAXIMUM_DURATION_SECONDS = 4 * 60 * 60;
const BRIDGE_READY_TIMEOUT_MS = 30_000;
const LambdaMicrovmErrorSchema = z.object({
@@ -51,6 +58,12 @@ type LambdaMicrovmSession = {
toolCallFiles: ReadonlyArray<SandboxFile>;
};
+type EnsuredLambdaSession = {
+ sessionId: string;
+ endpoint: string;
+ replacementReason?: InAppAgentSandboxSessionReplacementReason;
+};
+
type LambdaMicrovmInfo = {
microvmId: string;
endpoint: string;
@@ -69,67 +82,11 @@ export function createLambdaMicrovmSandboxProvider(params: {
});
const sessions = new Map<string, LambdaMicrovmSession>();
- const ensureSession = async (request: {
- conversationId: string;
- sessionId?: string | null;
- }) => {
- logger.debug("[Lambda MicroVM Sandbox] ensureSession", {
- conversationId: request.conversationId,
- requestedSessionId: request.sessionId,
- });
-
- if (request.sessionId) {
- logger.debug(
- "[Lambda MicroVM Sandbox] checking existing session before restore",
- {
- conversationId: request.conversationId,
- sessionId: request.sessionId,
- },
- );
- }
-
- if (request.sessionId) {
- const existing = await getMicrovm(client, request.sessionId);
- if (existing) {
- if (existing.state === "SUSPENDED") {
- logger.debug("[Lambda MicroVM Sandbox] resuming suspended session", {
- conversationId: request.conversationId,
- sessionId: request.sessionId,
- });
- await client.send(
- new ResumeMicrovmCommand({ microvmIdentifier: request.sessionId }),
- );
- }
-
- await waitForBridge({
- client,
- microvmId: request.sessionId,
- endpoint: existing.endpoint,
- });
-
- const session = sessions.get(request.sessionId);
- sessions.set(request.sessionId, {
- ...session,
- endpoint: existing.endpoint,
- toolCallFiles: session?.toolCallFiles ?? [],
- });
- logger.debug("[Lambda MicroVM Sandbox] reusing existing session", {
- conversationId: request.conversationId,
- sessionId: request.sessionId,
- state: existing.state,
- });
- return { sessionId: request.sessionId, endpoint: existing.endpoint };
- }
-
- logger.debug("[Lambda MicroVM Sandbox] existing session not found", {
- conversationId: request.conversationId,
- sessionId: request.sessionId,
- });
- sessions.delete(request.sessionId);
- }
-
+ const createMicrovm = async (
+ conversationId: string,
+ ): Promise<EnsuredLambdaSession> => {
logger.debug("[Lambda MicroVM Sandbox] creating new session", {
- conversationId: request.conversationId,
+ conversationId,
imageIdentifier: params.imageIdentifier,
hasExecutionRoleArn: Boolean(params.executionRoleArn),
});
@@ -156,14 +113,19 @@ export function createLambdaMicrovmSandboxProvider(params: {
endpoint: microvm.endpoint,
toolCallFiles: [],
});
- await waitForBridge({
+ const ready = await waitForBridge({
client,
microvmId: microvm.microvmId,
endpoint: microvm.endpoint,
});
+ if (ready.status !== "ready") {
+ throw new Error(
+ `[Lambda MicroVM Sandbox] startup failed before bridge became ready: ${ready.reason}`,
+ );
+ }
logger.debug("[Lambda MicroVM Sandbox] created new session", {
- conversationId: request.conversationId,
+ conversationId,
sessionId: microvm.microvmId,
state: microvm.state,
});
@@ -171,6 +133,127 @@ export function createLambdaMicrovmSandboxProvider(params: {
return { sessionId: microvm.microvmId, endpoint: microvm.endpoint };
};
+ const replaceSession = async (
+ conversationId: string,
+ previousSessionId: string,
+ replacementReason: InAppAgentSandboxSessionReplacementReason,
+ ): Promise<EnsuredLambdaSession> => {
+ sessions.delete(previousSessionId);
+ const created = await createMicrovm(conversationId);
+ return { ...created, replacementReason };
+ };
+
+ const ensureSession = async (request: {
+ conversationId: string;
+ sessionId?: string | null;
+ }): Promise<EnsuredLambdaSession> => {
+ logger.debug("[Lambda MicroVM Sandbox] ensureSession", {
+ conversationId: request.conversationId,
+ requestedSessionId: request.sessionId,
+ });
+
+ if (request.sessionId) {
+ logger.debug(
+ "[Lambda MicroVM Sandbox] checking existing session before restore",
+ {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ },
+ );
+
+ const existing = await getMicrovm(client, request.sessionId);
+ if (!existing) {
+ logger.debug("[Lambda MicroVM Sandbox] existing session not found", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ });
+ return replaceSession(
+ request.conversationId,
+ request.sessionId,
+ "not_found",
+ );
+ }
+
+ if (isTerminalMicrovmState(existing.state)) {
+ logger.debug("[Lambda MicroVM Sandbox] existing session is terminal", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ state: existing.state,
+ });
+ return replaceSession(
+ request.conversationId,
+ request.sessionId,
+ "terminal_state",
+ );
+ }
+
+ try {
+ if (existing.state === "SUSPENDED") {
+ logger.debug("[Lambda MicroVM Sandbox] resuming suspended session", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ });
+ await client.send(
+ new ResumeMicrovmCommand({ microvmIdentifier: request.sessionId }),
+ );
+ }
+ } catch (error) {
+ if (isMissingMicrovmError(error)) {
+ logger.debug(
+ "[Lambda MicroVM Sandbox] resume raced with session teardown",
+ {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ },
+ );
+ return replaceSession(
+ request.conversationId,
+ request.sessionId,
+ "resume_race",
+ );
+ }
+
+ throw error;
+ }
+
+ const ready = await waitForBridge({
+ client,
+ microvmId: request.sessionId,
+ endpoint: existing.endpoint,
+ });
+ if (ready.status !== "ready") {
+ logger.debug(
+ "[Lambda MicroVM Sandbox] restored session became unavailable",
+ {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ reason: ready.reason,
+ },
+ );
+ return replaceSession(
+ request.conversationId,
+ request.sessionId,
+ ready.reason,
+ );
+ }
+
+ const session = sessions.get(request.sessionId);
+ sessions.set(request.sessionId, {
+ ...session,
+ endpoint: existing.endpoint,
+ toolCallFiles: session?.toolCallFiles ?? [],
+ });
+ logger.debug("[Lambda MicroVM Sandbox] reusing existing session", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ state: existing.state,
+ });
+ return { sessionId: request.sessionId, endpoint: existing.endpoint };
+ }
+
+ return createMicrovm(request.conversationId);
+ };
+
const executeOperation = async (
sessionId: string,
operation: LambdaMicrovmOperation,
@@ -271,6 +354,20 @@ export function createLambdaMicrovmSandboxProvider(params: {
});
return {
+ async probeSession({ sessionId }) {
+ const existing = await getMicrovm(client, sessionId);
+ const lostReason = !existing
+ ? "not_found"
+ : isTerminalMicrovmState(existing.state)
+ ? "terminal_state"
+ : null;
+ logger.debug("[Lambda MicroVM Sandbox] probed session", {
+ sessionId,
+ state: existing?.state,
+ lostReason,
+ });
+ return lostReason;
+ },
async ensureSession({ conversationId, sessionId }) {
const session = await ensureSession({
conversationId,
@@ -279,6 +376,9 @@ export function createLambdaMicrovmSandboxProvider(params: {
return {
sessionId: session.sessionId,
sandbox: createSessionSandbox(session.sessionId),
+ ...(session.replacementReason
+ ? { replacementReason: session.replacementReason }
+ : {}),
};
},
async suspendSession({ sessionId }) {
@@ -337,22 +437,21 @@ async function waitForBridge(params: {
client: LambdaMicrovmsClient;
microvmId: string;
endpoint: string;
-}) {
+}): Promise<
+ | { status: "ready" }
+ | { status: "unavailable"; reason: "not_found" | "terminal_state" }
+> {
const startedAt = Date.now();
let lastError: unknown;
while (Date.now() - startedAt < BRIDGE_READY_TIMEOUT_MS) {
const microvm = await getMicrovm(params.client, params.microvmId);
if (!microvm) {
- throw new Error(
- `[Lambda MicroVM Sandbox] startup failed before bridge became ready: session ${params.microvmId} no longer exists`,
- );
+ return { status: "unavailable", reason: "not_found" };
}
- if (microvm.state === "TERMINATING" || microvm.state === "TERMINATED") {
- throw new Error(
- `[Lambda MicroVM Sandbox] startup failed before bridge became ready: state=${microvm.state}${microvm.stateReason ? ` stateReason=${microvm.stateReason}` : ""}`,
- );
+ if (isTerminalMicrovmState(microvm.state)) {
+ return { status: "unavailable", reason: "terminal_state" };
}
try {
@@ -374,7 +473,7 @@ async function waitForBridge(params: {
);
if (response.ok) {
- return;
+ return { status: "ready" };
}
lastError = new Error(
@@ -500,6 +599,10 @@ function getEndpointPort(endpoint: string) {
return parsedEndpoint.protocol === "http:" ? 80 : 443;
}
+function isTerminalMicrovmState(state: string) {
+ return state === "TERMINATING" || state === "TERMINATED";
+}
+
function isMissingMicrovmError(error: unknown) {
const parsedError = LambdaMicrovmErrorSchema.safeParse(error);
if (!parsedError.success) {
diff --git a/packages/shared/src/in-app-agent/server/sandbox/service.ts b/packages/shared/src/in-app-agent/server/sandbox/service.ts
index dbf9eea50d..6c3e3f47ac 100644
--- a/packages/shared/src/in-app-agent/server/sandbox/service.ts
+++ b/packages/shared/src/in-app-agent/server/sandbox/service.ts
@@ -1,4 +1,10 @@
-import type { InAppAgentSandbox, SandboxFile, SandboxProvider } from "./types";
+import type {
+ InAppAgentSandbox,
+ InAppAgentSandboxSessionReplacementReason,
+ SandboxFile,
+ SandboxProvider,
+} from "./types";
+import { logger, recordIncrement } from "../../../server";
export async function createInAppAgentSandbox(params: {
conversationId: string;
@@ -10,10 +16,37 @@ export async function createInAppAgentSandbox(params: {
}): Promise<{
sandbox: InAppAgentSandbox;
onTurnEnded: () => Promise<void>;
+ /** The earlier turn's workspace is gone; pass on as `sandboxWorkspaceWasReset`. */
+ workspaceWasReset: boolean;
}> {
let sessionId = params.providerSessionId ?? null;
let sessionIsKnownActive = sessionId !== null;
+ const recordSessionReplaced = (
+ reason: InAppAgentSandboxSessionReplacementReason,
+ ) => {
+ logger.info("In-app agent sandbox session replaced", {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ reason,
+ });
+ recordIncrement("langfuse.in_app_agent.sandbox.session_replaced", 1, {
+ reason,
+ });
+ };
+
+ // Probe up front: `ensureSession` only notices a lost session on the first tool
+ // call, too late to tell the model. Clearing the flag avoids a second probe.
+ let workspaceWasReset = false;
+ if (sessionId && params.provider.probeSession) {
+ const lostReason = await params.provider.probeSession({ sessionId });
+ if (lostReason) {
+ workspaceWasReset = true;
+ sessionIsKnownActive = false;
+ recordSessionReplaced(lostReason);
+ }
+ }
+
const persistState = async () => {
await params.saveState({
providerSessionId: sessionId,
@@ -37,6 +70,10 @@ export async function createInAppAgentSandbox(params: {
sessionId: sessionIsKnownActive ? sessionId : null,
});
+ if (session.replacementReason) {
+ recordSessionReplaced(session.replacementReason);
+ }
+
await updateSessionState(session.sessionId);
await session.sandbox.syncReadonlyFiles({
@@ -68,6 +105,7 @@ export async function createInAppAgentSandbox(params: {
return {
sandbox: createExecutionSandbox(),
+ workspaceWasReset,
onTurnEnded: async () => {
if (!sessionId) {
return;
diff --git a/packages/shared/src/in-app-agent/server/sandbox/types.ts b/packages/shared/src/in-app-agent/server/sandbox/types.ts
index 11efe52755..65555b211c 100644
--- a/packages/shared/src/in-app-agent/server/sandbox/types.ts
+++ b/packages/shared/src/in-app-agent/server/sandbox/types.ts
@@ -7,6 +7,12 @@ export type InAppAgentSandboxProviderType =
| "dangerous-docker"
| "lambda-microvm";
+/** Why a persisted sandbox session could not be reused, for logs and metrics. */
+export type InAppAgentSandboxSessionReplacementReason =
+ | "not_found"
+ | "terminal_state"
+ | "resume_race";
+
/**
* Session-bound sandbox execution handle returned by a provider.
* Implementations close over the backing runtime session so callers only pass
@@ -47,6 +53,13 @@ export type SandboxSession = {
* handles for isolated workspaces.
*/
export type SandboxProvider = {
+ /**
+ * Why a persisted session can no longer be resumed, or `null` if it still can.
+ * Creates nothing, so a lost workspace is known before the agent runs.
+ */
+ probeSession?(params: {
+ sessionId: string;
+ }): Promise<InAppAgentSandboxSessionReplacementReason | null>;
/**
* Reuses an existing sandbox session when possible or creates a new one,
* then returns a session-bound sandbox handle for tool execution.
@@ -54,7 +67,11 @@ export type SandboxProvider = {
ensureSession(params: {
conversationId: string;
sessionId?: string | null;
- }): Promise<{ sessionId: string; sandbox: SandboxSession }>;
+ }): Promise<{
+ sessionId: string;
+ sandbox: SandboxSession;
+ replacementReason?: InAppAgentSandboxSessionReplacementReason;
+ }>;
/**
* Persists session state for later reuse and releases any live runtime
* resources associated with the session.
diff --git a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
index a9df553ae7..cbb2ba6ce1 100644
--- a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
@@ -21,7 +21,6 @@ import {
createInAppAgentConversationId,
createInAppAgentRunId,
IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
} from "@langfuse/shared/in-app-agent";
import { ensureOwnedConversation } from "@langfuse/shared/in-app-agent/server/persistence";
import { env as sharedEnv } from "@langfuse/shared/src/env";
@@ -768,65 +767,6 @@ describe("in-app agent background runs", () => {
expect(enqueuedJobs).toEqual([]);
});
- it("rejects approval continuations for write-locked conversations before mutating", async () => {
- const { caller, projectId, userId } = await createCaller();
- const conversation = await createConversation({ projectId, userId });
- const parkedRunId = await parkRunForApproval({
- projectId,
- conversationId: conversation.id,
- userId,
- toolCallId: "write-locked-tool-call",
- });
-
- await prisma.inAppAgentConversation.update({
- where: {
- id_projectId: { id: conversation.id, projectId },
- },
- data: { createdAt: new Date(Date.now() - 9 * 60 * 60 * 1000) },
- });
- await prisma.inAppAgentEvent.create({
- data: {
- projectId,
- conversationId: conversation.id,
- runId: parkedRunId,
- sequenceNumber: 1,
- type: EventType.TOOL_CALL_START,
- event: {
- type: EventType.TOOL_CALL_START,
- toolCallId: "sandbox-tool-call",
- toolCallName: "bash",
- },
- },
- });
-
- await expect(
- caller.decideToolApproval({
- projectId,
- conversationId: conversation.id,
- runId: parkedRunId,
- toolCallId: "write-locked-tool-call",
- approved: true,
- }),
- ).rejects.toMatchObject({
- code: "PRECONDITION_FAILED",
- message: IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
- });
-
- await expect(
- prisma.inAppAgentRun.findFirstOrThrow({
- where: { id: parkedRunId, projectId },
- }),
- ).resolves.toMatchObject({
- status: InAppAgentRunStatus.AWAITING_APPROVAL,
- });
- await expect(
- prisma.inAppAgentRun.count({
- where: { projectId, conversationId: conversation.id },
- }),
- ).resolves.toBe(1);
- expect(enqueuedJobs).toEqual([]);
- });
-
it("persists approval expiry before rejecting a late decision", async () => {
const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index 63517e87a5..cba3980229 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -112,11 +112,16 @@ const defaultInAppAgentToolPolicy = createInAppAgentToolPolicy({
userAccess: defaultInAppAgentUserAccess,
});
-async function createTestSandbox() {
+async function createTestSandbox(opts?: {
+ /** A session persisted by an earlier turn, to exercise session reuse. */
+ providerSessionId?: string;
+ /** When set, the provider reports that persisted session as already gone. */
+ sessionLostReason?: "not_found" | "terminal_state";
+}) {
let sandboxState: {
providerSessionId: string | null;
} = {
- providerSessionId: null,
+ providerSessionId: opts?.providerSessionId ?? null,
};
let sessionCounter = 0;
const files = new Map<string, string>();
@@ -149,6 +154,9 @@ async function createTestSandbox() {
};
const provider: SandboxProvider = {
+ ...(opts?.sessionLostReason
+ ? { probeSession: async () => opts.sessionLostReason ?? null }
+ : {}),
async ensureSession({ sessionId }) {
if (sessionId && activeSessionId === sessionId) {
return { sessionId, sandbox: sandboxSession };
@@ -913,6 +921,80 @@ describe("createAgUiStream", () => {
expect(agentConfig?.defaultOptions).not.toHaveProperty("providerOptions");
});
+ it("adds a run instruction when the persisted workspace is gone", async () => {
+ const { createAgUiStream } =
+ await import("@langfuse/shared/in-app-agent/server/agent");
+ const input = {
+ threadId: "conversation-1",
+ runId: "run-1",
+ messages: [
+ { id: "user-message-1", role: "user" as const, content: "hello" },
+ ],
+ tools: [],
+ context: [],
+ state: {
+ type: "existingConversation" as const,
+ projectId: "project-1",
+ conversationId: "conversation-1",
+ },
+ forwardedProps: {},
+ };
+ const langfuseClient = {
+ getPrompt: promptMocks.getPrompt,
+ } as unknown as Langfuse;
+ const sandboxState = await createTestSandbox({
+ providerSessionId: "expired-session",
+ sessionLostReason: "terminal_state",
+ });
+
+ expect(sandboxState.workspaceWasReset).toBe(true);
+
+ adapterEvents.items = [
+ {
+ type: EventType.RUN_STARTED,
+ threadId: input.threadId,
+ runId: input.runId,
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ threadId: input.threadId,
+ runId: input.runId,
+ },
+ ];
+
+ const stream = await createAgUiStream({
+ input,
+ signal: new AbortController().signal,
+ options: {
+ awsBedrock: { modelId: "eu.anthropic.claude-opus-4-8" },
+ langfuseMcp: {
+ url: "https://example.com/api/public/mcp",
+ publicKey: "pk",
+ secretKey: "sk",
+ toolPolicy: defaultInAppAgentToolPolicy,
+ runOverride: "run-override",
+ },
+ redirectAction: { projectId: "project-1", isV4Enabled: false },
+ langfuseClient,
+ sandbox: sandboxState.sandbox,
+ sandboxWorkspaceWasReset: sandboxState.workspaceWasReset,
+ useLocalPrompt: false,
+ },
+ });
+
+ await readStream(stream);
+
+ // Rides on the run's system message, not the transcript or managed prompt.
+ const agentConfig = vi.mocked(Agent).mock.calls.at(-1)?.[0];
+ const runInstruction = (agentConfig?.defaultOptions as { system?: string })
+ ?.system;
+ expect(runInstruction).toContain("has been replaced with an empty one");
+ expect(runInstruction).toContain("restored in full");
+ expect(
+ promptMocks.compile.mock.calls.at(-1)?.[0]?.sandboxFilesystem,
+ ).not.toContain("has been replaced with an empty one");
+ });
+
it("stamps top-level error on TOOL_CALL_RESULT from structured failure payloads", async () => {
const { createAgUiStream } =
await import("@langfuse/shared/in-app-agent/server/agent");
diff --git a/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts
index 1abcff0a57..87f6d4a4c7 100644
--- a/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts
+++ b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts
@@ -221,4 +221,67 @@ describe("in-app agent lambda microvm sandbox provider", () => {
headers: { "X-aws-proxy-auth": "token-3" },
});
});
+
+ it("replaces a terminal saved session with a new microvm", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response(null, { status: 200 })),
+ );
+ microvmSendMock.mockImplementation(async (command: { input: unknown }) => {
+ const input = command.input as { microvmIdentifier?: string };
+
+ if (command.constructor.name === "GetMicrovmCommand") {
+ if (input.microvmIdentifier === "old-session") {
+ return {
+ microvmId: "old-session",
+ endpoint: "https://old.example.com:8443",
+ state: "TERMINATED",
+ };
+ }
+
+ return {
+ microvmId: input.microvmIdentifier,
+ endpoint: "https://microvm.example.com:8443",
+ state: "RUNNING",
+ };
+ }
+
+ if (command.constructor.name === "RunMicrovmCommand") {
+ return {
+ microvmId: "microvm-2",
+ endpoint: "https://microvm.example.com:8443",
+ state: "RUNNING",
+ };
+ }
+
+ if (command.constructor.name === "CreateMicrovmAuthTokenCommand") {
+ return { authToken: { "X-aws-proxy-auth": "token-1" } };
+ }
+
+ throw new Error(`Unexpected command ${command.constructor.name}`);
+ });
+
+ const { createLambdaMicrovmSandboxProvider } =
+ await import("@langfuse/shared/in-app-agent/server/sandbox/providers/lambdaMicrovm");
+ const provider = createLambdaMicrovmSandboxProvider({
+ imageIdentifier: "image-1",
+ executionRoleArn: "arn:aws:iam::123456789012:role/sandbox",
+ region: "us-east-1",
+ });
+
+ const session = await provider.ensureSession({
+ conversationId: "conversation-1",
+ sessionId: "old-session",
+ });
+
+ expect(session.sessionId).toBe("microvm-2");
+ expect(session.replacementReason).toBe("terminal_state");
+ expect(
+ microvmSendMock.mock.calls.find(
+ ([command]) => command.constructor.name === "ResumeMicrovmCommand",
+ ),
+ ).toBeUndefined();
+ });
});
diff --git a/web/src/features/in-app-agent/README.md b/web/src/features/in-app-agent/README.md
index c9f2c840c1..7b1e376b10 100644
--- a/web/src/features/in-app-agent/README.md
+++ b/web/src/features/in-app-agent/README.md
@@ -38,7 +38,7 @@ Closing the drawer detaches observation without cancelling the worker run.
- `server/router.ts`: tRPC routes for durable run start/cancel/approval, conversation snapshots and lists, and feedback.
- `server/instrumentation.ts`: optional Langfuse tracing for agent runs, prompts, events, and errors.
- `server/sandbox/config.ts`: sandbox provider selection and runtime configuration.
-- `server/sandbox/service.ts`: conversation-scoped sandbox session reuse, readonly file sync, and turn-end suspension.
+- `server/sandbox/service.ts`: conversation-scoped sandbox session reuse, readonly file sync, and turn-end session persistence.
- `server/sandbox/providers/*`: provider adapters for local Docker and Lambda MicroVM sandboxes.
- `server/sandbox/types.ts`: runtime-neutral sandbox interface used by tools/agent.
- `constants.ts`: stable names shared across prompts, tools, persistence, and rendering.
@@ -159,7 +159,7 @@ statuses remain separate project concerns.
## Sandbox Runtime
-`server/sandbox/service.ts` gives the agent a conversation-scoped sandbox interface with `read`, `write`, and `edit` plus a separate turn-end callback. It reuses an existing provider session when the stored provider/session/TTL still match, otherwise it boots a fresh session and persists the new state on the conversation.
+`server/sandbox/service.ts` gives the agent a conversation-scoped sandbox interface with `read`, `write`, `edit`, and `bash`. Sessions are created lazily on the first sandbox tool call. The service reuses a live or suspended provider session identified by `providerSessionId`; if that session is gone or terminal, it boots a fresh session and persists the replacement id.
Both sandbox providers target the same runtime contract from `packages/in-app-agent-sandbox-runtime`.
@@ -172,7 +172,9 @@ Provider contract:
- `ensureSession({ conversationId, sessionId? })`
- `syncReadonlyFiles({ sessionId, files })`
- `read`, `write`, `edit`, `bash`
+- optional `probeSession({ sessionId })`, returning why a stored session is unusable
- optional `suspendSession({ sessionId })`
+- optional `terminateSession({ sessionId })`
Runtime HTTP surface:
@@ -185,11 +187,13 @@ Runtime HTTP surface:
Sandbox state is stored on the conversation row as `providerSessionId`. The configured sandbox provider is assumed to remain stable for the lifetime of the database.
-Session reuse only relies on an existing live or suspended runtime instance identified by `providerSessionId`.
+Live or suspended MicroVMs keep workspace files and memory. A terminated session cannot be revived, so continuation starts a clean VM: conversation history and the reconstructed `tool_calls/` survive, but workspace files, installed packages, and process state do not.
-`server/router.ts` clears sandbox state before soft-deleting a conversation.
+`createInAppAgentSandbox` calls the provider's `probeSession` up front and returns `workspaceWasReset` when the stored session is gone. The worker passes that on as `sandboxWorkspaceWasReset`, which adds a run-scoped system message telling the model its earlier files are gone and that `tool_calls/` was restored. It is not a transcript message, so the user never sees it.
-`dangerous-docker` is development-only. Worker data-retention cleanup only tears down `lambda-microvm` sandboxes; local Docker sandbox cleanup stays in the web process where that provider is used.
+Nothing in the application terminates a MicroVM; the AWS idle policy reclaims them, suspending after 60s idle and terminating four hours after either suspension or creation. Deleting a conversation clears `providerSessionId` without terminating, so that workspace outlives the delete.
+
+`dangerous-docker` is development-only. Local Docker sandbox cleanup stays in the web process where that provider is used.
## MCP Tool Authorization
diff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index 272060c42d..250e9f64e3 100644
--- a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -85,7 +85,6 @@ export function ControlledInAppAgentWindow(
selectConversation,
selectedConversationId,
selectedConversationTitle,
- selectedConversationIsWriteLocked,
submit,
submitFeedback,
} = useInAppAiAgent();
@@ -107,10 +106,7 @@ export function ControlledInAppAgentWindow(
shouldFlush: error !== null || isCancellingRun || shouldFlushCancelledRun,
});
const windowExecutionUi: InAppAgentWindowExecutionUi = {
- notice:
- selectedConversationIsWriteLocked || error?.type === "write_lock"
- ? null
- : getBackgroundRunNotice(execution.run),
+ notice: getBackgroundRunNotice(execution.run),
stop:
execution.run && isCancellableBackgroundRun(execution.run.status)
? {
@@ -122,14 +118,10 @@ export function ControlledInAppAgentWindow(
}
: null,
};
- // Only a read-only conversation disables the composer outright. An assistant
- // turn -- including one paused on an approval -- blocks submission but leaves
- // the draft editable. A server write-lock rejection is treated the same as
- // the cached flag, so a stale conversation query cannot leave the composer open.
- const isConversationInteractionDisabled =
- selectedConversationIsWriteLocked ||
- isSelectedConversationHydrating ||
- error?.type === "write_lock";
+ // An assistant turn -- including one paused on an approval -- blocks
+ // submission but leaves the draft editable. Hydration is the only case that
+ // disables the composer outright so a stale snapshot cannot be submitted.
+ const isConversationInteractionDisabled = isSelectedConversationHydrating;
const isAssistantTurnInProgress =
isRunning ||
isAnimating ||
@@ -156,9 +148,6 @@ export function ControlledInAppAgentWindow(
execution.run?.status === InAppAgentRunStatus.AWAITING_APPROVAL &&
(pendingToolApprovals.length > 0 ||
displayedPendingToolApprovals.length > 0);
- const displayError = selectedConversationIsWriteLocked
- ? ({ type: "write_lock" } as const)
- : error;
const screenContextDescription = useMemo(
() => getInAppAgentScreenContextDescription(router.asPath),
[router.asPath],
@@ -197,7 +186,7 @@ export function ControlledInAppAgentWindow(
return (
<InAppAgentWindow
- error={displayError}
+ error={error}
isAssistantTurnInProgress={isAssistantTurnInProgress}
isRunUnsettled={isRunUnsettled}
isAwaitingApproval={isAwaitingApproval}
@@ -205,9 +194,6 @@ export function ControlledInAppAgentWindow(
isExpanded={props.isExpanded}
isConversationInteractionDisabled={isConversationInteractionDisabled}
isSelectedConversationHydrating={isSelectedConversationHydrating}
- disablePendingToolApprovalActions={
- selectedConversationIsWriteLocked || error?.type === "write_lock"
- }
messages={drawerMessages}
quickActionContext={quickActionContext}
focusedQuickActions={focusedQuickActions}
diff --git a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
index b8910a2272..c1713a15e3 100644
--- a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
@@ -53,7 +53,7 @@ const providerMocks = vi.hoisted(() => {
data: undefined as
| undefined
| {
- conversation: { id: string; isWriteLocked: boolean };
+ conversation: { id: string };
messages: AgUiMessage[];
eventCursor: number;
latestRun: {
@@ -331,7 +331,6 @@ describe("in-app agent execution", () => {
const approvedSnapshot = {
conversation: {
id: "conversation-1",
- isWriteLocked: false,
},
messages: [
{
@@ -447,7 +446,6 @@ describe("in-app agent execution", () => {
const completedSnapshot = {
conversation: {
id: "conversation-1",
- isWriteLocked: false,
},
messages: [
{
@@ -553,7 +551,6 @@ describe("in-app agent execution", () => {
providerMocks.conversationQuery.data = {
conversation: {
id: "conversation-1",
- isWriteLocked: false,
},
messages: [
{
@@ -606,7 +603,6 @@ describe("in-app agent execution", () => {
providerMocks.conversationQuery.data = {
conversation: {
id: "conversation-1",
- isWriteLocked: false,
},
messages: [
{
@@ -660,7 +656,7 @@ describe("in-app agent execution", () => {
it("does not observe a cached active run while the assistant is closed", async () => {
const runningSnapshot = {
- conversation: { id: "conversation-1", isWriteLocked: false },
+ conversation: { id: "conversation-1" },
messages: [],
eventCursor: 5,
latestRun: {
@@ -706,7 +702,7 @@ describe("in-app agent execution", () => {
const initialText = "I found the affected traces.";
const finalText = "The remaining analysis was cancelled before completion.";
const runningSnapshot = {
- conversation: { id: "conversation-1", isWriteLocked: false },
+ conversation: { id: "conversation-1" },
messages: [
{ id: "persisted-user", role: "user", content: "Investigate this" },
{
@@ -876,14 +872,14 @@ describe("in-app agent execution", () => {
const finalText = "The investigation was cancelled before it completed.";
providerMocks.conversationQuery.data = {
- conversation: { id: "conversation-1", isWriteLocked: false },
+ conversation: { id: "conversation-1" },
messages: [],
eventCursor: -1,
latestRun: null,
pendingToolApprovals: [],
};
const cancellingSnapshot = {
- conversation: { id: "conversation-1", isWriteLocked: false },
+ conversation: { id: "conversation-1" },
messages: [
{ id: "persisted-user", role: "user", content: "Investigate this" },
] satisfies AgUiMessage[],
@@ -1089,7 +1085,7 @@ describe("in-app agent concurrent conversations", () => {
it("starts a new conversation while another one is still running", async () => {
providerMocks.conversationQuery.data = {
- conversation: { id: "conversation-1", isWriteLocked: false },
+ conversation: { id: "conversation-1" },
messages: [],
eventCursor: 3,
latestRun: {
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
index 11d5670d01..f068eab1fd 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
@@ -7,7 +7,6 @@ import {
} from "@testing-library/react";
import { ScanSearch } from "lucide-react";
import { InAppAgentRunStatus } from "@langfuse/shared";
-import { IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE } from "@langfuse/shared/in-app-agent";
import { TooltipProvider } from "@/src/components/ui/tooltip";
import {
InAppAgentWindow,
@@ -47,7 +46,6 @@ const controlledAgent = vi.hoisted(() => ({
rejectToolCall: vi.fn(),
selectedConversationId: undefined,
selectedConversationTitle: null,
- selectedConversationIsWriteLocked: false,
selectConversation: vi.fn(),
submit: vi.fn(),
submitFeedback: vi.fn(),
@@ -300,7 +298,6 @@ describe("ControlledInAppAgentWindow composer", () => {
controlledAgent.value.isSelectedConversationHydrating = false;
controlledAgent.value.isSubmitting = false;
controlledAgent.value.pendingToolApprovals = [];
- controlledAgent.value.selectedConversationIsWriteLocked = false;
controlledAgent.value.selectConversation = vi.fn();
controlledAgent.value.execution = {
run: null,
@@ -370,63 +367,6 @@ describe("ControlledInAppAgentWindow composer", () => {
screen.getByRole("button", { name: /^Conversation history/ }),
).toBeEnabled();
});
-
- it("hides a failed-run notice when the conversation is write-locked", () => {
- controlledAgent.value.isRunning = false;
- controlledAgent.value.selectedConversationIsWriteLocked = true;
- controlledAgent.value.execution = {
- run: {
- id: "run-1",
- status: InAppAgentRunStatus.FAILED,
- errorCode: null,
- cancelRequested: false,
- },
- isCancelling: false,
- cancel: vi.fn(),
- };
-
- render(
- <TooltipProvider>
- <ControlledInAppAgentWindow
- isExpanded={false}
- onClose={vi.fn()}
- onDeleteConversation={vi.fn()}
- onExpandedChange={vi.fn()}
- />
- </TooltipProvider>,
- );
-
- expect(
- screen.getByText(IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE),
- ).toBeInTheDocument();
- expect(
- screen.queryByText("The run failed. Try again."),
- ).not.toBeInTheDocument();
- });
-
- it("locks the composer when a write-lock rejection arrives before the cached flag", () => {
- controlledAgent.value.isRunning = false;
- controlledAgent.value.selectedConversationIsWriteLocked = false;
- controlledAgent.value.error = { type: "write_lock" };
-
- render(
- <TooltipProvider>
- <ControlledInAppAgentWindow
- isExpanded={false}
- onClose={vi.fn()}
- onDeleteConversation={vi.fn()}
- onExpandedChange={vi.fn()}
- />
- </TooltipProvider>,
- );
-
- expect(
- screen.getByText(IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("textbox", { name: "Message the assistant" }),
- ).toBeDisabled();
- });
});
describe("ControlledInAppAgentWindow stop", () => {
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
index 870c0a8aba..22476efa77 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
@@ -3,7 +3,6 @@ import { type ReactNode, useEffect, useRef, useState } from "react";
import { expect, fn, screen, userEvent, waitFor, within } from "storybook/test";
import {
IN_APP_AGENT_GENERIC_ERROR_MESSAGE,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
type AgUiMessage,
} from "@langfuse/shared/in-app-agent";
import {
@@ -1434,42 +1433,6 @@ export const Error = meta.story({
},
});
-export const WriteLocked = meta.story({
- args: {
- error: { type: "write_lock" },
- isConversationInteractionDisabled: true,
- selectedConversationId: "conversation-1",
- messages: [
- {
- id: "user-1",
- role: "user",
- content: {
- type: "text",
- text: "Help me inspect this trace.",
- },
- },
- ],
- },
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
- const alert = canvas.getByRole("alert");
-
- await expect(alert).toHaveTextContent(
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
- );
- await expect(
- canvas.getByRole("textbox", { name: "Message the assistant" }),
- ).toBeDisabled();
- await expect(
- canvas.getByRole("button", { name: /^Conversation history/ }),
- ).toBeEnabled();
- await expect(within(alert).queryByRole("button")).not.toBeInTheDocument();
- await expect(
- canvas.getByRole("button", { name: "Start new conversation" }),
- ).toBeEnabled();
- },
-});
-
/**
* Every activity state in the row it belongs to, sharing one fixed-width slot
* so the column stays straight despite the dots being narrower than the icons.
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
index 8ecaaa3ea3..4ce8118b70 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -22,7 +22,6 @@ import {
Plus,
SendHorizontal,
Square,
- TriangleAlert,
Trash2,
X,
} from "lucide-react";
@@ -50,7 +49,6 @@ import {
} from "./InAppAgentMessage";
import {
IN_APP_AGENT_GENERIC_ERROR_MESSAGE,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
type InAppAgentMessageFeedbackValue,
type InAppAgentMessageSource,
} from "@langfuse/shared/in-app-agent";
@@ -826,7 +824,6 @@ export type InAppAgentWindowProps = {
conversations: InAppAgentWindowConversation[];
/** Per-conversation attention state, for the recent-conversation indicators. */
activityByConversationId: InAppAgentActivityByConversationId;
- disablePendingToolApprovalActions?: boolean;
error: InAppAgentError | null;
executionUi: InAppAgentWindowExecutionUi;
hasMoreConversations: boolean;
@@ -917,37 +914,20 @@ function InAppAgentRateLimitError({
);
}
-function InAppAgentIssueNotice({
- isExpanded,
- variant,
-}: {
- isExpanded: boolean;
- variant: "error" | "write_lock";
-}) {
- const isWriteLock = variant === "write_lock";
-
+function InAppAgentIssueNotice({ isExpanded }: { isExpanded: boolean }) {
return (
<div className="shrink-0 px-2 pb-2">
<div className={cn(isExpanded && "mx-auto max-w-3xl")}>
<p
role="alert"
className={cn(
- "flex w-full items-center gap-2 rounded-lg border px-2 py-1",
- isWriteLock
- ? "border-border bg-muted/60 text-foreground"
- : "border-destructive/40 bg-destructive/10 text-destructive",
+ "border-destructive/40 bg-destructive/10 text-destructive flex w-full items-center gap-2 rounded-lg border px-2 py-1",
isExpanded ? "text-sm" : "text-xs",
)}
>
- {isWriteLock ? (
- <TriangleAlert aria-hidden="true" className="size-3 shrink-0" />
- ) : (
- <Info aria-hidden="true" className="size-3 shrink-0" />
- )}
+ <Info aria-hidden="true" className="size-3 shrink-0" />
<span className="min-w-0 flex-1">
- {isWriteLock
- ? IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE
- : IN_APP_AGENT_GENERIC_ERROR_MESSAGE}
+ {IN_APP_AGENT_GENERIC_ERROR_MESSAGE}
</span>
</p>
</div>
@@ -959,7 +939,6 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
const {
activityByConversationId,
conversations,
- disablePendingToolApprovalActions = false,
error,
executionUi,
hasMoreConversations,
@@ -1492,9 +1471,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
key={`${tool.approval?.id ?? tool.name}-${index}`}
tool={tool}
isCompact={!isExpanded}
- isDisabled={
- isRateLimited || disablePendingToolApprovalActions
- }
+ isDisabled={isRateLimited}
onApproveToolCall={onApproveToolCall}
onAlwaysAllowToolCall={onAlwaysAllowToolCall}
onRejectToolCall={onRejectToolCall}
@@ -1521,11 +1498,8 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
</div>
</div>
) : null}
- {(error?.type === "generic" || error?.type === "write_lock") && (
- <InAppAgentIssueNotice
- isExpanded={isExpanded}
- variant={error.type === "write_lock" ? "write_lock" : "error"}
- />
+ {error?.type === "generic" && (
+ <InAppAgentIssueNotice isExpanded={isExpanded} />
)}
{backgroundHint.isVisible && props.onClose ? (
<InAppAgentBackgroundHint
diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
index 8e593709d4..c7250e9d94 100644
--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -143,7 +143,6 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
attentionCount: 0,
selectedConversationId: undefined,
selectedConversationTitle: null,
- selectedConversationIsWriteLocked: false,
loadMoreConversations: () => undefined,
invalidateConversations: () => undefined,
selectConversation: () => undefined,
@@ -171,7 +170,6 @@ export type InAppAiAgentConversation = {
id: string;
title: string | null;
updatedAt: Date;
- isWriteLocked: boolean;
};
type InAppAiAgentExecution = {
@@ -206,7 +204,6 @@ type InAppAiAgentContextType = {
selectedConversationId: string | undefined;
/** Server-given name of the selected conversation, null until it has one. */
selectedConversationTitle: string | null;
- selectedConversationIsWriteLocked: boolean;
loadMoreConversations: () => void;
invalidateConversations: () => void;
selectConversation: (conversationId: string | null) => void;
@@ -381,8 +378,6 @@ function InAppAiAgentProviderInner({
);
const hasMoreConversations = conversationListQuery.hasNextPage === true;
const isLoadingMoreConversations = conversationListQuery.isFetchingNextPage;
- const selectedConversationIsWriteLocked =
- conversationQuery.data?.conversation.isWriteLocked ?? false;
const bootstrapBackgroundView = useMemo<BackgroundExecutionView>(() => {
if (
@@ -1075,11 +1070,6 @@ function InAppAiAgentProviderInner({
return false;
}
- if (!startsNewConversation && selectedConversationIsWriteLocked) {
- setError({ type: "write_lock" });
- return false;
- }
-
submitInFlightRef.current = conversationId;
setSubmittingConversationId(conversationId);
setError(null);
@@ -1170,7 +1160,6 @@ function InAppAiAgentProviderInner({
isRunning,
releaseSubmitLock,
selectedConversationId,
- selectedConversationIsWriteLocked,
setSelectedConversationId,
unpersistedConversationIds,
],
@@ -1397,11 +1386,6 @@ function InAppAiAgentProviderInner({
approved: boolean,
approvalScope: "once" | "conversation" = "once",
) => {
- if (selectedConversationIsWriteLocked) {
- setError({ type: "write_lock" });
- return;
- }
-
const approval = effectivePendingToolApprovals.find(
(approval) => approval.id === approvalId,
);
@@ -1436,7 +1420,6 @@ function InAppAiAgentProviderInner({
error,
isRunning,
selectedConversationId,
- selectedConversationIsWriteLocked,
],
);
@@ -1514,7 +1497,6 @@ function InAppAiAgentProviderInner({
attentionCount,
selectedConversationId: selectedConversationId ?? undefined,
selectedConversationTitle,
- selectedConversationIsWriteLocked,
loadMoreConversations,
invalidateConversations,
selectConversation,
@@ -1537,7 +1519,6 @@ function InAppAiAgentProviderInner({
isLoadingMoreConversations,
isRunning,
isSelectedConversationHydrating,
- selectedConversationIsWriteLocked,
selectedConversationTitle,
isSubmitting,
isSelectedConversationNotFound,
diff --git a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/features/in-app-agent/components/utils/utils.clienttest.ts
index f357057f23..a012ca0d1e 100644
--- a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts
+++ b/web/src/features/in-app-agent/components/utils/utils.clienttest.ts
@@ -1,7 +1,6 @@
-import type { AgUiMessage } from "@langfuse/shared/in-app-agent";
import {
IN_APP_AGENT_REDIRECT_TOOL_NAME,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ type AgUiMessage,
} from "@langfuse/shared/in-app-agent";
import {
IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES,
@@ -245,15 +244,6 @@ describe("getInAppAgentError", () => {
});
});
- it("maps a write-lock rejection to the write-lock notice", () => {
- expect(
- getInAppAgentError(
- { message: IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE },
- now,
- ),
- ).toEqual({ type: "write_lock" });
- });
-
it("does not classify malformed embedded JSON as a rate limit", () => {
const message = 'Failed to initialize Langfuse MCP: {"code":"rate_limited"';
diff --git a/web/src/features/in-app-agent/components/utils/utils.ts b/web/src/features/in-app-agent/components/utils/utils.ts
index 2c4d7f2f0e..c85625d699 100644
--- a/web/src/features/in-app-agent/components/utils/utils.ts
+++ b/web/src/features/in-app-agent/components/utils/utils.ts
@@ -6,7 +6,6 @@ import { deduplicateBy } from "@/src/utils/arrays";
import { safeJsonParse, stableJsonStringify } from "@langfuse/shared";
import {
IN_APP_AGENT_REDIRECT_TOOL_NAME,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
} from "@langfuse/shared/in-app-agent";
import {
@@ -20,7 +19,6 @@ import {
export type InAppAgentError =
| { type: "generic"; message: string }
- | { type: "write_lock" }
| { type: "rate_limit"; retryAt: number };
const InAppAiAgentMessageSchema = AgUiMessageSchema.and(
@@ -350,10 +348,6 @@ export function getInAppAgentError(
};
}
- if (message.includes(IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE)) {
- return { type: "write_lock" };
- }
-
return { type: "generic", message };
}
diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.ts
index 50c5773c34..2d1d3d00b6 100644
--- a/web/src/features/in-app-agent/server/backgroundRunService.ts
+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts
@@ -20,7 +20,6 @@ import { deleteApiKeyFromDb } from "@langfuse/shared/src/server/auth/apiKeys";
import {
createInAppAgentMessageId,
createInAppAgentRunId,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
parseInAppAgentApprovalDecisionEvent,
type AgUiRunAgentInput,
} from "@langfuse/shared/in-app-agent";
@@ -30,7 +29,6 @@ import {
ensureOwnedConversation,
getConversationEvents,
getOwnedConversationOrThrow,
- isInAppAgentConversationWriteLocked,
maybeInferAndPersistConversationTitle,
serializeConversation,
type PersistedConversationEvent,
@@ -112,12 +110,7 @@ export async function getBackgroundConversationSnapshot(params: {
const latestRun = runs.at(-1) ?? null;
return {
- conversation: serializeConversation(conversation, {
- isWriteLocked: isInAppAgentConversationWriteLocked({
- conversation,
- events,
- }),
- }),
+ conversation: serializeConversation(conversation),
messages,
displayState: serializeInAppAgentDisplayState(displayState),
eventCursor: events.reduce(
@@ -228,21 +221,6 @@ export async function startBackgroundRun(params: {
userId: params.userId,
});
- const events = await getConversationEvents({
- prisma: params.prisma,
- projectId: params.projectId,
- conversationId: params.conversationId,
- });
-
- if (isInAppAgentConversationWriteLocked({ conversation, events })) {
- throw new BaseError(
- "PreconditionFailedError",
- 412,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
- true,
- );
- }
-
if (!params.model) {
throw new BaseError(
"PreconditionFailedError",
@@ -386,7 +364,7 @@ export async function decideBackgroundApproval(params: {
userId: string;
model: string | undefined;
}) {
- const conversation = await getOwnedConversationOrThrow({
+ await getOwnedConversationOrThrow({
prisma: params.prisma,
projectId: params.projectId,
conversationId: params.conversationId,
@@ -399,15 +377,6 @@ export async function decideBackgroundApproval(params: {
conversationId: params.conversationId,
});
- if (isInAppAgentConversationWriteLocked({ conversation, events })) {
- throw new BaseError(
- "PreconditionFailedError",
- 412,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
- true,
- );
- }
-
let approvalRequest: ReturnType<typeof parseInAppAgentInterruptEvent>;
for (const persisted of events) {
if (persisted.runId !== params.runId) {
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index e0a8311a1d..3819d71a4a 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -18,7 +18,6 @@ import {
} from "@langfuse/shared/src/server/auth/apiKeys";
import {
getInAppAgentInstrumentationTraceId,
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
type AgUiEvent,
type AgUiRunAgentInput,
type InAppAgentToolApprovalRequest,
@@ -37,7 +36,6 @@ import {
getInAppAgentPromptClient,
heartbeatClaimedRun,
IN_APP_AGENT_HEARTBEAT_INTERVAL_MS,
- isInAppAgentConversationWriteLocked,
createInAppAgentToolPolicy,
getInAppAgentMcpAllowedToolNames,
getInAppAgentRegistryToolName,
@@ -218,17 +216,6 @@ export async function executeInAppAgentRun(params: {
conversationId: conversation.id,
});
- if (
- isInAppAgentConversationWriteLocked({
- conversation,
- events: conversationEvents,
- })
- ) {
- throw new InAppAgentRunInitError(
- IN_APP_AGENT_SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
- );
- }
-
// ---- Build the agent input from the run request + persisted history. ----
const parsedRequest = InAppAgentRunRequestSchema.safeParse(run.request);
@@ -546,6 +533,8 @@ export async function executeInAppAgentRun(params: {
},
}),
sandbox: sandboxState?.sandbox,
+ // History still shows this agent's own earlier writes, so it needs telling.
+ sandboxWorkspaceWasReset: sandboxState?.workspaceWasReset,
},
});