: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(desktop): log session pipeline health to diagnose frozen transcripts (#84003)
Charles Vienf6b13a1458b2
diff --git a/products/desktop/apps/code/src/renderer/utils/logger.ts b/products/desktop/apps/code/src/renderer/utils/logger.tsindex 71c82fad7987..28692612aca2 100644--- a/products/desktop/apps/code/src/renderer/utils/logger.ts+++ b/products/desktop/apps/code/src/renderer/utils/logger.ts@@ -1,8 +1,23 @@-import { type HostLogger, logger as uiLogger } from "@posthog/ui/shell/logger";+import {+ type HostLogger,+ type ScopedLogger,+ logger as uiLogger,+} from "@posthog/ui/shell/logger";import log from "electron-log/renderer";log.transports.console.level = "debug";-export const hostLog = log as unknown as HostLogger;+// electron-log's renderer export is a Proxy that answers any unknown property+// with a log function, `then` included. Inversify treats a thenable constant+// as an async service and throws on `get`, the shell logger swallows that, and+// every ui/core log line dies before it reaches the main process. Bind a plain+// object instead.+export const hostLog: HostLogger = {+ scope: (name: string): ScopedLogger => log.scope(name),+ info: (...args: unknown[]) => log.info(...args),+ warn: (...args: unknown[]) => log.warn(...args),+ error: (...args: unknown[]) => log.error(...args),+ debug: (...args: unknown[]) => log.debug(...args),+};export const logger = uiLogger;diff --git a/products/desktop/apps/code/src/renderer/utils/queryClient.test.ts b/products/desktop/apps/code/src/renderer/utils/queryClient.test.tsindex 91a1353c2f2d..e6a19379877e 100644--- a/products/desktop/apps/code/src/renderer/utils/queryClient.test.ts+++ b/products/desktop/apps/code/src/renderer/utils/queryClient.test.ts@@ -1,8 +1,20 @@import type { Task } from "@posthog/shared/domain-types";import { focusManager } from "@tanstack/react-query";-import { beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getCachedTask, queryClient } from "./queryClient";+const warn = vi.hoisted(() => vi.fn());+vi.mock("./logger", () => ({+ logger: {+ scope: () => ({+ warn,+ info: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ }),+ },+}));+const createTask = (overrides: Partial<Task> = {}): Task => ({id: "task-1",task_number: 1,@@ -63,6 +75,49 @@ describe("getCachedTask", () => {});});+describe("query failure logging", () => {+ const realNow = Date.now();+ let clockOffset = 0;++ const failQuery = (queryKey: unknown[]) =>+ queryClient+ .fetchQuery({+ queryKey,+ queryFn: () => Promise.reject(new Error("boom")),+ retry: false,+ })+ .catch(() => undefined);++ beforeEach(() => {+ // The throttle state is module-level, so each test needs a fresh window.+ clockOffset += 5 * 60_000;+ vi.spyOn(Date, "now").mockImplementation(() => realNow + clockOffset);+ warn.mockClear();+ queryClient.clear();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("stops logging once a window fills up with distinct failures", async () => {+ await Promise.all(+ Array.from({ length: 200 }, (_, i) => failQuery(["flood", i])),+ );++ // 50 failures plus the one line saying the rest are muted.+ expect(warn).toHaveBeenCalledTimes(51);+ });++ it("truncates an oversized query key before logging it", async () => {+ await failQuery(["huge", "x".repeat(5_000)]);++ expect(warn).toHaveBeenCalledTimes(1);+ const [, payload] = warn.mock.calls[0];+ expect(payload.key.length).toBeLessThan(300);+ });+});+describe("focusManager", () => {it("flips focus state on window focus/blur events", () => {window.dispatchEvent(new Event("blur"));diff --git a/products/desktop/apps/code/src/renderer/utils/queryClient.ts b/products/desktop/apps/code/src/renderer/utils/queryClient.tsindex aa328987220d..a5033d74cd3e 100644--- a/products/desktop/apps/code/src/renderer/utils/queryClient.ts+++ b/products/desktop/apps/code/src/renderer/utils/queryClient.ts@@ -1,7 +1,93 @@import type { Task } from "@posthog/shared/domain-types";-import { focusManager, QueryClient } from "@tanstack/react-query";+import {+ focusManager,+ MutationCache,+ QueryCache,+ QueryClient,+} from "@tanstack/react-query";+import { logger } from "./logger";++const queryLog = logger.scope("react-query");++/**+ * A query that keeps failing refetches every poll interval; one line a minute+ * per query key keeps the log readable while an API is down.+ */+const FAILURE_LOG_INTERVAL_MS = 60_000;+/**+ * Query keys and error messages both carry caller-supplied detail, so a caller+ * that varies either one sidesteps the per-key throttle. Cap the lines written+ * per window, the keys retained, and the length of each so a burst of distinct+ * failures cannot flood the log or grow the map.+ */+const MAX_FAILURES_LOGGED_PER_INTERVAL = 50;+const MAX_THROTTLE_KEYS = 100;+const MAX_LOGGED_LENGTH = 200;++const lastFailureLogAt = new Map<string, number>();+let failureWindowStartedAt = 0;+let failuresSeenInWindow = 0;++function describeError(error: unknown): string {+ if (error instanceof Error) return `${error.name}: ${error.message}`;+ return String(error);+}++function truncate(value: string): string {+ if (value.length <= MAX_LOGGED_LENGTH) return value;+ return `${value.slice(0, MAX_LOGGED_LENGTH)}… (${value.length} chars)`;+}++function logFailure(kind: "query" | "mutation", key: string, error: unknown) {+ const shortKey = truncate(key);+ const message = truncate(describeError(error));+ const throttleKey = `${kind}:${shortKey}:${message}`;+ const now = Date.now();+ // Error messages can carry unique detail (ids, timestamps), so keys are+ // unbounded; drop the ones whose window has passed rather than keep them.+ for (const [storedKey, loggedAt] of lastFailureLogAt) {+ if (now - loggedAt >= FAILURE_LOG_INTERVAL_MS) {+ lastFailureLogAt.delete(storedKey);+ }+ }+ const last = lastFailureLogAt.get(throttleKey) ?? 0;+ if (now - last < FAILURE_LOG_INTERVAL_MS) return;++ if (now - failureWindowStartedAt >= FAILURE_LOG_INTERVAL_MS) {+ failureWindowStartedAt = now;+ failuresSeenInWindow = 0;+ }+ failuresSeenInWindow += 1;+ if (failuresSeenInWindow > MAX_FAILURES_LOGGED_PER_INTERVAL) {+ // One line saying the log is muted beats thousands saying why.+ if (failuresSeenInWindow === MAX_FAILURES_LOGGED_PER_INTERVAL + 1) {+ queryLog.warn("too many distinct failures, muting until the next minute");+ }+ return;+ }++ while (lastFailureLogAt.size >= MAX_THROTTLE_KEYS) {+ const oldest = lastFailureLogAt.keys().next().value;+ if (oldest === undefined) break;+ lastFailureLogAt.delete(oldest);+ }+ lastFailureLogAt.set(throttleKey, now);+ queryLog.warn(`${kind} failed`, { key: shortKey, error: message });+}export const queryClient = new QueryClient({+ queryCache: new QueryCache({+ onError: (error, query) =>+ logFailure("query", JSON.stringify(query.queryKey), error),+ }),+ mutationCache: new MutationCache({+ onError: (error, _variables, _context, mutation) =>+ logFailure(+ "mutation",+ JSON.stringify(mutation.options.mutationKey ?? "anonymous"),+ error,+ ),+ }),defaultOptions: {queries: {staleTime: 1000 * 60 * 5,diff --git a/products/desktop/packages/core/src/sessions/sessionEventDiagnostics.test.ts b/products/desktop/packages/core/src/sessions/sessionEventDiagnostics.test.tsnew file mode 100644index 000000000000..8842c9a0bb17--- /dev/null+++ b/products/desktop/packages/core/src/sessions/sessionEventDiagnostics.test.ts@@ -0,0 +1,181 @@+import type { AgentSession } from "@posthog/shared";+import { describe, expect, it, vi } from "vitest";+import { SessionService, type SessionServiceDeps } from "./sessionService";++const RUN_ID = "run-1";++interface Handlers {+ onData: (payload: unknown) => void;+ onError?: (err: unknown) => void;+}++function fakeSubscription() {+ const subscriptions: { handlers: Handlers; unsubscribe: () => void }[] = [];+ return {+ subscriptions,+ subscribe: vi.fn((_input: unknown, handlers: Handlers) => {+ const unsubscribe = vi.fn();+ subscriptions.push({ handlers, unsubscribe });+ return { unsubscribe };+ }),+ };+}++function createHarness(sessionOverrides: Partial<AgentSession> = {}) {+ const sessions: Record<string, AgentSession> = {+ [RUN_ID]: {+ taskRunId: RUN_ID,+ taskId: "task-1",+ taskTitle: "Local Task",+ events: [],+ messageQueue: [],+ pendingPermissions: new Map(),+ status: "connected",+ isPromptPending: false,+ promptStartedAt: null,+ ...sessionOverrides,+ } as unknown as AgentSession,+ };+ const events = fakeSubscription();+ const permissions = fakeSubscription();+ const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };+ const deps = {+ store: {+ getSessions: () => sessions,+ getSessionByTaskId: (taskId: string) =>+ Object.values(sessions).find((s) => s.taskId === taskId),+ updateSession: vi.fn(),+ appendEvents: vi.fn(),+ replaceOptimisticWithEvent: vi.fn(),+ setPendingPermissions: vi.fn(),+ clearMessageQueue: vi.fn(),+ clearTailOptimisticItems: vi.fn(),+ appendOptimisticItem: vi.fn(),+ },+ log,+ getIsOnline: () => true,+ notifyAgentSession: vi.fn(),+ enqueueSpeech: vi.fn(),+ trpc: {+ agent: {+ onSessionEvent: { subscribe: events.subscribe },+ onPermissionRequest: { subscribe: permissions.subscribe },+ onSessionIdleKilled: { subscribe: () => ({ unsubscribe: vi.fn() }) },+ },+ },+ } as unknown as SessionServiceDeps;+ const service = new SessionService(deps);+ (+ service as unknown as { subscribeToChannel(taskRunId: string): void }+ ).subscribeToChannel(RUN_ID);+ return { service, events, permissions, log, deps };+}++describe("session event diagnostics", () => {+ it("keeps applying a batch after one event throws, and logs the failure", () => {+ vi.useFakeTimers();+ try {+ const { events, log, deps } = createHarness();+ const chunk = (text: string) => ({+ type: "acp_message",+ ts: 1,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: RUN_ID,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text },+ },+ },+ },+ });+ const appendEvents = deps.store.appendEvents as ReturnType<typeof vi.fn>;+ appendEvents.mockImplementationOnce(() => {+ throw new Error("boom");+ });++ events.subscriptions[0].handlers.onData(chunk("first"));+ events.subscriptions[0].handlers.onData(chunk("second"));+ vi.advanceTimersByTime(20);++ expect(appendEvents).toHaveBeenCalledTimes(2);+ expect(log.error).toHaveBeenCalledWith(+ "Session event handling failed",+ expect.objectContaining({+ taskRunId: RUN_ID,+ method: "session/update:agent_message_chunk",+ failed: 1,+ received: 2,+ }),+ );+ } finally {+ vi.useRealTimers();+ }+ });++ describe("silence while a local prompt is pending", () => {+ const chunk = {+ type: "acp_message",+ ts: 1,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: RUN_ID,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: "x" },+ },+ },+ },+ };++ it.each([+ {+ name: "logs one warning after a minute of silence",+ eventEvery: null,+ warnings: 1,+ },+ {+ name: "stays quiet while events keep arriving",+ eventEvery: 30_000,+ warnings: 0,+ },+ ])("$name", ({ eventEvery, warnings }) => {+ vi.useFakeTimers();+ try {+ const { events, log, service } = createHarness({+ isPromptPending: true,+ promptStartedAt: Date.now(),+ });+ // A first event starts the check, as the prompt echo does in the app.+ events.subscriptions[0].handlers.onData(chunk);++ for (let elapsed = 0; elapsed < 150_000; elapsed += 30_000) {+ vi.advanceTimersByTime(30_000);+ if (eventEvery !== null) {+ events.subscriptions[0].handlers.onData(chunk);+ }+ }++ const silenceWarnings = log.warn.mock.calls.filter(+ ([message]) =>+ message === "Local session silent while a prompt is pending",+ );+ expect(silenceWarnings).toHaveLength(warnings);+ if (warnings > 0) {+ expect(silenceWarnings[0][1]).toMatchObject({+ taskRunId: RUN_ID,+ subscribed: true,+ online: true,+ });+ }+ service.reset();+ } finally {+ vi.useRealTimers();+ }+ });+ });+});diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex bbdf6d08a23b..12737e254c79 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -140,6 +140,20 @@ const MAX_HOST_ENDED_RESUBSCRIBES = 3;*/const LOCAL_SILENCE_WARN_AFTER_MS = 60_000;const LOCAL_SILENCE_CHECK_INTERVAL_MS = 30_000;++/** Short label for a log line: `session/update:agent_message_chunk`, `response`. */+function describeAcpMethod(acpMsg: AcpMessage): string {+ const msg = acpMsg.message as {+ method?: unknown;+ params?: { update?: { sessionUpdate?: unknown } };+ error?: unknown;+ };+ if (typeof msg.method !== "string") {+ return msg.error ? "error-response" : "response";+ }+ const update = msg.params?.update?.sessionUpdate;+ return typeof update === "string" ? `${msg.method}:${update}` : msg.method;+}/*** Streamed events are buffered and flushed on this cadence so a burst of tokens* coalesces into one processing pass (and roughly one render) instead of one@@ -1662,6 +1676,11 @@ export class SessionService {private hostEndedResubscribes = new Map<string, number>();/** When each local run last delivered a session event to this renderer. */private lastSessionEventAt = new Map<string, number>();+ /** Per-run tallies of what this renderer received and failed to apply. */+ private sessionEventStats = new Map<+ string,+ { received: number; failed: number; lastMethod: string }+ >();/** Runs already logged for their current stretch of silence. */private silenceLogged = new Set<string>();private silenceCheckHandle: ReturnType<typeof setInterval> | null = null;@@ -2662,6 +2681,9 @@ export class SessionService {this.lastSessionEventAt.set(taskRunId, Date.now());this.silenceLogged.delete(taskRunId);this.ensureSilenceCheck();+ const stats = this.statsFor(taskRunId);+ stats.received += 1;+ stats.lastMethod = describeAcpMethod(acpMsg);if (isAgentTextStreamEvent(acpMsg)) {this.lastAgentTextAt.set(taskRunId, Date.now());}@@ -2685,7 +2707,7 @@ export class SessionService {this.pendingSessionEvents = new Map();for (const [taskRunId, events] of batches) {for (const acpMsg of events) {- this.handleSessionEvent(taskRunId, acpMsg);+ this.applySessionEvent(taskRunId, acpMsg);}}}@@ -2697,10 +2719,46 @@ export class SessionService {if (!events) return;this.pendingSessionEvents.delete(taskRunId);for (const acpMsg of events) {+ this.applySessionEvent(taskRunId, acpMsg);+ }+ }++ /**+ * One event that throws must not take the rest of its batch (and every other+ * run's batch in the same flush) down with it: that leaves the transcript+ * frozen with nothing in the log. Log it, count it, keep going.+ */+ private applySessionEvent(taskRunId: string, acpMsg: AcpMessage): void {+ try {this.handleSessionEvent(taskRunId, acpMsg);+ } catch (error) {+ const stats = this.statsFor(taskRunId);+ stats.failed += 1;+ if (stats.failed === 1 || stats.failed % 100 === 0) {+ this.d.log.error("Session event handling failed", {+ taskRunId,+ method: describeAcpMethod(acpMsg),+ failed: stats.failed,+ received: stats.received,+ error,+ });+ }}}+ private statsFor(taskRunId: string): {+ received: number;+ failed: number;+ lastMethod: string;+ } {+ let stats = this.sessionEventStats.get(taskRunId);+ if (!stats) {+ stats = { received: 0, failed: 0, lastMethod: "" };+ this.sessionEventStats.set(taskRunId, stats);+ }+ return stats;+ }+private ensureSilenceCheck(): void {if (this.silenceCheckHandle !== null) return;this.silenceCheckHandle = setInterval(@@ -2726,6 +2784,7 @@ export class SessionService {const silentForMs = now - lastSignalAt;if (silentForMs < LOCAL_SILENCE_WARN_AFTER_MS) continue;this.silenceLogged.add(taskRunId);+ const stats = this.sessionEventStats.get(taskRunId);this.d.log.warn("Local session silent while a prompt is pending", {taskRunId,taskId: session.taskId,@@ -2733,6 +2792,9 @@ export class SessionService {subscribed: this.subscriptions.has(taskRunId),bufferedEvents: this.pendingSessionEvents.get(taskRunId)?.length ?? 0,eventCount: session.events.length,+ received: stats?.received ?? 0,+ failed: stats?.failed ?? 0,+ lastMethod: stats?.lastMethod ?? null,online: this.d.getIsOnline(),});}@@ -2941,6 +3003,7 @@ export class SessionService {subscription?.permission?.unsubscribe();this.hostEndedResubscribes.delete(taskRunId);this.lastSessionEventAt.delete(taskRunId);+ this.sessionEventStats.delete(taskRunId);this.silenceLogged.delete(taskRunId);this.liveTurnContent.delete(taskRunId);this.agentSpokeAt.delete(taskRunId);@@ -2978,6 +3041,7 @@ export class SessionService {this.pendingSessionEvents.clear();this.hostEndedResubscribes.clear();this.lastSessionEventAt.clear();+ this.sessionEventStats.clear();this.silenceLogged.clear();if (this.silenceCheckHandle !== null) {clearInterval(this.silenceCheckHandle);@@ -3028,6 +3092,7 @@ export class SessionService {if (!tally) return;this.liveTurnContent.delete(taskRunId);const session = this.d.store.getSessions()[taskRunId];+ const stats = this.sessionEventStats.get(taskRunId);const payload = {taskRunId,taskId: session?.taskId,@@ -3036,11 +3101,14 @@ export class SessionService {agentTextChunks: tally.agentTextChunks,agentOutputEvents: tally.agentOutputEvents,durationMs: Math.max(0, endedAtTs - tally.startedAtTs),+ eventCount: session?.events.length ?? 0,+ received: stats?.received ?? 0,+ failed: stats?.failed ?? 0,};if (tally.agentTextChunks === 0 && tally.agentOutputEvents === 0) {this.d.log.warn("Turn completed with no agent output", payload);} else {- this.d.log.debug("Turn completed", payload);+ this.d.log.info("Turn completed", payload);}}@@ -6179,7 +6247,19 @@ export class SessionService {taskRunId,normalizedUpdate,);- this.handleCloudTaskUpdate(taskRunId, normalizedUpdate);+ try {+ this.handleCloudTaskUpdate(taskRunId, normalizedUpdate);+ } catch (error) {+ // Same reasoning as applySessionEvent: one bad update must not end+ // the stream silently. The subscription stays up for the next one.+ this.d.log.error("Cloud task update handling failed", {+ taskId,+ taskRunId,+ kind: update.kind,+ error,+ });+ return;+ }if ((update.kind === "status" ||update.kind === "snapshot" ||diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsxindex 6a83bf3f1439..dc6f0153ea4a 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx@@ -118,6 +118,7 @@ import {import { toast } from "@posthog/ui/primitives/toast";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";+import { logger } from "@posthog/ui/shell/logger";import { Box, Flex } from "@radix-ui/themes";import { useNavigate, useRouterState } from "@tanstack/react-router";import {@@ -134,6 +135,8 @@ import {} from "react";import { hostClient } from "../hostClient";+const channelsLog = logger.scope("channels");+/*** A row's clickable surface.*@@ -1273,11 +1276,15 @@ function useOpenPersonalChannel(): {const spacesLayout = useChannelsLayout();const navigate = useNavigate();const setCurrentChannel = useCurrentChannelStore((s) => s.setCurrentChannel);- const { channels } = useChannels();+ const { channels, isLoading } = useChannels();const ensureChannelId = (): string | undefined => {const meChannel = channels.find((c) => c.channelType === "personal");if (!meChannel) {+ channelsLog.warn("Personal space missing from the channel list", {+ channelCount: channels.length,+ isLoading,+ });toast.error("Couldn't open personal space", {description:"Your personal space is still loading. Try again in a moment.",diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.test.tsnew file mode 100644index 000000000000..8e2cb67d108b--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.test.ts@@ -0,0 +1,61 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const warn = vi.hoisted(() => vi.fn());+vi.mock("@posthog/ui/shell/logger", () => ({+ logger: {+ scope: () => ({ error: vi.fn(), warn, info: vi.fn(), debug: vi.fn() }),+ },+}));++import type { AcpMessage } from "@posthog/shared";+import { useConversationItems } from "./useConversationItems";++let ts = 1;+function update(sessionUpdate: string, extra: Record<string, unknown> = {}) {+ return {+ type: "acp_message",+ ts: ts++,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: { sessionId: "run-1", update: { sessionUpdate, ...extra } },+ },+ } as unknown as AcpMessage;+}++const chunk = (text: string) =>+ update("agent_message_chunk", { content: { type: "text", text } });+const usage = () => update("usage_update", { used: 1, size: 100 });++describe("useConversationItems", () => {+ beforeEach(() => warn.mockClear());++ it("logs once when many events arrive without changing what is shown", () => {+ let events: AcpMessage[] = [chunk("hello")];+ const { rerender } = renderHook(() => useConversationItems(events, true));++ for (let i = 0; i < 60; i++) {+ events = [...events, usage()];+ rerender();+ }++ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith(+ "Transcript received events without a visible change",+ expect.objectContaining({ itemCount: 1, isPromptPending: true }),+ );+ });++ it("stays quiet while streamed text keeps growing the last item", () => {+ let events: AcpMessage[] = [chunk("a")];+ const { rerender } = renderHook(() => useConversationItems(events, true));++ for (let i = 0; i < 80; i++) {+ events = [...events, chunk("b")];+ rerender();+ }++ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.tsindex 0800e1511c6a..1d99b73d9964 100644--- a/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useConversationItems.ts@@ -4,14 +4,54 @@ import type {BuildResult,} from "@posthog/ui/features/sessions/components/buildConversationItems";import { createIncrementalConversationBuilder } from "@posthog/ui/features/sessions/components/incrementalConversationItems";+import { logger } from "@posthog/ui/shell/logger";import { useRef } from "react";+const log = logger.scope("transcript");++/**+ * How many new events may arrive without changing what the thread shows+ * before that is logged. Streamed text grows the last item on every event, so+ * a healthy turn never gets close.+ */+const STALL_EVENT_THRESHOLD = 50;+interface Cache {impl: ReturnType<typeof createIncrementalConversationBuilder>;events: AcpMessage[] | null;pending: boolean | null;debug: boolean | undefined;result: BuildResult | null;+ visible: string;+ eventsAtLastVisibleChange: number;+ stallLogged: boolean;+}++/**+ * Cheap fingerprint of what the thread would show for a build result: item+ * count, the last item and how much of it there is. Streamed text, tool status+ * flips and plan entries all move it; a batch of events that leaves it+ * untouched is a transcript that looks frozen.+ */+function visibleSignature(result: BuildResult): string {+ const last = result.items[result.items.length - 1];+ if (!last) return `0|${result.completedToolCallCount}`;+ let detail = "";+ if (last.type === "session_update") {+ const update = last.update as {+ sessionUpdate: string;+ status?: unknown;+ content?: { text?: unknown };+ entries?: unknown;+ };+ const text =+ typeof update.content?.text === "string" ? update.content.text.length : 0;+ const entries = Array.isArray(update.entries) ? update.entries.length : "";+ detail = `${update.sessionUpdate}:${String(update.status ?? "")}:${text}:${entries}`;+ } else if (last.type === "user_message") {+ detail = `user:${last.content.length}`;+ }+ return `${result.items.length}|${last.id}|${detail}|${result.completedToolCallCount}`;}/**@@ -34,6 +74,9 @@ export function useConversationItems(pending: null,debug: undefined,result: null,+ visible: "",+ eventsAtLastVisibleChange: 0,+ stallLogged: false,};}const cache = ref.current;@@ -53,5 +96,35 @@ export function useConversationItems(cache.pending = isPromptPending;cache.debug = debug;cache.result = result;+ noteVisibleChange(cache, events, isPromptPending, result);return result;}++function noteVisibleChange(+ cache: Cache,+ events: AcpMessage[],+ isPromptPending: boolean | null,+ result: BuildResult,+): void {+ const visible = visibleSignature(result);+ if (visible !== cache.visible) {+ cache.visible = visible;+ cache.eventsAtLastVisibleChange = events.length;+ cache.stallLogged = false;+ return;+ }+ const unseen = events.length - cache.eventsAtLastVisibleChange;+ if (unseen < STALL_EVENT_THRESHOLD || cache.stallLogged) return;+ cache.stallLogged = true;+ const lastEvent = events[events.length - 1]?.message as+ | { method?: unknown }+ | undefined;+ log.warn("Transcript received events without a visible change", {+ eventCount: events.length,+ unseenEvents: unseen,+ itemCount: result.items.length,+ isPromptPending,+ lastEventMethod:+ typeof lastEvent?.method === "string" ? lastEvent.method : "response",+ });+}diff --git a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsxindex a427c3bbb9ee..53c1541f52f7 100644--- a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx+++ b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx@@ -34,6 +34,7 @@ import { openTask, openTaskInput } from "@posthog/ui/router/useOpenTask";import { useCommandMenuStore } from "@posthog/ui/shell/commandMenuStore";import { logger } from "@posthog/ui/shell/logger";import { useRendererWindowFocusStore } from "@posthog/ui/shell/rendererWindowFocusStore";+import { installUncaughtErrorLogging } from "@posthog/ui/shell/uncaughtErrorLog";import { clearApplicationStorage } from "@posthog/ui/utils/clearStorage";import { useSubscription } from "@trpc/tanstack-react-query";import { useCallback, useEffect, useMemo, useRef } from "react";@@ -253,6 +254,8 @@ export function GlobalEventHandlers({[handleSwitchTask],);+ useEffect(() => installUncaughtErrorLogging(), []);+// Konami code confetticonst konamiProgressRef = useRef(0);useEffect(() => {diff --git a/products/desktop/packages/ui/src/shell/uncaughtErrorLog.test.ts b/products/desktop/packages/ui/src/shell/uncaughtErrorLog.test.tsnew file mode 100644index 000000000000..5594d7b658a7--- /dev/null+++ b/products/desktop/packages/ui/src/shell/uncaughtErrorLog.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it, vi } from "vitest";++const error = vi.hoisted(() => vi.fn());+vi.mock("@posthog/ui/shell/logger", () => ({+ logger: {+ scope: () => ({ error, warn: vi.fn(), info: vi.fn(), debug: vi.fn() }),+ },+}));++import { installUncaughtErrorLogging } from "./uncaughtErrorLog";++describe("installUncaughtErrorLogging", () => {+ afterEach(() => error.mockClear());++ it("mirrors uncaught errors into the host log, capped per minute", () => {+ const uninstall = installUncaughtErrorLogging();+ try {+ for (let i = 0; i < 25; i++) {+ window.dispatchEvent(+ new ErrorEvent("error", {+ message: `boom ${i}`,+ filename: "renderer.js",+ lineno: 1,+ colno: 2,+ error: new Error(`boom ${i}`),+ }),+ );+ }+ expect(error).toHaveBeenCalledTimes(20);+ expect(error).toHaveBeenCalledWith(+ "Uncaught renderer error",+ expect.objectContaining({+ message: "boom 0",+ source: "renderer.js:1:2",+ }),+ );+ } finally {+ uninstall();+ }+ });++ it("stops listening once uninstalled", () => {+ installUncaughtErrorLogging()();+ window.dispatchEvent(new ErrorEvent("error", { message: "late" }));+ expect(error).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/ui/src/shell/uncaughtErrorLog.ts b/products/desktop/packages/ui/src/shell/uncaughtErrorLog.tsnew file mode 100644index 000000000000..252372376b45--- /dev/null+++ b/products/desktop/packages/ui/src/shell/uncaughtErrorLog.ts@@ -0,0 +1,61 @@+import { logger } from "@posthog/ui/shell/logger";++const log = logger.scope("renderer");++/** A tight error loop must not turn the host log into a firehose. */+const MAX_LINES_PER_MINUTE = 20;++function describeReason(reason: unknown): { message: string; stack?: string } {+ if (reason instanceof Error) {+ return {+ message: `${reason.name}: ${reason.message}`,+ stack: reason.stack,+ };+ }+ if (typeof reason === "string") return { message: reason };+ try {+ return { message: JSON.stringify(reason) ?? String(reason) };+ } catch {+ return { message: String(reason) };+ }+}++/**+ * Mirrors uncaught renderer errors and unhandled rejections into the host log,+ * next to the session lifecycle lines they may explain. Error tracking already+ * receives them; the host log is what a user can hand over from a machine.+ */+export function installUncaughtErrorLogging(): () => void {+ let windowStartedAt = Date.now();+ let linesThisWindow = 0;++ const allow = (): boolean => {+ const now = Date.now();+ if (now - windowStartedAt >= 60_000) {+ windowStartedAt = now;+ linesThisWindow = 0;+ }+ linesThisWindow += 1;+ return linesThisWindow <= MAX_LINES_PER_MINUTE;+ };++ const onError = (event: ErrorEvent): void => {+ if (!allow()) return;+ log.error("Uncaught renderer error", {+ message: event.message,+ source: `${event.filename}:${event.lineno}:${event.colno}`,+ stack: event.error instanceof Error ? event.error.stack : undefined,+ });+ };+ const onRejection = (event: PromiseRejectionEvent): void => {+ if (!allow()) return;+ log.error("Unhandled renderer rejection", describeReason(event.reason));+ };++ window.addEventListener("error", onError);+ window.addEventListener("unhandledrejection", onRejection);+ return () => {+ window.removeEventListener("error", onError);+ window.removeEventListener("unhandledrejection", onRejection);+ };+}