: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
feat(desktop): add in-app feedback delivery (#95397)
Dylan Martin163c0cc81d8b
diff --git a/products/desktop/README.md b/products/desktop/README.mdindex 1599cb62e3ba..d9d5429b8b83 100644--- a/products/desktop/README.md+++ b/products/desktop/README.md@@ -3,7 +3,7 @@**[Download the latest version](https://github.com/PostHog/posthog/releases?q=desktop-v)**-Found a bug or want to share feedback? [Open an issue](https://github.com/PostHog/posthog/issues/new) on GitHub.+Found a bug or want to share feedback? Open the account menu in PostHog Desktop and select **Send feedback…**, or [open an issue](https://github.com/PostHog/posthog/issues/new) on GitHub.# PostHog Desktopdiff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex 333a39986eef..48fe1bc59d2f 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -129,6 +129,7 @@ import type { DEEP_LINK_SERVICE } from "@posthog/platform/deep-link";import type { DEV_HOST_ACTIONS_SERVICE } from "@posthog/platform/dev-host-actions";import type { DIALOG_SERVICE } from "@posthog/platform/dialog";import type { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";+import type { FEEDBACK_CONTEXT_SERVICE } from "@posthog/platform/feedback-context";import type { FILE_ICON_SERVICE } from "@posthog/platform/file-icon";import type { IMAGE_PROCESSOR_SERVICE } from "@posthog/platform/image-processor";import type { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";@@ -246,6 +247,7 @@ import type { ElectronContextMenu } from "../platform-adapters/electron-context-import type { ElectronCrypto } from "../platform-adapters/electron-crypto";import type { ElectronDevHostActions } from "../platform-adapters/electron-dev-host-actions";import type { ElectronDialog } from "../platform-adapters/electron-dialog";+import type { ElectronFeedbackContext } from "../platform-adapters/electron-feedback-context";import type { ElectronFileIcon } from "../platform-adapters/electron-file-icon";import type { ElectronImageProcessor } from "../platform-adapters/electron-image-processor";import type { ElectronMainWindow } from "../platform-adapters/electron-main-window";@@ -337,6 +339,7 @@ export interface MainBindings {[CLIPBOARD_SERVICE]: ElectronClipboard;[CRYPTO_SERVICE]: ElectronCrypto;[ANALYTICS_SERVICE]: IAnalytics;+ [FEEDBACK_CONTEXT_SERVICE]: ElectronFeedbackContext;[FILE_ICON_SERVICE]: ElectronFileIcon;[SECURE_STORAGE_SERVICE]: ElectronSecureStorage;[MAIN_WINDOW_SERVICE]: ElectronMainWindow;diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex 7a6de2dca4d2..f4f8e267d428 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -32,6 +32,7 @@ import {CONTEXT_MENU_EXTERNAL_APPS_SERVICE,} from "@posthog/core/context-menu/identifiers";import { CUSTOM_CLOUD_STORE } from "@posthog/core/custom-cloud/identifiers";+import { feedbackCoreModule } from "@posthog/core/feedback/feedback.module";import { FocusHostService } from "@posthog/core/focus/focus-service";import { FocusServiceEvent } from "@posthog/core/focus/identifiers";import { gitHostModule } from "@posthog/core/git/git-host.module";@@ -112,6 +113,7 @@ import { DEEP_LINK_SERVICE } from "@posthog/platform/deep-link";import { DEV_HOST_ACTIONS_SERVICE } from "@posthog/platform/dev-host-actions";import { DIALOG_SERVICE } from "@posthog/platform/dialog";import { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";+import { FEEDBACK_CONTEXT_SERVICE } from "@posthog/platform/feedback-context";import { FILE_ICON_SERVICE } from "@posthog/platform/file-icon";import { IMAGE_PROCESSOR_SERVICE } from "@posthog/platform/image-processor";import { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";@@ -248,6 +250,7 @@ import { ElectronCrypto } from "../platform-adapters/electron-crypto";import { ElectronCustomCloudStore } from "../platform-adapters/electron-custom-cloud-store";import { ElectronDevHostActions } from "../platform-adapters/electron-dev-host-actions";import { ElectronDialog } from "../platform-adapters/electron-dialog";+import { ElectronFeedbackContext } from "../platform-adapters/electron-feedback-context";import { ElectronFileIcon } from "../platform-adapters/electron-file-icon";import { ElectronImageProcessor } from "../platform-adapters/electron-image-processor";import { ElectronMainWindow } from "../platform-adapters/electron-main-window";@@ -359,6 +362,7 @@ container.bind(DIALOG_SERVICE).to(ElectronDialog);container.bind(CLIPBOARD_SERVICE).to(ElectronClipboard);container.bind(CRYPTO_SERVICE).to(ElectronCrypto);container.bind(ANALYTICS_SERVICE).toConstantValue(posthogNodeAnalytics);+container.bind(FEEDBACK_CONTEXT_SERVICE).to(ElectronFeedbackContext);container.bind(FILE_ICON_SERVICE).to(ElectronFileIcon);container.bind(SECURE_STORAGE_SERVICE).to(ElectronSecureStorage);container.bind(MAIN_WINDOW_SERVICE).to(ElectronMainWindow);@@ -420,6 +424,7 @@ container.toConstantValue(process.env.VITE_POSTHOG_ACCESS_TOKEN_OVERRIDE ?? null);container.bind(MAIN_AUTH_SERVICE).to(AuthService);container.bind(AUTH_SERVICE).toService(MAIN_AUTH_SERVICE);+container.load(feedbackCoreModule);container.load(authProxyModule);container.bind(AUTH_PROXY_AUTH).toDynamicValue((ctx) => ({authenticatedFetch: (url: string, init?: RequestInit) =>diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.test.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.test.tsnew file mode 100644index 000000000000..2fe5464fa46e--- /dev/null+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.test.ts@@ -0,0 +1,61 @@+import { afterEach, describe, expect, it, vi } from "vitest";++vi.mock("inversify", () => ({+ injectable: () => (target: unknown) => target,+ inject: () => () => undefined,+}));++vi.mock("@posthog/core/feedback/feedbackAttachmentService", () => ({+ FEEDBACK_SUBMISSION_SERVICE: Symbol.for(+ "posthog.core.feedback.submissionService",+ ),+}));++vi.mock("../utils/env", () => ({ getAppVersion: () => "1.2.3" }));++vi.mock("../utils/logger", () => ({+ getLogFilePath: () => "/tmp/posthog-desktop-test.log",+}));++import { ElectronFeedbackContext } from "./electron-feedback-context";++function makeContext(capturePage: () => Promise<unknown>) {+ const submissionService = { submitFeedback: vi.fn() };+ const mainWindow = {+ getBrowserWindow: () => ({ webContents: { capturePage } }),+ };+ return new ElectronFeedbackContext(+ submissionService as never,+ mainWindow as never,+ );+}++const jpegImage = {+ isEmpty: () => false,+ getSize: () => ({ width: 1_000, height: 800 }),+ resize: () => ({ toJPEG: () => Buffer.from("jpeg") }),+};++describe("ElectronFeedbackContext.captureScreenshot", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("returns the captured window as a JPEG data URL", async () => {+ const context = makeContext(() => Promise.resolve(jpegImage));++ await expect(context.captureScreenshot()).resolves.toBe(+ `data:image/jpeg;base64,${Buffer.from("jpeg").toString("base64")}`,+ );+ });++ it("gives up on a capture that never settles", async () => {+ vi.useFakeTimers();+ const context = makeContext(() => new Promise(() => {}));++ const pending = context.captureScreenshot();+ await vi.advanceTimersByTimeAsync(2_000);++ await expect(pending).resolves.toBeNull();+ });+});diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.tsnew file mode 100644index 000000000000..dcd5f7166b67--- /dev/null+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-feedback-context.ts@@ -0,0 +1,87 @@+import { open } from "node:fs/promises";+import {+ FEEDBACK_SUBMISSION_SERVICE,+ type IFeedbackSubmissionService,+} from "@posthog/core/feedback/feedbackAttachmentService";+import type {+ FeedbackSubmissionInput,+ IFeedbackContext,+} from "@posthog/platform/feedback-context";+import { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";+import { withTimeout } from "@posthog/shared";+import { inject, injectable } from "inversify";+import { getAppVersion } from "../utils/env";+import { getLogFilePath } from "../utils/logger";+import type { ElectronMainWindow } from "./electron-main-window";++const MAX_SCREENSHOT_BYTES = 240 * 1024;+const SCREENSHOT_DEADLINE_MS = 2_000;+const MAX_LOG_BYTES = 16 * 1024;++@injectable()+export class ElectronFeedbackContext implements IFeedbackContext {+ public constructor(+ @inject(FEEDBACK_SUBMISSION_SERVICE)+ private readonly submissionService: IFeedbackSubmissionService,+ @inject(MAIN_WINDOW_SERVICE)+ private readonly mainWindow: ElectronMainWindow,+ ) {}++ public async captureScreenshot(): Promise<string | null> {+ const browserWindow = this.mainWindow.getBrowserWindow();+ if (!browserWindow) return null;++ const capture = await withTimeout(+ browserWindow.webContents.capturePage(),+ SCREENSHOT_DEADLINE_MS,+ );+ if (capture.result === "timeout") return null;++ const captured = capture.value;+ if (captured.isEmpty()) return null;+ const size = captured.getSize();+ const widths = [1_200, 900, 720];+ const qualities = [65, 55, 45];++ for (let index = 0; index < widths.length; index += 1) {+ const resized = captured.resize({+ width: Math.min(size.width, widths[index]),+ });+ const jpeg = resized.toJPEG(qualities[index]);+ if (jpeg.byteLength <= MAX_SCREENSHOT_BYTES) {+ return `data:image/jpeg;base64,${jpeg.toString("base64")}`;+ }+ }++ return null;+ }++ public async readRecentLogs(): Promise<string | null> {+ let handle: Awaited<ReturnType<typeof open>> | undefined;+ try {+ handle = await open(getLogFilePath(), "r");+ const { size } = await handle.stat();+ if (size === 0) return null;++ const length = Math.min(size, MAX_LOG_BYTES);+ const buffer = Buffer.alloc(length);+ const { bytesRead } = await handle.read(buffer, 0, length, size - length);+ const content = buffer.subarray(0, bytesRead).toString("utf8");++ if (length === size) return content;+ const firstLineEnd = content.indexOf("\n");+ return firstLineEnd === -1 ? content : content.slice(firstLineEnd + 1);+ } catch {+ return null;+ } finally {+ if (handle) await handle.close().catch(() => undefined);+ }+ }++ public submitFeedback(input: FeedbackSubmissionInput): Promise<void> {+ return this.submissionService.submitFeedback({+ ...input,+ appVersion: getAppVersion(),+ });+ }+}diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.tsindex 012bc5c6fabf..b472921401e8 100644--- a/products/desktop/apps/code/src/main/trpc/router.ts+++ b/products/desktop/apps/code/src/main/trpc/router.ts@@ -21,6 +21,7 @@ import { diskCacheRouter } from "@posthog/host-router/routers/disk-cache.router"import { enrichmentRouter } from "@posthog/host-router/routers/enrichment.router";import { environmentRouter } from "@posthog/host-router/routers/environment.router";import { externalAppsRouter } from "@posthog/host-router/routers/external-apps.router";+import { feedbackContextRouter } from "@posthog/host-router/routers/feedback-context.router";import { fileWatcherRouter } from "@posthog/host-router/routers/file-watcher.router";import { focusRouter } from "@posthog/host-router/routers/focus.router";import { foldersRouter } from "@posthog/host-router/routers/folders.router";@@ -84,6 +85,7 @@ export const trpcRouter = router({environment: environmentRouter,encryption: encryptionRouter,externalApps: externalAppsRouter,+ feedbackContext: feedbackContextRouter,fileWatcher: fileWatcherRouter,focus: focusRouter,folders: foldersRouter,diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.tsindex 5f6a559787ac..3a98bb83c04f 100644--- a/products/desktop/apps/code/src/renderer/di/bindings.ts+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts@@ -157,6 +157,10 @@ import {DISK_CACHE_IMAGES,type IDiskCacheImages,} from "@posthog/platform/disk-cache";+import {+ FEEDBACK_CONTEXT_SERVICE,+ type IFeedbackContext,+} from "@posthog/platform/feedback-context";import {HOST_CAPABILITIES,type HostCapabilities,@@ -299,6 +303,7 @@ export interface RendererBindings {[HOST_LOGGER]: HostLogger;[TRPC_CLIENT]: TRPCClient<TrpcRouter>;[HOST_TRPC_CLIENT]: HostTrpcClient;+ [FEEDBACK_CONTEXT_SERVICE]: IFeedbackContext;[UPDATES_CLIENT]: UpdatesClient;[DEV_MODE_CLIENT]: DevModeClient;[CONNECTIVITY_CLIENT]: ConnectivityClient;diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.tsindex 43064268b738..6ebb873024f1 100644--- a/products/desktop/apps/code/src/renderer/di/container.ts+++ b/products/desktop/apps/code/src/renderer/di/container.ts@@ -90,6 +90,10 @@ import { HOST_TRPC_CLIENT } from "@posthog/host-router/client";import { TrpcCloudTaskClient } from "@posthog/host-router/cloud-task-client";import { TrpcPiRunner } from "@posthog/host-router/pi-runner";import { TrpcPiSessionFactory } from "@posthog/host-router/pi-session-factory";+import {+ FEEDBACK_CONTEXT_SERVICE,+ type IFeedbackContext,+} from "@posthog/platform/feedback-context";import {BROWSER_TABS_CLIENT,type BrowserTabsClient,@@ -181,6 +185,14 @@ container.bind<TRPCClient<TrpcRouter>>(TRPC_CLIENT).toConstantValue(trpcClient);container.bind(HOST_TRPC_CLIENT).toConstantValue(hostTrpcClient);+container.bind(FEEDBACK_CONTEXT_SERVICE).toConstantValue({+ captureScreenshot: () =>+ hostTrpcClient.feedbackContext.captureScreenshot.query(),+ readRecentLogs: () => hostTrpcClient.feedbackContext.readRecentLogs.query(),+ submitFeedback: (input) =>+ hostTrpcClient.feedbackContext.submitFeedback.mutate(input),+} satisfies IFeedbackContext);+container.bind(UPDATES_CLIENT).toConstantValue(updatesClient);// dev mode client — exposes the dev-toolbar flag store to the shared settings UIdiff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.tsindex cda0148dc29f..902e2f21f9b0 100644--- a/products/desktop/apps/web/src/web-container.ts+++ b/products/desktop/apps/web/src/web-container.ts@@ -56,6 +56,11 @@ import {type ExternalAppsFocusCoordinator,type ExternalAppsWorkspaceClient,} from "@posthog/core/external-apps/identifiers";+import { feedbackCoreModule } from "@posthog/core/feedback/feedback.module";+import {+ FEEDBACK_SUBMISSION_SERVICE,+ type IFeedbackSubmissionService,+} from "@posthog/core/feedback/feedbackAttachmentService";import {FILE_READ_CLIENT,type FileReadClient,@@ -181,6 +186,10 @@ import {ANALYTICS_SERVICE,type IAnalytics,} from "@posthog/platform/analytics";+import {+ FEEDBACK_CONTEXT_SERVICE,+ type IFeedbackContext,+} from "@posthog/platform/feedback-context";import {HOST_CAPABILITIES,type HostCapabilities,@@ -339,6 +348,7 @@ import { hostTrpcClient } from "./web-trpc";interface WebBindings {[HOST_TRPC_CLIENT]: HostTrpcClient;+ [FEEDBACK_CONTEXT_SERVICE]: IFeedbackContext;[PI_SESSION_PROVIDER]: PiSessionProvider;[LOCAL_PI_SESSION_FACTORY]: PiSessionFactory;[CLOUD_TASK_CLIENT]: CloudTaskClient;@@ -449,6 +459,15 @@ container.bind(HOST_LOGGER).toConstantValue(scoped());// machine-bound cipher, deep-link OAuth). Web runs the SAME service in the// browser over localStorage adapters and a popup PKCE flow.container.load(authCoreModule);+container.load(feedbackCoreModule);+container.bind(FEEDBACK_CONTEXT_SERVICE).toConstantValue({+ captureScreenshot: () => Promise.resolve(null),+ readRecentLogs: () => Promise.resolve(null),+ submitFeedback: (input) =>+ container+ .get<IFeedbackSubmissionService>(FEEDBACK_SUBMISSION_SERVICE)+ .submitFeedback(input),+});container.bind(AUTH_SESSION_STORE).toConstantValue(new WebAuthSessionStore());container.bind(AUTH_PREFERENCE_STORE)@@ -542,18 +561,11 @@ container.bind(IMPERATIVE_QUERY_CLIENT).toConstantValue(queryClient);container.bind(AUTH_SIDE_EFFECTS).to(WebAuthSideEffects);// Interactive MCP App iframe host. Electron isolates the proxy with a custom-// privileged scheme; web gets a separate origin for free via a blob URL of the-// same (host-agnostic) proxy HTML. The blob is created once, lazily.+// privileged scheme; web loads the same host-agnostic proxy HTML through a+// data URL. The iframe sandbox keeps it on an opaque origin.container.bind(MCP_APP_HOST_COMPONENT).toConstantValue(McpAppHost);-let sandboxProxyUrl: string | null = null;-container.bind(MCP_SANDBOX_PROXY_URL).toConstantValue(() => {- if (!sandboxProxyUrl) {- sandboxProxyUrl = URL.createObjectURL(- new Blob([sandboxProxyHtml], { type: "text/html" }),- );- }- return sandboxProxyUrl;-});+const sandboxProxyUrl = `data:text/html;charset=utf-8,${encodeURIComponent(sandboxProxyHtml)}`;+container.bind(MCP_SANDBOX_PROXY_URL).toConstantValue(() => sandboxProxyUrl);// ── Post-login shell: the tokens __root.tsx resolves eagerly via useService ──// The shared app shell (packages/ui __root.tsx) mounts the full desktop surfacediff --git a/products/desktop/docs/FEEDBACK.md b/products/desktop/docs/FEEDBACK.mdnew file mode 100644index 000000000000..2303dd05b120--- /dev/null+++ b/products/desktop/docs/FEEDBACK.md@@ -0,0 +1,14 @@+# Desktop feedback++People can select **Send feedback…** from the account menu, use the command menu, or press `Cmd+Shift+F` on macOS and `Ctrl+Shift+F` on other systems.+In the form, press `Cmd+Enter` or `Ctrl+Enter` to send feedback.++The form sends one authenticated request to the Desktop feedback endpoint. The endpoint records the response in the Desktop feedback survey only after it accepts the full submission. Each response includes the current view, app version, session, and related task or folder ID when available.++The app captures the current window before the form opens. The screenshot can be reviewed and stays off until selected. People can also attach up to two images. Recent app logs can be reviewed while they stay off, and are sent only when selected.++Selected screenshots and images are stored in PostHog's internal media project, not the project selected in Desktop. The survey response contains authenticated image links instead of image data. Only people with access to the internal feedback project can open them, and the public media route returns `404`. Links stop working after 30 days, and a daily cleanup removes the stored media. If the response fails, the endpoint removes the new media. The feedback modal is excluded from Session Replay, so previews and logs do not enter the recording.++The survey event keeps its normal session link, so authorized reviewers can inspect the app state before the modal opened.++The Signals surveys scout can review these responses. It groups open-text answers into recurring themes and files what it finds in the Signals inbox.diff --git a/products/desktop/docs/README.md b/products/desktop/docs/README.mdindex f68c94fc398e..b7368a68f17f 100644--- a/products/desktop/docs/README.md+++ b/products/desktop/docs/README.md@@ -23,6 +23,8 @@ Start with the guide that matches the work you are doing. [AGENTS.md](../AGENTS.## Feature references+- [Desktop feedback](./FEEDBACK.md)+| Guide | Use it for || --- | --- || [Inbox report states](./INBOX-REPORT-STATES.md) | Understand dismissal feedback and investigation status. |diff --git a/products/desktop/packages/core/src/feedback/feedback.module.ts b/products/desktop/packages/core/src/feedback/feedback.module.tsnew file mode 100644index 000000000000..909a7aa7d3d3--- /dev/null+++ b/products/desktop/packages/core/src/feedback/feedback.module.ts@@ -0,0 +1,10 @@+import {+ FEEDBACK_SUBMISSION_SERVICE,+ FeedbackSubmissionService,+} from "@posthog/core/feedback/feedbackAttachmentService";+import { ContainerModule } from "inversify";++export const feedbackCoreModule = new ContainerModule(({ bind }) => {+ bind(FeedbackSubmissionService).toSelf().inSingletonScope();+ bind(FEEDBACK_SUBMISSION_SERVICE).toService(FeedbackSubmissionService);+});diff --git a/products/desktop/packages/core/src/feedback/feedbackAttachmentService.test.ts b/products/desktop/packages/core/src/feedback/feedbackAttachmentService.test.tsnew file mode 100644index 000000000000..8e3395f26f0c--- /dev/null+++ b/products/desktop/packages/core/src/feedback/feedbackAttachmentService.test.ts@@ -0,0 +1,97 @@+import type { AuthService } from "@posthog/core/auth/auth";+import { describe, expect, it, vi } from "vitest";+import { FeedbackSubmissionService } from "./feedbackAttachmentService";++describe("FeedbackSubmissionService", () => {+ it("submits feedback and images through the authenticated feedback endpoint", async () => {+ const authenticatedFetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ accepted: true,+ response_id: "00000000-0000-0000-0000-000000000001",+ }),+ { status: 201, headers: { "Content-Type": "application/json" } },+ ),+ );+ const authService = {+ getValidAccessToken: vi+ .fn()+ .mockResolvedValue({ apiHost: "https://app.example.com" }),+ getState: vi.fn().mockReturnValue({ currentProjectId: 42 }),+ authenticatedFetch,+ } as unknown as AuthService;+ const service = new FeedbackSubmissionService(authService);++ await expect(+ service.submitFeedback({+ response: "The page did not load",+ source: "Generic (Leave feedback button)",+ feedbackView: "task-detail",+ feedbackTaskId: "task-123",+ appVersion: "1.2.3",+ screenshot: {+ name: "screenshot.jpg",+ dataUrl: "data:image/jpeg;base64,aGVsbG8=",+ },+ images: [+ {+ name: "state.png",+ dataUrl: "data:image/png;base64,aGVsbG8=",+ },+ ],+ }),+ ).resolves.toBeUndefined();++ const [, url, init] = authenticatedFetch.mock.calls[0];+ expect(url).toBe(+ "https://app.example.com/api/projects/42/desktop_feedback/",+ );+ expect(init).toMatchObject({ method: "POST" });+ const form = init.body as FormData;+ expect(form.get("response")).toBe("The page did not load");+ expect(form.get("feedback_task_id")).toBe("task-123");+ expect(form.get("app_version")).toBe("1.2.3");+ const image = form.get("image_1");+ expect(image).toBeInstanceOf(File);+ expect(image).toMatchObject({ name: "state.png", type: "image/png" });+ expect(form.get("screenshot")).toMatchObject({+ name: "screenshot.jpg",+ type: "image/jpeg",+ });+ });++ it.each([+ {+ response: new Response("unavailable", { status: 503 }),+ error: "Could not send feedback (503)",+ },+ {+ response: new Response(JSON.stringify({ accepted: false }), {+ status: 201,+ headers: { "Content-Type": "application/json" },+ }),+ error: "Feedback response was not accepted",+ },+ ])(+ "rejects when the server does not accept feedback",+ async ({ response, error }) => {+ const authService = {+ getValidAccessToken: vi+ .fn()+ .mockResolvedValue({ apiHost: "https://app.example.com" }),+ getState: vi.fn().mockReturnValue({ currentProjectId: 42 }),+ authenticatedFetch: vi.fn().mockResolvedValue(response),+ } as unknown as AuthService;+ const service = new FeedbackSubmissionService(authService);++ await expect(+ service.submitFeedback({+ response: "Example feedback",+ source: "Generic (Leave feedback button)",+ feedbackView: "home",+ images: [],+ }),+ ).rejects.toThrow(error);+ },+ );+});diff --git a/products/desktop/packages/core/src/feedback/feedbackAttachmentService.ts b/products/desktop/packages/core/src/feedback/feedbackAttachmentService.tsnew file mode 100644index 000000000000..d74e89549142--- /dev/null+++ b/products/desktop/packages/core/src/feedback/feedbackAttachmentService.ts@@ -0,0 +1,94 @@+import type { AuthService } from "@posthog/core/auth/auth";+import { AUTH_SERVICE } from "@posthog/core/auth/auth.module";+import type {+ FeedbackImageUpload,+ FeedbackSubmissionInput,+} from "@posthog/platform/feedback-context";+import { inject, injectable } from "inversify";++export const FEEDBACK_SUBMISSION_SERVICE = Symbol.for(+ "posthog.core.feedback.submissionService",+);++export interface IFeedbackSubmissionService {+ submitFeedback(+ input: FeedbackSubmissionInput & { appVersion?: string },+ ): Promise<void>;+}++function dataUrlToBlob(dataUrl: string): Blob {+ const match = /^data:(image\/(?:jpeg|png|webp));base64,(.+)$/.exec(dataUrl);+ if (!match) throw new Error("Unsupported feedback image");++ const decoded = atob(match[2]);+ const buffer = new ArrayBuffer(decoded.length);+ const bytes = new Uint8Array(buffer);+ for (let index = 0; index < decoded.length; index += 1) {+ bytes[index] = decoded.charCodeAt(index);+ }+ return new Blob([buffer], { type: match[1] });+}++@injectable()+export class FeedbackSubmissionService implements IFeedbackSubmissionService {+ public constructor(+ @inject(AUTH_SERVICE)+ private readonly authService: AuthService,+ ) {}++ public async submitFeedback(+ input: FeedbackSubmissionInput & { appVersion?: string },+ ): Promise<void> {+ const { apiHost } = await this.authService.getValidAccessToken();+ const projectId = this.authService.getState().currentProjectId;+ if (projectId === null) {+ throw new Error("Select a project before sending feedback");+ }+ const form = new FormData();+ form.append("response", input.response);+ form.append("source", input.source);+ form.append("feedback_view", input.feedbackView);+ if (input.feedbackTaskId) {+ form.append("feedback_task_id", input.feedbackTaskId);+ }+ if (input.feedbackFolderId) {+ form.append("feedback_folder_id", input.feedbackFolderId);+ }+ if (input.feedbackAppLogs) {+ form.append("feedback_app_logs", input.feedbackAppLogs);+ }+ if (input.appVersion) form.append("app_version", input.appVersion);+ if (input.sessionId) form.append("session_id", input.sessionId);+ if (input.screenshot) {+ appendImage(form, "screenshot", input.screenshot);+ }+ input.images.forEach((image, index) => {+ appendImage(form, `image_${index + 1}`, image);+ });++ const response = await this.authService.authenticatedFetch(+ fetch,+ `${apiHost}/api/projects/${projectId}/desktop_feedback/`,+ { method: "POST", body: form },+ );+ if (!response.ok) {+ throw new Error(`Could not send feedback (${response.status})`);+ }++ const payload = (await response.json()) as {+ accepted?: unknown;+ response_id?: unknown;+ };+ if (payload.accepted !== true || typeof payload.response_id !== "string") {+ throw new Error("Feedback response was not accepted");+ }+ }+}++function appendImage(+ form: FormData,+ field: string,+ image: FeedbackImageUpload,+): void {+ form.append(field, dataUrlToBlob(image.dataUrl), image.name);+}diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.tsindex 7cdbc6124152..d6d415bd1d51 100644--- a/products/desktop/packages/host-router/src/router.ts+++ b/products/desktop/packages/host-router/src/router.ts@@ -20,6 +20,7 @@ import { diskCacheRouter } from "./routers/disk-cache.router";import { enrichmentRouter } from "./routers/enrichment.router";import { environmentRouter } from "./routers/environment.router";import { externalAppsRouter } from "./routers/external-apps.router";+import { feedbackContextRouter } from "./routers/feedback-context.router";import { fileWatcherRouter } from "./routers/file-watcher.router";import { focusRouter } from "./routers/focus.router";import { foldersRouter } from "./routers/folders.router";@@ -74,6 +75,7 @@ export const hostRouter = router({enrichment: enrichmentRouter,environment: environmentRouter,externalApps: externalAppsRouter,+ feedbackContext: feedbackContextRouter,fileWatcher: fileWatcherRouter,focus: focusRouter,folders: foldersRouter,diff --git a/products/desktop/packages/host-router/src/routers/feedback-context.router.ts b/products/desktop/packages/host-router/src/routers/feedback-context.router.tsnew file mode 100644index 000000000000..7a988ecb7a7b--- /dev/null+++ b/products/desktop/packages/host-router/src/routers/feedback-context.router.ts@@ -0,0 +1,34 @@+import { publicProcedure, router } from "@posthog/host-trpc/trpc";+import {+ FEEDBACK_CONTEXT_SERVICE,+ type IFeedbackContext,+} from "@posthog/platform/feedback-context";+import {+ feedbackLogsOutput,+ feedbackScreenshotOutput,+ feedbackSubmissionInput,+} from "./feedback-context.schemas";++export const feedbackContextRouter = router({+ captureScreenshot: publicProcedure+ .output(feedbackScreenshotOutput)+ .query(({ ctx }) =>+ ctx.container+ .get<IFeedbackContext>(FEEDBACK_CONTEXT_SERVICE)+ .captureScreenshot(),+ ),+ readRecentLogs: publicProcedure+ .output(feedbackLogsOutput)+ .query(({ ctx }) =>+ ctx.container+ .get<IFeedbackContext>(FEEDBACK_CONTEXT_SERVICE)+ .readRecentLogs(),+ ),+ submitFeedback: publicProcedure+ .input(feedbackSubmissionInput)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<IFeedbackContext>(FEEDBACK_CONTEXT_SERVICE)+ .submitFeedback(input),+ ),+});diff --git a/products/desktop/packages/host-router/src/routers/feedback-context.schemas.ts b/products/desktop/packages/host-router/src/routers/feedback-context.schemas.tsnew file mode 100644index 000000000000..3cdc85cee800--- /dev/null+++ b/products/desktop/packages/host-router/src/routers/feedback-context.schemas.ts@@ -0,0 +1,25 @@+import { z } from "zod";++export const feedbackLogsOutput = z.string().max(20_000).nullable();++export const feedbackScreenshotOutput = z.string().max(350_000).nullable();++const feedbackImage = z.object({+ name: z.string().min(1).max(1_000),+ dataUrl: z+ .string()+ .max(350_000)+ .regex(/^data:image\/(?:jpeg|png|webp);base64,/),+});++export const feedbackSubmissionInput = z.object({+ response: z.string().trim().min(1).max(4_000),+ source: z.string().min(1).max(100),+ feedbackView: z.string().min(1).max(100),+ feedbackTaskId: z.string().max(100).optional(),+ feedbackFolderId: z.string().max(100).optional(),+ feedbackAppLogs: z.string().max(20_000).optional(),+ sessionId: z.uuid().optional(),+ screenshot: feedbackImage.optional(),+ images: z.array(feedbackImage).max(2),+});diff --git a/products/desktop/packages/platform/package.json b/products/desktop/packages/platform/package.jsonindex 7f5b6ff85a36..137e029d2def 100644--- a/products/desktop/packages/platform/package.json+++ b/products/desktop/packages/platform/package.json@@ -36,6 +36,10 @@"types": "./dist/file-icon.d.ts","import": "./dist/file-icon.js"},+ "./feedback-context": {+ "types": "./dist/feedback-context.d.ts",+ "import": "./dist/feedback-context.js"+ },"./secure-storage": {"types": "./dist/secure-storage.d.ts","import": "./dist/secure-storage.js"diff --git a/products/desktop/packages/platform/src/feedback-context.ts b/products/desktop/packages/platform/src/feedback-context.tsnew file mode 100644index 000000000000..4f6f76ecf196--- /dev/null+++ b/products/desktop/packages/platform/src/feedback-context.ts@@ -0,0 +1,26 @@+export interface FeedbackImageUpload {+ name: string;+ dataUrl: string;+}++export interface FeedbackSubmissionInput {+ response: string;+ source: string;+ feedbackView: string;+ feedbackTaskId?: string;+ feedbackFolderId?: string;+ feedbackAppLogs?: string;+ sessionId?: string;+ screenshot?: FeedbackImageUpload;+ images: FeedbackImageUpload[];+}++export interface IFeedbackContext {+ captureScreenshot(): Promise<string | null>;+ readRecentLogs(): Promise<string | null>;+ submitFeedback(input: FeedbackSubmissionInput): Promise<void>;+}++export const FEEDBACK_CONTEXT_SERVICE = Symbol.for(+ "posthog.platform.feedbackContext",+);diff --git a/products/desktop/packages/platform/tsup.config.ts b/products/desktop/packages/platform/tsup.config.tsindex 05315800e4e8..68701038a65a 100644--- a/products/desktop/packages/platform/tsup.config.ts+++ b/products/desktop/packages/platform/tsup.config.ts@@ -9,6 +9,7 @@ export default defineConfig({"src/dialog.ts","src/clipboard.ts","src/file-icon.ts",+ "src/feedback-context.ts","src/secure-storage.ts","src/main-window.ts","src/app-lifecycle.ts",diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex ddf78ed3da5f..46f381b289b3 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -74,6 +74,7 @@ export type CommandMenuAction =| "open-loops"| "open-usage"| "open-cost-management"+ | "send-feedback"| "search-files"| "open-file"| "reload-window"diff --git a/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsxindex 2d045cab52e0..7fe9b456833f 100644--- a/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx+++ b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx@@ -69,11 +69,12 @@ describe("agents page selection", () => {});});- it("drops the agent when returning to a page tab", () =>+ it("drops the agent when returning to a page tab", () => {+ agentsPageActions().showTab("memory");expect(- (agentsPageActions().showTab("memory"),- lastSearch({ from: "/activity", agent: "a", agentTab: "output" })),- ).toEqual({ from: "/activity", tab: "memory" }));+ lastSearch({ from: "/activity", agent: "a", agentTab: "output" }),+ ).toEqual({ from: "/activity", tab: "memory" });+ });it("replaces the entry when switching the agent's own tab", () => {agentsPageActions().showAgentTab("settings");diff --git a/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.test.tsxdeleted file mode 100644index 3eba16d4e612..000000000000--- a/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.test.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { Theme } from "@radix-ui/themes";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { beforeEach, describe, expect, it, vi } from "vitest";--const { captureSurveyResponse, layout } = vi.hoisted(() => ({- captureSurveyResponse: vi.fn(),- layout: { enabled: false },-}));--vi.mock("@posthog/ui/shell/analytics", () => ({ captureSurveyResponse }));-vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({- useChannelsLayout: () => layout.enabled,-}));--import { FeedbackModal, type FeedbackModalMode } from "./FeedbackModal";--function renderModal(mode: FeedbackModalMode | null, onFinished = vi.fn()) {- render(- <Theme>- <FeedbackModal mode={mode} onFinished={onFinished} />- </Theme>,- );- return onFinished;-}--describe("FeedbackModal", () => {- beforeEach(() => {- captureSurveyResponse.mockReset();- layout.enabled = false;- });-- it("uses the Spaces prompt when the layout is enabled", () => {- layout.enabled = true;- renderModal("feedback");- expect(screen.getByText(/How's the Spaces experience/)).toBeInTheDocument();- });-- it.each([- { mode: "posthog-web" as const, expected: "Skip", missing: "Cancel" },- { mode: "feedback" as const, expected: "Cancel", missing: "Skip" },- ])(- "shows the $expected secondary button in $mode mode",- ({ mode, expected, missing }) => {- renderModal(mode);- expect(- screen.getByRole("button", { name: expected }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: missing }),- ).not.toBeInTheDocument();- },- );-- it("disables submit until text is entered", async () => {- const user = userEvent.setup();- renderModal("feedback");- const submit = screen.getByRole("button", { name: "Send feedback" });- // The quill Button signals disabled state via aria-disabled, not the native attr.- expect(submit).toHaveAttribute("aria-disabled", "true");-- await user.type(screen.getByPlaceholderText("Share your feedback"), "hi");- expect(submit).not.toHaveAttribute("aria-disabled", "true");- });-- it("captures the trimmed response with its source and finishes on submit", async () => {- const user = userEvent.setup();- const onFinished = renderModal("posthog-web");-- await user.type(- screen.getByPlaceholderText("Share your feedback"),- " great work ",- );- await user.click(screen.getByRole("button", { name: "Send feedback" }));-- expect(captureSurveyResponse).toHaveBeenCalledTimes(1);- expect(captureSurveyResponse).toHaveBeenCalledWith(- expect.objectContaining({- responses: [- expect.objectContaining({ response: "great work" }),- expect.objectContaining({ response: "Visiting PostHog web" }),- ],- }),- );- expect(onFinished).toHaveBeenCalledTimes(1);- });-- it("finishes without capturing when skipped", async () => {- const user = userEvent.setup();- const onFinished = renderModal("posthog-web");-- await user.click(screen.getByRole("button", { name: "Skip" }));-- expect(captureSurveyResponse).not.toHaveBeenCalled();- expect(onFinished).toHaveBeenCalledTimes(1);- });-});diff --git a/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.tsx b/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.tsxdeleted file mode 100644index 06563214fa4d..000000000000--- a/products/desktop/packages/ui/src/features/canvas/components/FeedbackModal.tsx+++ /dev/null@@ -1,141 +0,0 @@-import {- Button,- Dialog,- DialogBody,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- Textarea,-} from "@posthog/quill";-import {- FEEDBACK_SOURCE_BY_MODE,- FEEDBACK_SURVEY_ID,- FEEDBACK_SURVEY_QUESTION_ID,- FEEDBACK_SURVEY_SOURCE_QUESTION_ID,-} from "@posthog/ui/features/canvas/feedbackSurvey";-import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";-import { captureSurveyResponse } from "@posthog/ui/shell/analytics";-import { useState } from "react";--export type FeedbackModalMode = "feedback" | "posthog-web";--/** Title + prompt shown for each way the modal can be opened. */-const MODAL_COPY: Record<FeedbackModalMode, { title: string; prompt: string }> =- {- feedback: {- title: "Leave feedback",- prompt:- "How's the Channels experience? Tell us what's working and what you'd change.",- },- "posthog-web": {- title: "Before you head to PostHog web",- prompt: "Why are you going back to PostHog web?",- },- };--export interface FeedbackModalProps {- /** `null` closes the modal. `"feedback"` shows a Cancel button; the navigation-intercept mode (`"posthog-web"`) shows a Skip button. */- mode: FeedbackModalMode | null;- /** Called after the response is submitted, and when the modal is skipped/cancelled/dismissed. */- onFinished: () => void;-}--/**- * Feedback modal for the Channels space. Submitting records the text as a- * PostHog survey response (see {@link FEEDBACK_SURVEY_ID}) along with where the- * modal was opened from. The secondary button reads "Skip" when the modal- * intercepts a navigation (`"posthog-web"`) and "Cancel" when opened directly- * by "Leave feedback".- */-export function FeedbackModal({ mode, onFinished }: FeedbackModalProps) {- const open = mode !== null;- const spacesLayout = useChannelsLayout();- const prompt =- mode === "feedback" && spacesLayout- ? "How's the Spaces experience? Tell us what's working and what you'd change."- : mode- ? MODAL_COPY[mode].prompt- : "";-- return (- <Dialog- open={open}- onOpenChange={(isOpen) => {- // Esc / outside-click dismiss behaves like the secondary button.- if (!isOpen) onFinished();- }}- >- <DialogContent showCloseButton={false} className="sm:max-w-md">- <DialogHeader>- <DialogTitle>{mode ? MODAL_COPY[mode].title : ""}</DialogTitle>- {/* The prompt is the question we want answered, so render it at full- contrast rather than the muted default. */}- <DialogDescription className="text-base text-gray-12">- {prompt}- </DialogDescription>- </DialogHeader>- {/* Mounted only while open so the textarea resets on each open without- syncing state to the `mode` prop in an effect. */}- {mode !== null && (- <FeedbackModalForm mode={mode} onFinished={onFinished} />- )}- </DialogContent>- </Dialog>- );-}--function FeedbackModalForm({- mode,- onFinished,-}: {- mode: FeedbackModalMode;- onFinished: () => void;-}) {- const [value, setValue] = useState("");-- const handleSubmit = () => {- const response = value.trim();- if (!response) return;- captureSurveyResponse({- surveyId: FEEDBACK_SURVEY_ID,- responses: [- { questionId: FEEDBACK_SURVEY_QUESTION_ID, response },- {- questionId: FEEDBACK_SURVEY_SOURCE_QUESTION_ID,- response: FEEDBACK_SOURCE_BY_MODE[mode],- },- ],- });- onFinished();- };-- return (- <>- <DialogBody>- <Textarea- value={value}- onChange={(event) => setValue(event.target.value)}- placeholder="Share your feedback"- rows={4}- maxLength={4000}- autoFocus- />- </DialogBody>- <DialogFooter>- <Button variant="outline" size="sm" onClick={onFinished}>- {mode === "feedback" ? "Cancel" : "Skip"}- </Button>- <Button- variant="primary"- size="sm"- disabled={value.trim().length === 0}- onClick={handleSubmit}- >- Send feedback- </Button>- </DialogFooter>- </>- );-}diff --git a/products/desktop/packages/ui/src/features/canvas/feedbackSurvey.ts b/products/desktop/packages/ui/src/features/canvas/feedbackSurvey.tsdeleted file mode 100644index 77941bf786e0..000000000000--- a/products/desktop/packages/ui/src/features/canvas/feedbackSurvey.ts+++ /dev/null@@ -1,23 +0,0 @@-// PostHog survey backing the Channels "Leave feedback" modal. Created via the-// MCP in project 2 ("PostHog App + Website") and launched so it collects-// responses. Responses are sent client-side as a `survey sent` event and only-// attach to this survey if the app reports to the same project.-// https://us.posthog.com/project/2/surveys/019ee235-2e3b-0000-64b3-5f2efa487452-export const FEEDBACK_SURVEY_ID = "019ee235-2e3b-0000-64b3-5f2efa487452";--// Open-text question: "How's the Channels experience? What would you change?".-export const FEEDBACK_SURVEY_QUESTION_ID =- "68648b23-caaf-4080-ae5f-051513d3097f";--// Single-choice question recording where the feedback was submitted from. The-// submitted response string must match one of the survey's choices exactly —-// see FEEDBACK_SOURCE_BY_MODE.-export const FEEDBACK_SURVEY_SOURCE_QUESTION_ID =- "e4560a6b-3eab-4c61-a731-8d0c10dd1b7d";--// Maps the modal's open reason to the source question's choice label. Values-// MUST stay in sync with the survey's single_choice options.-export const FEEDBACK_SOURCE_BY_MODE = {- feedback: "Generic (Leave feedback button)",- "posthog-web": "Visiting PostHog web",-} as const;diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsxindex 44216aaf826e..924b5c2b65e1 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx@@ -149,6 +149,42 @@ describe("CommandMenu feed queries", () => {expect(await screen.findByText("Save search", { selector: "h2" }),).toBeTruthy();+ expect(+ screen.getByPlaceholderText(/Search commands and tasks/),+ ).toHaveValue("");+ });++ it("clears the query after a save closes the palette", async () => {+ const user = userEvent.setup();+ const onOpenChange = vi.fn();+ const { rerender } = render(+ <Theme>+ <CommandMenu open onOpenChange={onOpenChange} />+ </Theme>,+ );++ await user.type(+ screen.getByPlaceholderText(/Search commands and tasks/),+ "created-by:@me ",+ );+ await user.keyboard("{Meta>}s{/Meta}");+ expect(onOpenChange).toHaveBeenCalledWith(false);++ // The parent owns `open`, so the Dialog never runs its own close handler.+ rerender(+ <Theme>+ <CommandMenu open={false} onOpenChange={onOpenChange} />+ </Theme>,+ );+ rerender(+ <Theme>+ <CommandMenu open onOpenChange={onOpenChange} />+ </Theme>,+ );++ expect(+ await screen.findByPlaceholderText(/Search commands and tasks/),+ ).toHaveValue("");});it("shows a selected command in the recent section", async () => {diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.tsxindex ce194ee37464..8b4e16a35d60 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx@@ -4,6 +4,7 @@ import {CaretLeftIcon,CaretRightIcon,ChartLineIcon,+ ChatCircleDotsIcon,CubeIcon,DesktopIcon,EnvelopeSimpleIcon,@@ -106,6 +107,7 @@ import { useSearchRows } from "@posthog/ui/features/command/useSearchRows";import { useTaskSearch } from "@posthog/ui/features/command/useTaskSearch";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useInboxAvailable } from "@posthog/ui/features/feature-flags/useInboxAvailable";+import { useFeedbackStore } from "@posthog/ui/features/feedback/feedbackStore";import { useFolders } from "@posthog/ui/features/folders/useFolders";import { useProvisioningStore } from "@posthog/ui/features/provisioning/store";import {@@ -246,6 +248,7 @@ function PaletteQueryMirror({);}+// oxlint-disable-next-line react-doctor/no-giant-component -- This PR only adds the feedback command.export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {const spacesLayout = useChannelsLayout();const openSettingsDialog = openSettings;@@ -261,6 +264,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {const openBrowserTab = useOpenBrowserTab();const { theme, setTheme } = useThemeStore();const toggleLeftSidebar = useSidebarStore((state) => state.toggle);+ const openFeedback = useFeedbackStore((state) => state.open);const view = useAppView();const setReviewMode = useReviewNavigationStore((state) => state.setReviewMode,@@ -337,13 +341,24 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {});useEffect(() => {- if (open) {- track(ANALYTICS_EVENTS.COMMAND_MENU_OPENED);- } else {- setQuery("");- }+ if (open) track(ANALYTICS_EVENTS.COMMAND_MENU_OPENED);}, [open]);+ const handleOpenChange = useCallback(+ (nextOpen: boolean) => {+ if (!nextOpen) setQuery("");+ onOpenChange(nextOpen);+ },+ [onOpenChange],+ );++ // The Dialog is not the only thing that closes the palette, so every internal+ // close path goes through here and gets the same query reset.+ const closeMenu = useCallback(+ () => handleOpenChange(false),+ [handleOpenChange],+ );+const themeOptions = useMemo<Command[]>(() => {const options: Command[] = [];if (theme !== "light") {@@ -537,6 +552,15 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {shortcut: SHORTCUTS.TOGGLE_LEFT_SIDEBAR,onRun: toggleLeftSidebar,},+ {+ id: "send-feedback",+ label: "Send feedback",+ keywords: "report issue bug screenshot logs",+ icon: <ChatCircleDotsIcon size={12} className="text-gray-11" />,+ action: "send-feedback",+ shortcut: SHORTCUTS.SEND_FEEDBACK,+ onRun: () => openFeedback(),+ },...(reviewTaskId? [{@@ -683,6 +707,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {openSettingsDialog,closeSettingsDialog,toggleLeftSidebar,+ openFeedback,openReviewPanel,reviewTaskId,openedTask,@@ -812,10 +837,10 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {const [feedModalQuery, setFeedModalQuery] = useState<string | null>(null);const onSaveAsFeed = useCallback((feedQuery: string) => {- onOpenChange(false);+ closeMenu();setFeedModalQuery(feedQuery);},- [onOpenChange],+ [closeMenu],);const [caret, setCaret] = useState(0);@@ -941,15 +966,17 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {(command) => currentCommands.get(command.id) ?? command,);const recentIds = new Set(recentItems.map((command) => command.id));- return [- { label: "Recent", items: recentItems },- ...baseSections- .map((section) => ({- ...section,- items: section.items.filter((command) => !recentIds.has(command.id)),- }))- .filter((section) => section.items.length > 0),- ];+ const remainingSections = baseSections.reduce<CommandSection[]>(+ (sections, section) => {+ const items = section.items.filter(+ (command) => !recentIds.has(command.id),+ );+ if (items.length > 0) sections.push({ ...section, items });+ return sections;+ },+ [],+ );+ return [{ label: "Recent", items: recentItems }, ...remainingSections];}, [baseSections, query, recentCommands]);const paletteFilter = useCallback(@@ -979,8 +1006,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {channel_id: cmd.channelId,});openBrowserTab(cmd.href);- onOpenChange(false);- setQuery("");+ closeMenu();return true;};@@ -998,8 +1024,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {}cmd.onRun();if (cmd.keepOpen) return;- onOpenChange(false);- setQuery("");+ closeMenu();};const onInputKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {@@ -1040,7 +1065,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {return (<>- <Dialog open={open} onOpenChange={onOpenChange}>+ <Dialog open={open} onOpenChange={handleOpenChange}><DialogContentclassName="w-[720px] max-w-[90vw] gap-0 p-0"showCloseButton={false}diff --git a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.tsindex 419f3bee6928..c921faf283a1 100644--- a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts+++ b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts@@ -14,6 +14,7 @@ export const SHORTCUTS = {NEW_TAB: "mod+t",SETTINGS: "mod+,",SHORTCUTS_SHEET: "mod+/",+ SEND_FEEDBACK: "mod+shift+f",GO_BACK: "mod+[",GO_FORWARD: "mod+]",// Arrow variants must stay outside form fields/editors, where mod+left/right@@ -111,6 +112,12 @@ export const KEYBOARD_SHORTCUTS: KeyboardShortcut[] = [description: "Show keyboard shortcuts",category: "general",},+ {+ id: "send-feedback",+ keys: SHORTCUTS.SEND_FEEDBACK,+ description: "Send feedback",+ category: "general",+ },{id: "zoom-in",keys: SHORTCUTS.ZOOM_IN,diff --git a/products/desktop/packages/ui/src/features/feedback/FeedbackAttachments.tsx b/products/desktop/packages/ui/src/features/feedback/FeedbackAttachments.tsxnew file mode 100644index 000000000000..4d5592fb8f52--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/FeedbackAttachments.tsx@@ -0,0 +1,362 @@+import { Eye, Paperclip } from "@phosphor-icons/react";+import type { IFeedbackContext } from "@posthog/platform/feedback-context";+import {+ Button,+ Checkbox,+ Field,+ FieldLabel,+ Text,+ Textarea,+} from "@posthog/quill";+import { toast } from "@posthog/ui/primitives/toast";+import {+ type ChangeEvent,+ type Dispatch,+ type ReactNode,+ type SetStateAction,+ useRef,+ useState,+} from "react";+import {+ type FeedbackImage,+ MAX_FEEDBACK_IMAGE_COUNT,+ readFeedbackImage,+} from "./feedbackImages";++export interface FeedbackAttachmentsValue {+ includeScreenshot: boolean;+ includeLogs: boolean;+ logs: string | null;+ images: FeedbackImage[];+ logsLoading: boolean;+ imagesLoading: boolean;+}++interface FeedbackAttachmentsProps {+ screenshot: string | null;+ value: FeedbackAttachmentsValue;+ onChange: Dispatch<SetStateAction<FeedbackAttachmentsValue>>;+ contextClient: IFeedbackContext;+}++function AttachmentRow({ children }: { children: ReactNode }) {+ return (+ <div className="flex min-h-8 min-w-0 items-center justify-between gap-3">+ {children}+ </div>+ );+}++function AttachmentPreviewButton({+ isVisible,+ label,+ dataAttr,+ onClick,+}: {+ isVisible: boolean;+ label: string;+ dataAttr: string;+ onClick: () => void;+}) {+ return (+ <Button+ variant="link-muted"+ size="xs"+ aria-label={`${isVisible ? "Hide" : "View"} ${label}`}+ data-attr={dataAttr}+ onPointerUp={(event) => event.currentTarget.blur()}+ onClick={onClick}+ >+ <Eye size={14} />+ {isVisible ? "Hide" : "View"}+ </Button>+ );+}++export function FeedbackAttachments({+ screenshot,+ value,+ onChange,+ contextClient,+}: FeedbackAttachmentsProps) {+ const [visibleAttachment, setVisibleAttachment] = useState<+ "screenshot" | "logs" | "images" | null+ >(null);+ const [logsUnavailable, setLogsUnavailable] = useState(false);+ const imageInputRef = useRef<HTMLInputElement>(null);+ const logsRequestRef = useRef(0);++ const loadLogs = async (+ includeWhenLoaded: boolean,+ ): Promise<string | null> => {+ const requestId = ++logsRequestRef.current;+ onChange((current) => ({+ ...current,+ includeLogs: includeWhenLoaded ? true : current.includeLogs,+ logsLoading: true,+ }));+ setLogsUnavailable(false);+ try {+ const recentLogs = await contextClient.readRecentLogs().catch(() => null);+ if (logsRequestRef.current !== requestId) return null;+ onChange((current) => ({+ ...current,+ includeLogs: includeWhenLoaded+ ? recentLogs !== null+ : current.includeLogs,+ logs: recentLogs,+ }));+ setLogsUnavailable(!recentLogs);+ return recentLogs;+ } finally {+ if (logsRequestRef.current === requestId) {+ onChange((current) => ({ ...current, logsLoading: false }));+ }+ }+ };++ const handleIncludeLogsChange = async (checked: boolean) => {+ if (!checked) {+ logsRequestRef.current += 1;+ onChange((current) => ({+ ...current,+ includeLogs: false,+ logsLoading: false,+ }));+ return;+ }++ if (value.logs) {+ onChange((current) => ({ ...current, includeLogs: true }));+ return;+ }++ await loadLogs(true);+ };++ const handleToggleLogsPreview = async () => {+ if (visibleAttachment === "logs") {+ setVisibleAttachment(null);+ return;+ }++ if (!value.logs && !(await loadLogs(false))) return;+ setVisibleAttachment("logs");+ };++ const handleImageSelect = async (event: ChangeEvent<HTMLInputElement>) => {+ const selectedFiles = Array.from(event.currentTarget.files ?? []);+ event.currentTarget.value = "";+ const availableSlots = MAX_FEEDBACK_IMAGE_COUNT - value.images.length;+ if (selectedFiles.length > availableSlots) {+ toast.warning(`You can attach up to ${MAX_FEEDBACK_IMAGE_COUNT} images.`);+ }++ onChange((current) => ({ ...current, imagesLoading: true }));+ try {+ const nextImages = await Promise.all(+ selectedFiles.slice(0, availableSlots).map(async (file) => {+ try {+ return await readFeedbackImage(file);+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Could not attach this image.",+ );+ return null;+ }+ }),+ );+ onChange((current) => ({+ ...current,+ images: [+ ...current.images,+ ...nextImages.filter(+ (image): image is FeedbackImage =>+ image !== null &&+ !current.images.some((existing) => existing.id === image.id),+ ),+ ].slice(0, MAX_FEEDBACK_IMAGE_COUNT),+ }));+ } finally {+ onChange((current) => ({ ...current, imagesLoading: false }));+ }+ };++ return (+ <div className="mt-1 flex flex-col border-gray-6 border-y py-1">+ <AttachmentRow>+ <Field orientation="horizontal" className="min-w-0 items-center gap-2">+ <Checkbox+ id="feedback-include-screenshot"+ data-attr="desktop-feedback-include-screenshot"+ checked={value.includeScreenshot}+ disabled={!screenshot}+ onCheckedChange={(checked) => {+ onChange((current) => ({+ ...current,+ includeScreenshot: checked === true,+ }));+ if (!checked && visibleAttachment === "screenshot") {+ setVisibleAttachment(null);+ }+ }}+ />+ <FieldLabel+ htmlFor="feedback-include-screenshot"+ className="font-normal"+ >+ {screenshot+ ? "Include screenshot of this window"+ : "Screenshot unavailable"}+ </FieldLabel>+ </Field>+ {screenshot && (+ <AttachmentPreviewButton+ isVisible={visibleAttachment === "screenshot"}+ label="screenshot"+ dataAttr="desktop-feedback-view-screenshot"+ onClick={() =>+ setVisibleAttachment((current) =>+ current === "screenshot" ? null : "screenshot",+ )+ }+ />+ )}+ </AttachmentRow>+ {screenshot && visibleAttachment === "screenshot" && (+ <div className="mb-2 ml-6 flex min-w-0 flex-col rounded border border-gray-6 p-2">+ <img+ src={screenshot}+ alt="App screenshot captured before this dialog opened"+ className="max-h-72 w-full rounded object-contain"+ data-ph-mask+ />+ </div>+ )}++ <AttachmentRow>+ <Field orientation="horizontal" className="min-w-0 items-center gap-2">+ <Checkbox+ id="feedback-include-logs"+ data-attr="desktop-feedback-include-logs"+ checked={value.includeLogs}+ onCheckedChange={(checked) =>+ void handleIncludeLogsChange(checked === true)+ }+ />+ <FieldLabel htmlFor="feedback-include-logs" className="font-normal">+ Include recent app logs+ </FieldLabel>+ </Field>+ <AttachmentPreviewButton+ isVisible={visibleAttachment === "logs"}+ label="app logs"+ dataAttr="desktop-feedback-view-logs"+ onClick={() => void handleToggleLogsPreview()}+ />+ </AttachmentRow>+ <Text size="xxs" variant="muted" className="mb-1 ml-6">+ Logs can contain file paths or personal data.+ </Text>+ {logsUnavailable && (+ <Text size="xxs" variant="muted" className="mb-1 ml-6">+ No recent app logs found.+ </Text>+ )}+ {value.logs && visibleAttachment === "logs" && (+ <div className="mb-2 ml-6 flex min-w-0 flex-col rounded border border-gray-6 p-2">+ <Textarea+ value={value.logs}+ readOnly+ rows={5}+ className="h-64 min-h-64 resize-none overflow-auto font-mono text-[11px] leading-4 [field-sizing:fixed]"+ aria-label="Recent app logs"+ />+ </div>+ )}++ <input+ ref={imageInputRef}+ type="file"+ accept="image/jpeg,image/png,image/webp"+ multiple+ aria-label="Choose feedback images"+ className="hidden"+ onChange={(event) => void handleImageSelect(event)}+ />+ <div className="mt-2">+ <AttachmentRow>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="xs"+ loading={value.imagesLoading}+ disabled={value.images.length >= MAX_FEEDBACK_IMAGE_COUNT}+ data-attr="desktop-feedback-attach-images"+ onClick={() => imageInputRef.current?.click()}+ >+ <Paperclip size={14} />+ Attach images+ </Button>+ {value.images.length > 0 && (+ <Text size="xxs" variant="muted">+ {value.images.length} attached+ </Text>+ )}+ </div>+ {value.images.length > 0 && (+ <AttachmentPreviewButton+ isVisible={visibleAttachment === "images"}+ label="attached images"+ dataAttr="desktop-feedback-view-images"+ onClick={() =>+ setVisibleAttachment((current) =>+ current === "images" ? null : "images",+ )+ }+ />+ )}+ </AttachmentRow>+ </div>+ {visibleAttachment === "images" && value.images.length > 0 && (+ <div className="mb-2 ml-6 grid min-w-0 grid-cols-2 gap-2">+ {value.images.map((image) => (+ <div+ key={image.id}+ className="flex min-w-0 flex-col gap-1 rounded border border-gray-6 p-2"+ >+ <img+ src={image.dataUrl}+ alt={`Attachment ${image.name}`}+ className="h-40 w-full rounded object-contain"+ />+ <div className="flex min-w-0 items-center justify-between gap-2">+ <Text size="xxs" className="truncate">+ {image.name}+ </Text>+ <Button+ variant="link-muted"+ size="xs"+ aria-label={`Remove ${image.name}`}+ data-attr="desktop-feedback-remove-image"+ onClick={() =>+ onChange((current) => ({+ ...current,+ images: current.images.filter(+ (item) => item.id !== image.id,+ ),+ }))+ }+ >+ Remove+ </Button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/feedback/FeedbackHost.tsx b/products/desktop/packages/ui/src/features/feedback/FeedbackHost.tsxnew file mode 100644index 000000000000..315a5d36d9af--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/FeedbackHost.tsx@@ -0,0 +1,21 @@+import { useService } from "@posthog/di/react";+import {+ FEEDBACK_CONTEXT_SERVICE,+ type IFeedbackContext,+} from "@posthog/platform/feedback-context";+import { FeedbackModal } from "@posthog/ui/features/feedback/FeedbackModal";+import { useFeedbackStore } from "@posthog/ui/features/feedback/feedbackStore";++export function FeedbackHost() {+ const mode = useFeedbackStore((state) => state.mode);+ const finishFeedback = useFeedbackStore((state) => state.finish);+ const contextClient = useService<IFeedbackContext>(FEEDBACK_CONTEXT_SERVICE);++ return (+ <FeedbackModal+ mode={mode}+ onFinished={finishFeedback}+ contextClient={contextClient}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/feedback/FeedbackModal.stories.tsx b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.stories.tsxnew file mode 100644index 000000000000..6e33ab3e8002--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.stories.tsx@@ -0,0 +1,105 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { within } from "storybook/test";+import { FeedbackModal } from "./FeedbackModal";++async function createStoryScreenshot(): Promise<string> {+ const canvas = document.createElement("canvas");+ canvas.width = 800;+ canvas.height = 450;+ const context = canvas.getContext("2d");+ if (!context) return "data:image/jpeg;base64,";+ context.fillStyle = "#1d1f24";+ context.fillRect(0, 0, 800, 450);+ context.fillStyle = "#292c33";+ context.fillRect(24, 24, 180, 402);+ context.fillRect(228, 24, 548, 72);+ context.fillRect(228, 120, 548, 306);+ return canvas.toDataURL("image/jpeg", 0.7);+}++const meta = {+ title: "Feedback/Desktop feedback modal",+ component: FeedbackModal,+ args: {+ mode: "feedback",+ onFinished: () => {},+ contextClient: {+ captureScreenshot: createStoryScreenshot,+ readRecentLogs: () => Promise.resolve("[info] Example app log"),+ submitFeedback: () => Promise.resolve(),+ },+ },+} satisfies Meta<typeof FeedbackModal>;++export default meta;+type Story = StoryObj<typeof meta>;++const LONG_LOGS = Array.from(+ { length: 80 },+ (_, index) =>+ `[info] Example app operation ${index + 1} completed successfully`,+).join("\n");++export const Default: Story = {};++export const WithExpandedScreenshot: Story = {+ play: async ({ canvasElement, userEvent }) => {+ const dialog = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ await dialog.findByRole("button", { name: "View screenshot" }),+ );+ },+};++export const WithLogsLoading: Story = {+ args: {+ contextClient: {+ captureScreenshot: createStoryScreenshot,+ readRecentLogs: () => new Promise<string | null>(() => {}),+ submitFeedback: () => Promise.resolve(),+ },+ },+ play: async ({ canvasElement, userEvent }) => {+ const dialog = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ dialog.getByRole("checkbox", { name: "Include recent app logs" }),+ );+ },+};++export const WithAttachments: Story = {+ play: async ({ canvasElement, userEvent }) => {+ const dialog = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ dialog.getByRole("checkbox", { name: "Include recent app logs" }),+ );+ const imageBlob = await (await fetch(await createStoryScreenshot())).blob();+ await userEvent.upload(+ dialog.getByLabelText("Choose feedback images"),+ new File([imageBlob], "feedback-example.jpg", {+ type: "image/jpeg",+ }),+ );+ await dialog.findByText("1 attached");+ },+};++export const WithExpandedLogs: Story = {+ args: {+ contextClient: {+ captureScreenshot: createStoryScreenshot,+ readRecentLogs: () => Promise.resolve(LONG_LOGS),+ submitFeedback: () => Promise.resolve(),+ },+ },+ play: async ({ canvasElement, userEvent }) => {+ const dialog = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ await dialog.findByRole("button", { name: "View app logs" }),+ );+ },+};++export const BeforePostHogWeb: Story = {+ args: { mode: "posthog-web" },+};diff --git a/products/desktop/packages/ui/src/features/feedback/FeedbackModal.test.tsx b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.test.tsxnew file mode 100644index 000000000000..3fb05ccd764b--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.test.tsx@@ -0,0 +1,275 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { captureException, getAnalyticsSessionId, toastError, toastSuccess } =+ vi.hoisted(() => ({+ captureException: vi.fn(),+ getAnalyticsSessionId: vi.fn(),+ toastError: vi.fn(),+ toastSuccess: vi.fn(),+ }));++vi.mock("@posthog/ui/shell/analytics", () => ({+ captureException,+ getAnalyticsSessionId,+}));+vi.mock("@posthog/ui/primitives/toast", () => ({+ toast: { error: toastError, success: toastSuccess, warning: vi.fn() },+}));+vi.mock("@posthog/ui/router/useAppView", () => ({+ getAppViewSnapshot: () => ({ type: "task-detail", taskId: "task-123" }),+}));++import { FeedbackModal, type FeedbackModalMode } from "./FeedbackModal";++const readRecentLogs = vi.fn<() => Promise<string | null>>();+const captureScreenshot = vi.fn<() => Promise<string | null>>();+const submitFeedback = vi.fn<() => Promise<void>>();++async function renderModal(+ mode: FeedbackModalMode | null,+ onFinished = vi.fn(),+) {+ render(+ <FeedbackModal+ mode={mode}+ onFinished={onFinished}+ contextClient={{ captureScreenshot, readRecentLogs, submitFeedback }}+ />,+ );+ if (mode !== null) await screen.findByRole("dialog");+ return onFinished;+}++describe("FeedbackModal", () => {+ beforeEach(() => {+ vi.stubGlobal(+ "createImageBitmap",+ vi.fn().mockResolvedValue({ width: 2, height: 2, close: vi.fn() }),+ );+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({+ fillStyle: "",+ fillRect: vi.fn(),+ drawImage: vi.fn(),+ } as unknown as CanvasRenderingContext2D);+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation(+ (callback) => callback(new Blob(["re-encoded"], { type: "image/jpeg" })),+ );+ captureException.mockReset();+ getAnalyticsSessionId.mockReset();+ getAnalyticsSessionId.mockReturnValue(+ "00000000-0000-0000-0000-000000000001",+ );+ readRecentLogs.mockReset();+ readRecentLogs.mockResolvedValue("[info] Example log");+ captureScreenshot.mockReset();+ captureScreenshot.mockResolvedValue(+ "data:image/jpeg;base64,c2NyZWVuc2hvdA==",+ );+ submitFeedback.mockReset();+ submitFeedback.mockResolvedValue();+ toastError.mockReset();+ toastSuccess.mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("asks for specific Desktop feedback", async () => {+ await renderModal("feedback");+ expect(+ screen.getByText("What should we improve in PostHog Desktop?"),+ ).toBeInTheDocument();+ expect(+ screen.getByPlaceholderText("What happened, and what did you expect?"),+ ).toBeInTheDocument();+ });++ it("keeps the dialog out of session replay", async () => {+ await renderModal("feedback");+ expect(screen.getByRole("dialog")).toHaveClass("ph-no-capture");+ });++ it.each([+ { mode: "posthog-web" as const, expected: "Skip", missing: "Cancel" },+ { mode: "feedback" as const, expected: "Cancel", missing: "Skip" },+ ])(+ "shows the $expected secondary button in $mode mode",+ async ({ mode, expected, missing }) => {+ await renderModal(mode);+ expect(+ screen.getByRole("button", { name: expected }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: missing }),+ ).not.toBeInTheDocument();+ },+ );++ it("disables submit until text is entered", async () => {+ const user = userEvent.setup();+ await renderModal("feedback");+ const submit = screen.getByRole("button", { name: "Send feedback" });+ expect(submit).toBeDisabled();++ await user.type(+ screen.getByPlaceholderText("What happened, and what did you expect?"),+ "hi",+ );+ expect(submit).toBeEnabled();+ });++ it("submits the response with its source and page context", async () => {+ const user = userEvent.setup();+ const onFinished = await renderModal("feedback");+ const logsCheckbox = screen.getByRole("checkbox", {+ name: "Include recent app logs",+ });++ expect(logsCheckbox).not.toBeChecked();+ await user.click(screen.getByRole("button", { name: "View app logs" }));+ expect(await screen.findByLabelText("Recent app logs")).toHaveValue(+ "[info] Example log",+ );+ expect(logsCheckbox).not.toBeChecked();++ await user.type(+ screen.getByPlaceholderText("What happened, and what did you expect?"),+ " improve search ",+ );+ await user.keyboard("{Meta>}{Enter}{/Meta}");++ expect(submitFeedback).toHaveBeenCalledWith({+ response: "improve search",+ source: "Generic (Leave feedback button)",+ feedbackView: "task-detail",+ feedbackTaskId: "task-123",+ sessionId: "00000000-0000-0000-0000-000000000001",+ images: [],+ });+ expect(toastSuccess).toHaveBeenCalledWith("Feedback sent");+ expect(onFinished).toHaveBeenCalledTimes(1);+ });++ it("sends selected logs, screenshot, and images together", async () => {+ const user = userEvent.setup();+ await renderModal("feedback");++ expect(readRecentLogs).not.toHaveBeenCalled();+ expect(captureScreenshot).toHaveBeenCalledTimes(1);+ expect(+ screen.getByRole("checkbox", {+ name: "Include screenshot of this window",+ }),+ ).not.toBeChecked();+ await user.click(+ screen.getByRole("checkbox", {+ name: "Include screenshot of this window",+ }),+ );+ let resolveLogs: (value: string | null) => void = () => {};+ readRecentLogs.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveLogs = resolve;+ }),+ );+ const logsCheckbox = screen.getByRole("checkbox", {+ name: "Include recent app logs",+ });+ await user.click(logsCheckbox);+ expect(readRecentLogs).toHaveBeenCalledTimes(1);+ expect(logsCheckbox).toBeChecked();+ expect(logsCheckbox).toBeEnabled();+ expect(+ screen.queryByText("Loading recent app logs"),+ ).not.toBeInTheDocument();+ resolveLogs("[info] Example log");+ await screen.findByRole("button", { name: "View app logs" });++ const image = new File(["image bytes"], "feedback.png", {+ type: "image/png",+ });+ await user.upload(screen.getByLabelText("Choose feedback images"), image);+ expect(await screen.findByText("1 attached")).toBeInTheDocument();++ await user.type(+ screen.getByPlaceholderText("What happened, and what did you expect?"),+ "The page did not load",+ );+ await user.click(screen.getByRole("button", { name: "Send feedback" }));++ await waitFor(() => expect(submitFeedback).toHaveBeenCalled());+ expect(submitFeedback).toHaveBeenCalledWith(+ expect.objectContaining({+ feedbackAppLogs: "[info] Example log",+ screenshot: {+ name: "posthog-desktop-screenshot.jpg",+ dataUrl: "data:image/jpeg;base64,c2NyZWVuc2hvdA==",+ },+ images: [+ expect.objectContaining({+ name: "feedback.png",+ dataUrl: expect.stringMatching(/^data:image\/jpeg;base64,/),+ }),+ ],+ }),+ );+ });++ it("does not add logs after they are unchecked while loading", async () => {+ const user = userEvent.setup();+ let resolveLogs: (value: string | null) => void = () => {};+ readRecentLogs.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveLogs = resolve;+ }),+ );+ await renderModal("feedback");++ const logsCheckbox = screen.getByRole("checkbox", {+ name: "Include recent app logs",+ });+ await user.click(logsCheckbox);+ await user.click(logsCheckbox);+ resolveLogs("[info] Example log");++ await waitFor(() => expect(logsCheckbox).not.toBeChecked());+ expect(+ screen.getByRole("button", { name: "View app logs" }),+ ).toBeInTheDocument();+ });++ it("finishes without capturing when skipped", async () => {+ const user = userEvent.setup();+ const onFinished = await renderModal("posthog-web");+ await user.click(screen.getByRole("button", { name: "Skip" }));+ expect(submitFeedback).not.toHaveBeenCalled();+ expect(onFinished).toHaveBeenCalledTimes(1);+ });++ it("keeps the form open when the server does not accept feedback", async () => {+ const user = userEvent.setup();+ const onFinished = await renderModal("feedback");+ submitFeedback.mockRejectedValue(new Error("Unavailable"));++ await user.type(+ screen.getByPlaceholderText("What happened, and what did you expect?"),+ "Example feedback",+ );+ await user.click(screen.getByRole("button", { name: "Send feedback" }));++ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith(+ "Could not send feedback. Try again.",+ ),+ );+ expect(toastSuccess).not.toHaveBeenCalled();+ expect(onFinished).not.toHaveBeenCalled();+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/feedback/FeedbackModal.tsx b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.tsxnew file mode 100644index 000000000000..c9c66821b589--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/FeedbackModal.tsx@@ -0,0 +1,247 @@+import type { IFeedbackContext } from "@posthog/platform/feedback-context";+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Kbd,+ Text,+ Textarea,+} from "@posthog/quill";+import { formatHotkey } from "@posthog/ui/features/command/keyboard-shortcuts";+import { FEEDBACK_SOURCE_BY_MODE } from "@posthog/ui/features/feedback/feedbackSurvey";+import { toast } from "@posthog/ui/primitives/toast";+import { getAppViewSnapshot } from "@posthog/ui/router/useAppView";+import {+ captureException,+ getAnalyticsSessionId,+} from "@posthog/ui/shell/analytics";+import { useEffect, useState } from "react";+import {+ FeedbackAttachments,+ type FeedbackAttachmentsValue,+} from "./FeedbackAttachments";+import type { FeedbackModalMode } from "./feedbackStore";++export type { FeedbackModalMode } from "./feedbackStore";++const MODAL_COPY: Record<+ FeedbackModalMode,+ { title: string; description?: string; placeholder: string }+> = {+ feedback: {+ title: "What should we improve in PostHog Desktop?",+ placeholder: "What happened, and what did you expect?",+ },+ "posthog-web": {+ title: "Before you head to PostHog web",+ description: "Why are you going back to PostHog web?",+ placeholder: "What are you looking for in PostHog web?",+ },+};++export interface FeedbackModalProps {+ mode: FeedbackModalMode | null;+ onFinished: () => void;+ contextClient: IFeedbackContext;+}++export function FeedbackModal({+ mode,+ onFinished,+ contextClient,+}: FeedbackModalProps) {+ const open = mode !== null;+ const copy = mode ? MODAL_COPY[mode] : null;+ const [capturedScreenshot, setCapturedScreenshot] = useState<{+ mode: FeedbackModalMode;+ dataUrl: string | null;+ } | null>(null);++ useEffect(() => {+ if (mode !== "feedback") return;+ let active = true;+ setCapturedScreenshot(null);+ void contextClient+ .captureScreenshot()+ .catch(() => null)+ .then((dataUrl) => {+ if (active) setCapturedScreenshot({ mode, dataUrl });+ });+ return () => {+ active = false;+ };+ }, [mode, contextClient]);++ if (+ mode === "feedback" &&+ (!capturedScreenshot || capturedScreenshot.mode !== mode)+ ) {+ return null;+ }++ const handleFinished = () => {+ setCapturedScreenshot(null);+ onFinished();+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(isOpen) => {+ if (!isOpen) handleFinished();+ }}+ >+ <DialogContent+ showCloseButton={false}+ className="ph-no-capture sm:max-w-lg"+ >+ <DialogHeader>+ <DialogTitle>{copy?.title ?? ""}</DialogTitle>+ {copy?.description && (+ <DialogDescription>{copy.description}</DialogDescription>+ )}+ </DialogHeader>+ {mode !== null && (+ <FeedbackModalForm+ mode={mode}+ onFinished={handleFinished}+ contextClient={contextClient}+ initialScreenshot={capturedScreenshot?.dataUrl ?? null}+ />+ )}+ </DialogContent>+ </Dialog>+ );+}++function FeedbackModalForm({+ mode,+ onFinished,+ contextClient,+ initialScreenshot,+}: {+ mode: FeedbackModalMode;+ onFinished: () => void;+ contextClient: IFeedbackContext;+ initialScreenshot: string | null;+}) {+ const [value, setValue] = useState("");+ const [view] = useState(getAppViewSnapshot);+ const [submitting, setSubmitting] = useState(false);+ const [attachments, setAttachments] = useState<FeedbackAttachmentsValue>({+ includeScreenshot: false,+ includeLogs: false,+ logs: null,+ images: [],+ logsLoading: false,+ imagesLoading: false,+ });+ const canSubmit =+ value.trim().length > 0 &&+ !submitting &&+ !attachments.logsLoading &&+ !attachments.imagesLoading;++ const handleSubmit = async () => {+ const response = value.trim();+ if (!canSubmit || !response) return;+ setSubmitting(true);+ try {+ const includeScreenshot =+ attachments.includeScreenshot && initialScreenshot !== null;+ const sessionId = getAnalyticsSessionId();+ await contextClient.submitFeedback({+ response,+ source: FEEDBACK_SOURCE_BY_MODE[mode],+ feedbackView: view.type,+ ...(view.taskId ? { feedbackTaskId: view.taskId } : {}),+ ...(view.folderId ? { feedbackFolderId: view.folderId } : {}),+ ...(attachments.includeLogs && attachments.logs+ ? { feedbackAppLogs: attachments.logs }+ : {}),+ ...(sessionId ? { sessionId } : {}),+ ...(includeScreenshot && initialScreenshot+ ? {+ screenshot: {+ name: "posthog-desktop-screenshot.jpg",+ dataUrl: initialScreenshot,+ },+ }+ : {}),+ images: attachments.images,+ });+ toast.success("Feedback sent");+ onFinished();+ } catch (error) {+ captureException(+ error instanceof Error ? error : new Error("Could not send feedback"),+ { feedback_stage: "submission" },+ );+ toast.error("Could not send feedback. Try again.");+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <>+ <DialogBody>+ <div className="flex flex-col gap-3">+ <Textarea+ value={value}+ onChange={(event) => setValue(event.target.value)}+ placeholder={MODAL_COPY[mode].placeholder}+ rows={4}+ maxLength={4000}+ autoFocus+ className="focus-visible:shadow-none"+ aria-keyshortcuts="Meta+Enter Control+Enter"+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void handleSubmit();+ }+ }}+ />+ {mode === "feedback" && (+ <>+ <Text size="xxs" variant="muted" className="mt-1">+ Always included: app version and current page.+ </Text>+ <FeedbackAttachments+ screenshot={initialScreenshot}+ value={attachments}+ onChange={setAttachments}+ contextClient={contextClient}+ />+ </>+ )}+ </div>+ </DialogBody>+ <DialogFooter className="border-t-0">+ <Button variant="outline" size="sm" onClick={onFinished}>+ {mode === "feedback" ? "Cancel" : "Skip"}+ </Button>+ <Button+ variant={canSubmit ? "primary" : "outline"}+ size="sm"+ loading={submitting}+ focusableWhenDisabled={false}+ disabled={!canSubmit}+ aria-label="Send feedback"+ onClick={() => void handleSubmit()}+ >+ Send feedback+ <Kbd aria-hidden="true" className="ml-1">+ {formatHotkey("mod+enter")}+ </Kbd>+ </Button>+ </DialogFooter>+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/feedback/feedbackImages.ts b/products/desktop/packages/ui/src/features/feedback/feedbackImages.tsnew file mode 100644index 000000000000..87fca2dbd30e--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/feedbackImages.ts@@ -0,0 +1,82 @@+const MAX_FEEDBACK_IMAGE_INPUT_BYTES = 10 * 1024 * 1024;+const MAX_FEEDBACK_IMAGE_BYTES = 160 * 1024;+const FEEDBACK_IMAGE_WIDTHS = [1_200, 900, 720];+const FEEDBACK_IMAGE_QUALITIES = [0.7, 0.55, 0.4];+const SUPPORTED_IMAGE_TYPES = new Set([+ "image/jpeg",+ "image/png",+ "image/webp",+]);++export const MAX_FEEDBACK_IMAGE_COUNT = 2;++export interface FeedbackImage {+ id: string;+ name: string;+ dataUrl: string;+}++function blobToDataUrl(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ if (typeof reader.result === "string") {+ resolve(reader.result);+ } else {+ reject(new Error("Could not read this image."));+ }+ };+ reader.onerror = () => reject(new Error("Could not read this image."));+ reader.readAsDataURL(blob);+ });+}++function canvasToBlob(+ canvas: HTMLCanvasElement,+ quality: number,+): Promise<Blob | null> {+ return new Promise((resolve) => {+ canvas.toBlob(resolve, "image/jpeg", quality);+ });+}++async function resizeImage(file: File): Promise<string> {+ const bitmap = await createImageBitmap(file);+ try {+ for (let index = 0; index < FEEDBACK_IMAGE_WIDTHS.length; index += 1) {+ const scale = Math.min(1, FEEDBACK_IMAGE_WIDTHS[index] / bitmap.width);+ const canvas = document.createElement("canvas");+ canvas.width = Math.max(1, Math.round(bitmap.width * scale));+ canvas.height = Math.max(1, Math.round(bitmap.height * scale));+ const context = canvas.getContext("2d");+ if (!context) break;+ context.fillStyle = "#ffffff";+ context.fillRect(0, 0, canvas.width, canvas.height);+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);++ const blob = await canvasToBlob(canvas, FEEDBACK_IMAGE_QUALITIES[index]);+ if (blob && blob.size <= MAX_FEEDBACK_IMAGE_BYTES) {+ return blobToDataUrl(blob);+ }+ }+ } finally {+ bitmap.close();+ }++ throw new Error("Could not resize this image. Try a smaller file.");+}++export async function readFeedbackImage(file: File): Promise<FeedbackImage> {+ if (!SUPPORTED_IMAGE_TYPES.has(file.type)) {+ throw new Error("Choose a JPEG, PNG, or WebP image.");+ }+ if (file.size > MAX_FEEDBACK_IMAGE_INPUT_BYTES) {+ throw new Error("Choose an image smaller than 10 MB.");+ }++ return {+ id: `${file.name}:${file.size}:${file.lastModified}`,+ name: file.name,+ dataUrl: await resizeImage(file),+ };+}diff --git a/products/desktop/packages/ui/src/features/feedback/feedbackStore.test.ts b/products/desktop/packages/ui/src/features/feedback/feedbackStore.test.tsnew file mode 100644index 000000000000..d064afef4e95--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/feedbackStore.test.ts@@ -0,0 +1,19 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useFeedbackStore } from "./feedbackStore";++describe("feedbackStore", () => {+ beforeEach(() => {+ useFeedbackStore.setState({ mode: null, onFinished: null });+ });++ it("keeps the active flow when another entry point opens feedback", () => {+ const onFinished = vi.fn();+ useFeedbackStore.getState().open("posthog-web", onFinished);++ useFeedbackStore.getState().open();++ expect(useFeedbackStore.getState().mode).toBe("posthog-web");+ useFeedbackStore.getState().finish();+ expect(onFinished).toHaveBeenCalledOnce();+ });+});diff --git a/products/desktop/packages/ui/src/features/feedback/feedbackStore.ts b/products/desktop/packages/ui/src/features/feedback/feedbackStore.tsnew file mode 100644index 000000000000..fcc410590f58--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/feedbackStore.ts@@ -0,0 +1,24 @@+import { create } from "zustand";++export type FeedbackModalMode = "feedback" | "posthog-web";++interface FeedbackState {+ mode: FeedbackModalMode | null;+ onFinished: (() => void) | null;+ open: (mode?: FeedbackModalMode, onFinished?: () => void) => void;+ finish: () => void;+}++export const useFeedbackStore = create<FeedbackState>((set, get) => ({+ mode: null,+ onFinished: null,+ open: (mode = "feedback", onFinished) =>+ set((state) =>+ state.mode ? state : { mode, onFinished: onFinished ?? null },+ ),+ finish: () => {+ const onFinished = get().onFinished;+ set({ mode: null, onFinished: null });+ onFinished?.();+ },+}));diff --git a/products/desktop/packages/ui/src/features/feedback/feedbackSurvey.ts b/products/desktop/packages/ui/src/features/feedback/feedbackSurvey.tsnew file mode 100644index 000000000000..7d6056392d65--- /dev/null+++ b/products/desktop/packages/ui/src/features/feedback/feedbackSurvey.ts@@ -0,0 +1,4 @@+export const FEEDBACK_SOURCE_BY_MODE = {+ feedback: "Generic (Leave feedback button)",+ "posthog-web": "Visiting PostHog web",+} as const;diff --git a/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx b/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsxindex a30ad2e2c330..1a331691574d 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx@@ -2,6 +2,7 @@ import {Archive,ArrowSquareOut,Buildings,+ ChatCircleDots,DiscordLogo,FolderSimple,Gear,@@ -45,6 +46,11 @@ import {} from "@posthog/ui/features/auth/useAuthMutations";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";+import {+ formatHotkey,+ SHORTCUTS,+} from "@posthog/ui/features/command/keyboard-shortcuts";+import { useFeedbackStore } from "@posthog/ui/features/feedback/feedbackStore";import { useProjects } from "@posthog/ui/features/projects/useProjects";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import type { SettingsCategory } from "@posthog/ui/features/settings/types";@@ -73,12 +79,12 @@ interface ProjectSwitcherProps {onNavigateToSettings?: (category: SettingsCategory) => void;}-/** The account / project / org menu. */export function ProjectSwitcher({appearance = "row",onNavigateToSettings,}: ProjectSwitcherProps = {}) {const [popoverOpen, setPopoverOpen] = useState(false);+ const openFeedback = useFeedbackStore((state) => state.open);const trackMenu = (action: ProjectMenuAction,@@ -241,6 +247,11 @@ export function ProjectSwitcher({setPopoverOpen(false);};+ const handleFeedback = () => {+ setPopoverOpen(false);+ openFeedback();+ };+const handleLogout = () => {trackMenu("log_out");setPopoverOpen(false);@@ -384,6 +395,14 @@ export function ProjectSwitcher({View changelog</DropdownMenuItem>+ <DropdownMenuItem onClick={handleFeedback}>+ <ChatCircleDots size={14} className="text-gray-11" />+ Send feedback…+ <DropdownMenuShortcut>+ {formatHotkey(SHORTCUTS.SEND_FEEDBACK)}+ </DropdownMenuShortcut>+ </DropdownMenuItem>+<DropdownMenuSub><DropdownMenuSubTrigger><Info size={14} className="text-gray-11" />diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsxindex 7ca4fb2f6aeb..254cd0bb184d 100644--- a/products/desktop/packages/ui/src/router/routes/__root.tsx+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx@@ -21,10 +21,6 @@ import { isBluebirdOnlyPath } from "@posthog/ui/features/canvas/bluebirdRoutes";import { ChannelHotkeys } from "@posthog/ui/features/canvas/components/ChannelHotkeys";import { ChannelRouteSync } from "@posthog/ui/features/canvas/components/ChannelRouteSync";import { ChannelsSidebar } from "@posthog/ui/features/canvas/components/ChannelsSidebar";-import {- FeedbackModal,- type FeedbackModalMode,-} from "@posthog/ui/features/canvas/components/FeedbackModal";import { NavRail } from "@posthog/ui/features/canvas/components/NavRail";import { CanvasConnectorPermissionDialog } from "@posthog/ui/features/canvas/freeform/CanvasConnectorPermissionDialog";import { useCanvasDeepLink } from "@posthog/ui/features/canvas/hooks/useCanvasDeepLink";@@ -43,6 +39,7 @@ import { useNewTaskDeepLink } from "@posthog/ui/features/deep-links/useNewTaskDeimport { useOpenTargetDeepLink } from "@posthog/ui/features/deep-links/useOpenTargetDeepLink";import { useTaskDeepLink } from "@posthog/ui/features/deep-links/useTaskDeepLink";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";+import { useFeedbackStore } from "@posthog/ui/features/feedback/feedbackStore";import { useInboxDeepLink } from "@posthog/ui/features/inbox/hooks/useInboxDeepLink";import { useIntegrations } from "@posthog/ui/features/integrations/useIntegrations";import { useLoopDeepLink } from "@posthog/ui/features/loops/hooks/useLoopDeepLink";@@ -144,11 +141,6 @@ function RootLayout() {}, [router]);const canGoForward = historyIndex < newestIndex;- // Feedback modal shown as an intercept before "PostHog Web" opens the web- // app, routing once the modal is submitted or skipped.- const [feedbackMode, setFeedbackMode] = useState<FeedbackModalMode | null>(- null,- );const currentProjectId = useAuthStateValue((s) => s.currentProjectId);// The user's current project on the correct cloud (region comes from@@ -166,27 +158,20 @@ function RootLayout() {const markPostHogWebFeedbackSeen = usePostHogWebFeedbackStore((s) => s.markSeen,);-- // "PostHog Web" opens the feedback modal first and performs its navigation- // only once the modal is submitted or skipped.- const handleFeedbackFinished = () => {- const finishedMode = feedbackMode;- setFeedbackMode(null);- if (finishedMode === "posthog-web" && posthogWebUrl) {- markPostHogWebFeedbackSeen();- void openUrlInBrowser(posthogWebUrl);- }- };+ const openFeedback = useFeedbackStore((s) => s.open);const handleOpenPostHogWeb = () => {track(ANALYTICS_EVENTS.POSTHOG_WEB_OPENED);- // Only skip the intercept once the persisted flag has hydrated, so a stale- // pre-hydration default can't wrongly re-show it.if (posthogWebFeedbackHydrated && posthogWebFeedbackSeen && posthogWebUrl) {void openUrlInBrowser(posthogWebUrl);return;}- setFeedbackMode("posthog-web");+ if (posthogWebUrl) {+ openFeedback("posthog-web", () => {+ markPostHogWebFeedbackSeen();+ void openUrlInBrowser(posthogWebUrl);+ });+ }};const {isOpen: commandMenuOpen,@@ -514,10 +499,6 @@ function RootLayout() {<AnnouncementsHost /><WhatsNewModal /><RemoteBranchCheckoutDialog />- <FeedbackModal- mode={feedbackMode}- onFinished={handleFeedbackFinished}- /><ExistingWorktreeDialog /><CanvasConnectorPermissionDialog /><HedgehogMode />diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex e5a62cf22bf9..12e806385eff 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -21,6 +21,7 @@ import { useSpaceTreeStore } from "@posthog/ui/features/canvas/stores/spaceTreeSimport { ConsentScreen } from "@posthog/ui/features/consent/ConsentScreen";import { useConsentAnalytics } from "@posthog/ui/features/consent/consentAnalytics";import { useOrgConsent } from "@posthog/ui/features/consent/useOrgConsent";+import { FeedbackHost } from "@posthog/ui/features/feedback/FeedbackHost";import { AddDirectoryDialog } from "@posthog/ui/features/folder-picker/AddDirectoryDialog";import { ErrorDetailsDialog } from "@posthog/ui/features/notifications/ErrorDetailsDialog";import { OnboardingFlow } from "@posthog/ui/features/onboarding/components/OnboardingFlow";@@ -145,7 +146,9 @@ function App({ devToolbar }: AppProps) {// Read through a ref so a flag arriving mid-startup cannot re-run the resolve and replace// a route the user has already moved off.const spacesLayoutEnabledRef = useRef(spacesLayoutEnabled);- spacesLayoutEnabledRef.current = spacesLayoutEnabled;+ useEffect(() => {+ spacesLayoutEnabledRef.current = spacesLayoutEnabled;+ }, [spacesLayoutEnabled]);const readyForMainApp =isBootstrapped &&@@ -338,6 +341,7 @@ function App({ devToolbar }: AppProps) {<AddDirectoryDialog /><ErrorDetailsDialog /><UpdateAvailableModal />+ {isAuthenticated && <FeedbackHost />}</div>{devToolbar}</div>diff --git a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsxindex 61904d6fb6a8..b861c18d8e05 100644--- a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx+++ b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx@@ -16,6 +16,7 @@ import { useReviewNavigationStore } from "@posthog/ui/features/code-review/revieimport { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useInboxAvailable } from "@posthog/ui/features/feature-flags/useInboxAvailable";+import { useFeedbackStore } from "@posthog/ui/features/feedback/feedbackStore";import { useFolders } from "@posthog/ui/features/folders/useFolders";import { toggleRightPanel } from "@posthog/ui/features/navigation/rightPanelSide";import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";@@ -49,7 +50,13 @@ interface GlobalEventHandlersProps {visualTaskOrder: TaskData[];}-export function GlobalEventHandlers({+const GLOBAL_HOTKEY_OPTIONS = {+ enableOnFormTags: true,+ enableOnContentEditable: true,+ preventDefault: true,+} as const;++function useGlobalEventHandlers({allTasks,onToggleCommandMenu,onToggleShortcutsSheet,@@ -61,6 +68,7 @@ export function GlobalEventHandlers({PI_SESSION_CONTROLLER,);const commandMenuOpen = useCommandMenuStore((s) => s.isOpen);+ const openFeedback = useFeedbackStore((s) => s.open);const openSettingsDialog = openSettings;const view = useAppView();const goBack = goBackInHistory;@@ -175,20 +183,19 @@ export function GlobalEventHandlers({log.info("Main access token invalidated for testing");}, []);- const globalOptions = {- enableOnFormTags: true,- enableOnContentEditable: true,- preventDefault: true,- } as const;-useHotkeys(SHORTCUTS.COMMAND_MENU, onToggleCommandMenu, {- ...globalOptions,+ ...GLOBAL_HOTKEY_OPTIONS,enabled: !commandMenuOpen,});- useHotkeys(SHORTCUTS.NEW_TASK, handleFocusTaskMode, globalOptions);- useHotkeys(SHORTCUTS.SETTINGS, handleOpenSettings, globalOptions);- useHotkeys(SHORTCUTS.GO_BACK, goBack, globalOptions);- useHotkeys(SHORTCUTS.GO_FORWARD, goForward, globalOptions);+ useHotkeys(SHORTCUTS.NEW_TASK, handleFocusTaskMode, GLOBAL_HOTKEY_OPTIONS);+ useHotkeys(SHORTCUTS.SETTINGS, handleOpenSettings, GLOBAL_HOTKEY_OPTIONS);+ useHotkeys(+ SHORTCUTS.SEND_FEEDBACK,+ () => openFeedback(),+ GLOBAL_HOTKEY_OPTIONS,+ );+ useHotkeys(SHORTCUTS.GO_BACK, goBack, GLOBAL_HOTKEY_OPTIONS);+ useHotkeys(SHORTCUTS.GO_FORWARD, goForward, GLOBAL_HOTKEY_OPTIONS);// mod+left/right means jump to line start/end inside inputs and editors, so// the arrow variants skip enableOnFormTags/enableOnContentEditable.useHotkeys(SHORTCUTS.GO_BACK_ALT, goBack, { preventDefault: true });@@ -205,10 +212,18 @@ export function GlobalEventHandlers({useHotkeys(SHORTCUTS.RELOAD_WINDOW,() => window.location.reload(),- globalOptions,+ GLOBAL_HOTKEY_OPTIONS,+ );+ useHotkeys(+ SHORTCUTS.TOGGLE_LEFT_SIDEBAR,+ toggleLeftSidebar,+ GLOBAL_HOTKEY_OPTIONS,+ );+ useHotkeys(+ SHORTCUTS.TOGGLE_REVIEW_PANEL,+ handleToggleReview,+ GLOBAL_HOTKEY_OPTIONS,);- useHotkeys(SHORTCUTS.TOGGLE_LEFT_SIDEBAR, toggleLeftSidebar, globalOptions);- useHotkeys(SHORTCUTS.TOGGLE_REVIEW_PANEL, handleToggleReview, globalOptions);// Under the spaces chrome a session's activity is the right panel, and the// dock this shortcut used to collapse is not rendered, so it goes to the// panel instead. Off that chrome, only the dock exists.@@ -221,18 +236,22 @@ export function GlobalEventHandlers({}, [channelsLayout, currentTaskId]);useHotkeys(SHORTCUTS.TOGGLE_ACTIVITY_PANEL, handleToggleActivityPanel, {- ...globalOptions,+ ...GLOBAL_HOTKEY_OPTIONS,enabled: channelsLayout,});- useHotkeys(SHORTCUTS.SHORTCUTS_SHEET, onToggleShortcutsSheet, globalOptions);+ useHotkeys(+ SHORTCUTS.SHORTCUTS_SHEET,+ onToggleShortcutsSheet,+ GLOBAL_HOTKEY_OPTIONS,+ );useHotkeys(SHORTCUTS.INBOX, navigateToInbox, {- ...globalOptions,+ ...GLOBAL_HOTKEY_OPTIONS,enabled: inboxAvailable,});- useHotkeys(SHORTCUTS.PREV_TASK, handlePrevTask, globalOptions, [+ useHotkeys(SHORTCUTS.PREV_TASK, handlePrevTask, GLOBAL_HOTKEY_OPTIONS, [handlePrevTask,]);- useHotkeys(SHORTCUTS.NEXT_TASK, handleNextTask, globalOptions, [+ useHotkeys(SHORTCUTS.NEXT_TASK, handleNextTask, GLOBAL_HOTKEY_OPTIONS, [handleNextTask,]);@@ -240,7 +259,7 @@ export function GlobalEventHandlers({SHORTCUTS.TOGGLE_FOCUS,handleToggleFocus,{- ...globalOptions,+ ...GLOBAL_HOTKEY_OPTIONS,enabled: !!currentTaskId && isWorktreeTask,},[handleToggleFocus],@@ -259,7 +278,7 @@ export function GlobalEventHandlers({handleSwitchTask(index);},{- ...globalOptions,+ ...GLOBAL_HOTKEY_OPTIONS,enabled: !channelsEnabled && !browserTabStripMounted,},[handleSwitchTask],@@ -383,3 +402,8 @@ export function GlobalEventHandlers({return null;}++export function GlobalEventHandlers(props: GlobalEventHandlersProps) {+ useGlobalEventHandlers(props);+ return null;+}diff --git a/products/desktop/packages/ui/src/shell/analytics.ts b/products/desktop/packages/ui/src/shell/analytics.tsindex 011ddc64e960..7c3896948054 100644--- a/products/desktop/packages/ui/src/shell/analytics.ts+++ b/products/desktop/packages/ui/src/shell/analytics.ts@@ -30,10 +30,12 @@ export interface AnalyticsTracker {identifyUser(userId: string, properties?: UserIdentifyProperties): void;setUserGroups(user: AnalyticsUserGroups): void;resetUser(): void;- captureSurveyResponse(params: {- surveyId: string;- responses: Array<{ questionId: string; response: string }>;- }): void;+ recordNavigationSettled(+ durationMs: number,+ route: string,+ visibilityAtSettle: DocumentVisibilityState,+ ): void;+ getSessionId(): string | undefined;}export const ANALYTICS_TRACKER = Symbol.for("posthog.ui.AnalyticsTracker");@@ -79,11 +81,18 @@ export function resetUser(): void {resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).resetUser();}-export function captureSurveyResponse(params: {- surveyId: string;- responses: Array<{ questionId: string; response: string }>;-}): void {- resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).captureSurveyResponse(- params,+export function recordNavigationSettled(+ durationMs: number,+ route: string,+ visibilityAtSettle: DocumentVisibilityState,+): void {+ resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).recordNavigationSettled(+ durationMs,+ route,+ visibilityAtSettle,);}++export function getAnalyticsSessionId(): string | undefined {+ return resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).getSessionId();+}diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.tsindex 050287317f34..d49bb58574a3 100644--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts@@ -230,9 +230,8 @@ export function initializePostHog(sessionId?: string) {},// The shared analytics project runs many popover surveys aimed at the// PostHog web app; any one without URL/event conditions would render here- // too. This app only submits survey responses through its own UI- // (captureSurveyResponse), which posthog-js survey rendering being off- // does not affect.+ // too. This app submits survey responses through its server-owned feedback+ // endpoint, which survey rendering being off does not affect.disable_surveys: true,session_idle_timeout_seconds: SESSION_IDLE_TIMEOUT_SECONDS,...(sessionId ? { bootstrap: { sessionID: sessionId } } : {}),@@ -418,38 +417,23 @@ export function track<K extends keyof EventPropertyMap>(posthog.capture(eventName, properties);}-/**- * Record a survey response via posthog-js's `survey sent` event. Pass one entry- * per answered question; they're submitted together as a single response. The- * survey must already exist (and be launched) in the project the app reports to,- * or the response will not attach to it.- */-export function captureSurveyResponse({- surveyId,- responses,-}: {- surveyId: string;- responses: Array<{ questionId: string; response: string }>;-}) {+export function recordNavigationSettled(+ durationMs: number,+ route: string,+ visibilityAtSettle: DocumentVisibilityState,+): void {if (!isInitialized) {return;}- const properties: Record<string, unknown> = {- $survey_id: surveyId,- $survey_questions: responses.map(({ questionId }) => ({ id: questionId })),- };- // Newer ingestion keys each response by question id.- for (const { questionId, response } of responses) {- properties[`$survey_response_${questionId}`] = response;- }- // `$survey_response` is the legacy single-question key; only set it when there- // is exactly one answer, otherwise it would be ambiguous.- if (responses.length === 1) {- properties.$survey_response = responses[0].response;- }+ posthog.metrics.histogram("desktop.navigation.settled.duration", durationMs, {+ unit: "ms",+ attributes: { route, visibility_at_settle: visibilityAtSettle },+ });+}- posthog.capture("survey sent", properties);+export function getAnalyticsSessionId(): string | undefined {+ return isInitialized ? posthog.get_session_id() : undefined;}/**@@ -582,7 +566,8 @@ export const posthogAnalyticsTracker: AnalyticsTracker = {identifyUser,setUserGroups,resetUser,- captureSurveyResponse,+ recordNavigationSettled,+ getSessionId: getAnalyticsSessionId,};/**diff --git a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.tsindex d509e8dcd7e1..72a7764f0223 100644--- a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts+++ b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts@@ -4,6 +4,7 @@ import {SPEECH_USER_NAME_PROVIDER,} from "@posthog/core/speech/identifiers";import type { HostCapabilityRequirement } from "@posthog/di/hostCapabilities";+import { FEEDBACK_CONTEXT_SERVICE } from "@posthog/platform/feedback-context";import { HOST_CAPABILITIES } from "@posthog/platform/host-capabilities";import { SPEECH_SERVICE } from "@posthog/platform/speech";import { AUTH_SIDE_EFFECTS } from "@posthog/ui/features/auth/identifiers";@@ -48,6 +49,10 @@ export const REQUIRED_HOST_CAPABILITIES: readonly HostCapabilityRequirement[] =token: FEATURE_FLAGS,description: "feature-flag gating across the app",},+ {+ token: FEEDBACK_CONTEXT_SERVICE,+ description: "recent app logs for explicit feedback attachments",+ },{token: AUTH_SIDE_EFFECTS,description: "auth lifecycle side effects (login/logout/session)",