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(desktop): prevent duplicate shadow context messages (#82593)

Alessandro Pogliaghi1668457e8c72
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 77bd549d9352..06f719b6432e 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -97,6 +97,7 @@ import type {
} from "../types";
import { resourceLink } from "../utils/acp-content";
import { AsyncMutex } from "../utils/async-mutex";
+import { withTimeout } from "../utils/common";
import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";
import { resolveGithubToken } from "../utils/github-token";
import { Logger } from "../utils/logger";
@@ -129,6 +130,8 @@ const agentErrorClassificationSchema = z.enum([
"agent_error",
]) satisfies z.ZodType<AgentErrorClassification>;
+const INITIAL_TASK_RUN_REFRESH_TIMEOUT_MS = 5_000;
+
export const UPSTREAM_PROVIDER_FAILURE_MESSAGE =
"The upstream AI provider failed to process the request. Please retry the task in a few minutes.";
@@ -2193,21 +2196,19 @@ export class AgentServer {
): Promise<void> {
if (!this.session) return;
- // Fetch TaskRun early — needed for both resume detection and initial prompt
let taskRun = prefetchedRun ?? null;
- if (!taskRun) {
- try {
- taskRun = await this.posthogAPI.getTaskRun(
- payload.task_id,
- payload.run_id,
- );
- } catch (error) {
- this.logger.debug("Failed to fetch task run", {
- taskId: payload.task_id,
- runId: payload.run_id,
- error,
- });
- }
+ try {
+ const refresh = await withTimeout(
+ this.posthogAPI.getTaskRun(payload.task_id, payload.run_id),
+ INITIAL_TASK_RUN_REFRESH_TIMEOUT_MS,
+ );
+ if (refresh.result === "success") taskRun = refresh.value;
+ } catch (error) {
+ this.logger.debug("Failed to refresh task run before initial message", {
+ taskId: payload.task_id,
+ runId: payload.run_id,
+ error,
+ });
}
if (this.nativeResume) {
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 bf1603a70ada..3f9b7dac5951 100644
--- a/products/desktop/packages/agent/src/server/question-relay.test.ts
+++ b/products/desktop/packages/agent/src/server/question-relay.test.ts
@@ -2,7 +2,11 @@ import { type SetupServerApi, setupServer } from "msw/node";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { classifyAgentError } from "../adapters/error-classification";
import type { PostHogAPIClient } from "../posthog-api";
-import { createTestRepo, type TestRepo } from "../test/fixtures/api";
+import {
+ createTaskRun,
+ createTestRepo,
+ type TestRepo,
+} 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";
@@ -27,7 +31,10 @@ interface TestableAgentServer {
payload: Record<string, unknown>,
messageId?: string,
) => Promise<void>;
- sendInitialTaskMessage: (payload: Record<string, unknown>) => Promise<void>;
+ sendInitialTaskMessage: (
+ payload: Record<string, unknown>,
+ prefetchedRun?: TaskRun | null,
+ ) => Promise<void>;
}
const TEST_PAYLOAD = {
@@ -39,6 +46,20 @@ const TEST_PAYLOAD = {
mode: "interactive" as const,
};
+function createTask(overrides: Partial<Task> = {}): Task {
+ return {
+ id: "test-task-id",
+ task_number: null,
+ slug: "test-task",
+ title: "t",
+ description: "original task description",
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ origin_product: "tasks",
+ ...overrides,
+ };
+}
+
const QUESTION_META = {
codeToolKind: "question",
questions: [
@@ -764,6 +785,86 @@ describe("Question relay", () => {
expect(promptSpy).not.toHaveBeenCalled();
});
+ it("refreshes stale bootstrap state before choosing the initial prompt", async () => {
+ vi.spyOn(server.posthogAPI, "getTask").mockResolvedValue(createTask());
+ vi.spyOn(server.posthogAPI, "getTaskRun").mockResolvedValue(
+ createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: { prewarmed: true },
+ }),
+ );
+
+ const promptSpy = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
+ server.session = {
+ payload: TEST_PAYLOAD,
+ acpSessionId: "acp-session",
+ clientConnection: { prompt: promptSpy },
+ logWriter: {
+ flushAll: vi.fn().mockResolvedValue(undefined),
+ getFullAgentResponse: vi.fn().mockReturnValue(null),
+ resetTurnMessages: vi.fn(),
+ appendRawLine: vi.fn(),
+ flush: vi.fn().mockResolvedValue(undefined),
+ isRegistered: vi.fn().mockReturnValue(true),
+ },
+ };
+
+ await server.sendInitialTaskMessage(
+ TEST_PAYLOAD,
+ createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: {},
+ }),
+ );
+
+ expect(promptSpy).not.toHaveBeenCalled();
+ });
+
+ it("uses prefetched state when the initial task run refresh times out", async () => {
+ vi.useFakeTimers();
+ try {
+ vi.spyOn(server.posthogAPI, "getTask").mockResolvedValue(createTask());
+ vi.spyOn(server.posthogAPI, "getTaskRun").mockReturnValue(
+ new Promise(() => {}),
+ );
+
+ const promptSpy = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
+ server.session = {
+ payload: TEST_PAYLOAD,
+ acpSessionId: "acp-session",
+ clientConnection: { prompt: promptSpy },
+ logWriter: {
+ flushAll: vi.fn().mockResolvedValue(undefined),
+ getFullAgentResponse: vi.fn().mockReturnValue(null),
+ resetTurnMessages: vi.fn(),
+ appendRawLine: vi.fn(),
+ flush: vi.fn().mockResolvedValue(undefined),
+ isRegistered: vi.fn().mockReturnValue(true),
+ },
+ };
+
+ const sendPromise = server.sendInitialTaskMessage(
+ TEST_PAYLOAD,
+ createTaskRun({
+ id: "test-run-id",
+ task: "test-task-id",
+ state: {},
+ }),
+ );
+ await vi.advanceTimersByTimeAsync(5_000);
+ await sendPromise;
+
+ expect(promptSpy).toHaveBeenCalledWith({
+ sessionId: "acp-session",
+ prompt: [{ type: "text", text: "original task description" }],
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("replays a transient upstream termination with a continuation prompt", async () => {
vi.spyOn(server.posthogAPI, "getTask").mockResolvedValue({
id: "test-task-id",
diff --git a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts
index 43691e9f4935..5ffaa89b376e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts
@@ -90,6 +90,35 @@ describe("mergeConversationItems", () => {
expect(pinned.content).toBe(echoedWithContext);
});
+ it.each([
+ { name: "plain bare echo", bare: "hello" },
+ {
+ name: "bare echo carrying an attachment summary",
+ bare: "hello\n\nAttached files: clipboard.png",
+ },
+ ])(
+ "cloud: folds a raced $name and the shadow-context echo into the pinned message",
+ ({ bare }) => {
+ const echoedWithContext =
+ 'hello\n\n<channel_context channel="bluebird">background</channel_context>';
+ const result = mergeConversationItems({
+ conversationItems: [
+ userMessage("bare", bare),
+ userMessage("shadow", echoedWithContext),
+ userMessage("other", "different"),
+ ],
+ optimisticItems: [userMessage("opt", echoedWithContext)],
+ isCloud: true,
+ });
+
+ expect(result.map((item) => item.id)).toEqual(["opt", "other"]);
+ const pinned = result[0];
+ if (pinned.type !== "user_message")
+ throw new Error("expected user_message");
+ expect(pinned.content).toBe(echoedWithContext);
+ },
+ );
+
it("cloud: dedupes the echo when the placeholder carries an 'Attached files:' summary the echo lacks", () => {
const echoed = {
...userMessage("echo", "hello\n\nDo this"),
diff --git a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts
index 940a491f2239..64c0e2f011d7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts
@@ -1,7 +1,13 @@
import { stripTrailingAttachmentSummary } from "@posthog/core/editor/cloud-prompt";
import type { ConversationItem } from "./buildConversationItems";
-import { extractChannelContext } from "./session-update/channelContext";
-import { extractCustomInstructions } from "./session-update/customInstructions";
+import {
+ extractChannelContext,
+ hasChannelContext,
+} from "./session-update/channelContext";
+import {
+ extractCustomInstructions,
+ hasCustomInstructions,
+} from "./session-update/customInstructions";
interface MergeConversationItemsArgs {
conversationItems: ConversationItem[];
@@ -27,6 +33,10 @@ function strippedUserContent(content: string): string {
return stripTrailingAttachmentSummary(withoutInstructions);
}
+function hasShadowContext(content: string): boolean {
+ return hasChannelContext(content) || hasCustomInstructions(content);
+}
+
// Cloud's initial optimistic is pinned to the top so the user's prompt stays
// visible above setup progress. Follow-up optimistics render at the tail, but
// before trailing progress cards, to match where the streamed `session/prompt`
@@ -68,6 +78,7 @@ export function mergeConversationItems({
// attachment chips the placeholder lacks, so we surface the richer copy on
// the pinned bubble below.
const echoedItemByKey = new Map<string, UserMessageItem>();
+ const consumedPlainEchoByKey = new Set<string>();
const dedupedConversation =
unconsumedPinnedKeyCounts.size === 0
? conversationItems
@@ -75,12 +86,23 @@ export function mergeConversationItems({
if (item.type !== "user_message") return true;
const key = strippedUserContent(item.content);
const remaining = unconsumedPinnedKeyCounts.get(key) ?? 0;
- if (remaining === 0) return true;
- unconsumedPinnedKeyCounts.set(key, remaining - 1);
- if (!echoedItemByKey.has(key)) {
+ if (remaining > 0) {
+ unconsumedPinnedKeyCounts.set(key, remaining - 1);
+ echoedItemByKey.set(key, item);
+ if (!hasShadowContext(item.content))
+ consumedPlainEchoByKey.add(key);
+ return false;
+ }
+
+ if (
+ consumedPlainEchoByKey.has(key) &&
+ hasShadowContext(item.content)
+ ) {
echoedItemByKey.set(key, item);
+ consumedPlainEchoByKey.delete(key);
+ return false;
}
- return false;
+ return true;
});
const resolvedPinnedItems =