Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): resume from the new user message after inactivity (#96752)

Georgiy Tarasov41c5dccd1cbc
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index d726d990b3c5..7128d5ea5511 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -477,6 +477,22 @@ The flow, driven from the PostHog Desktop Environments → Cloud tab:
falling back to the standard base if the image can't be loaded.
Repo-setup snapshots are skipped for custom-image runs; resume snapshots still apply.
+## Continuing after sandbox inactivity
+
+When a sandbox expires, a new user message starts the next turn with the preserved
+conversation and workspace. A prewarmed successor waits for the queued message even
+after activation clears `await_user_message`. The agent restores context and decides
+whether to wait before accepting commands. Message IDs deduplicate retried deliveries.
+
+Explicit recovery of an interrupted run can still continue automatically. Idle
+same-run restores stay idle until a message arrives. Internal recovery instructions
+use hidden content blocks; adapters and transcript rendering omit those blocks from
+user message echoes. Existing unmarked transcript entries are unchanged.
+
+The agent advertises `prewarmedResumeMessageDriven` alongside `prewarmedResumeIdle`.
+Publish the updated agent and rebuild sandbox images before changing backend snapshot
+compatibility checks to require the new capability.
+
## Local development
To set up sandboxed agents for local development:
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
index b94df955d36d..f6c282f2e9a8 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
@@ -331,6 +331,16 @@ describe("ClaudeAcpAgent /clear", () => {
expect(
findExtNotification(client, POSTHOG_NOTIFICATIONS.CONVERSATION_CLEARED),
).toBeDefined();
+ expect(
+ client.sessionUpdate.mock.calls
+ .map(([call]) => call.update)
+ .filter((update) => update.sessionUpdate === "user_message_chunk"),
+ ).toEqual([
+ {
+ sessionUpdate: "user_message_chunk",
+ content: { type: "text", text: "/clear" },
+ },
+ ]);
});
// A mode change updates the running query; queryOptions keeps the mode the session
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 04797370e17d..fe33bfac74ef 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -3642,7 +3642,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
private async broadcastUserMessage(params: PromptRequest): Promise<void> {
- for (const chunk of params.prompt) {
+ for (const chunk of visiblePromptBlocks(params.prompt)) {
const notification = {
sessionId: params.sessionId,
update: {
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 32745030ac67..cc4eb97e93e8 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -44,7 +44,9 @@ import type { StoredEntry, TaskRun } from "../types";
import {
AgentServer,
isTurnCompleteNotification,
+ MESSAGE_DRIVEN_RESUME_CAPABILITY,
PREWARMED_RESUME_IDLE_CAPABILITY,
+ type PreparedInitialTaskMessage,
SSE_KEEPALIVE_INTERVAL_MS,
UPSTREAM_PROVIDER_FAILURE_MESSAGE,
} from "./agent-server";
@@ -224,6 +226,17 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
query: mockedClaudeSdk.query,
}));
+interface StartupTestServer {
+ prepareInitialTaskMessage(
+ payload: JwtPayload,
+ run?: TaskRun | null,
+ ): Promise<PreparedInitialTaskMessage>;
+ sendInitialTaskMessage(
+ payload: JwtPayload,
+ startup: PreparedInitialTaskMessage,
+ ): Promise<void>;
+}
+
interface TestableServer {
getInitialPromptOverride(run: TaskRun): string | null;
getClearedPendingUserState(run: TaskRun | null): string[] | null;
@@ -392,6 +405,16 @@ o7kFcjIuxu/b/Dr4o4SzCYyQYd03W1SH4vkZFY/x/eFFHylkXyQNHi8pAFb04hX9
JwIDAQAB
-----END PUBLIC KEY-----`;
+async function startInitialTaskMessage(
+ server: AgentServer,
+ payload: JwtPayload,
+ run: TaskRun | null,
+): Promise<void> {
+ const startup = server as unknown as StartupTestServer;
+ const prepared = await startup.prepareInitialTaskMessage(payload, run);
+ await startup.sendInitialTaskMessage(payload, prepared);
+}
+
describe("AgentServer HTTP Mode", () => {
let repo: TestRepo;
let server: AgentServer | undefined;
@@ -571,7 +594,10 @@ describe("AgentServer HTTP Mode", () => {
totalMs: expect.any(Number),
phasesMs: expect.any(Object),
}),
- capabilities: [PREWARMED_RESUME_IDLE_CAPABILITY],
+ capabilities: [
+ PREWARMED_RESUME_IDLE_CAPABILITY,
+ MESSAGE_DRIVEN_RESUME_CAPABILITY,
+ ],
});
}, 30000);
@@ -4217,6 +4243,85 @@ describe("AgentServer HTTP Mode", () => {
await firstTurn;
}, 20000);
+ it("steers the turn after startup delivered the prewarmed message", async () => {
+ const s = createServer();
+ await s.start();
+ let finishFollowup!: (result: { stopReason: "end_turn" }) => void;
+ const prompt = vi.fn((params: { _meta?: Record<string, unknown> }) => {
+ if (params._meta?.steer === true) {
+ return Promise.resolve({
+ stopReason: "steered",
+ _meta: { steer: true },
+ });
+ }
+ // First call is the startup message; the follow-up turn stays open for the steer.
+ if (prompt.mock.calls.length === 1) {
+ return Promise.resolve({ stopReason: "end_turn" });
+ }
+ return new Promise<{ stopReason: "end_turn" }>((resolve) => {
+ finishFollowup = resolve;
+ });
+ });
+ const serverInternals = s as unknown as {
+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
+ session: { clientConnection: { prompt: typeof prompt } };
+ };
+ serverInternals.session.clientConnection.prompt = prompt;
+ const taskRun = createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: {
+ prewarmed: true,
+ pending_user_message: "start on this",
+ pending_user_message_id: "startup-message",
+ },
+ });
+ vi.spyOn(serverInternals.posthogAPI, "getTaskRun").mockResolvedValue(
+ taskRun,
+ );
+
+ await startInitialTaskMessage(
+ s,
+ {
+ task_id: "test-task-id",
+ run_id: "test-run-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive",
+ },
+ taskRun,
+ );
+ expect(prompt).toHaveBeenCalledOnce();
+
+ const token = createToken();
+ const send = (id: string, steer = false) =>
+ fetch(`http://localhost:${port}/command`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id,
+ method: "user_message",
+ params: { content: id, messageId: id, ...(steer && { steer }) },
+ }),
+ });
+
+ const followupTurn = send("follow-up-turn");
+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledTimes(2));
+
+ const steerResponse = await send("steer-during-follow-up", true);
+ await expect(steerResponse.json()).resolves.toMatchObject({
+ result: { stopReason: "steered", steered: true },
+ });
+
+ finishFollowup({ stopReason: "end_turn" });
+ await followupTurn;
+ }, 20000);
+
it("does not queue steering behind an active non-steering turn", async () => {
const s = createServer();
await s.start();
@@ -4884,9 +4989,47 @@ describe("AgentServer HTTP Mode", () => {
});
describe("resume prompt display", () => {
- it.each(["native", "summary"] as const)(
- "keeps a prewarmed %s resume idle until the forwarded user message arrives",
- async (resumeKind) => {
+ it("does not accept commands until startup context is prepared", async () => {
+ const s = createServer();
+ const internals = s as unknown as {
+ posthogAPI: PostHogAPIClient;
+ };
+ const run = createTaskRun({
+ state: { prewarmed: true, warm_activated: true },
+ });
+ const refresh = Promise.withResolvers<TaskRun>();
+ const refreshing = Promise.withResolvers<void>();
+ vi.spyOn(internals.posthogAPI, "getTaskRun")
+ .mockResolvedValueOnce(run)
+ .mockImplementationOnce(() => {
+ refreshing.resolve();
+ return refresh.promise;
+ })
+ .mockResolvedValue(run);
+
+ const starting = s.start();
+ try {
+ await refreshing.promise;
+ const health = await fetch(`http://localhost:${port}/health`);
+ expect(await health.json()).toMatchObject({ hasSession: false });
+ } finally {
+ refresh.resolve(run);
+ await starting;
+ }
+ const health = await fetch(`http://localhost:${port}/health`);
+ expect(await health.json()).toMatchObject({ hasSession: true });
+ });
+
+ it.each([
+ { resumeKind: "native", activated: false, beforeStartup: false },
+ { resumeKind: "native", activated: true, beforeStartup: false },
+ { resumeKind: "summary", activated: false, beforeStartup: false },
+ { resumeKind: "summary", activated: true, beforeStartup: false },
+ { resumeKind: "native", activated: true, beforeStartup: true },
+ { resumeKind: "summary", activated: true, beforeStartup: true },
+ ] as const)(
+ "keeps a prewarmed $resumeKind resume idle until delivery (activated=$activated, beforeStartup=$beforeStartup)",
+ async ({ resumeKind, activated, beforeStartup }) => {
const s = createServer();
await s.start();
@@ -4904,7 +5047,9 @@ describe("AgentServer HTTP Mode", () => {
task: "test-task-id",
state: {
prewarmed: true,
- await_user_message: true,
+ ...(activated
+ ? { warm_activated: true }
+ : { await_user_message: true }),
resume_from_run_id: "previous-run",
},
});
@@ -4919,10 +5064,6 @@ describe("AgentServer HTTP Mode", () => {
enqueue: ReturnType<typeof vi.fn>;
stop: ReturnType<typeof vi.fn>;
};
- sendInitialTaskMessage(
- payload: JwtPayload,
- taskRun: TaskRun | null,
- ): Promise<void>;
};
internals.session.clientConnection.prompt = prompt;
internals.prewarmedRun = true;
@@ -4952,12 +5093,19 @@ describe("AgentServer HTTP Mode", () => {
: null;
vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);
- await internals.sendInitialTaskMessage(payload, taskRun);
+ const startup = s as unknown as StartupTestServer;
+ const prepared = await startup.prepareInitialTaskMessage(
+ payload,
+ taskRun,
+ );
+ if (!beforeStartup) {
+ await startup.sendInitialTaskMessage(payload, prepared);
+ }
expect(prompt).not.toHaveBeenCalled();
expect(internals.resumeState).not.toBeNull();
- const response = await fetch(`http://localhost:${port}/command`, {
+ const request = {
method: "POST",
headers: {
Authorization: `Bearer ${createToken()}`,
@@ -4967,11 +5115,32 @@ describe("AgentServer HTTP Mode", () => {
jsonrpc: "2.0",
id: `deferred-${resumeKind}`,
method: "user_message",
- params: { content: "continue with this change" },
+ params: {
+ content: [
+ { type: "text", text: "continue with this change" },
+ {
+ type: "resource_link",
+ uri: "file:///tmp/example.txt",
+ name: "example.txt",
+ },
+ ],
+ messageId: "forwarded-first-message",
+ },
}),
- });
+ };
+ const response = await fetch(
+ `http://localhost:${port}/command`,
+ request,
+ );
expect(response.status).toBe(200);
+ if (beforeStartup) {
+ await startup.sendInitialTaskMessage(payload, prepared);
+ }
+ const retry = await fetch(`http://localhost:${port}/command`, request);
+ expect(await retry.json()).toMatchObject({
+ result: { duplicate: true },
+ });
expect(prompt).toHaveBeenCalledOnce();
expect(
internals.eventStreamSender.enqueue.mock.calls.filter(
@@ -4994,13 +5163,18 @@ describe("AgentServer HTTP Mode", () => {
)
.map((block) => (block as { text: string }).text);
expect(visibleText).toEqual(["continue with this change"]);
+ expect(promptBlocks).toContainEqual({
+ type: "resource_link",
+ uri: "file:///tmp/example.txt",
+ name: "example.txt",
+ });
if (resumeKind === "summary") {
- expect(promptBlocks).toHaveLength(3);
+ expect(promptBlocks).toHaveLength(4);
expect((promptBlocks[0] as { text: string }).text).toContain(
"work completed so far",
);
} else {
- expect(promptBlocks).toHaveLength(1);
+ expect(promptBlocks).toHaveLength(2);
}
expect(internals.resumeState).toBeNull();
expect(internals.nativeResume).toBeNull();
@@ -5008,62 +5182,69 @@ describe("AgentServer HTTP Mode", () => {
30000,
);
- it("resumes instead of idling once the run is no longer awaiting its first message", async () => {
- // `prewarmed` outlives activation; `await_user_message` is what the backend clears. Idling on
- // provenance alone strands every reinitialization of an activated run, waiting for a first
- // message that was already delivered.
- const s = createServer();
- await s.start();
+ it.each(["native", "summary"])(
+ "recovers an explicitly restarted prewarmed run with %s context",
+ async (resumeKind) => {
+ const s = createServer();
+ await s.start();
- const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));
- const payload: JwtPayload = {
- run_id: "test-run-id",
- task_id: "test-task-id",
- team_id: 1,
- user_id: 1,
- distinct_id: "test-distinct-id",
- mode: "interactive",
- };
- const taskRun = createTaskRun({
- id: "test-run-id",
- task: "test-task-id",
- state: { prewarmed: true, resume_from_run_id: "previous-run" },
- });
- const internals = s as unknown as {
- posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
- session: { clientConnection: { prompt: typeof prompt } };
- resumeState: ResumeState | null;
- nativeResume: { sessionId: string; warm: boolean } | null;
- prewarmedRun: boolean;
- sendInitialTaskMessage(
- payload: JwtPayload,
- taskRun: TaskRun | null,
- ): Promise<void>;
- };
- internals.session.clientConnection.prompt = prompt;
- internals.nativeResume = null;
- internals.resumeState = {
- conversation: [
- {
- role: "user",
- content: [{ type: "text", text: "original request" }],
- },
- {
- role: "assistant",
- content: [{ type: "text", text: "work completed so far" }],
- },
- ],
- interrupted: false,
- logEntryCount: 2,
- sessionId: "prior-session",
- };
- vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);
+ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));
+ const payload: JwtPayload = {
+ run_id: "test-run-id",
+ task_id: "test-task-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive",
+ };
+ const taskRun = createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: { prewarmed: true, same_run_resume: true },
+ });
+ const internals = s as unknown as {
+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
+ session: { clientConnection: { prompt: typeof prompt } };
+ resumeState: ResumeState | null;
+ nativeResume: { sessionId: string; warm: boolean } | null;
+ prewarmedRun: boolean;
+ };
+ internals.session.clientConnection.prompt = prompt;
+ internals.nativeResume =
+ resumeKind === "native"
+ ? { sessionId: "prior-session", warm: true }
+ : null;
+ internals.resumeState = {
+ conversation: [
+ {
+ role: "user",
+ content: [{ type: "text", text: "original request" }],
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "work completed so far" }],
+ },
+ ],
+ interrupted: false,
+ logEntryCount: 2,
+ sessionId: "prior-session",
+ };
+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);
- await internals.sendInitialTaskMessage(payload, taskRun);
+ await startInitialTaskMessage(s, payload, taskRun);
- expect(internals.prewarmedRun).toBe(false);
- expect(prompt).toHaveBeenCalledOnce();
- }, 30000);
+ expect(internals.prewarmedRun).toBe(true);
+ expect(prompt).toHaveBeenCalledOnce();
+ expect(prompt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ prompt: [
+ expect.objectContaining({ _meta: { ui: { hidden: true } } }),
+ ],
+ }),
+ );
+ },
+ 30000,
+ );
it("loads the summary fallback before a prewarmed run idles", async () => {
// Initialization may fail to fetch the run `prepareNativeResume` needed. If the fallback load
@@ -5099,10 +5280,6 @@ describe("AgentServer HTTP Mode", () => {
resumeRunId: string,
currentRunId: string,
): Promise<void>;
- sendInitialTaskMessage(
- payload: JwtPayload,
- taskRun: TaskRun | null,
- ): Promise<void>;
};
internals.nativeResume = null;
internals.resumeState = null;
@@ -5123,7 +5300,7 @@ describe("AgentServer HTTP Mode", () => {
};
});
- await internals.sendInitialTaskMessage(payload, taskRun);
+ await startInitialTaskMessage(s, payload, taskRun);
expect(loadResumeState).toHaveBeenCalledWith(
"test-task-id",
@@ -5419,6 +5596,7 @@ describe("AgentServer HTTP Mode", () => {
const setupIdleResume = async (
state: Record<string, unknown>,
+ resumeKind: "native" | "summary" = "native",
): Promise<{
prompt: ReturnType<typeof vi.fn>;
turnCompleteEvents: () => unknown[];
@@ -5433,14 +5611,29 @@ describe("AgentServer HTTP Mode", () => {
posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
session: { clientConnection: { prompt: typeof prompt } };
nativeResume: { sessionId: string; warm: boolean } | null;
+ resumeState: ResumeState | null;
broadcastEvent: typeof broadcastEvent;
- sendInitialTaskMessage(
- payload: JwtPayload,
- taskRun: TaskRun | null,
- ): Promise<void>;
};
internals.session.clientConnection.prompt = prompt;
- internals.nativeResume = { sessionId: "prior-session", warm: true };
+ internals.nativeResume =
+ resumeKind === "native"
+ ? { sessionId: "prior-session", warm: true }
+ : null;
+ internals.resumeState = {
+ conversation: [
+ {
+ role: "user",
+ content: [{ type: "text", text: "Original request" }],
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "Preserved work" }],
+ },
+ ],
+ interrupted: false,
+ logEntryCount: 2,
+ sessionId: "prior-session",
+ };
internals.broadcastEvent = broadcastEvent;
vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(
createTaskRun({ id: "test-run-id", task: "test-task-id", state }),
@@ -5456,7 +5649,7 @@ describe("AgentServer HTTP Mode", () => {
?.method === POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
),
sendInitialTaskMessage: () =>
- internals.sendInitialTaskMessage(idlePayload, null),
+ startInitialTaskMessage(s, idlePayload, null),
};
};
@@ -5464,15 +5657,41 @@ describe("AgentServer HTTP Mode", () => {
delete process.env.POSTHOG_RESUME_IDLE;
});
- it("does not prompt the resumed session", async () => {
- const { prompt, turnCompleteEvents, sendInitialTaskMessage } =
- await setupIdleResume({});
+ it.each(["native", "summary"] as const)(
+ "defers the next turn with %s context on idle restore",
+ async (resumeKind) => {
+ const { prompt, turnCompleteEvents, sendInitialTaskMessage } =
+ await setupIdleResume({}, resumeKind);
- await sendInitialTaskMessage();
+ await sendInitialTaskMessage();
- expect(prompt).not.toHaveBeenCalled();
- expect(turnCompleteEvents()).toHaveLength(1);
- });
+ expect(prompt).not.toHaveBeenCalled();
+ expect(turnCompleteEvents()).toHaveLength(1);
+ const response = await fetch(`http://localhost:${port}/command`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${createToken()}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: "next-turn",
+ method: "user_message",
+ params: { content: "Next request" },
+ }),
+ });
+ expect(response.status).toBe(200);
+ expect(prompt).toHaveBeenCalledOnce();
+ const blocks = prompt.mock.calls[0]?.[0].prompt;
+ expect(blocks).toContainEqual({ type: "text", text: "Next request" });
+ if (resumeKind === "summary") {
+ expect(blocks[0]).toMatchObject({
+ text: expect.stringContaining("Preserved work"),
+ _meta: { ui: { hidden: true } },
+ });
+ }
+ },
+ );
it("still delivers a message that landed during the swap", async () => {
const { prompt, sendInitialTaskMessage } = await setupIdleResume({
@@ -5518,7 +5737,8 @@ describe("AgentServer HTTP Mode", () => {
}),
);
- await internals.sendResumeContinuation(
+ await startInitialTaskMessage(
+ s,
{
task_id: "test-task-id",
run_id: "test-run-id",
@@ -5840,6 +6060,113 @@ describe("AgentServer HTTP Mode", () => {
20000,
);
+ it("answers the pending user message on the fresh-session retry", async () => {
+ const s = createServer();
+ await s.start();
+
+ const prompts: ContentBlock[][] = [];
+ const prompt = vi.fn(async (params: { prompt: ContentBlock[] }) => {
+ prompts.push(params.prompt);
+ if (prompts.length === 1) {
+ throw new Error("Internal error: Prompt is too long");
+ }
+ return { stopReason: "end_turn" };
+ });
+ const newSession = vi.fn(async () => ({ sessionId: "fresh-session" }));
+ const broadcastEvent = vi.fn();
+
+ const internals = s as unknown as {
+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
+ session: {
+ clientConnection: {
+ prompt: typeof prompt;
+ newSession: typeof newSession;
+ };
+ };
+ resumeState: ResumeState | null;
+ nativeResume: { sessionId: string; warm: boolean } | null;
+ broadcastEvent: typeof broadcastEvent;
+ loadResumeState(
+ taskId: string,
+ resumeRunId: string,
+ runId: string,
+ ): Promise<void>;
+ sendResumeContinuation(
+ payload: JwtPayload,
+ taskRun: TaskRun | null,
+ ): Promise<void>;
+ };
+ internals.session.clientConnection.prompt = prompt;
+ internals.session.clientConnection.newSession = newSession;
+ internals.nativeResume = { sessionId: "prior-session", warm: true };
+ internals.broadcastEvent = broadcastEvent;
+ internals.loadResumeState = vi.fn(async () => {
+ internals.resumeState = {
+ conversation: [
+ {
+ role: "user",
+ content: [{ type: "text", text: "original task" }],
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "progress so far" }],
+ },
+ ],
+ interrupted: false,
+ logEntryCount: 2,
+ sessionId: "prior-session",
+ };
+ });
+
+ const taskRun = createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: {
+ resume_from_run_id: "previous-run",
+ pending_user_message: "answer this now",
+ pending_user_message_id: "pending-message-1",
+ },
+ });
+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);
+
+ await internals.sendResumeContinuation(
+ {
+ task_id: "test-task-id",
+ run_id: "test-run-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive",
+ },
+ taskRun,
+ );
+
+ expect(prompts).toHaveLength(2);
+ const retryBlocks = prompts[1];
+ expect(
+ retryBlocks
+ .map((block) => ("text" in block ? block.text : ""))
+ .join("\n"),
+ ).toContain("progress so far");
+ expect(
+ retryBlocks
+ .filter(
+ (block) =>
+ block.type === "text" &&
+ (block as { _meta?: { ui?: { hidden?: boolean } } })._meta?.ui
+ ?.hidden !== true,
+ )
+ .map((block) => (block as { text: string }).text),
+ ).toEqual(["answer this now"]);
+ expect(
+ broadcastEvent.mock.calls.filter(
+ ([event]) =>
+ (event as { notification?: { method?: string } }).notification
+ ?.method === POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ ),
+ ).toHaveLength(1);
+ }, 20000);
+
it("hydrates cold sessions from S3 logs instead of cached resume conversation", async () => {
const originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
process.env.CLAUDE_CONFIG_DIR = join(repo.path, ".claude-test");
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 5358e027f95c..0242f00308a1 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -277,6 +277,12 @@ interface BuiltPrompt {
export const PREWARMED_RESUME_IDLE_CAPABILITY = "prewarmedResumeIdle";
export const CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE =
"The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.";
+export const MESSAGE_DRIVEN_RESUME_CAPABILITY = "prewarmedResumeMessageDriven";
+
+export interface PreparedInitialTaskMessage {
+ taskRun: TaskRun;
+ action: "wait" | "idle" | "resume" | "initial";
+}
function hiddenTextBlock(text: string): ContentBlock {
return {
@@ -728,7 +734,10 @@ export class AgentServer {
bootMs: this.sessionReadyBootMs,
sessionInitMs: this.sessionInitMs,
boot,
- capabilities: [PREWARMED_RESUME_IDLE_CAPABILITY],
+ capabilities: [
+ PREWARMED_RESUME_IDLE_CAPABILITY,
+ MESSAGE_DRIVEN_RESUME_CAPABILITY,
+ ],
});
});
@@ -2299,6 +2308,13 @@ export class AgentServer {
this.evaluatedPrUrls.clear();
this.prAttributionChain = Promise.resolve();
+ // Assigning this.session admits /command requests. Restore context and choose the startup
+ // action first so a forwarded message cannot be overtaken by a second startup decision.
+ const initialTaskMessage = await this.prepareInitialTaskMessage(
+ payload,
+ preTaskRun,
+ );
+
this.shutdownController.signal.throwIfAborted();
this.initializingConnection = null;
this.session = {
@@ -2338,7 +2354,11 @@ export class AgentServer {
this.logger.debug(
`Agent version: ${this.config.version ?? packageJson.version}`,
);
- await logAgentshRuntimeInfo(this.logger);
+ // The version probe spawns a process, so it runs beside the startup turn. Its records reach
+ // the run log through the session logger installed above.
+ void logAgentshRuntimeInfo(this.logger).catch((error) =>
+ this.logger.debug("Failed to read agentsh runtime info", error),
+ );
this.logger.debug(`Initial permission mode: ${initialPermissionMode}`);
// Lifecycle handshake: clients gate "agent is ready to accept user
@@ -2387,7 +2407,7 @@ export class AgentServer {
);
await this.runStartupTurn(() =>
- this.sendInitialTaskMessage(payload, preTaskRun),
+ this.sendInitialTaskMessage(payload, initialTaskMessage),
);
}
@@ -2696,12 +2716,10 @@ export class AgentServer {
});
}
- private async sendInitialTaskMessage(
+ private async prepareInitialTaskMessage(
payload: JwtPayload,
prefetchedRun?: TaskRun | null,
- ): Promise<void> {
- if (!this.session) return;
-
+ ): Promise<PreparedInitialTaskMessage> {
let taskRun = prefetchedRun ?? null;
try {
const refresh = await withTimeout(
@@ -2717,8 +2735,17 @@ export class AgentServer {
});
}
- const taskRunState = taskRun?.state as Record<string, unknown> | undefined;
- const prewarmed = taskRunState?.prewarmed === true;
+ if (!taskRun) {
+ throw new Error(
+ "Could not load task run to determine its initial prompt",
+ );
+ }
+ const taskRunState = taskRun.state;
+ const prewarmed = taskRunState.prewarmed === true;
+ const sameRunResume =
+ taskRunState.same_run_resume === true ||
+ taskRunState.handoff_resumed === true ||
+ this.getResumeRunId(taskRun) === payload.run_id;
const hasPendingUserPrompt =
(typeof taskRunState?.pending_user_message === "string" &&
taskRunState.pending_user_message.trim().length > 0) ||
@@ -2740,29 +2767,54 @@ export class AgentServer {
}
}
- // `await_user_message` is the marker the backend clears on activation. `prewarmed` is permanent
- // provenance that outlives it, so idling on that alone would strand a run whose first message
- // was already delivered — every later reinitialization would wait for a message nobody sends.
- const awaitsFirstMessage = taskRunState?.await_user_message === true;
- if (prewarmed && awaitsFirstMessage && !hasPendingUserPrompt) {
- this.prewarmedRun = true;
- this.logger.debug(
- "Prewarmed run awaits its forwarded first message, skipping initial message",
- );
- return;
+ this.prewarmedRun = prewarmed;
+ // Activation clears await_user_message when Temporal accepts the signal, before the agent
+ // receives it. Only an explicit same-run restart transfers startup ownership back to the agent.
+ const awaitsForwardedMessage =
+ prewarmed && !sameRunResume && !hasPendingUserPrompt;
+ // The forwarded message owns the startup turn only while the run waits for it. When startup
+ // sends the pending prompt itself, the next message is a normal follow-up, so a steer during
+ // that turn must reach the agent instead of being declined.
+ this.prewarmedStartupTurnPending = awaitsForwardedMessage;
+ if (awaitsForwardedMessage) {
+ return { taskRun, action: "wait" };
}
- if (this.nativeResume) {
- if (await this.settleIdleResume(payload, taskRun)) return;
- await this.sendResumeContinuation(payload, taskRun);
- return;
+ if (!hasPendingUserPrompt && process.env.POSTHOG_RESUME_IDLE === "1") {
+ return { taskRun, action: "idle" };
}
+ return {
+ taskRun,
+ action:
+ this.nativeResume || this.resumeState?.conversation.length
+ ? "resume"
+ : "initial",
+ };
+ }
- if (this.resumeState && this.resumeState.conversation.length > 0) {
- await this.sendResumeMessage(payload, taskRun);
+ private async sendInitialTaskMessage(
+ payload: JwtPayload,
+ { taskRun, action }: PreparedInitialTaskMessage,
+ ): Promise<void> {
+ if (!this.session) return;
+ if (action === "wait") {
+ this.logger.debug("Prewarmed run awaits its forwarded first message");
+ return;
+ }
+ if (action === "idle") {
+ await this.settleIdleResume(payload);
+ return;
+ }
+ if (action === "resume") {
+ if (this.nativeResume) {
+ await this.sendResumeContinuation(payload, taskRun);
+ } else {
+ await this.sendResumeMessage(payload, taskRun);
+ }
return;
}
+ const prewarmed = taskRun.state.prewarmed === true;
let promptDispatched = false;
let releaseSelfDelivery: (() => void) | undefined;
try {
@@ -2867,72 +2919,71 @@ export class AgentServer {
private async sendResumeMessage(
payload: JwtPayload,
taskRun: TaskRun | null,
- ): Promise<void> {
- if (!this.session || !this.resumeState) return;
+ reservedMessageId?: string,
+ ): Promise<boolean> {
+ if (!this.session || !this.resumeState) return false;
const resumeState = this.resumeState;
- taskRun = await this.refreshTaskRunForResume(payload, taskRun);
+ return await this.runStartupTurn(() =>
+ this.runResumeTurn(
+ payload,
+ taskRun,
+ "Resume message",
+ async () => {
+ const conversationSummary = formatConversationForResume(
+ resumeState.conversation,
+ );
- await this.runStartupTurn(() =>
- this.runResumeTurn(payload, taskRun, "Resume message", async () => {
- const conversationSummary = formatConversationForResume(
- resumeState.conversation,
- );
+ const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
- const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
-
- let resumePromptBlocks: ContentBlock[];
- let resumePromptMeta: Record<string, unknown> | undefined;
- let resumePromptMessageId: string | undefined;
- if (pendingUserPrompt?.prompt.length) {
- resumePromptMeta = pendingUserPrompt.meta;
- resumePromptMessageId = pendingUserPrompt.messageId;
- resumePromptBlocks = [
- hiddenTextBlock(
- "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
- `Here is the conversation history from the previous session:\n\n` +
- `${conversationSummary}\n\n` +
- `The user has sent a new message:\n\n`,
- ),
- ...pendingUserPrompt.prompt,
- hiddenTextBlock(
- "\n\nRespond to the user's new message above. You have full context from the previous session.",
- ),
- ];
- } else {
- resumePromptBlocks = [
- hiddenTextBlock(
- "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
- `Here is the conversation history from the previous session:\n\n` +
- `${conversationSummary}\n\n` +
- `Continue from where you left off. The user is waiting for your response.`,
- ),
- ];
- }
+ let resumePromptBlocks: ContentBlock[];
+ let resumePromptMeta: Record<string, unknown> | undefined;
+ let resumePromptMessageId: string | undefined;
+ if (pendingUserPrompt?.prompt.length) {
+ resumePromptMeta = pendingUserPrompt.meta;
+ resumePromptMessageId = pendingUserPrompt.messageId;
+ resumePromptBlocks = [
+ hiddenTextBlock(
+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
+ `Here is the conversation history from the previous session:\n\n` +
+ `${conversationSummary}\n\n` +
+ `The user has sent a new message:\n\n`,
+ ),
+ ...pendingUserPrompt.prompt,
+ hiddenTextBlock(
+ "\n\nRespond to the user's new message above. You have full context from the previous session.",
+ ),
+ ];
+ } else {
+ resumePromptBlocks = [
+ hiddenTextBlock(
+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
+ `Here is the conversation history from the previous session:\n\n` +
+ `${conversationSummary}\n\n` +
+ `Continue from where you left off. The user is waiting for your response.`,
+ ),
+ ];
+ }
- this.logger.debug("Sending resume message", {
- taskId: payload.task_id,
- conversationTurns: resumeState.conversation.length,
- promptLength: promptBlocksToText(resumePromptBlocks).length,
- hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,
- });
+ this.logger.debug("Sending resume message", {
+ taskId: payload.task_id,
+ conversationTurns: resumeState.conversation.length,
+ promptLength: promptBlocksToText(resumePromptBlocks).length,
+ hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,
+ });
- return {
- prompt: resumePromptBlocks,
- ...(resumePromptMeta ? { meta: resumePromptMeta } : {}),
- messageId: resumePromptMessageId,
- };
- }),
+ return {
+ prompt: resumePromptBlocks,
+ ...(resumePromptMeta ? { meta: resumePromptMeta } : {}),
+ messageId: resumePromptMessageId,
+ };
+ },
+ reservedMessageId ? { reservedMessageId } : {},
+ ),
);
}
- private async settleIdleResume(
- payload: JwtPayload,
- taskRun: TaskRun | null,
- ): Promise<boolean> {
- if (!this.session || process.env.POSTHOG_RESUME_IDLE !== "1") return false;
-
- const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
- if (pendingUserPrompt?.prompt.length) return false;
+ private async settleIdleResume(payload: JwtPayload): Promise<void> {
+ if (!this.session) return;
this.logger.debug("Idle resume settled without a turn", {
taskId: payload.task_id,
@@ -2941,19 +2992,15 @@ export class AgentServer {
warm: this.nativeResume?.warm,
});
- this.resumeState = null;
- this.nativeResume = null;
-
this.broadcastTurnComplete("end_turn");
await this.session.logWriter.flushAll();
- return true;
}
private async preparePrewarmedResumePrompt(
payload: JwtPayload,
prompt: ContentBlock[],
): Promise<{ prompt: ContentBlock[]; consumed: boolean }> {
- if (!this.prewarmedRun) {
+ if (!this.prewarmedRun && process.env.POSTHOG_RESUME_IDLE !== "1") {
return { prompt, consumed: false };
}
@@ -3069,8 +3116,6 @@ export class AgentServer {
taskRun: TaskRun | null,
): Promise<void> {
if (!this.session) return;
- taskRun = await this.refreshTaskRunForResume(payload, taskRun);
-
await this.runStartupTurn(() =>
this.runResumeTurn(
payload,
@@ -3081,10 +3126,9 @@ export class AgentServer {
const prompt: ContentBlock[] = pendingUserPrompt?.prompt.length
? pendingUserPrompt.prompt
: [
- {
- type: "text",
- text: "Continue from where you left off. The user is waiting for your response.",
- },
+ hiddenTextBlock(
+ "Continue from where you left off. The user is waiting for your response.",
+ ),
];
this.logger.debug("Sending resume continuation", {
taskId: payload.task_id,
@@ -3131,6 +3175,7 @@ export class AgentServer {
private async retryOversizedResumeOnFreshSession(
payload: JwtPayload,
taskRun: TaskRun | null,
+ reservedMessageId?: string,
): Promise<boolean> {
if (this.oversizedResumeRetried || !this.session) {
return false;
@@ -3175,8 +3220,7 @@ export class AgentServer {
}
try {
- await this.sendResumeMessage(payload, taskRun);
- return true;
+ return await this.sendResumeMessage(payload, taskRun, reservedMessageId);
} finally {
this.resumeState = null;
this.nativeResume = null;
@@ -3188,24 +3232,41 @@ export class AgentServer {
taskRun: TaskRun | null,
logLabel: string,
buildPrompt: () => Promise<BuiltPrompt>,
- opts: { retryOnOversizedPrompt?: boolean } = {},
- ): Promise<void> {
- if (!this.session) return;
+ opts: {
+ retryOnOversizedPrompt?: boolean;
+ reservedMessageId?: string;
+ } = {},
+ ): Promise<boolean> {
+ if (!this.session) return false;
let promptDispatched = false;
+ let heldMessageId = opts.reservedMessageId;
let releaseSelfDelivery: (() => void) | undefined;
try {
const builtPrompt = await buildPrompt();
- this.session.logWriter.resetTurnMessages(payload.run_id);
const acpSessionId = this.session.acpSessionId;
if (!acpSessionId) {
throw new Error("Agent session is missing its ACP session ID");
}
- if (builtPrompt.messageId) {
+ // The fresh-session retry rebuilds the same pending message. It reuses the reservation
+ // that the failed attempt still holds, because a second reservation reads as a duplicate
+ // delivery and sends nothing.
+ if (
+ builtPrompt.messageId &&
+ builtPrompt.messageId !== opts.reservedMessageId
+ ) {
+ if (
+ this.deliveredMessageIds.has(builtPrompt.messageId) ||
+ this.inFlightMessageDeliveries.has(builtPrompt.messageId)
+ ) {
+ return false;
+ }
releaseSelfDelivery = this.beginSelfDelivery(builtPrompt.messageId);
+ heldMessageId = builtPrompt.messageId;
}
+ this.session.logWriter.resetTurnMessages(payload.run_id);
promptDispatched = true;
const result = await this.promptWithUpstreamRetry({
@@ -3242,12 +3303,18 @@ export class AgentServer {
if (this.session) {
await this.session.logWriter.flushAll();
}
+ // The retry owns the outcome only when it sends a prompt. If it sends nothing, this turn
+ // must still report the failure, so the run does not stay in progress with no answer.
if (
opts.retryOnOversizedPrompt &&
isPromptTooLongError(error) &&
- (await this.retryOversizedResumeOnFreshSession(payload, taskRun))
+ (await this.retryOversizedResumeOnFreshSession(
+ payload,
+ taskRun,
+ heldMessageId,
+ ))
) {
- return;
+ return true;
}
if (promptDispatched) {
await this.clearPendingInitialPromptState(payload, taskRun);
@@ -3256,6 +3323,7 @@ export class AgentServer {
} finally {
releaseSelfDelivery?.();
}
+ return promptDispatched;
}
private getInitialPromptOverride(taskRun: TaskRun): string | null {
diff --git a/products/desktop/packages/agent/src/server/question-relay.test.ts b/products/desktop/packages/agent/src/server/question-relay.test.ts
index be53e1b54047..4b50dc1854c3 100644
--- a/products/desktop/packages/agent/src/server/question-relay.test.ts
+++ b/products/desktop/packages/agent/src/server/question-relay.test.ts
@@ -18,7 +18,11 @@ import {
} from "../test/fixtures/api";
import { createPostHogHandlers } from "../test/mocks/msw-handlers";
import type { Task, TaskRun } from "../types";
-import { AgentServer, UPSTREAM_PROVIDER_FAILURE_MESSAGE } from "./agent-server";
+import {
+ AgentServer,
+ type PreparedInitialTaskMessage,
+ UPSTREAM_PROVIDER_FAILURE_MESSAGE,
+} from "./agent-server";
interface TestableAgentServer {
posthogAPI: PostHogAPIClient;
@@ -41,12 +45,28 @@ interface TestableAgentServer {
messageId?: string,
traceId?: string | null,
) => Promise<void>;
- sendInitialTaskMessage: (
+ prepareInitialTaskMessage: (
payload: Record<string, unknown>,
prefetchedRun?: TaskRun | null,
+ ) => Promise<PreparedInitialTaskMessage>;
+ sendInitialTaskMessage: (
+ payload: Record<string, unknown>,
+ prepared: PreparedInitialTaskMessage,
) => Promise<void>;
}
+async function startInitialTaskMessage(
+ server: TestableAgentServer,
+ payload: Record<string, unknown>,
+ prefetchedRun?: TaskRun | null,
+): Promise<void> {
+ const prepared = await server.prepareInitialTaskMessage(
+ payload,
+ prefetchedRun,
+ );
+ await server.sendInitialTaskMessage(payload, prepared);
+}
+
const TEST_PAYLOAD = {
run_id: "test-run-id",
task_id: "test-task-id",
@@ -689,7 +709,7 @@ describe("Question relay", () => {
},
};
- await server.sendInitialTaskMessage(TEST_PAYLOAD);
+ await startInitialTaskMessage(server, TEST_PAYLOAD);
expect(promptSpy).toHaveBeenCalledWith({
sessionId: "acp-session",
@@ -734,7 +754,7 @@ describe("Question relay", () => {
},
};
- await server.sendInitialTaskMessage(TEST_PAYLOAD);
+ await startInitialTaskMessage(server, TEST_PAYLOAD);
expect(promptSpy).toHaveBeenCalledWith({
sessionId: "acp-session",
@@ -769,7 +789,7 @@ describe("Question relay", () => {
},
};
- await server.sendInitialTaskMessage(TEST_PAYLOAD);
+ await startInitialTaskMessage(server, TEST_PAYLOAD);
expect(promptSpy).toHaveBeenCalledWith({
sessionId: "acp-session",
@@ -804,7 +824,7 @@ describe("Question relay", () => {
},
};
- await server.sendInitialTaskMessage(TEST_PAYLOAD);
+ await startInitialTaskMessage(server, TEST_PAYLOAD);
expect(promptSpy).not.toHaveBeenCalled();
});
@@ -834,7 +854,8 @@ describe("Question relay", () => {
},
};
- await server.sendInitialTaskMessage(
+ await startInitialTaskMessage(
+ server,
TEST_PAYLOAD,
createTaskRun({
id: "test-run-id",
@@ -869,7 +890,8 @@ describe("Question relay", () => {
},
};
- const sendPromise = server.sendInitialTaskMessage(
+ const sendPromise = startInitialTaskMessage(
+ server,
TEST_PAYLOAD,
createTaskRun({
id: "test-run-id",
@@ -924,7 +946,7 @@ describe("Question relay", () => {
vi.useFakeTimers();
try {
- const sendPromise = server.sendInitialTaskMessage(TEST_PAYLOAD);
+ const sendPromise = startInitialTaskMessage(server, TEST_PAYLOAD);
await vi.advanceTimersByTimeAsync(5_000);
await sendPromise;
} finally {
@@ -976,7 +998,7 @@ describe("Question relay", () => {
vi.useFakeTimers();
try {
- const sendPromise = server.sendInitialTaskMessage(TEST_PAYLOAD);
+ const sendPromise = startInitialTaskMessage(server, TEST_PAYLOAD);
await vi.advanceTimersByTimeAsync(5_000);
await sendPromise;
} finally {
@@ -1025,7 +1047,7 @@ describe("Question relay", () => {
vi.useFakeTimers();
try {
- const sendPromise = server.sendInitialTaskMessage(TEST_PAYLOAD);
+ const sendPromise = startInitialTaskMessage(server, TEST_PAYLOAD);
await vi.advanceTimersByTimeAsync(10_000);
await sendPromise;
} finally {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 7d5d996896b4..79c27bf1cb32 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -977,6 +977,36 @@ describe('runStreamLogic', () => {
})
describe('_posthog/user_message rendering', () => {
+ it.each(['live', 'replay'] as const)('omits hidden user content from %s frames', async (source) => {
+ const hidden = { type: 'text', text: 'Internal recovery instruction', _meta: { ui: { hidden: true } } }
+ const visible = { type: 'text', text: 'Use the updated requirements' }
+ const frames = [
+ notification('_posthog/user_message', { content: [hidden] }),
+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: hidden }),
+ sessionUpdate({ sessionUpdate: 'user_message', content: hidden }),
+ ]
+ await expectLogic(logic, () => {
+ for (const frame of frames) {
+ logic.actions.ingestAcpFrame(frame, source)
+ }
+ }).toFinishAllListeners()
+ expect(logic.values.threadItems).toEqual([])
+
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/user_message', { content: [hidden, visible] }),
+ source
+ )
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: visible }),
+ source
+ )
+ }).toFinishAllListeners()
+ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toEqual([
+ expect.objectContaining({ text: visible.text }),
+ ])
+ })
+
it('renders a seeded user turn into the thread on bootstrap replay', async () => {
const frames: StoredLogEntry[] = [
notification('_posthog/user_message', { content: 'Why did checkout drop?' }),
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index cc9e042e4743..8264faa90972 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -340,6 +340,7 @@ function extractUserMessageText(content: string | unknown[] | undefined): string
}
if (Array.isArray(content)) {
return content
+ .filter((block) => !isHiddenUserContent(block))
.map((block) =>
block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
? (block as { text: string }).text
@@ -350,6 +351,13 @@ function extractUserMessageText(content: string | unknown[] | undefined): string
return ''
}
+function isHiddenUserContent(content: unknown): boolean {
+ if (!isRecord(content) || !isRecord(content._meta) || !isRecord(content._meta.ui)) {
+ return false
+ }
+ return content._meta.ui.hidden === true
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
@@ -1350,6 +1358,9 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
const sessionUpdate = update.sessionUpdate
if (sessionUpdate === 'user_message_chunk' || sessionUpdate === 'user_message') {
+ if (isHiddenUserContent(update.content)) {
+ continue
+ }
const content = update.content as { text?: string } | undefined
const userText = String(content?.text ?? update.text ?? '')
if (source === 'replay') {
@@ -3456,6 +3467,10 @@ export const runStreamLogic = kea<runStreamLogicType>([
// unattached optimistic stream has no task id and records nothing — its send path marks
// sent keys directly.
if (isPosthogNotification(notification, '_posthog/user_message')) {
+ const content = notification.params?.content
+ if (Array.isArray(content) && content.length > 0 && content.every(isHiddenUserContent)) {
+ return
+ }
actions.markTurnStarted()
if (values.bootstrappedTaskId) {
const lines = contextBlockLinesFromUserMessage(extractUserMessageText(notification.params?.content))
@@ -3500,6 +3515,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
// chains persist a turn in both wire forms, and the seen-lines reducer dedupes the overlap.
// Chunked frames are skipped: a partial text could truncate a block mid-line.
if (isSessionUpdateUserMessage(update)) {
+ if (isHiddenUserContent(update.content)) {
+ return
+ }
actions.markTurnStarted()
if (values.bootstrappedTaskId && update.sessionUpdate === 'user_message') {
const lines = contextBlockLinesFromUserMessage(String(update.content?.text ?? update.text ?? ''))