: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): quick-ask floating PostHog AI panel prototype (#82996)
Shy Altera60817cd9e58
diff --git a/products/desktop/apps/code/README.md b/products/desktop/apps/code/README.mdindex b814ee533694..e82f533735cc 100644--- a/products/desktop/apps/code/README.md+++ b/products/desktop/apps/code/README.md@@ -42,6 +42,32 @@ pnpm run check:write # Linting & typecheck- `⌘⇧[/]` - Switch between tabs- `⌘W` - Close current tab+### Screen recording permission in development++Quick ask's screen capture needs the macOS Screen Recording permission. In development the app runs inside the stock Electron binary (`node_modules/electron/dist/Electron.app`), and macOS attributes the consent to the **responsible process** — for a `pnpm start` from a terminal, that is the terminal (Ghostty, iTerm, Terminal, or the IDE hosting the integrated terminal), not Electron:++- Grant it to **your terminal** in System Settings → Privacy & Security → Screen & System Audio Recording, quit the terminal fully, reopen it, and start the app again. An enabled "Electron" row alone is usually not enough (it belongs to a Finder-launched Electron).+- On a capture failure the app logs the consent status macOS reports (`Quick ask screen capture unavailable` in main.log) — "denied" while the toggles look on means the grant sits on the wrong identity.+- To see what TCC actually holds: `sudo sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT client, auth_value FROM access WHERE service='kTCCServiceScreenCapture';"` (2 = allowed).+- The first capture attempt is what registers Electron in that list and fires the consent prompt — hit the camera button once if the entry is missing.+- An Electron version bump replaces the binary, which invalidates the grant (macOS ties it to the code identity). If capture silently stops working after `pnpm install`, reset and re-grant:++```bash+tccutil reset ScreenCapture com.github.Electron+```++- Several checkouts share the same `com.github.Electron` identity, so a grant made from another project's Electron can shadow yours — the reset above clears all of them.+- If that reset fails with `No such bundle identifier` (OSStatus -10814), LaunchServices has never seen the node_modules Electron as an app bundle. Register it first, or fall back to resetting Screen Recording for every app:++```bash+/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister \+ -f node_modules/electron/dist/Electron.app+tccutil reset ScreenCapture com.github.Electron++# or, resets the permission for all apps:+tccutil reset ScreenCapture+```+### Building DistributablesTo create production distributables (DMG, ZIP):diff --git a/products/desktop/apps/code/electron.vite.config.ts b/products/desktop/apps/code/electron.vite.config.tsindex 16bce4a5c25e..95dcb3c30d3e 100644--- a/products/desktop/apps/code/electron.vite.config.ts+++ b/products/desktop/apps/code/electron.vite.config.ts@@ -245,7 +245,14 @@ export default defineConfig(({ mode }) => {outDir: path.join(__dirname, ".vite/renderer/main_window"),sourcemap: true,rollupOptions: {- input: path.resolve(__dirname, "index.html"),+ input: {+ main_window: path.resolve(__dirname, "index.html"),+ quick_ask: path.resolve(__dirname, "quick-ask.html"),+ quick_ask_annotate: path.resolve(+ __dirname,+ "quick-ask-annotate.html",+ ),+ },},},},diff --git a/products/desktop/apps/code/package.json b/products/desktop/apps/code/package.jsonindex c2167468db01..14955a7a122e 100644--- a/products/desktop/apps/code/package.json+++ b/products/desktop/apps/code/package.json@@ -15,6 +15,7 @@"start": "electron-vite dev --watch","start:debug": "electron-vite dev --watch --inspect=5858","compile": "electron-vite build",+ "e2e:quick-ask": "tsx --tsconfig scripts/tsconfig.e2e.json scripts/quick-ask-e2e.mts","package": "electron-vite build && electron-builder build --dir --config electron-builder.ts","package:dev": "FORCE_DEV_MODE=1 SKIP_NOTARIZE=1 electron-vite build && electron-builder build --dir --config electron-builder.ts","make": "electron-vite build && electron-builder build --config electron-builder.ts",@@ -111,6 +112,7 @@"@posthog/host-router": "workspace:*","@posthog/host-trpc": "workspace:*","@posthog/platform": "workspace:*",+ "@posthog/quick-ask": "workspace:*","@posthog/quill": "catalog:","@posthog/shared": "workspace:*","@posthog/ui": "workspace:*",diff --git a/products/desktop/apps/code/quick-ask-annotate.html b/products/desktop/apps/code/quick-ask-annotate.htmlnew file mode 100644index 000000000000..c361a0db728d--- /dev/null+++ b/products/desktop/apps/code/quick-ask-annotate.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en" class="dark">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Annotate screenshot</title>+</head>++<body>+ <div id="root"></div>+ <script type="module" src="/src/renderer/quick-ask-annotate/main.tsx"></script>+</body>++</html>diff --git a/products/desktop/apps/code/quick-ask.html b/products/desktop/apps/code/quick-ask.htmlnew file mode 100644index 000000000000..36447bc29202--- /dev/null+++ b/products/desktop/apps/code/quick-ask.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en" class="dark">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>PostHog AI</title>+</head>++<body>+ <div id="root"></div>+ <script type="module" src="/src/renderer/quick-ask/main.tsx"></script>+</body>++</html>diff --git a/products/desktop/apps/code/scripts/quick-ask-e2e.mts b/products/desktop/apps/code/scripts/quick-ask-e2e.mtsnew file mode 100644index 000000000000..61b71c947429--- /dev/null+++ b/products/desktop/apps/code/scripts/quick-ask-e2e.mts@@ -0,0 +1,866 @@+import { readFileSync } from "node:fs";+import http from "node:http";+import type { AddressInfo } from "node:net";+import path from "node:path";+import { fileURLToPath } from "node:url";+import type { AuthService } from "@posthog/core/auth/auth";+import { QuickAskService } from "@posthog/quick-ask/service/quick-ask";+import {+ REPLAY_FOLLOW_UP,+ REPLAY_FOLLOW_UP_ANSWER,+ REPLAY_FOLLOW_UP_PRELUDE,+ REPLAY_QUESTION,+ REPLAY_STRAY_ANSWER,+ startReplayServer,+} from "@posthog/quick-ask/service/replay-fixture";+import { chromium } from "playwright-core";++/**+ * The whole quick-ask pipeline: the real QuickAskService asks a replay of a+ * production run's tasks API and stream, and its events drive the built panel+ * in headless Chromium through the real input. Asserts the rendered DOM.+ *+ * Run from apps/code after `pnpm compile`: `pnpm e2e:quick-ask`.+ */++const rendererDir = path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ "../.vite/renderer/main_window",+);++const MIME: Record<string, string> = {+ ".html": "text/html",+ ".js": "text/javascript",+ ".css": "text/css",+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".woff2": "font/woff2",+};++function serveRenderer(): Promise<{ origin: string; close: () => void }> {+ const server = http.createServer((request, response) => {+ const file = path.join(rendererDir, (request.url ?? "/").split("?")[0]);+ try {+ const body = readFileSync(file);+ response.writeHead(200, {+ "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream",+ });+ response.end(body);+ } catch {+ response.writeHead(404);+ response.end();+ }+ });+ return new Promise((resolve) => {+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as AddressInfo;+ resolve({+ origin: `http://127.0.0.1:${port}`,+ close: () => server.close(),+ });+ });+ });+}++function fail(message: string): never {+ console.error(`✗ ${message}`);+ process.exit(1);+}++function pass(message: string): void {+ console.log(`✓ ${message}`);+}++const replay = await startReplayServer();+const renderer = await serveRenderer();++const auth = {+ getValidAccessToken: async () => ({+ accessToken: "t",+ apiHost: replay.origin,+ }),+ getState: () => ({ currentProjectId: 2 }),+ authenticatedFetch: (+ fetchImpl: typeof fetch,+ url: string,+ init: RequestInit,+ ) => fetchImpl(url, init),+} as unknown as AuthService;+const service = new QuickAskService(auth);++const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 700, height: 900 } });+const pageErrors: string[] = [];+page.on("pageerror", (error) => pageErrors.push(error.message));++// The panel's preload bridges, stubbed: tRPC absorbs requests (chart cards+// stay in their loading state without a session), and quickAsk.ask routes to+// the real service in this process.+// A capture in this harness attaches a canned PNG; the real annotator UI is+// exercised separately below.+const SHOT_BASE64 =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";+let pendingShot: { name: string; base64: string; mimeType: string } | null =+ null;+await page.exposeFunction(+ "__hostAsk",+ (question: string, conversationId?: string) => {+ const attachments = pendingShot ? [pendingShot] : [];+ pendingShot = null;+ void page.evaluate("window.__qaAttach({ previewDataUrl: null })");+ void (async () => {+ for await (const event of service.ask({+ question,+ conversationId,+ attachments,+ })) {+ await page.evaluate(`window.__qaEmit(${JSON.stringify(event)})`);+ }+ })();+ },+);+await page.exposeFunction("__hostCapture", () => {+ pendingShot = {+ name: "screenshot.png",+ base64: SHOT_BASE64,+ mimeType: "image/png",+ };+ void page.evaluate(+ `window.__qaAttach({ previewDataUrl: "data:image/png;base64,${SHOT_BASE64}" })`,+ );+});+await page.exposeFunction("__hostDiscard", () => {+ pendingShot = null;+});+// The panel's chart cards resolve data through the authenticated client,+// which forms from auth state served over the tRPC bridge. Stub the bridge+// wire protocol so the real client forms, and intercept its API calls below.+// A string, not a function: tsx's esbuild transform injects helpers that do+// not exist inside the page.+await page.addInitScript(`+ window.electronTRPC = {+ handlers: [],+ sendMessage(message) {+ if (message.method !== "request") return;+ const { id, type, path } = message.operation;+ if (type === "subscription") return;+ const respond = (data) => {+ for (const handler of window.electronTRPC.handlers) {+ handler({ id, result: { type: "data", data: { json: data } } });+ }+ };+ if (path === "auth.getState") {+ respond({+ status: "authenticated",+ bootstrapComplete: true,+ cloudRegion: "us",+ orgProjectsMap: {},+ currentOrgId: "org-1",+ currentProjectId: 2,+ hasCodeAccess: true,+ needsScopeReauth: false,+ sessionType: "desktop",+ sessionExpiresAt: null,+ sessionEndReason: null,+ });+ } else if (path === "auth.getValidAccessToken") {+ respond({ accessToken: "e2e-token", apiHost: "https://us.posthog.com" });+ } else {+ respond({});+ }+ },+ onMessage(callback) {+ window.electronTRPC.handlers.push(callback);+ },+ };+ const listeners = [];+ const attachListeners = [];+ window.__qaEmit = (event) => { for (const listener of listeners) listener(event); };+ window.__qaAttach = (payload) => { for (const listener of attachListeners) listener(payload); };+ window.quickAsk = {+ hide: () => { window.__qaHides = (window.__qaHides ?? 0) + 1; },+ resize: () => {},+ openInApp: () => {},+ dragStart: () => {},+ dragEnd: () => {},+ ask: (question, conversationId) => window.__hostAsk(question, conversationId),+ cancel: () => {},+ reset: () => {},+ onEvent: (callback) => { listeners.push(callback); return () => {}; },+ onLayout: () => () => {},+ onShown: () => () => {},+ onShake: (cb) => { window.__qaShake = cb; return () => { window.__qaShake = undefined; }; },+ capture: () => window.__hostCapture(),+ discardAttachment: () => window.__hostDiscard(),+ onAttachment: (callback) => { attachListeners.push(callback); return () => {}; },+ openScreenSettings: () => { window.__qaSettingsOpens = (window.__qaSettingsOpens ?? 0) + 1; },+ };+`);++// The chart card's live query, canned: a date-keyed grid that shapes into a+// line chart.+await page.route("https://us.posthog.com/**", async (route) => {+ if (route.request().url().includes("/query/")) {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ columns: ["day", "count()"],+ results: [+ ["2026-08-08", 34000],+ ["2026-08-09", 48000],+ ["2026-08-10", 86000],+ ["2026-08-11", 84000],+ ["2026-08-12", 82000],+ ["2026-08-13", 79000],+ ["2026-08-14", 68000],+ ],+ }),+ });+ return;+ }+ await route.fulfill({ status: 404, body: "" });+});++await page.goto(`${renderer.origin}/quick-ask.html`);+await page.waitForSelector(".qa-pill input", { timeout: 15_000 });+pass("panel booted");++await service.warm();+pass("sandbox warmed");++// First question through the real input.+await page.fill(".qa-pill input", REPLAY_QUESTION);+await page.press(".qa-pill input", "Enter");+await page.waitForSelector(".qa-actions", { timeout: 15_000 });+const focused = (await page.evaluate(+ 'document.activeElement === document.querySelector(".qa-pill input")',+)) as boolean;+if (!focused) {+ fail("input did not regain focus after the answer");+}++const answer = (await page.evaluate(+ 'document.querySelector(".qa-answer")?.textContent ?? ""',+)) as string;+if (!answer.includes("Signups held steady this week")) {+ fail(`answer text not rendered: ${JSON.stringify(answer.slice(0, 200))}`);+}+if (answer.includes(REPLAY_STRAY_ANSWER)) {+ fail("description-turn output leaked into the panel");+}+if (/<\/?hogql/.test(answer)) {+ fail("raw object tag leaked into the rendered answer");+}+const chip = (await page.evaluate(+ 'document.querySelector(".qa-answer .qa-ref")?.textContent ?? ""',+)) as string;+if (!chip.includes("Tuesday spike")) {+ fail(`inline tag did not render as a chip: ${JSON.stringify(chip)}`);+}+pass("answer rendered, inline tag is a chip, stray turn skipped, no raw tags");++await page.waitForSelector(".qa-chart .qa-chart-svg path", { timeout: 15_000 });+const chartTitle = (await page.evaluate(+ 'document.querySelector(".qa-chart .qa-chart-title")?.textContent ?? ""',+)) as string;+if (chartTitle !== "Signups per day, last 7 days") {+ fail(`chart card missing or mistitled: ${JSON.stringify(chartTitle)}`);+}+const stat = (await page.evaluate(+ 'document.querySelector(".qa-chart-stat-value")?.textContent ?? ""',+)) as string;+if (!stat) {+ fail("chart headline stat missing");+}+pass(`hogql block tag drew the compact chart (latest ${stat})`);++// Hovering a chip mounts the live preview card.+await page.hover(".qa-answer .qa-ref");+await page.waitForSelector("[data-testid=evidence-hover-card]", {+ timeout: 5_000,+});+// The card is styled by layered Tailwind utilities; an unscoped panel reset+// would flatten its padding and surface to nothing.+const cardStyle = (await page.evaluate(`(() => {+ const wrapper = document.querySelector("[data-testid=evidence-hover-card]");+ const card = wrapper?.querySelector(".w-80");+ const surface = card?.parentElement ? getComputedStyle(card.parentElement) : null;+ return {+ padding: card ? getComputedStyle(card).paddingTop : "",+ background: surface?.backgroundColor ?? "",+ };+})()`)) as { padding: string; background: string };+if (!cardStyle.padding || cardStyle.padding === "0px") {+ fail(+ `hover card lost its padding (padding-top: ${cardStyle.padding || "none"})`,+ );+}+if (!cardStyle.background || cardStyle.background === "rgba(0, 0, 0, 0)") {+ fail(`hover card surface is transparent (${cardStyle.background || "none"})`);+}+pass(+ `chip hover mounts the preview card (padding ${cardStyle.padding}, solid surface)`,+);++// The close button hides the panel; clicking elsewhere must not.+await page.click(".qa-close");+const hides = (await page.evaluate("window.__qaHides ?? 0")) as number;+if (hides !== 1) {+ fail(`close button did not hide the panel (hides: ${hides})`);+}+pass("close button hides the panel");++// Shaking the panel (relayed from the main-process drag loop) cycles the hedgehog.+const hogBefore = (await page.evaluate(+ 'document.querySelector(".qa-hog img")?.getAttribute("src") ?? ""',+)) as string;+await page.evaluate("window.__qaShake?.()");+await page+ .waitForFunction(+ `document.querySelector(".qa-hog img")?.getAttribute("src") !== ${JSON.stringify(hogBefore)}`,+ undefined,+ { timeout: 2_000 },+ )+ .catch(() => {});+const hogAfter = (await page.evaluate(+ 'document.querySelector(".qa-hog img")?.getAttribute("src") ?? ""',+)) as string;+if (!hogBefore || hogBefore === hogAfter) {+ fail("shaking did not change the hedgehog");+}+pass("shake cycles the hedgehog");++// Double-clicking the hedgehog collapses to mini mode: hedgehog + status dot.+await page.dblclick(".qa-hog");+const miniState = (await page.evaluate(`(() => {+ const pill = document.querySelector(".qa-pill");+ const card = document.querySelector(".qa-card");+ const dot = document.querySelector(".qa-status");+ return {+ pillHidden: !pill || getComputedStyle(pill).display === "none",+ cardHidden: !card || getComputedStyle(card).display === "none",+ dotVisible: !!dot && getComputedStyle(dot).display !== "none",+ dotStatus: dot?.className ?? "",+ };+})()`)) as {+ pillHidden: boolean;+ cardHidden: boolean;+ dotVisible: boolean;+ dotStatus: string;+};+if (!miniState.pillHidden || !miniState.cardHidden) {+ fail("mini mode did not hide the pill and answer");+}+if (!miniState.dotVisible || !miniState.dotStatus.includes("qa-status-ready")) {+ fail(`mini mode status dot wrong (${miniState.dotStatus || "missing"})`);+}+// Double-click again restores the panel and refocuses the input.+await page.dblclick(".qa-hog");+await page.waitForSelector(".qa-pill input", { timeout: 2_000 });+await page+ .waitForFunction(+ 'document.activeElement === document.querySelector(".qa-pill input")',+ undefined,+ { timeout: 2_000 },+ )+ .catch(() => {});+const restored = (await page.evaluate(+ 'document.activeElement === document.querySelector(".qa-pill input")',+)) as boolean;+if (!restored) {+ fail("leaving mini mode did not refocus the input");+}+pass("double-click toggles mini mode with a status dot");++// A long shake summons hogzilla and takes the panel hostage; another long+// shake calms it back down.+await page.waitForTimeout(1_600); // separate from the single-shake streak+for (let i = 0; i < 5; i++) {+ await page.evaluate("window.__qaShake?.()");+}+await page.waitForSelector(".qa-zilla", { timeout: 2_000 });+const zilla = (await page.evaluate(`(() => {+ const pill = document.querySelector(".qa-pill");+ const img = document.querySelector(".qa-hog img");+ return {+ pillHidden: !pill || getComputedStyle(pill).display === "none",+ src: img?.getAttribute("src") ?? "",+ };+})()`)) as { pillHidden: boolean; src: string };+if (!zilla.pillHidden) {+ fail("hogzilla left the pill usable");+}+if (!zilla.src.includes("hogzilla")) {+ fail(`hogzilla shows the wrong avatar (${zilla.src})`);+}+await page.waitForTimeout(1_600);+for (let i = 0; i < 5; i++) {+ await page.evaluate("window.__qaShake?.()");+}+await page.waitForSelector(".qa-zilla", { state: "detached", timeout: 2_000 });+await page.waitForSelector(".qa-pill input", { timeout: 2_000 });+pass("long shake summons hogzilla, another long shake calms it");++if (process.env.QUICK_ASK_E2E_METRICS) {+ const metrics = await page.evaluate(`(() => {+ const rect = (selector) => {+ const el = document.querySelector(selector);+ if (!el) return null;+ const r = el.getBoundingClientRect();+ const cs = getComputedStyle(el);+ return { w: Math.round(r.width), h: Math.round(r.height), font: cs.fontSize, mt: cs.marginTop, mb: cs.marginBottom, pad: cs.padding };+ };+ return JSON.stringify({+ card: rect(".qa-card"),+ answer: rect(".qa-answer"),+ chart: rect(".qa-chart"),+ chartSvg: rect(".qa-chart-svg"),+ chartTitle: rect(".qa-chart-title"),+ stat: rect(".qa-chart-stat-value"),+ text: rect(".qa-answer .rt-Text"),+ code: rect(".qa-answer .rt-Code"),+ chip: rect(".qa-ref"),+ labels: rect(".qa-chart-labels"),+ }, null, 1);+ })()`);+ console.log("metrics:", metrics);+}++const shot = process.env.QUICK_ASK_E2E_SCREENSHOT;+if (shot) {+ const box = await page.locator(".qa-root").boundingBox();+ if (box) await page.screenshot({ path: shot, clip: box });+ pass(`screenshot written to ${shot}`);+}++// Capture attaches a screenshot chip; remove discards it; a second capture+// rides the follow-up.+// A denied capture surfaces the permission error with a settings link.+await page.evaluate(+ 'window.__qaAttach({ previewDataUrl: null, error: "PostHog needs screen recording permission.", canOpenSettings: true })',+);+await page.waitForSelector(".qa-attach-settings", { timeout: 5_000 });+await page.click(".qa-attach-settings");+await page.waitForSelector(".qa-attach", { state: "detached", timeout: 5_000 });+if (((await page.evaluate("window.__qaSettingsOpens")) as number) !== 1) {+ fail("settings link did not reach the bridge");+}+pass("permission error offers the settings link");++await page.click(".qa-shot");+await page.waitForSelector(".qa-attach img", { timeout: 5_000 });+await page.click('.qa-attach button[aria-label="Remove screenshot"]');+await page.waitForSelector(".qa-attach", { state: "detached", timeout: 5_000 });+if (pendingShot !== null) {+ fail("removing the chip did not discard the pending screenshot");+}+await page.click(".qa-shot");+await page.waitForSelector(".qa-attach img", { timeout: 5_000 });+pass("screenshot chip attaches and removes");++// Follow-up through the same input.+await page.fill(".qa-pill input", REPLAY_FOLLOW_UP);+await page.press(".qa-pill input", "Enter");+await page.waitForFunction(+ `document.querySelector(".qa-answer")?.textContent?.includes(${JSON.stringify(REPLAY_FOLLOW_UP_ANSWER)})`,+ undefined,+ { timeout: 15_000 },+);+pass("follow-up answer rendered");++await page.waitForSelector(".qa-attach", { state: "detached", timeout: 5_000 });+const prepare = replay.requests.find((r) =>+ r.path.endsWith("/prepare_upload/"),+);+if (!prepare || !prepare.path.includes("/runs/run-1/artifacts/")) {+ fail(`screenshot was not uploaded to the live run: ${prepare?.path}`);+}+const userMessage = replay.requests.find(+ (r) => (r.body as { method?: string } | null)?.method === "user_message",+);+const artifactIds = (+ userMessage?.body as { params?: { artifact_ids?: string[] } }+).params?.artifact_ids;+if (JSON.stringify(artifactIds) !== '["art-1"]') {+ fail(+ `follow-up did not reference the artifact: ${JSON.stringify(artifactIds)}`,+ );+}+pass("screenshot uploaded and referenced on the follow-up");++// The follow-up turn has text on both sides of a tool call, so the answer+// arrives as two segments with a pager pinned to the top of the card.+await page.waitForSelector(".qa-actions", { timeout: 15_000 });+await page.waitForSelector(".qa-status-row .qa-pager", { timeout: 5_000 });+// Let the card's mount animation finish so bounding boxes are stable.+await page.waitForTimeout(400);+const pagerBefore = await page+ .locator(".qa-status-row .qa-pager")+ .boundingBox();+await page.click('.qa-pager button[aria-label="Previous part"]');+await page.waitForFunction(+ `document.querySelector(".qa-answer")?.textContent?.includes(${JSON.stringify(REPLAY_FOLLOW_UP_PRELUDE)})`,+ undefined,+ { timeout: 5_000 },+);+const pagerAfter = await page.locator(".qa-status-row .qa-pager").boundingBox();+if (!pagerBefore || !pagerAfter || pagerBefore.y !== pagerAfter.y) {+ throw new Error(+ `pager moved while paging: ${pagerBefore?.y} -> ${pagerAfter?.y}`,+ );+}+if (+ await page+ .locator(".qa-actions")+ .textContent()+ .then((t) => t?.includes("PostHog AI"))+) {+ throw new Error("source label still present in the actions row");+}+await page.click('.qa-pager button[aria-label="Next part"]');+pass("segment pager pages back without moving");++// New chat clears the thread and hands focus back to the input.+await page.click(".qa-new");+await page.waitForSelector(".qa-card", { state: "detached", timeout: 5_000 });+// Focus returns on the next frame after the re-render.+await page+ .waitForFunction(+ 'document.activeElement === document.querySelector(".qa-pill input")',+ undefined,+ { timeout: 2_000 },+ )+ .catch(() => {});+const focusedAfterReset = (await page.evaluate(+ 'document.activeElement === document.querySelector(".qa-pill input")',+)) as boolean;+if (!focusedAfterReset) {+ fail("input not focused after new chat");+}+pass("new chat clears the thread and focuses the input");++// An empty, untouched panel folds into mini mode; a draft keeps it open.+await page.goto(`${renderer.origin}/quick-ask.html?idleCollapse=400`);+await page.waitForSelector(".qa-pill input", { timeout: 15_000 });+await page.waitForSelector(".qa-mini", { timeout: 3_000 });+await page.goto(`${renderer.origin}/quick-ask.html?idleCollapse=400`);+await page.waitForSelector(".qa-pill input", { timeout: 15_000 });+await page.fill(".qa-pill input", "still typing");+await page.waitForTimeout(900);+if (await page.locator(".qa-mini").count()) {+ fail("panel collapsed while a draft was in the input");+}+pass("empty idle panel folds into mini mode, drafts keep it open");++// The panel follows the app theme; the system scheme flips the palette live.+await page.emulateMedia({ colorScheme: "dark" });+await page.waitForFunction(+ 'document.documentElement.classList.contains("dark")',+ undefined,+ { timeout: 2_000 },+);+const darkPill = (await page.evaluate(+ 'getComputedStyle(document.querySelector(".qa-pill")).backgroundColor',+)) as string;+await page.emulateMedia({ colorScheme: "light" });+await page.waitForFunction(+ '!document.documentElement.classList.contains("dark")',+ undefined,+ { timeout: 2_000 },+);+const lightPill = (await page.evaluate(+ 'getComputedStyle(document.querySelector(".qa-pill")).backgroundColor',+)) as string;+if (!darkPill || darkPill === lightPill) {+ fail(`theme change did not restyle the pill (${darkPill} vs ${lightPill})`);+}+pass("panel palette follows the theme");++if (pageErrors.length > 0) {+ fail(`page errors: ${pageErrors.join(" | ")}`);+}+pass("no page errors");++// The annotator app: crop by drag, ink an arrow, export the flattened PNG.+const annotate = await browser.newPage({+ viewport: { width: 1200, height: 800 },+});+const annotateErrors: string[] = [];+annotate.on("pageerror", (error) => annotateErrors.push(error.message));+await annotate.addInitScript(`+ window.quickAskAnnotate = {+ shot: async () => {+ const canvas = document.createElement("canvas");+ canvas.width = 2400;+ canvas.height = 1600;+ const ctx = canvas.getContext("2d");+ ctx.fillStyle = "#1d4ed8";+ ctx.fillRect(0, 0, 2400, 1600);+ return canvas.toDataURL("image/png");+ },+ done: (dataUrl) => { window.__annotated = dataUrl; },+ cancel: () => { window.__cancelled = true; },+ };+`);+await annotate.goto(`${renderer.origin}/quick-ask-annotate.html`);+await annotate.waitForSelector(".an-shot", { timeout: 15_000 });++// The whole screen is selected from the start; the toolbar is up+// immediately and no selection is forced.+await annotate.waitForSelector(".an-toolbar", { timeout: 15_000 });+const fullDims = await annotate.locator(".an-size").textContent();+if (fullDims?.trim() !== "2400 × 1600") {+ fail(`initial dimension label reads "${fullDims}", expected full screen`);+}++// Crop via the toolbar tool: 300x200 at (100, 100). The shot is 2x the+// viewport, so the dimension label reads export pixels.+await annotate.click('[aria-label="Crop (C)"]');+await annotate.waitForSelector(".an-hint", { timeout: 5_000 });+await annotate.mouse.move(100, 100);+await annotate.mouse.down();+await annotate.mouse.move(400, 300, { steps: 5 });+await annotate.mouse.up();+// The toolbar is pinned to the top of the screen, away from the selection.+const toolbarBox = await annotate.locator(".an-toolbar").boundingBox();+if (!toolbarBox || toolbarBox.y > 40) {+ fail(`toolbar sits at y=${toolbarBox?.y}, expected the top of the screen`);+}+const dims = await annotate.locator(".an-size").textContent();+if (dims?.trim() !== "600 × 400") {+ fail(`dimension label reads "${dims}", expected "600 × 400"`);+}++// Grow the selection by its south-east handle; the label follows.+await annotate.mouse.move(400, 300);+await annotate.mouse.down();+await annotate.mouse.move(450, 350, { steps: 5 });+await annotate.mouse.up();+const grown = await annotate.locator(".an-size").textContent();+if (grown?.trim() !== "700 × 500") {+ fail(`dimension label reads "${grown}" after resize, expected "700 × 500"`);+}++// Ink: an arrow, a text label, and a pixelated region.+await annotate.click('[aria-label="Arrow (A)"]');+await annotate.mouse.move(150, 150);+await annotate.mouse.down();+await annotate.mouse.move(320, 240, { steps: 5 });+await annotate.mouse.up();++await annotate.click('[aria-label="Text (T)"]');+// The text tool opens its options row, and the editor previews the+// default background exactly as it exports.+await annotate.waitForSelector(".an-subbar", { timeout: 5_000 });+await annotate.mouse.click(200, 180);+await annotate.waitForSelector(".an-text-input.an-text-solid", {+ timeout: 5_000,+});+await annotate.keyboard.type("LGTM");+await annotate.keyboard.press("Enter");+// The editor commits into a shape; a lost focus race would leave it open.+await annotate.waitForSelector(".an-text-input", {+ state: "detached",+ timeout: 5_000,+});++await annotate.click('[aria-label="Pixelate (X)"]');+await annotate.mouse.move(250, 210);+await annotate.mouse.down();+await annotate.mouse.move(340, 270, { steps: 5 });+await annotate.mouse.up();++// Undo removes the pixelation; redo restores it.+await annotate.click('[aria-label="Undo (⌘Z)"]');+const redoEnabled = await annotate+ .locator('[aria-label="Redo (⇧⌘Z)"]')+ .isEnabled();+if (!redoEnabled) {+ fail("undo did not enable redo");+}+await annotate.click('[aria-label="Redo (⇧⌘Z)"]');++// Counter drops numbered badges; the select tool moves and deletes objects.+await annotate.click('[aria-label="Counter (N)"]');+await annotate.mouse.click(180, 320);+await annotate.mouse.click(220, 320);+await annotate.click('[aria-label="Select (V)"]');+await annotate.mouse.click(220, 320);+await annotate.waitForSelector('[aria-label="Delete (⌫)"]', {+ timeout: 5_000,+});+await annotate.mouse.move(220, 320);+await annotate.mouse.down();+await annotate.mouse.move(262, 332, { steps: 4 });+await annotate.mouse.up();+await annotate.click('[aria-label="Ink #3b82f6"]');+await annotate.click('[aria-label="Delete (⌫)"]');+await annotate.waitForSelector('[aria-label="Delete (⌫)"]', {+ state: "detached",+ timeout: 5_000,+});+pass("counter badges place; select tool moves, recolors, and deletes");++// Arrow endpoints re-aim the line, and boxes resize by their handles;+// drawing hands over the select tool.+await annotate.mouse.click(170, 161); // on the arrow's shaft+await annotate.waitForSelector('[aria-label="Delete (⌫)"]', {+ timeout: 5_000,+});+await annotate.mouse.move(320, 240); // the arrow's tip handle+await annotate.mouse.down();+await annotate.mouse.move(400, 300, { steps: 5 });+await annotate.mouse.up();+const inkAt = async (x: number, y: number): Promise<number> =>+ (await annotate.evaluate(`(() => {+ const ctx = document.querySelector(".an-overlay").getContext("2d");+ return ctx.getImageData(${x}, ${y}, 1, 1).data[3];+ })()`)) as number;+if ((await inkAt(380, 288)) < 128) {+ fail("dragging the arrow tip did not extend the line");+}+await annotate.keyboard.press("r"); // shortcut into the box tool+if ((await inkAt(230, 220)) > 128) {+ fail("box resize probe already inked");+}+await annotate.mouse.move(120, 120);+await annotate.mouse.down();+await annotate.mouse.move(200, 170, { steps: 5 });+await annotate.mouse.up();+const selectAfterDraw = await annotate+ .locator('[aria-label="Select (V)"]')+ .getAttribute("class");+if (!selectAfterDraw?.includes("an-active")) {+ fail("drawing a box did not hand over the select tool");+}+await annotate.mouse.move(200, 170); // the box's south-east handle+await annotate.mouse.down();+await annotate.mouse.move(260, 220, { steps: 5 });+await annotate.mouse.up();+if ((await inkAt(230, 220)) < 128) {+ fail("dragging the box handle did not resize it");+}+pass("arrow tips re-aim, boxes resize, drawing hands over select");++// Text sizing and wrapping: a second label, resized via the options row,+// then narrowed by its side handle until it breaks into two lines.+await annotate.click('[aria-label="Text (T)"]');+await annotate.mouse.click(140, 260);+await annotate.waitForSelector(".an-text-input", { timeout: 5_000 });+await annotate.keyboard.type("wrap me please now");+await annotate.keyboard.press("Enter");+await annotate.waitForSelector(".an-text-input", {+ state: "detached",+ timeout: 5_000,+});+await annotate.click('[aria-label="Select (V)"]');+await annotate.mouse.click(160, 265);+await annotate.waitForSelector('[aria-label="Delete (⌫)"]', {+ timeout: 5_000,+});+const sizeBefore = await annotate.locator(".an-sub-value").textContent();+const slider = await annotate.locator('[aria-label="Text size"]').boundingBox();+if (!slider) {+ fail("text size slider not visible for a selected text object");+} else {+ await annotate.mouse.click(slider.x + slider.width - 2, slider.y + 2);+}+const sizeAfter = await annotate.locator(".an-sub-value").textContent();+if (Number(sizeAfter) <= Number(sizeBefore)) {+ fail(`slider left size at ${sizeAfter}, expected above ${sizeBefore}`);+}+// Undo the size change so the wrap drag starts from known 17px metrics;+// undo drops the selection, so pick the label up again.+await annotate.click('[aria-label="Undo (\u2318Z)"]');+await annotate.mouse.click(160, 265);+await annotate.waitForSelector('[aria-label="Delete (\u232b)"]', {+ timeout: 5_000,+});+const textW = (await annotate.evaluate(`(() => {+ const ctx = document.createElement("canvas").getContext("2d");+ ctx.font = '600 17px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';+ return ctx.measureText("wrap me please now").width;+})()`)) as number;+// Solid pill ink only; the pill's soft drop shadow does not count.+const probe = async (): Promise<number> =>+ (await annotate.evaluate(`(() => {+ const ctx = document.querySelector(".an-overlay").getContext("2d");+ return ctx.getImageData(150, 295, 1, 1).data[3];+ })()`)) as number;+if ((await probe()) > 128) {+ fail("second text line is inked before the width drag");+}+const edgeX = 140 + textW + 13;+await annotate.mouse.move(edgeX, 271);+await annotate.mouse.down();+await annotate.mouse.move(140 + textW / 2, 271, { steps: 5 });+await annotate.mouse.up();+if ((await probe()) < 128) {+ fail("narrowing the text did not wrap it onto a second line");+}+pass("text options row sizes text; side handle wraps it to multi-line");++// A long line auto-wraps to the room inside the selection, and finishing+// hands over the select tool with the fresh label selected.+await annotate.click('[aria-label="Text (T)"]');+await annotate.mouse.click(140, 305);+await annotate.waitForSelector(".an-text-input", { timeout: 5_000 });+await annotate.keyboard.type(+ "a very long single line that should wrap by itself",+);+await annotate.keyboard.press("Enter");+await annotate.waitForSelector(".an-text-input", {+ state: "detached",+ timeout: 5_000,+});+await annotate.waitForSelector('[aria-label="Delete (⌫)"]', {+ timeout: 5_000,+});+const selectActive = await annotate+ .locator('[aria-label="Select (V)"]')+ .getAttribute("class");+if (!selectActive?.includes("an-active")) {+ fail("finishing a label did not hand over the select tool");+}+const wrapped = (await annotate.evaluate(`(() => {+ const ctx = document.querySelector(".an-overlay").getContext("2d");+ return ctx.getImageData(150, 335, 1, 1).data[3];+})()`)) as number;+if (wrapped < 128) {+ fail("long label did not auto-wrap inside the selection");+}+pass("long labels auto-wrap and finish into the select tool");++await annotate.click(".an-attach");+await annotate.waitForFunction("typeof window.__annotated === 'string'", {+ timeout: 5_000,+});+const exported = (await annotate.evaluate(`+ new Promise((resolve) => {+ const image = new Image();+ image.onload = () =>+ resolve({+ prefix: window.__annotated.slice(0, 22),+ width: image.naturalWidth,+ height: image.naturalHeight,+ });+ image.src = window.__annotated;+ })+`)) as { prefix: string; width: number; height: number };+if (exported.prefix !== "data:image/png;base64,") {+ fail(`annotator exported ${exported.prefix}`);+}+if (exported.width !== 700 || exported.height !== 500) {+ fail(+ `annotator export is ${exported.width}x${exported.height}, expected 700x500`,+ );+}+if (annotateErrors.length > 0) {+ fail(`annotator page errors: ${annotateErrors.join(" | ")}`);+}+pass("annotator crops, resizes, inks arrow/text/pixelate, and exports");++await browser.close();+renderer.close();+await replay.close();+console.log("quick-ask e2e: all checks passed");diff --git a/products/desktop/apps/code/scripts/tsconfig.e2e.json b/products/desktop/apps/code/scripts/tsconfig.e2e.jsonnew file mode 100644index 000000000000..30a9c233ec18--- /dev/null+++ b/products/desktop/apps/code/scripts/tsconfig.e2e.json@@ -0,0 +1,9 @@+{+ "compilerOptions": {+ "experimentalDecorators": true,+ "jsx": "react-jsx",+ "target": "ES2022",+ "useDefineForClassFields": false+ },+ "include": ["./**/*", "../src/**/*", "../../../packages/**/*"]+}diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex 334ee00bb377..e49e0c8237ec 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -1,4 +1,4 @@-import type { AuthService } from "@posthog/core/auth/auth";+import type { AuthService, FetchLike } from "@posthog/core/auth/auth";import type { AUTH_SERVICE } from "@posthog/core/auth/auth.module";import type {AUTH_CONNECTIVITY,@@ -131,6 +131,11 @@ import type { STORAGE_PATHS_SERVICE } from "@posthog/platform/storage-paths";import type { UPDATER_SERVICE } from "@posthog/platform/updater";import type { URL_LAUNCHER_SERVICE } from "@posthog/platform/url-launcher";import type { WORKSPACE_SETTINGS_SERVICE } from "@posthog/platform/workspace-settings";+import type {+ QUICK_ASK_FETCH,+ QUICK_ASK_RUN_DEFAULTS,+ QuickAskRunDefaults,+} from "@posthog/quick-ask/service/quick-ask";import type { WorkspaceClient } from "@posthog/workspace-client/client";import type { DatabaseService } from "@posthog/workspace-server/db/service";import type { GIT_SERVICE as WS_GIT_SERVICE } from "@posthog/workspace-server/di/tokens";@@ -377,6 +382,8 @@ export interface MainBindings {[AUTH_TOKEN_OVERRIDE]: string | null;[MAIN_AUTH_SERVICE]: AuthService;[AUTH_SERVICE]: AuthService;+ [QUICK_ASK_FETCH]: FetchLike;+ [QUICK_ASK_RUN_DEFAULTS]: () => QuickAskRunDefaults;// Auth proxy / mcp proxy / mcp relay[AUTH_PROXY_AUTH]: AuthProxyAuth;diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex 0bcf9760ab12..d41653c9cb04 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -121,6 +121,11 @@ import { STORAGE_PATHS_SERVICE } from "@posthog/platform/storage-paths";import { UPDATER_SERVICE } from "@posthog/platform/updater";import { URL_LAUNCHER_SERVICE } from "@posthog/platform/url-launcher";import { WORKSPACE_SETTINGS_SERVICE } from "@posthog/platform/workspace-settings";+import {+ QUICK_ASK_FETCH,+ QUICK_ASK_RUN_DEFAULTS,+} from "@posthog/quick-ask/service/quick-ask";+import { quickAskCoreModule } from "@posthog/quick-ask/service/quick-ask.module";import type { WorkspaceClient } from "@posthog/workspace-client/client";import { databaseModule } from "@posthog/workspace-server/db/db.module";import {@@ -247,6 +252,7 @@ import { ElectronFileIcon } from "../platform-adapters/electron-file-icon";import { ElectronImageProcessor } from "../platform-adapters/electron-image-processor";import { ElectronMainWindow } from "../platform-adapters/electron-main-window";import { MissionControlService } from "../platform-adapters/electron-mission-control";+import { electronNetFetch } from "../platform-adapters/electron-net-fetch";import { ElectronNotifier } from "../platform-adapters/electron-notifier";import { ElectronPowerManager } from "../platform-adapters/electron-power-manager";import { ElectronSecureStorage } from "../platform-adapters/electron-secure-storage";@@ -278,7 +284,7 @@ import { ElevenLabsSpeechService } from "../services/speech/service";import { WorkspaceServerService } from "../services/workspace-server/service";import { getUserDataDir, isDevBuild } from "../utils/env";import { logger } from "../utils/logger";-import { rendererStore } from "../utils/store";+import { quickAskStore, rendererStore } from "../utils/store";import type { MainBindings } from "./bindings";import {APP_LIFECYCLE_SERVICE as MAIN_APP_LIFECYCLE_SERVICE,@@ -816,6 +822,23 @@ container.bind(MAIN_MISSION_CONTROL_SERVICE).to(MissionControlService);// live in @posthog/core (bound via canvasCoreModule) and resolve through// ctx.container in the host-router routers.container.load(canvasCoreModule);+container.load(quickAskCoreModule);+// Chromium's network stack, not Node's undici: it honors system proxies and+// VPN routing, which undici intermittently fails against ("fetch failed").+container.bind(QUICK_ASK_FETCH).toConstantValue(electronNetFetch);+container.bind(QUICK_ASK_RUN_DEFAULTS).toConstantValue(() => {+ const repositories = quickAskStore.get("defaultRepositories");+ const integrationId = quickAskStore.get("defaultGithubIntegrationId");+ return {+ channelId: quickAskStore.get("defaultChannelId") || null,+ repositories,+ githubIntegrationId:+ repositories.length > 0 && integrationId ? integrationId : null,+ adapter: quickAskStore.get("defaultAdapter") || null,+ model: quickAskStore.get("defaultModel") || null,+ reasoningEffort: quickAskStore.get("defaultEffort") || null,+ };+});// Browser tabs for the Channels canvas surface. Authoritative sqlite-backed// service in the main process; resolved by the host-router browserTabs router.diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.tsindex 1e567bb9815a..e8c2cce5dccd 100644--- a/products/desktop/apps/code/src/main/index.ts+++ b/products/desktop/apps/code/src/main/index.ts@@ -77,6 +77,7 @@ import {import { setupExternalLinkPermissionHandlers } from "./external-links";import { posthogNodeAnalytics } from "./platform-adapters/posthog-analytics";import { registerMcpSandboxProtocol } from "./protocols/mcp-sandbox";+import { destroyQuickAskWindow, setupQuickAsk } from "./quick-ask";import type { AppLifecycleService } from "./services/app-lifecycle/service";import type { DevNetworkService } from "./services/dev-network/service";import { initDevToolbar } from "./services/dev-toolbar";@@ -104,7 +105,7 @@ import {import { isMacosPackagedUnsafeBundleLocation } from "./utils/macos-packaged-install-guard";import { installMainFetchLogging } from "./utils/network-fetch-logger";import { installRendererNetworkLogging } from "./utils/network-webrequest-logger";-import { createWindow } from "./window";+import { createWindow, onMainWindowClosed } from "./window";type FileWatcherEventsByKind = {[K in FileWatcherEvent["kind"]]: Extract<FileWatcherEvent, { kind: K }>;@@ -371,6 +372,10 @@ app.whenReady().then(async () => {container.get<DevNetworkService>(DEV_NETWORK_SERVICE),);createWindow();+ setupQuickAsk();+ // The hidden quick-ask panel must not keep the app alive after the main+ // window closes.+ onMainWindowClosed(destroyQuickAskWindow);const wsServer = container.get<WorkspaceServerService>(WORKSPACE_SERVER_SERVICE,diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-net-fetch.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-net-fetch.tsnew file mode 100644index 000000000000..1c0e60b37e63--- /dev/null+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-net-fetch.ts@@ -0,0 +1,10 @@+import type { FetchLike } from "@posthog/core/auth/auth";+import { net } from "electron";++/**+ * Fetch over Chromium's network stack. Unlike Node's undici (`globalThis.+ * fetch`), it honors system proxies and VPN routing, which undici+ * intermittently fails against ("fetch failed").+ */+export const electronNetFetch: FetchLike = (input, init) =>+ net.fetch(input, init);diff --git a/products/desktop/apps/code/src/main/preload.test.ts b/products/desktop/apps/code/src/main/preload.test.tsindex 126b0488c731..db24b9d27fe9 100644--- a/products/desktop/apps/code/src/main/preload.test.ts+++ b/products/desktop/apps/code/src/main/preload.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { APP_WINDOW_ARG } from "../shared/constants";+import { APP_WINDOW_ARG, QUICK_ASK_WINDOW_ARG } from "../shared/constants";const { contextBridge, ipcRenderer } = vi.hoisted(() => ({contextBridge: { exposeInMainWorld: vi.fn() },@@ -15,15 +15,22 @@ vi.mock("electron", () => ({webUtils: { getPathForFile: vi.fn() },}));vi.mock("electron-log/preload", () => ({}));-vi.mock("@posthog/electron-trpc/main", () => ({+const { exposeElectronTRPC } = vi.hoisted(() => ({exposeElectronTRPC: vi.fn(),}));+vi.mock("@posthog/electron-trpc/main", () => ({+ exposeElectronTRPC,+}));import { setupPreload } from "./preload";describe("preload mode selection", () => {beforeEach(() => {contextBridge.exposeInMainWorld.mockClear();+ exposeElectronTRPC.mockClear();+ // Each setupPreload registers a once-listener; drop leftovers so the+ // emit below only reaches the branch under test.+ process.removeAllListeners("loaded");});it("defaults an untagged process to the restricted artifact preload", () => {@@ -40,4 +47,16 @@ describe("preload mode selection", () => {expect.any(Object),);});++ it("exposes the quickAsk bridge and the tRPC bridge to a quick-ask window", () => {+ setupPreload([QUICK_ASK_WINDOW_ARG]);++ expect(contextBridge.exposeInMainWorld).toHaveBeenCalledTimes(1);+ expect(contextBridge.exposeInMainWorld).toHaveBeenCalledWith(+ "quickAsk",+ expect.any(Object),+ );+ (process as unknown as { emit(event: string): boolean }).emit("loaded");+ expect(exposeElectronTRPC).toHaveBeenCalledTimes(1);+ });});diff --git a/products/desktop/apps/code/src/main/preload.ts b/products/desktop/apps/code/src/main/preload.tsindex f97abd4862b9..1a313c75398c 100644--- a/products/desktop/apps/code/src/main/preload.ts+++ b/products/desktop/apps/code/src/main/preload.ts@@ -6,6 +6,28 @@ import {ARTIFACT_HOST_TO_PREVIEW_CHANNEL,ARTIFACT_OPEN_EXTERNAL_CHANNEL,ARTIFACT_PREVIEW_TO_HOST_CHANNEL,+ QUICK_ASK_ANNOTATE_DONE_CHANNEL,+ QUICK_ASK_ANNOTATE_SHOT_CHANNEL,+ QUICK_ASK_ANNOTATE_WINDOW_ARG,+ QUICK_ASK_ASK_CHANNEL,+ QUICK_ASK_ATTACHMENT_CHANNEL,+ QUICK_ASK_CANCEL_CHANNEL,+ QUICK_ASK_CAPTURE_CHANNEL,+ QUICK_ASK_DISCARD_ATTACHMENT_CHANNEL,+ QUICK_ASK_DRAG_END_CHANNEL,+ QUICK_ASK_DRAG_START_CHANNEL,+ QUICK_ASK_EVENT_CHANNEL,+ QUICK_ASK_HIDE_CHANNEL,+ QUICK_ASK_LAYOUT_CHANNEL,+ QUICK_ASK_OPEN_IN_APP_CHANNEL,+ QUICK_ASK_RESET_CHANNEL,+ QUICK_ASK_RESIZE_CHANNEL,+ QUICK_ASK_SCREEN_SETTINGS_CHANNEL,+ QUICK_ASK_SHAKE_CHANNEL,+ QUICK_ASK_SHOWN_CHANNEL,+ QUICK_ASK_WINDOW_ARG,+ type QuickAskDragStartPayload,+ type QuickAskResizePayload,} from "../shared/constants";import { trustedArtifactLink } from "./artifact-preview-link";import { parseSessionIdArg } from "./posthog-session-arg";@@ -84,8 +106,74 @@ function setupApplicationPreload(argv: string[]): void {});}+function setupQuickAskPreload(): void {+ contextBridge.exposeInMainWorld("quickAsk", {+ hide: () => ipcRenderer.send(QUICK_ASK_HIDE_CHANNEL),+ resize: (size: QuickAskResizePayload) =>+ ipcRenderer.send(QUICK_ASK_RESIZE_CHANNEL, size),+ openInApp: () => ipcRenderer.send(QUICK_ASK_OPEN_IN_APP_CHANNEL),+ dragStart: (offset: QuickAskDragStartPayload) =>+ ipcRenderer.send(QUICK_ASK_DRAG_START_CHANNEL, offset),+ dragEnd: () => ipcRenderer.send(QUICK_ASK_DRAG_END_CHANNEL),+ ask: (question: string, conversationId?: string) =>+ ipcRenderer.send(QUICK_ASK_ASK_CHANNEL, question, conversationId),+ cancel: () => ipcRenderer.send(QUICK_ASK_CANCEL_CHANNEL),+ reset: () => ipcRenderer.send(QUICK_ASK_RESET_CHANNEL),+ onEvent: (callback: (event: unknown) => void): (() => void) => {+ const listener = (_e: unknown, event: unknown): void => callback(event);+ ipcRenderer.on(QUICK_ASK_EVENT_CHANNEL, listener);+ return () => ipcRenderer.off(QUICK_ASK_EVENT_CHANNEL, listener);+ },+ onLayout: (callback: (layout: unknown) => void): (() => void) => {+ const listener = (_e: unknown, layout: unknown): void => callback(layout);+ ipcRenderer.on(QUICK_ASK_LAYOUT_CHANNEL, listener);+ return () => ipcRenderer.off(QUICK_ASK_LAYOUT_CHANNEL, listener);+ },+ onShown: (callback: () => void): (() => void) => {+ const listener = (): void => callback();+ ipcRenderer.on(QUICK_ASK_SHOWN_CHANNEL, listener);+ return () => ipcRenderer.off(QUICK_ASK_SHOWN_CHANNEL, listener);+ },+ onShake: (callback: () => void): (() => void) => {+ const listener = (): void => callback();+ ipcRenderer.on(QUICK_ASK_SHAKE_CHANNEL, listener);+ return () => ipcRenderer.off(QUICK_ASK_SHAKE_CHANNEL, listener);+ },+ capture: () => ipcRenderer.send(QUICK_ASK_CAPTURE_CHANNEL),+ discardAttachment: () =>+ ipcRenderer.send(QUICK_ASK_DISCARD_ATTACHMENT_CHANNEL),+ openScreenSettings: () =>+ ipcRenderer.send(QUICK_ASK_SCREEN_SETTINGS_CHANNEL),+ onAttachment: (callback: (payload: unknown) => void): (() => void) => {+ const listener = (_e: unknown, payload: unknown): void =>+ callback(payload);+ ipcRenderer.on(QUICK_ASK_ATTACHMENT_CHANNEL, listener);+ return () => ipcRenderer.off(QUICK_ASK_ATTACHMENT_CHANNEL, listener);+ },+ });+}++function setupQuickAskAnnotatePreload(): void {+ contextBridge.exposeInMainWorld("quickAskAnnotate", {+ shot: (): Promise<string | null> =>+ ipcRenderer.invoke(QUICK_ASK_ANNOTATE_SHOT_CHANNEL),+ done: (dataUrl: string) =>+ ipcRenderer.send(QUICK_ASK_ANNOTATE_DONE_CHANNEL, { dataUrl }),+ cancel: () => ipcRenderer.send(QUICK_ASK_ANNOTATE_DONE_CHANNEL, null),+ });+}+export function setupPreload(argv: string[]): void {- if (argv.includes(APP_WINDOW_ARG)) {+ if (argv.includes(QUICK_ASK_ANNOTATE_WINDOW_ARG)) {+ setupQuickAskAnnotatePreload();+ } else if (argv.includes(QUICK_ASK_WINDOW_ARG)) {+ setupQuickAskPreload();+ // Answer rendering needs the host tRPC bridge for auth tokens and+ // external links.+ process.once("loaded", () => {+ exposeElectronTRPC();+ });+ } else if (argv.includes(APP_WINDOW_ARG)) {setupApplicationPreload(argv);} else {setupArtifactPreviewPreload();diff --git a/products/desktop/apps/code/src/main/quick-ask-capture.ts b/products/desktop/apps/code/src/main/quick-ask-capture.tsnew file mode 100644index 000000000000..3230e1d65087--- /dev/null+++ b/products/desktop/apps/code/src/main/quick-ask-capture.ts@@ -0,0 +1,243 @@+import { readFile } from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import type { QuickAskAttachment } from "@posthog/quick-ask/service/quick-ask";+import {+ BrowserWindow,+ type Display,+ desktopCapturer,+ ipcMain,+ screen,+ shell,+ systemPreferences,+} from "electron";+import {+ QUICK_ASK_ANNOTATE_DONE_CHANNEL,+ QUICK_ASK_ANNOTATE_SHOT_CHANNEL,+ QUICK_ASK_ANNOTATE_WINDOW_ARG,+ QUICK_ASK_ATTACHMENT_CHANNEL,+ QUICK_ASK_SCREEN_SETTINGS_CHANNEL,+ type QuickAskAttachmentPayload,+} from "../shared/constants";+import { isDevBuild } from "./utils/env";+import { logger } from "./utils/logger";++const log = logger.scope("quick-ask");++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);++const VITE_DEV_SERVER_URL = process.env.ELECTRON_RENDERER_URL;+/** Lets the e2e run without a screen: a PNG file stands in for the capture. */+const FAKE_CAPTURE_ENV = "QUICK_ASK_FAKE_CAPTURE";+/** Compositor settle time between hiding the panel and grabbing the frame. */+const HIDE_SETTLE_MS = 220;++let annotateWindow: BrowserWindow | null = null;+/** Raw shot handed to the annotator, held until it exports or cancels. */+let shotDataUrl: string | null = null;+let pending: QuickAskAttachment | null = null;+let handlersRegistered = false;+/** Windows the app is tearing down itself, so `closed` skips the OS-close+ * cleanup (done handler, reopen, teardown all go through closeAnnotator). */+const appInitiatedClose = new WeakSet<BrowserWindow>();++interface CaptureHost {+ getPanel(): BrowserWindow | null;+ showPanel(): void;+ hidePanel(): void;+}++export function pendingAttachments(): QuickAskAttachment[] {+ return pending ? [pending] : [];+}++export function clearPendingAttachment(host?: CaptureHost): void {+ pending = null;+ if (host) sendAttachment(host, { previewDataUrl: null });+}++function sendAttachment(+ host: CaptureHost,+ payload: QuickAskAttachmentPayload,+): void {+ const panel = host.getPanel();+ if (panel && !panel.isDestroyed()) {+ panel.webContents.send(QUICK_ASK_ATTACHMENT_CHANNEL, payload);+ }+}++async function grabScreen(display: Display): Promise<string | null> {+ const fakePath = process.env[FAKE_CAPTURE_ENV];+ if (fakePath) {+ const bytes = await readFile(fakePath);+ return `data:image/png;base64,${bytes.toString("base64")}`;+ }+ // Ask before checking consent: this call is what registers the app in the+ // macOS Screen Recording list and fires the consent prompt on first use+ // (askForMediaAccess does not support "screen").+ const sources = await desktopCapturer.getSources({+ types: ["screen"],+ thumbnailSize: {+ width: Math.round(display.size.width * display.scaleFactor),+ height: Math.round(display.size.height * display.scaleFactor),+ },+ });+ if (+ process.platform === "darwin" &&+ systemPreferences.getMediaAccessStatus("screen") !== "granted"+ ) {+ return null;+ }+ const source =+ sources.find((s) => s.display_id === String(display.id)) ?? sources[0];+ if (!source || source.thumbnail.isEmpty()) return null;+ return source.thumbnail.toDataURL();+}++function openAnnotator(display: Display, host: CaptureHost): void {+ closeAnnotator();+ const window = new BrowserWindow({+ ...display.bounds,+ show: false,+ frame: false,+ resizable: false,+ movable: false,+ fullscreenable: false,+ skipTaskbar: true,+ hiddenInMissionControl: true,+ backgroundColor: "#101014",+ ...(process.platform === "darwin" ? { type: "panel" as const } : {}),+ webPreferences: {+ nodeIntegration: false,+ contextIsolation: true,+ preload: path.join(__dirname, "preload.js"),+ additionalArguments: [QUICK_ASK_ANNOTATE_WINDOW_ARG],+ },+ });+ window.setAlwaysOnTop(true, "screen-saver");+ window.on("closed", () => {+ if (annotateWindow === window) annotateWindow = null;+ // A close the app did not initiate (Alt+F4, the window menu's Close) never+ // ran the done handler, so drop the held capture and re-show the panel the+ // capture flow hid — otherwise the panel looks gone until the next summon.+ if (appInitiatedClose.delete(window)) return;+ shotDataUrl = null;+ host.showPanel();+ });+ if (VITE_DEV_SERVER_URL) {+ void window.loadURL(`${VITE_DEV_SERVER_URL}/quick-ask-annotate.html`);+ } else {+ void window.loadFile(+ path.join(__dirname, "../renderer/main_window/quick-ask-annotate.html"),+ );+ }+ window.once("ready-to-show", () => {+ window.show();+ window.focus();+ });+ annotateWindow = window;+}++function closeAnnotator(): void {+ if (annotateWindow && !annotateWindow.isDestroyed()) {+ appInitiatedClose.add(annotateWindow);+ annotateWindow.destroy();+ }+ annotateWindow = null;+}++/** Hides the panel, freezes the screen it is on, opens the annotator. */+export async function beginCapture(host: CaptureHost): Promise<void> {+ const panel = host.getPanel();+ // Match the whole panel rect, not just its top-left point: a panel dragged+ // across a display edge can straddle two, and the corner may sit on the+ // display holding the smaller part. getDisplayMatching picks the display+ // with the largest overlap. No panel means summon-at-cursor never ran, so+ // fall back to the cursor's display.+ const display =+ panel && !panel.isDestroyed()+ ? screen.getDisplayMatching(panel.getBounds())+ : screen.getDisplayNearestPoint(screen.getCursorScreenPoint());+ host.hidePanel();+ await new Promise((resolve) => setTimeout(resolve, HIDE_SETTLE_MS));+ let dataUrl: string | null = null;+ try {+ dataUrl = await grabScreen(display);+ } catch (error) {+ log.warn("Quick ask screen capture failed", { error });+ }+ if (!dataUrl && process.platform === "darwin") {+ // "denied" with the app toggled on in System Settings usually means the+ // grant sits on the wrong identity: dev runs launched from a terminal+ // are attributed to the terminal (the responsible process).+ log.warn("Quick ask screen capture unavailable", {+ mediaAccessStatus: systemPreferences.getMediaAccessStatus("screen"),+ });+ }+ if (!dataUrl) {+ host.showPanel();+ // Dev runs are the stock Electron binary; macOS attributes the consent+ // to "Electron", and a version bump invalidates it (new code identity).+ const consentIdentity = isDevBuild() ? "Electron" : "PostHog";+ sendAttachment(+ host,+ process.platform === "darwin"+ ? {+ previewDataUrl: null,+ error: `Grant screen recording to ${consentIdentity}, then relaunch.`,+ canOpenSettings: true,+ }+ : { previewDataUrl: null, error: "Screen capture failed." },+ );+ return;+ }+ shotDataUrl = dataUrl;+ openAnnotator(display, host);+}++/** Events must come from the named window: these ipcMain channels are shared+ * by every renderer, and only the annotator may read or submit the held+ * screenshot, only the panel may open system settings. */+function fromWindow(+ event: { sender: Electron.WebContents },+ window: BrowserWindow | null,+): boolean {+ return (+ window !== null &&+ !window.isDestroyed() &&+ event.sender === window.webContents+ );+}++export function setupQuickAskCapture(host: CaptureHost): void {+ if (handlersRegistered) return;+ handlersRegistered = true;+ ipcMain.handle(QUICK_ASK_ANNOTATE_SHOT_CHANNEL, (event) =>+ fromWindow(event, annotateWindow) ? shotDataUrl : null,+ );+ ipcMain.on(QUICK_ASK_SCREEN_SETTINGS_CHANNEL, (event) => {+ if (!fromWindow(event, host.getPanel())) return;+ void shell.openExternal(+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",+ );+ });+ ipcMain.on(QUICK_ASK_ANNOTATE_DONE_CHANNEL, (event, result: unknown) => {+ if (!fromWindow(event, annotateWindow)) return;+ shotDataUrl = null;+ closeAnnotator();+ host.showPanel();+ const dataUrl = (result as { dataUrl?: unknown } | null)?.dataUrl;+ if (typeof dataUrl !== "string") return;+ const base64 = dataUrl.split(",")[1];+ if (!base64) return;+ pending = { name: "screenshot.png", base64, mimeType: "image/png" };+ sendAttachment(host, { previewDataUrl: dataUrl });+ });+}++export function teardownQuickAskCapture(): void {+ closeAnnotator();+ shotDataUrl = null;+ pending = null;+}diff --git a/products/desktop/apps/code/src/main/quick-ask.ts b/products/desktop/apps/code/src/main/quick-ask.tsnew file mode 100644index 000000000000..a254d28b6e7d--- /dev/null+++ b/products/desktop/apps/code/src/main/quick-ask.ts@@ -0,0 +1,650 @@+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { TASK_LINK_SERVICE } from "@posthog/core/links/identifiers";+import type { TaskLinkService } from "@posthog/core/links/task-link";+import {+ computeGeometry,+ PILL_HEIGHT,+ PILL_TOP_TO_WINDOW_BOTTOM,+ PILL_TOP_TO_WINDOW_TOP,+ SCREEN_MARGIN,+} from "@posthog/quick-ask/geometry/geometry";+import { ShakeDetector } from "@posthog/quick-ask/gesture/shake";+import {+ QUICK_ASK_SERVICE,+ type QuickAskService,+} from "@posthog/quick-ask/service/quick-ask";+import {+ isValidQuickAskAccelerator,+ QUICK_ASK_DEFAULT_SHORTCUT,+} from "@posthog/shared/quick-ask-shortcuts";+import { app, BrowserWindow, globalShortcut, ipcMain, screen } from "electron";+import {+ QUICK_ASK_ASK_CHANNEL,+ QUICK_ASK_CANCEL_CHANNEL,+ QUICK_ASK_CAPTURE_CHANNEL,+ QUICK_ASK_DISCARD_ATTACHMENT_CHANNEL,+ QUICK_ASK_DRAG_END_CHANNEL,+ QUICK_ASK_DRAG_START_CHANNEL,+ QUICK_ASK_EVENT_CHANNEL,+ QUICK_ASK_HIDE_CHANNEL,+ QUICK_ASK_LAYOUT_CHANNEL,+ QUICK_ASK_OPEN_IN_APP_CHANNEL,+ QUICK_ASK_RESET_CHANNEL,+ QUICK_ASK_RESIZE_CHANNEL,+ QUICK_ASK_SHAKE_CHANNEL,+ QUICK_ASK_SHOWN_CHANNEL,+ QUICK_ASK_WINDOW_ARG,+ type QuickAskDragStartPayload,+ type QuickAskLayoutPayload,+ type QuickAskResizePayload,+} from "../shared/constants";+import { container } from "./di/container";+import { setupExternalLinkHandlers } from "./external-links";+import {+ beginCapture,+ clearPendingAttachment,+ pendingAttachments,+ setupQuickAskCapture,+ teardownQuickAskCapture,+} from "./quick-ask-capture";+import { isDevBuild } from "./utils/env";+import { logger } from "./utils/logger";+import { quickAskStore } from "./utils/store";+import { attachWindowToTrpc, focusMainWindow } from "./window";++const log = logger.scope("quick-ask");++const QUICK_ASK_VITE_DEV_SERVER_URL = process.env.ELECTRON_RENDERER_URL;+const QUICK_ASK_VITE_NAME = "main_window";++// The window's bounds always hug the visible content (the reliable way to+// run a floating widget: anything outside the pill and card is simply not+// part of the window, so clicks land on whatever is behind with no+// click-through juggling). Width starts at the empty pill row and follows+// the renderer's measurements, capped here.+const PANEL_MAX_WIDTH = 640;+const PANEL_INITIAL_WIDTH = 300;+const PANEL_INITIAL_HEIGHT = PILL_HEIGHT;+// Where the cursor lands inside the window: on the hedgehog, Figma-style.+const CURSOR_IN_WINDOW_X = 55;+const CURSOR_IN_WINDOW_X_OFFSET = 8;+const CURSOR_ABOVE_PILL_PX = 10;+/** Last geometry the renderer reported; reused across hides/shows. */+let cachedContentHeight = PANEL_INITIAL_HEIGHT;+let cachedContentWidth = PANEL_INITIAL_WIDTH;+/** Whether the current layout has the card above the pill. */+let currentFlip = false;+/**+ * The pill row's top-left corner in screen coordinates — the single fixed+ * point every other placement value derives from. Planted at summon,+ * carried along by dragging.+ */+let pillAnchor: { x: number; y: number } | null = null;++type QuickAskDragState = {+ dx: number;+ dy: number;+ timer: NodeJS.Timeout;+};+let dragState: QuickAskDragState | null = null;++export interface QuickAskState {+ /** The panel exists in this build. */+ enabled: boolean;+ /** The user toggle; off unregisters the shortcut and drops the window. */+ active: boolean;+ shortcut: string;+ /** False when another app owns the accelerator. */+ registered: boolean;+ /** Space new threads file into; empty means the personal space. */+ defaultChannelId: string;+ defaultRepositories: string[];+ defaultGithubIntegrationId: number;+ /** Empty strings follow the adapter/model defaults. */+ defaultAdapter: string;+ defaultModel: string;+ defaultEffort: string;+}++export interface QuickAskSettingsPatch {+ active?: boolean;+ defaultChannelId?: string;+ defaultRepositories?: string[];+ defaultGithubIntegrationId?: number;+ defaultAdapter?: string;+ defaultModel?: string;+ defaultEffort?: string;+}++let quickAskEnabled = false;+let currentShortcut: string = QUICK_ASK_DEFAULT_SHORTCUT;+let shortcutRegistered = false;++function registerShortcut(accelerator: string): boolean {+ // Re-recording the accelerator that is already live is a no-op, not a change.+ if (shortcutRegistered && accelerator === currentShortcut) {+ return true;+ }+ // Register the replacement before releasing the old one, so a rejected+ // accelerator (owned by another app) leaves the working shortcut intact.+ const registered = globalShortcut.register(accelerator, toggleQuickAsk);+ if (registered) {+ if (shortcutRegistered) {+ globalShortcut.unregister(currentShortcut);+ }+ currentShortcut = accelerator;+ shortcutRegistered = true;+ log.info("Quick ask shortcut registered", { shortcut: accelerator });+ } else {+ log.warn("Quick ask shortcut is taken by another app", {+ shortcut: accelerator,+ });+ }+ return registered;+}++export function getQuickAskState(): QuickAskState {+ return {+ enabled: quickAskEnabled,+ active: quickAskStore.get("panelEnabled"),+ shortcut: currentShortcut,+ registered: shortcutRegistered,+ defaultChannelId: quickAskStore.get("defaultChannelId"),+ defaultRepositories: quickAskStore.get("defaultRepositories"),+ defaultGithubIntegrationId: quickAskStore.get("defaultGithubIntegrationId"),+ defaultAdapter: quickAskStore.get("defaultAdapter"),+ defaultModel: quickAskStore.get("defaultModel"),+ defaultEffort: quickAskStore.get("defaultEffort"),+ };+}++export function setQuickAskSettings(+ patch: QuickAskSettingsPatch,+): QuickAskState {+ if (patch.active !== undefined && quickAskEnabled) {+ quickAskStore.set("panelEnabled", patch.active);+ if (patch.active) {+ activateQuickAsk();+ } else {+ deactivateQuickAsk();+ }+ }+ if (patch.defaultChannelId !== undefined) {+ quickAskStore.set("defaultChannelId", patch.defaultChannelId);+ }+ if (patch.defaultRepositories !== undefined) {+ quickAskStore.set("defaultRepositories", patch.defaultRepositories);+ }+ if (patch.defaultGithubIntegrationId !== undefined) {+ quickAskStore.set(+ "defaultGithubIntegrationId",+ patch.defaultGithubIntegrationId,+ );+ }+ if (patch.defaultAdapter !== undefined) {+ quickAskStore.set("defaultAdapter", patch.defaultAdapter);+ }+ if (patch.defaultModel !== undefined) {+ quickAskStore.set("defaultModel", patch.defaultModel);+ }+ if (patch.defaultEffort !== undefined) {+ quickAskStore.set("defaultEffort", patch.defaultEffort);+ }+ return getQuickAskState();+}++export function setQuickAskShortcut(accelerator: string): QuickAskState {+ if (!quickAskEnabled || !isValidQuickAskAccelerator(accelerator)) {+ return getQuickAskState();+ }+ if (!quickAskStore.get("panelEnabled")) {+ quickAskStore.set("shortcut", accelerator);+ currentShortcut = accelerator;+ return getQuickAskState();+ }+ const registered = registerShortcut(accelerator);+ if (registered) {+ quickAskStore.set("shortcut", accelerator);+ }+ // On failure the old accelerator stays registered and `currentShortcut`+ // keeps its name; report the requested one so the settings UI can show it+ // is taken.+ return { ...getQuickAskState(), shortcut: accelerator, registered };+}++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);++let quickAskWindow: BrowserWindow | null = null;++/**+ * The only host tRPC routes the panel renderer may call: auth state and+ * tokens for its PostHog API client, and opening vetted external links.+ * Everything else on the router (shell, fs, secureStore, git…) stays+ * unreachable from this window even if its renderer is compromised.+ */+const QUICK_ASK_TRPC_ROUTES = new Set([+ "auth.getState",+ "auth.onStateChanged",+ "auth.getValidAccessToken",+ "auth.refreshAccessToken",+ "os.openExternal",+]);++function createQuickAskWindow(): BrowserWindow {+ const window = new BrowserWindow({+ width: PANEL_INITIAL_WIDTH,+ height: PANEL_INITIAL_HEIGHT,+ show: false,+ frame: false,+ transparent: true,+ backgroundColor: "#00000000",+ // The content draws its own shadows; the native shadow would outline the+ // whole (mostly empty) window rectangle.+ hasShadow: false,+ resizable: false,+ maximizable: false,+ minimizable: false,+ fullscreenable: false,+ skipTaskbar: true,+ hiddenInMissionControl: true,+ // On macOS this applies NSWindowStyleMaskNonactivatingPanel behavior:+ // the panel takes keyboard input without activating the app, so the app+ // the user was in stays visually frontmost (fixed in Electron >= 30).+ ...(process.platform === "darwin" ? { type: "panel" as const } : {}),+ webPreferences: {+ nodeIntegration: false,+ contextIsolation: true,+ preload: path.join(__dirname, "preload.js"),+ // Shares the app session so a future real PostHog AI wiring is already+ // authenticated.+ partition: "persist:main",+ additionalArguments: [QUICK_ASK_WINDOW_ARG],+ },+ });++ // Answer rendering fetches live data over the host tRPC bridge, narrowed+ // to the auth-token and external-link routes the panel actually uses.+ attachWindowToTrpc(window, (path) => QUICK_ASK_TRPC_ROUTES.has(path));++ // The panel shares the app session and its privileged preload bridges, so+ // it gets the same navigation boundary as the main window: links open in+ // the external browser and the window itself never leaves its own page —+ // an in-place navigation would carry the bridges into a foreign origin.+ const quickAskHome = QUICK_ASK_VITE_DEV_SERVER_URL+ ? new URL(`${QUICK_ASK_VITE_DEV_SERVER_URL}/quick-ask.html`)+ : pathToFileURL(+ path.join(+ __dirname,+ `../renderer/${QUICK_ASK_VITE_NAME}/quick-ask.html`,+ ),+ );+ setupExternalLinkHandlers(window, quickAskHome);++ window.setAlwaysOnTop(true, "screen-saver");+ // macOS: a `panel` window already floats over full-screen apps on every+ // Space. Do NOT call setVisibleOnAllWorkspaces with visibleOnFullScreen:+ // it flips the app's activation policy to accessory, which removes the app+ // from the Dock and the Cmd+Tab switcher.+ if (process.platform !== "darwin") {+ window.setVisibleOnAllWorkspaces(true);+ }+ window.on("closed", () => {+ quickAskWindow = null;+ });++ if (QUICK_ASK_VITE_DEV_SERVER_URL) {+ void window.loadURL(`${QUICK_ASK_VITE_DEV_SERVER_URL}/quick-ask.html`);+ } else {+ void window.loadFile(+ path.join(__dirname, `../renderer/${QUICK_ASK_VITE_NAME}/quick-ask.html`),+ );+ }++ return window;+}++function applyGeometry(window: BrowserWindow): void {+ if (window.isDestroyed()) return;+ const bounds = window.getBounds();+ const anchor = pillAnchor ?? {+ x: bounds.x,+ y: bounds.y + PILL_TOP_TO_WINDOW_TOP,+ };+ const area = screen.getDisplayNearestPoint(anchor).workArea;+ const content = { width: cachedContentWidth, height: cachedContentHeight };+ const geometry = computeGeometry(anchor, content, area, currentFlip);+ currentFlip = geometry.flip;+ if (+ geometry.x !== bounds.x ||+ geometry.y !== bounds.y ||+ geometry.width !== bounds.width ||+ geometry.height !== bounds.height+ ) {+ window.setBounds({+ x: geometry.x,+ y: geometry.y,+ width: geometry.width,+ height: geometry.height,+ });+ }+ const payload: QuickAskLayoutPayload = {+ flip: geometry.flip,+ maxHeight: geometry.maxHeight,+ };+ window.webContents.send(QUICK_ASK_LAYOUT_CHANNEL, payload);+}++function stopDrag(): void {+ if (dragState) {+ clearInterval(dragState.timer);+ dragState = null;+ }+}++/**+ * Summon: plant the pill anchor so the cursor lands on the hedgehog's nose+ * (Figma cursor-chat style); `applyGeometry` derives everything else.+ */+function summonAtCursor(window: BrowserWindow): void {+ const cursor = screen.getCursorScreenPoint();+ const area = screen.getDisplayNearestPoint(cursor).workArea;+ const x = Math.round(+ Math.min(+ Math.max(+ cursor.x + CURSOR_IN_WINDOW_X_OFFSET - CURSOR_IN_WINDOW_X,+ area.x + SCREEN_MARGIN,+ ),+ area.x + area.width - PANEL_MAX_WIDTH - SCREEN_MARGIN,+ ),+ );+ pillAnchor = { x, y: Math.round(cursor.y + CURSOR_ABOVE_PILL_PX) };+ // Fresh summon, fresh direction decision.+ currentFlip = false;+ applyGeometry(window);+}++function showQuickAsk(): void {+ if (!quickAskWindow || quickAskWindow.isDestroyed()) {+ quickAskWindow = createQuickAskWindow();+ }+ summonAtCursor(quickAskWindow);+ quickAskWindow.show();+ quickAskWindow.focus();+ quickAskWindow.webContents.send(QUICK_ASK_SHOWN_CHANNEL);+ // Boot a sandbox while the user types.+ void getQuickAskService().warm();+}++function hideQuickAsk(): void {+ // The stream keeps running while hidden so reopening restores the finished+ // answer; it is only cancelled by a new question or app quit.+ stopDrag();+ if (!quickAskWindow || quickAskWindow.isDestroyed()) return;+ if (!quickAskWindow.isVisible()) return;+ quickAskWindow.hide();+}++function getQuickAskService(): QuickAskService {+ return container.get<QuickAskService>(QUICK_ASK_SERVICE);+}++const captureHost = {+ getPanel: (): BrowserWindow | null => quickAskWindow,+ showPanel: (): void => {+ if (quickAskWindow && !quickAskWindow.isDestroyed()) {+ quickAskWindow.show();+ quickAskWindow.focus();+ }+ },+ hidePanel: (): void => hideQuickAsk(),+};++/** Streams one PostHog AI turn, forwarding each event to the panel. */+async function streamAnswer(+ question: string,+ conversationId: string | undefined,+): Promise<void> {+ const target = quickAskWindow;+ if (!target || target.isDestroyed()) return;+ const send = (event: unknown): void => {+ if (!target.isDestroyed()) {+ target.webContents.send(QUICK_ASK_EVENT_CHANNEL, event);+ }+ };+ const attachments = pendingAttachments();+ clearPendingAttachment(captureHost);+ try {+ for await (const event of getQuickAskService().ask({+ question,+ conversationId,+ attachments,+ })) {+ if (event.type === "error") {+ log.warn("Quick ask answered with an error", {+ message: event.message,+ detail: event.detail,+ });+ }+ send(event);+ }+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return; // Cancelled: a newer question or the panel hid.+ }+ log.warn("Quick ask stream failed", { error });+ send({+ type: "error",+ message: "PostHog AI is unavailable right now. Try again.",+ });+ }+}++export function toggleQuickAsk(): void {+ if (+ quickAskWindow &&+ !quickAskWindow.isDestroyed() &&+ quickAskWindow.isVisible()+ ) {+ hideQuickAsk();+ } else {+ showQuickAsk();+ }+}++/** Tear down the panel so `window-all-closed` app-quit behavior is preserved. */+export function destroyQuickAskWindow(): void {+ stopDrag();+ teardownQuickAskCapture();+ if (quickAskWindow && !quickAskWindow.isDestroyed()) {+ quickAskWindow.destroy();+ }+ quickAskWindow = null;+}++function activateQuickAsk(): void {+ const stored = quickAskStore.get("shortcut");+ const preferred =+ stored && isValidQuickAskAccelerator(stored)+ ? stored+ : QUICK_ASK_DEFAULT_SHORTCUT;+ let registered = registerShortcut(preferred);+ // The default may be taken (Option+Space is popular); fall back so the+ // feature still works until the user picks another one in settings.+ if (!registered && preferred !== "CommandOrControl+Shift+Space") {+ registered = registerShortcut("CommandOrControl+Shift+Space");+ }+ if (!registered) {+ currentShortcut = preferred;+ }+ // Pre-create hidden so the first summon is instant.+ if (!quickAskWindow || quickAskWindow.isDestroyed()) {+ quickAskWindow = createQuickAskWindow();+ }+}++function deactivateQuickAsk(): void {+ if (shortcutRegistered) {+ globalShortcut.unregister(currentShortcut);+ shortcutRegistered = false;+ }+ destroyQuickAskWindow();+}++/**+ * Every window shares these ipcMain channels, so each handler accepts events+ * only from the panel's own webContents — no other renderer (main window,+ * webviews, or a hypothetically compromised frame) may drive the panel's+ * privileged surface (asking, capture, window placement).+ */+function fromPanel(event: Electron.IpcMainEvent): boolean {+ return (+ quickAskWindow !== null &&+ !quickAskWindow.isDestroyed() &&+ event.sender === quickAskWindow.webContents+ );+}++export function setupQuickAsk(): void {+ // Prototype: dev builds only, or explicit opt-in.+ if (!isDevBuild() && process.env.POSTHOG_QUICK_ASK !== "1") {+ return;+ }+ quickAskEnabled = true;++ ipcMain.on(QUICK_ASK_HIDE_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ hideQuickAsk();+ });+ ipcMain.on(QUICK_ASK_RESIZE_CHANNEL, (event, size: unknown) => {+ if (!fromPanel(event)) return;+ if (!quickAskWindow || quickAskWindow.isDestroyed()) return;+ const { width, height } = (size ?? {}) as Partial<QuickAskResizePayload>;+ if (typeof width !== "number" || !Number.isFinite(width)) {+ log.warn("Quick ask resize payload malformed", { size });+ return;+ }+ if (typeof height !== "number" || !Number.isFinite(height)) {+ log.warn("Quick ask resize payload malformed", { size });+ return;+ }+ cachedContentWidth = Math.min(+ PANEL_MAX_WIDTH,+ Math.max(PANEL_INITIAL_WIDTH, Math.round(width)),+ );+ cachedContentHeight = Math.max(PILL_HEIGHT, Math.round(height));+ applyGeometry(quickAskWindow);+ });+ // Dragging: native `-webkit-app-region: drag` is incompatible with the+ // forwarded click-through events, so the renderer reports a grab offset+ // and the main process follows the cursor.+ ipcMain.on(QUICK_ASK_DRAG_START_CHANNEL, (event, offset: unknown) => {+ if (!fromPanel(event)) return;+ if (!quickAskWindow || quickAskWindow.isDestroyed()) return;+ const { dx, dy } = (offset ?? {}) as Partial<QuickAskDragStartPayload>;+ if (+ typeof dx !== "number" ||+ typeof dy !== "number" ||+ !Number.isFinite(dx) ||+ !Number.isFinite(dy)+ ) {+ return;+ }+ stopDrag();+ const shakeDetector = new ShakeDetector();+ dragState = {+ dx,+ dy,+ timer: setInterval(() => {+ if (+ !quickAskWindow ||+ quickAskWindow.isDestroyed() ||+ !quickAskWindow.isVisible()+ ) {+ stopDrag();+ return;+ }+ const point = screen.getCursorScreenPoint();+ if (shakeDetector.sample(point.x, Date.now())) {+ quickAskWindow.webContents.send(QUICK_ASK_SHAKE_CHANNEL);+ }+ const bounds = quickAskWindow.getBounds();+ const x = Math.round(point.x - dx);+ const y = Math.round(point.y - dy);+ if (x !== bounds.x || y !== bounds.y) {+ quickAskWindow.setPosition(x, y);+ // The anchor rides along; the grow direction is re-decided once+ // at drag end, so the panel does not flip mid-drag.+ pillAnchor = {+ x,+ y: currentFlip+ ? y + bounds.height - PILL_TOP_TO_WINDOW_BOTTOM+ : y + PILL_TOP_TO_WINDOW_TOP,+ };+ }+ }, 15),+ };+ });+ ipcMain.on(QUICK_ASK_DRAG_END_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ stopDrag();+ if (quickAskWindow && !quickAskWindow.isDestroyed()) {+ applyGeometry(quickAskWindow);+ }+ });+ ipcMain.on(QUICK_ASK_OPEN_IN_APP_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ hideQuickAsk();+ // The thread is a task; land the main window on it.+ const taskId = getQuickAskService().currentTaskId;+ if (taskId) {+ container.get<TaskLinkService>(TASK_LINK_SERVICE).openTask({ taskId });+ }+ focusMainWindow("quick-ask-open-in-app");+ app.focus({ steal: true });+ });+ ipcMain.on(+ QUICK_ASK_ASK_CHANNEL,+ (event, question: unknown, conversationId: unknown) => {+ if (!fromPanel(event)) return;+ if (typeof question !== "string" || !question.trim()) return;+ void streamAnswer(+ question.trim(),+ typeof conversationId === "string" && conversationId+ ? conversationId+ : undefined,+ );+ },+ );+ ipcMain.on(QUICK_ASK_CANCEL_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ getQuickAskService().cancel();+ });+ ipcMain.on(QUICK_ASK_RESET_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ clearPendingAttachment(captureHost);+ const service = getQuickAskService();+ service.reset();+ void service.warm();+ });+ ipcMain.on(QUICK_ASK_CAPTURE_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ void beginCapture(captureHost);+ });+ ipcMain.on(QUICK_ASK_DISCARD_ATTACHMENT_CHANNEL, (event) => {+ if (!fromPanel(event)) return;+ clearPendingAttachment(captureHost);+ });+ setupQuickAskCapture(captureHost);++ if (quickAskStore.get("panelEnabled")) {+ activateQuickAsk();+ }++ app.on("will-quit", () => {+ if (shortcutRegistered) {+ globalShortcut.unregister(currentShortcut);+ }+ });+}diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.tsindex 9507990dbd23..16706cd0bc00 100644--- a/products/desktop/apps/code/src/main/trpc/router.ts+++ b/products/desktop/apps/code/src/main/trpc/router.ts@@ -56,6 +56,7 @@ import { devRouter } from "./routers/dev";import { discordPresenceRouter } from "./routers/discord-presence";import { encryptionRouter } from "./routers/encryption";import { missionControlRouter } from "./routers/mission-control";+import { quickAskRouter } from "./routers/quick-ask";import { workspaceServerRouter } from "./routers/workspace-server";import { router } from "./trpc";@@ -97,6 +98,7 @@ export const trpcRouter = router({mcpCallback: mcpCallbackRouter,mcpRelay: mcpRelayRouter,missionControl: missionControlRouter,+ quickAsk: quickAskRouter,notification: notificationRouter,oauth: oauthRouter,onboardingImport: onboardingImportRouter,diff --git a/products/desktop/apps/code/src/main/trpc/routers/quick-ask.ts b/products/desktop/apps/code/src/main/trpc/routers/quick-ask.tsnew file mode 100644index 000000000000..49f6c8e6103d--- /dev/null+++ b/products/desktop/apps/code/src/main/trpc/routers/quick-ask.ts@@ -0,0 +1,54 @@+import { isValidQuickAskAccelerator } from "@posthog/shared/quick-ask-shortcuts";+import { z } from "zod";+import {+ getQuickAskState,+ setQuickAskSettings,+ setQuickAskShortcut,+} from "../../quick-ask";+import { publicProcedure, router } from "../trpc";++const quickAskStateSchema = z.object({+ enabled: z.boolean(),+ active: z.boolean(),+ shortcut: z.string(),+ registered: z.boolean(),+ defaultChannelId: z.string(),+ defaultRepositories: z.array(z.string()),+ defaultGithubIntegrationId: z.number(),+ defaultAdapter: z.string(),+ defaultModel: z.string(),+ defaultEffort: z.string(),+});++export const quickAskRouter = router({+ getState: publicProcedure+ .output(quickAskStateSchema)+ .query(() => getQuickAskState()),++ setShortcut: publicProcedure+ .input(+ z.object({+ accelerator: z+ .string()+ .max(64)+ .refine(isValidQuickAskAccelerator, "Not a recordable shortcut"),+ }),+ )+ .output(quickAskStateSchema)+ .mutation(({ input }) => setQuickAskShortcut(input.accelerator)),++ setSettings: publicProcedure+ .input(+ z.object({+ active: z.boolean().optional(),+ defaultChannelId: z.string().optional(),+ defaultRepositories: z.array(z.string()).optional(),+ defaultGithubIntegrationId: z.number().optional(),+ defaultAdapter: z.enum(["", "claude", "codex"]).optional(),+ defaultModel: z.string().max(120).optional(),+ defaultEffort: z.string().max(32).optional(),+ }),+ )+ .output(quickAskStateSchema)+ .mutation(({ input }) => setQuickAskSettings(input)),+});diff --git a/products/desktop/apps/code/src/main/utils/store.ts b/products/desktop/apps/code/src/main/utils/store.tsindex f50824ec197e..f2c38c0dc296 100644--- a/products/desktop/apps/code/src/main/utils/store.ts+++ b/products/desktop/apps/code/src/main/utils/store.ts@@ -29,6 +29,17 @@ interface RendererStoreSchema {[key: string]: string;}+interface QuickAskStoreSchema {+ panelEnabled: boolean;+ shortcut: string;+ defaultChannelId: string;+ defaultRepositories: string[];+ defaultGithubIntegrationId: number;+ defaultAdapter: string;+ defaultModel: string;+ defaultEffort: string;+}+export interface WindowStateSchema {x: number | undefined;y: number | undefined;@@ -54,6 +65,21 @@ export const focusStore = new Store<FocusStoreSchema>({defaults: { sessions: {} },});+export const quickAskStore = new Store<QuickAskStoreSchema>({+ name: "quick-ask",+ cwd: userDataDir,+ defaults: {+ panelEnabled: false,+ shortcut: "",+ defaultChannelId: "",+ defaultRepositories: [],+ defaultGithubIntegrationId: 0,+ defaultAdapter: "",+ defaultModel: "",+ defaultEffort: "",+ },+});+export type { FocusSession };export const windowStateStore = new Store<WindowStateSchema>({diff --git a/products/desktop/apps/code/src/main/window.ts b/products/desktop/apps/code/src/main/window.tsindex ef89e9d06a55..507d87d7e590 100644--- a/products/desktop/apps/code/src/main/window.ts+++ b/products/desktop/apps/code/src/main/window.ts@@ -109,6 +109,28 @@ export function saveWindowState(window: BrowserWindow): void {}let mainWindow: BrowserWindow | null = null;+let trpcIpcHandler: ReturnType<typeof createIPCHandler> | null = null;++/**+ * Serves the host tRPC router to a secondary window (the quick-ask panel).+ * No-op until the main window creates the handler. `allowedPaths` narrows+ * the window to a route allowlist: auxiliary windows get only the procedures+ * they need, never the full privileged router.+ */+export function attachWindowToTrpc(+ window: BrowserWindow,+ allowedPaths?: (path: string) => boolean,+): void {+ trpcIpcHandler?.attachWindow(window, { allowedPaths });+}++const mainWindowClosedListeners = new Set<() => void>();++/** Runs when the main window closes. Lets auxiliary windows (quick ask) tear+ * down so `window-all-closed` app-quit behavior is preserved. */+export function onMainWindowClosed(listener: () => void): void {+ mainWindowClosedListeners.add(listener);+}export function focusMainWindow(reason: string): void {if (mainWindow) {@@ -334,7 +356,7 @@ export function createWindow(): void {.get<ElectronMainWindow>(MAIN_WINDOW_SERVICE).setMainWindowGetter(() => mainWindow);- createIPCHandler({+ trpcIpcHandler = createIPCHandler({router: trpcRouter,windows: [mainWindow],createContext: async () => ({ container }),@@ -376,5 +398,8 @@ export function createWindow(): void {saveTimeout = null;}mainWindow = null;+ for (const listener of mainWindowClosedListeners) {+ listener();+ }});}diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.tsindex e8a3589ae5db..838fcb7d7637 100644--- a/products/desktop/apps/code/src/renderer/di/bindings.ts+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts@@ -229,6 +229,10 @@ import {NOTIFICATION_SETTINGS_PROVIDER,SPEECH_NOTIFY_SETTINGS,} from "@posthog/ui/features/notifications/identifiers";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+} from "@posthog/ui/features/quick-ask/identifiers";import {AGENT_PROMPT_SENDER,type AgentPromptSender,@@ -300,6 +304,7 @@ export interface RendererBindings {[CONNECTIVITY_CLIENT]: ConnectivityClient;[BROWSER_TABS_CLIENT]: BrowserTabsClient;[DISCORD_PRESENCE_CLIENT]: DiscordPresenceClient;+ [QUICK_ASK_SETTINGS_CLIENT]: QuickAskSettingsClient;[MISSION_CONTROL_CLIENT]: MissionControlClient;[SHELL_CLIENT]: ShellClient;[FOCUS_CONTROLLER_DEPS]: FocusControllerDeps;diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.tsindex 6f0256f863d9..998fb24fa1cb 100644--- a/products/desktop/apps/code/src/renderer/di/container.ts+++ b/products/desktop/apps/code/src/renderer/di/container.ts@@ -131,6 +131,10 @@ import {MISSION_CONTROL_CLIENT,type MissionControlClient,} from "@posthog/ui/features/mission-control/identifiers";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+} from "@posthog/ui/features/quick-ask/identifiers";import { ARTIFACT_HTML_FRAME_COMPONENT } from "@posthog/ui/features/sessions/components/artifactHtmlFrameHost";import { MCP_TOOL_BLOCK_COMPONENT } from "@posthog/ui/features/sessions/components/session-update/identifiers";import {@@ -248,6 +252,24 @@ const discordPresenceClient: DiscordPresenceClient = {};container.bind(DISCORD_PRESENCE_CLIENT).toConstantValue(discordPresenceClient);+const quickAskSettingsClient: QuickAskSettingsClient = {+ getState: () => trpcClient.quickAsk.getState.query(),+ setShortcut: (accelerator) =>+ trpcClient.quickAsk.setShortcut.mutate({ accelerator }),+ setSettings: (patch) =>+ trpcClient.quickAsk.setSettings.mutate({+ ...patch,+ defaultAdapter: patch.defaultAdapter as+ | ""+ | "claude"+ | "codex"+ | undefined,+ }),+};+container+ .bind(QUICK_ASK_SETTINGS_CLIENT)+ .toConstantValue(quickAskSettingsClient);+// mission control overlay clientconst missionControlClient: MissionControlClient = {onStateChanged: (onData) => {diff --git a/products/desktop/apps/code/src/renderer/quick-ask-annotate/main.tsx b/products/desktop/apps/code/src/renderer/quick-ask-annotate/main.tsxnew file mode 100644index 000000000000..820c35f0440a--- /dev/null+++ b/products/desktop/apps/code/src/renderer/quick-ask-annotate/main.tsx@@ -0,0 +1,13 @@+import { Annotate } from "@posthog/quick-ask/annotate/Annotate";+import React from "react";+import { createRoot } from "react-dom/client";+import "@posthog/quick-ask/annotate/annotate.css";++const root = document.getElementById("root");+if (root) {+ createRoot(root).render(+ <React.StrictMode>+ <Annotate />+ </React.StrictMode>,+ );+}diff --git a/products/desktop/apps/code/src/renderer/quick-ask/main.tsx b/products/desktop/apps/code/src/renderer/quick-ask/main.tsxnew file mode 100644index 000000000000..0ea75bc3afc2--- /dev/null+++ b/products/desktop/apps/code/src/renderer/quick-ask/main.tsx@@ -0,0 +1,97 @@+// Global styles first so quick-ask.css overrides win at equal specificity.+import "@posthog/ui/styles/globals.css";+import "@posthog/quick-ask/panel/quick-ask.css";+import type { AuthState } from "@posthog/core/auth/schemas";+import { setRootContainer } from "@posthog/di/container";+import { ipcLink } from "@posthog/electron-trpc/renderer";+import { HOST_TRPC_CLIENT } from "@posthog/host-router/client";+import { HostTRPCProvider } from "@posthog/host-router/react";+import type { HostRouter } from "@posthog/host-router/router";+import { QuickAsk } from "@posthog/quick-ask/panel/QuickAsk";+import { getAuthIdentity, useAuthStore } from "@posthog/ui/features/auth/store";+import { ThemeWrapper } from "@posthog/ui/primitives/ThemeWrapper";+import { useThemeStore } from "@posthog/ui/shell/themeStore";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createTRPCClient } from "@trpc/client";+import { Container } from "inversify";+import React from "react";+import ReactDOM from "react-dom/client";+import superjson from "superjson";+import { BootErrorBoundary } from "../components/BootErrorBoundary";++// The panel boots only what answer rendering needs: host tRPC (auth tokens,+// external links), react-query, and the theme.+const hostTrpcClient = createTRPCClient<HostRouter>({+ links: [ipcLink({ transformer: superjson })],+});++// Components outside React's tree (openExternalUrl) resolve the host client+// through the shared service locator.+const container = new Container();+container.bind(HOST_TRPC_CLIENT).toConstantValue(hostTrpcClient);+setRootContainer(container);++const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: 1, refetchOnWindowFocus: false },+ },+});++// The panel has its own react-query cache and never runs the main window's+// project-switch side effects, so it purges auth-scoped queries itself when+// the identity (region + project) changes. Without this, a chart or preview+// cached in project A would serve under project B for its stale period.+let authIdentity: string | null | undefined;+function applyAuthState(state: AuthState): void {+ const next = getAuthIdentity(state);+ if (authIdentity !== undefined && next !== authIdentity) {+ queryClient.removeQueries({+ predicate: (query) => query.meta?.authScoped === true,+ });+ }+ authIdentity = next;+ useAuthStore.getState().setAuthState(state);+}++// Subscription first so no auth state change is missed while the initial+// query is in flight.+hostTrpcClient.auth.onStateChanged.subscribe(undefined, {+ onData: (state) => applyAuthState(state),+});+void hostTrpcClient.auth.getState+ .query()+ .then((state) => applyAuthState(state))+ .catch(() => {+ // Signed-out rendering is fine; chips fall back to static cards.+ });++// Theme changes made in the main window land in shared localStorage;+// re-reading them keeps this window on the app's theme.+window.addEventListener("storage", (event) => {+ if (event.key === "theme-storage") {+ void useThemeStore.persist.rehydrate();+ }+});++const root = document.getElementById("root");+if (root) {+ ReactDOM.createRoot(root).render(+ <React.StrictMode>+ {/* A render crash (rich answer content is live data) otherwise unmounts+ the whole panel with no way to close, reset, or retry; the boundary's+ reload boots the window fresh. */}+ <BootErrorBoundary>+ <QueryClientProvider client={queryClient}>+ <HostTRPCProvider+ trpcClient={hostTrpcClient}+ queryClient={queryClient}+ >+ <ThemeWrapper>+ <QuickAsk />+ </ThemeWrapper>+ </HostTRPCProvider>+ </QueryClientProvider>+ </BootErrorBoundary>+ </React.StrictMode>,+ );+}diff --git a/products/desktop/apps/code/src/shared/constants.ts b/products/desktop/apps/code/src/shared/constants.tsindex cf3e7cc15f17..30a5a3cd5ee9 100644--- a/products/desktop/apps/code/src/shared/constants.ts+++ b/products/desktop/apps/code/src/shared/constants.ts@@ -6,6 +6,62 @@ export const SELF_DRIVING_SETUP_TASK_FLAG =export const DISCOVERY_RUN_FLAG = "posthog-code-discovery-run";export const BRANCH_PREFIX = "posthog/";export const APP_WINDOW_ARG = "--posthog-app-window";+export const QUICK_ASK_WINDOW_ARG = "--posthog-quick-ask-window";+export const QUICK_ASK_HIDE_CHANNEL = "posthog-quick-ask-hide";+export const QUICK_ASK_RESIZE_CHANNEL = "posthog-quick-ask-resize";+export const QUICK_ASK_OPEN_IN_APP_CHANNEL = "posthog-quick-ask-open-in-app";+export const QUICK_ASK_SHOWN_CHANNEL = "posthog-quick-ask-shown";+export const QUICK_ASK_SHAKE_CHANNEL = "posthog-quick-ask-shake";+export const QUICK_ASK_ASK_CHANNEL = "posthog-quick-ask-ask";+export const QUICK_ASK_CANCEL_CHANNEL = "posthog-quick-ask-cancel";+export const QUICK_ASK_RESET_CHANNEL = "posthog-quick-ask-reset";+export const QUICK_ASK_EVENT_CHANNEL = "posthog-quick-ask-event";+export const QUICK_ASK_LAYOUT_CHANNEL = "posthog-quick-ask-layout";+export const QUICK_ASK_DRAG_START_CHANNEL = "posthog-quick-ask-drag-start";+export const QUICK_ASK_DRAG_END_CHANNEL = "posthog-quick-ask-drag-end";+export const QUICK_ASK_CAPTURE_CHANNEL = "posthog-quick-ask-capture";+export const QUICK_ASK_ATTACHMENT_CHANNEL = "posthog-quick-ask-attachment";+export const QUICK_ASK_DISCARD_ATTACHMENT_CHANNEL =+ "posthog-quick-ask-discard-attachment";+export const QUICK_ASK_ANNOTATE_WINDOW_ARG = "--posthog-quick-ask-annotate";+export const QUICK_ASK_ANNOTATE_SHOT_CHANNEL = "posthog-quick-ask-shot";+export const QUICK_ASK_SCREEN_SETTINGS_CHANNEL =+ "posthog-quick-ask-screen-settings";+export const QUICK_ASK_ANNOTATE_DONE_CHANNEL = "posthog-quick-ask-annotated";++/** Sent to the panel when a screenshot is ready to attach (or cleared). */+export interface QuickAskAttachmentPayload {+ /** Preview for the chip; the full image stays in the main process. */+ previewDataUrl: string | null;+ /** Why capture produced nothing, e.g. missing screen-recording consent. */+ error?: string;+ /** The OS has a settings pane that grants the missing permission. */+ canOpenSettings?: boolean;+}++/**+ * Payload contracts for the quick-ask IPC channels. The preload and the main+ * process must import these instead of retyping the shapes: the two sides+ * are compiled separately, so a shape change that touches only one of them+ * is invisible to the typechecker and fails silently at runtime.+ */+export interface QuickAskResizePayload {+ width: number;+ height: number;+}++export interface QuickAskDragStartPayload {+ /** Grab offset from the window's top-left corner, in CSS pixels. */+ dx: number;+ dy: number;+}++export interface QuickAskLayoutPayload {+ /** Card renders above the pill (anchor sits low on the screen). */+ flip: boolean;+ /** Room between the pill's anchor and the screen edge, in CSS pixels. */+ maxHeight: number;+}export const ARTIFACT_PREVIEW_ARG = "--posthog-artifact-preview";export const ARTIFACT_OPEN_EXTERNAL_CHANNEL = "posthog-artifact-open-external";export const ARTIFACT_HOST_TO_PREVIEW_CHANNEL = "posthog-artifact-host-message";diff --git a/products/desktop/apps/code/src/shared/test/setup.ts b/products/desktop/apps/code/src/shared/test/setup.tsindex 7978c69794c4..318502644a15 100644--- a/products/desktop/apps/code/src/shared/test/setup.ts+++ b/products/desktop/apps/code/src/shared/test/setup.ts@@ -81,7 +81,11 @@ globalThis.ResizeObserver = class ResizeObserver {disconnect = vi.fn();};-if (typeof globalThis.PointerEvent === "undefined") {+// Node-environment tests (`@vitest-environment node`) have no MouseEvent.+if (+ typeof MouseEvent !== "undefined" &&+ typeof globalThis.PointerEvent === "undefined"+) {class JsdomPointerEvent extends MouseEvent {pointerId: number;pointerType: string;@@ -111,22 +115,25 @@ if (typeof globalThis.PointerEvent === "undefined") {globalThis.PointerEvent = JsdomPointerEvent as unknown as typeof PointerEvent;}-HTMLCanvasElement.prototype.getContext = vi.fn();-Element.prototype.scrollIntoView = vi.fn();+// Node-environment tests have no DOM to patch.+if (typeof window !== "undefined") {+ HTMLCanvasElement.prototype.getContext = vi.fn();+ Element.prototype.scrollIntoView = vi.fn();-Object.defineProperty(window, "matchMedia", {- writable: true,- value: vi.fn().mockImplementation((query) => ({- matches: false,- media: query,- onchange: null,- addListener: vi.fn(),- removeListener: vi.fn(),- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- dispatchEvent: vi.fn(),- })),-});+ Object.defineProperty(window, "matchMedia", {+ writable: true,+ value: vi.fn().mockImplementation((query) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ });+}afterEach(() => {cleanup();diff --git a/products/desktop/apps/code/vite.shared.mts b/products/desktop/apps/code/vite.shared.mtsindex 4ad3ddb95e86..02f257531e13 100644--- a/products/desktop/apps/code/vite.shared.mts+++ b/products/desktop/apps/code/vite.shared.mts@@ -76,6 +76,10 @@ export const workspaceAliases: Alias[] = [find: /^@posthog\/api-client\/(.+)$/,replacement: path.resolve(__dirname, "../../packages/api-client/src/$1"),},+ {+ find: /^@posthog\/quick-ask\/(.+)$/,+ replacement: path.resolve(__dirname, "../../packages/quick-ask/src/$1"),+ },{find: /^@posthog\/ui\/(.+)$/,replacement: path.resolve(__dirname, "../../packages/ui/src/$1"),diff --git a/products/desktop/biome.jsonc b/products/desktop/biome.jsoncindex b5697eaf7b31..fbbf6a84f694 100644--- a/products/desktop/biome.jsonc+++ b/products/desktop/biome.jsonc@@ -78,6 +78,8 @@"!apps/code/src/main/bootstrap.ts","!apps/code/src/main/index.ts","!apps/code/src/main/window.ts",+ "!apps/code/src/main/quick-ask.ts",+ "!apps/code/src/main/quick-ask-capture.ts","!apps/code/src/main/external-links.ts","!apps/code/src/main/menu.ts","!apps/code/src/main/preload.ts",@@ -210,6 +212,43 @@}}},+ {+ // The quick-ask feature package runs in any renderer. The replay+ // fixture and the tests it feeds are the only node-touching files.+ "includes": [+ "packages/quick-ask/src/**/*.ts",+ "packages/quick-ask/src/**/*.tsx",+ "!packages/quick-ask/src/service/replay-fixture.ts",+ "!packages/quick-ask/src/**/*.test.ts"+ ],+ "linter": {+ "rules": {+ "style": {+ "noRestrictedImports": {+ "level": "error",+ "options": {+ "patterns": [+ {+ "group": [+ "electron",+ "node:*",+ "@posthog/*",+ "!@posthog/core",+ "!@posthog/core/*",+ "!@posthog/shared",+ "!@posthog/shared/*",+ "!@posthog/ui",+ "!@posthog/ui/*"+ ],+ "message": "quick-ask is host-agnostic. Allowed @posthog deps: core, shared, ui. The Electron host lives in apps/code."+ }+ ]+ }+ }+ }+ }+ }+ },{"includes": ["packages/api-client/src/**/*.ts",diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex 85a95cf78610..5f3fc4cd1647 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -43,7 +43,7 @@ import {const TOKEN_EXPIRY_SKEW_MS = 60_000;const AUTH_FETCH_TIMEOUT_MS = 30_000;const AUTH_BOOTSTRAP_DEADLINE_MS = 20_000;-type FetchLike = (+export type FetchLike = (input: string | Request,init?: RequestInit,) => Promise<Response>;diff --git a/products/desktop/packages/core/src/links/task-link.ts b/products/desktop/packages/core/src/links/task-link.tsindex 770434b1db5d..f501640e5b21 100644--- a/products/desktop/packages/core/src/links/task-link.ts+++ b/products/desktop/packages/core/src/links/task-link.ts@@ -72,18 +72,22 @@ export class TaskLinkService extends TypedEventEmitter<TaskLinkEvents> {itemId: searchParams.get("item") ?? undefined,}: undefined;- const payload: TaskLinkPayload = { taskId, taskRunId, comment };+ return this.openTask({ taskId, taskRunId, comment });+ }+ /** Routes the main window to a task, queueing until the renderer is ready. */+ public openTask(payload: TaskLinkPayload): boolean {+ const { taskId, taskRunId, comment } = payload;const hasListeners = this.listenerCount(TaskLinkEvent.OpenTask) > 0;if (hasListeners) {this.log.info(- `Emitting task link event: taskId=${taskId}, taskRunId=${taskRunId ?? "none"}, comment=${threadId ?? "none"}`,+ `Emitting task link event: taskId=${taskId}, taskRunId=${taskRunId ?? "none"}, comment=${comment?.threadId ?? "none"}`,);this.emit(TaskLinkEvent.OpenTask, payload);} else {this.log.info(- `Queueing task link (renderer not ready): taskId=${taskId}, taskRunId=${taskRunId ?? "none"}, comment=${threadId ?? "none"}`,+ `Queueing task link (renderer not ready): taskId=${taskId}, taskRunId=${taskRunId ?? "none"}, comment=${comment?.threadId ?? "none"}`,);this.pendingDeepLink = payload;}diff --git a/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.ts b/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.tsnew file mode 100644index 000000000000..b348f3177088--- /dev/null+++ b/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.ts@@ -0,0 +1,107 @@+import * as trpc from "@trpc/server";+import type { BrowserWindow } from "electron";+import { ipcMain } from "electron";+import { describe, expect, test, vi } from "vitest";++import { ELECTRON_TRPC_CHANNEL } from "../../constants";+import { createIPCHandler } from "../createIPCHandler";++vi.mock("electron", async () => {+ const { EventEmitter } = await import("node:events");+ return { ipcMain: new EventEmitter() };+});++const t = trpc.initTRPC.create();+const router = t.router({+ open: t.procedure.query(() => "ok"),+ secret: t.procedure.query(() => "secret"),+});++function fakeWindow(id: number): {+ win: BrowserWindow;+ webContents: { id: number };+} {+ const webContents = {+ id,+ isDestroyed: () => false,+ on: vi.fn(),+ once: vi.fn(),+ };+ return {+ win: {+ isDestroyed: () => false,+ webContents,+ } as unknown as BrowserWindow,+ webContents,+ };+}++function requestFor(path: string, id: number) {+ return {+ method: "request" as const,+ operation: {+ context: {},+ id,+ input: undefined,+ path,+ type: "query" as const,+ signal: undefined,+ },+ };+}++function eventFrom(webContents: unknown) {+ return {+ sender: webContents,+ senderFrame: undefined,+ reply: vi.fn(),+ };+}++const flush = () => new Promise((resolve) => setImmediate(resolve));++describe("createIPCHandler sender gating", () => {+ test("answers attached windows and drops unattached senders", async () => {+ const { win, webContents } = fakeWindow(1);+ createIPCHandler({ router, windows: [win as BrowserWindow] });++ const attached = eventFrom(webContents);+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, attached, requestFor("open", 1));+ await flush();+ expect(attached.reply).toHaveBeenCalled();++ // A webContents never attached (another window, a webview) gets nothing.+ const stranger = eventFrom({ id: 99, isDestroyed: () => false });+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, stranger, requestFor("open", 2));+ await flush();+ expect(stranger.reply).not.toHaveBeenCalled();+ });++ test("enforces a window's path allowlist", async () => {+ const main = fakeWindow(1);+ const panel = fakeWindow(2);+ const handler = createIPCHandler({+ router,+ windows: [main.win as BrowserWindow],+ });+ handler.attachWindow(panel.win as BrowserWindow, {+ allowedPaths: (path) => path === "open",+ });++ const allowed = eventFrom(panel.webContents);+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, allowed, requestFor("open", 1));+ await flush();+ expect(allowed.reply).toHaveBeenCalled();++ const blocked = eventFrom(panel.webContents);+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, blocked, requestFor("secret", 2));+ await flush();+ expect(blocked.reply).not.toHaveBeenCalled();++ // The unrestricted main window still reaches every route.+ const mainEvent = eventFrom(main.webContents);+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, mainEvent, requestFor("secret", 3));+ await flush();+ expect(mainEvent.reply).toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts b/products/desktop/packages/electron-trpc/src/main/createIPCHandler.tsindex 83896f617146..123eef125868 100644--- a/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts+++ b/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts@@ -15,8 +15,19 @@ const getInternalId = (event: IpcMainEvent, request: ETRPCRequest) => {return `${event.sender.id}-${event.senderFrame?.routingId ?? 0}:${messageId}`;};+export interface AttachWindowOptions {+ /**+ * Restricts the window to a subset of procedure paths (e.g. a narrow+ * bridge for an auxiliary window). Requests outside the set are dropped+ * before they reach the router. Subscription stops and operation cancels+ * always pass: they only touch the sender's own operations.+ */+ allowedPaths?: (path: string) => boolean;+}+class IPCHandler<TRouter extends AnyTRPCRouter> {#windows: BrowserWindow[] = [];+ #pathFilters: Map<number, (path: string) => boolean> = new Map();#operations: Map<string, AbortController> = new Map();#listener: (event: IpcMainEvent, request: ETRPCRequest) => void;@@ -38,6 +49,18 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {}this.#listener = (event: IpcMainEvent, request: ETRPCRequest) => {+ // Only attached windows get answers: the channel is a global ipcMain+ // listener, so without this any webContents in the app could reach+ // the full router.+ if (!this.#allows(event, request)) {+ console.warn(+ "electron-trpc: dropped request from unauthorized sender",+ request.method === "request"+ ? request.operation.path+ : request.method,+ );+ return;+ }handleIPCMessage({router,createContext,@@ -51,6 +74,18 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {ipcMain.on(ELECTRON_TRPC_CHANNEL, this.#listener);}+ #allows(event: IpcMainEvent, request: ETRPCRequest): boolean {+ const attached = this.#windows.some(+ (win) => !win.isDestroyed() && win.webContents === event.sender,+ );+ if (!attached) return false;+ // Stops and cancels are keyed by the sender's own internal id, so they+ // can only ever abort that sender's operations.+ if (request.method !== "request") return true;+ const filter = this.#pathFilters.get(event.sender.id);+ return filter ? filter(request.operation.path) : true;+ }+destroy() {ipcMain.removeListener(ELECTRON_TRPC_CHANNEL, this.#listener);for (const sub of this.#operations.values()) {@@ -59,7 +94,10 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {this.#operations.clear();}- attachWindow(win: BrowserWindow) {+ attachWindow(win: BrowserWindow, options?: AttachWindowOptions) {+ if (options?.allowedPaths) {+ this.#pathFilters.set(win.webContents.id, options.allowedPaths);+ }if (this.#windows.includes(win)) {return;}@@ -77,8 +115,10 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {);}+ const senderId = webContentsId ?? win.webContents.id;+ this.#pathFilters.delete(senderId);this.#cleanUpSubscriptions({- webContentsId: webContentsId ?? win.webContents.id,+ webContentsId: senderId,});}diff --git a/products/desktop/packages/quick-ask/package.json b/products/desktop/packages/quick-ask/package.jsonnew file mode 100644index 000000000000..7d1b77bb5d5c--- /dev/null+++ b/products/desktop/packages/quick-ask/package.json@@ -0,0 +1,35 @@+{+ "name": "@posthog/quick-ask",+ "version": "1.0.0",+ "description": "The quick-ask floating assistant, host-agnostic: the prewarmed-task transport (service), the panel and annotator UI, and the pure gesture/geometry logic. The Electron host in apps/code only owns windows, IPC, and capture.",+ "private": true,+ "type": "module",+ "exports": {+ "./*": [+ "./src/*.ts",+ "./src/*.tsx",+ "./src/*"+ ]+ },+ "scripts": {+ "typecheck": "tsc --noEmit",+ "test": "vitest run",+ "clean": "node ../../scripts/rimraf.mjs .turbo"+ },+ "dependencies": {+ "@posthog/core": "workspace:*",+ "@posthog/shared": "workspace:*",+ "@posthog/ui": "workspace:*",+ "inversify": "catalog:",+ "react": "catalog:",+ "react-markdown": "^10.1.0"+ },+ "devDependencies": {+ "@posthog/tsconfig": "workspace:*",+ "typescript": "catalog:",+ "vitest": "^4.1.8"+ },+ "files": [+ "src/**/*"+ ]+}diff --git a/products/desktop/packages/quick-ask/src/annotate/Annotate.tsx b/products/desktop/packages/quick-ask/src/annotate/Annotate.tsxnew file mode 100644index 000000000000..42b3fcdf5d8e--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/Annotate.tsx@@ -0,0 +1,1129 @@+import type React from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import { annotateHost } from "./host-bridge";+import {+ contrastInk,+ drawShape,+ hitShape,+ normalizeRect,+ type Point,+ type Rect,+ type Shape,+ shapeBBox,+ TEXT_BG_PAD_X,+ TEXT_BG_PAD_Y,+ TEXT_LINE,+ TEXT_MAX_SIZE,+ TEXT_MIN_SIZE,+ TEXT_MIN_WIDTH,+ TEXT_SIZE,+ type Tool,+ textFont,+ textNaturalWidth,+ translateShape,+} from "./shapes";+import { ToolIcon } from "./ToolIcon";++/** Long-edge cap for the exported PNG, well under the attachment size limit. */+const EXPORT_MAX_EDGE = 2000;+/** Drags smaller than this are clicks, not rects. */+const MIN_DRAG_PX = 6;+/** Hit radius around a resize handle, larger than its visual size. */+const HANDLE_HIT_PX = 12;++const COLORS = ["#ff4d1f", "#ffb224", "#3b82f6", "#ffffff"];++const TOOLS: { tool: Tool; label: string; key: string }[] = [+ { tool: "select", label: "Select", key: "V" },+ { tool: "crop", label: "Crop", key: "C" },+ { tool: "arrow", label: "Arrow", key: "A" },+ { tool: "rect", label: "Box", key: "R" },+ { tool: "ellipse", label: "Ellipse", key: "O" },+ { tool: "pen", label: "Draw", key: "P" },+ { tool: "text", label: "Text", key: "T" },+ { tool: "counter", label: "Counter", key: "N" },+ { tool: "pixelate", label: "Pixelate", key: "X" },+];++type Handle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";++const HANDLES: Handle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];++const HANDLE_CURSORS: Record<Handle, string> = {+ nw: "nwse-resize",+ se: "nwse-resize",+ ne: "nesw-resize",+ sw: "nesw-resize",+ n: "ns-resize",+ s: "ns-resize",+ e: "ew-resize",+ w: "ew-resize",+};++function handlePoint(crop: Rect, handle: Handle): Point {+ const cx = crop.x + crop.w / 2;+ const cy = crop.y + crop.h / 2;+ switch (handle) {+ case "nw":+ return { x: crop.x, y: crop.y };+ case "n":+ return { x: cx, y: crop.y };+ case "ne":+ return { x: crop.x + crop.w, y: crop.y };+ case "e":+ return { x: crop.x + crop.w, y: cy };+ case "se":+ return { x: crop.x + crop.w, y: crop.y + crop.h };+ case "s":+ return { x: cx, y: crop.y + crop.h };+ case "sw":+ return { x: crop.x, y: crop.y + crop.h };+ case "w":+ return { x: crop.x, y: cy };+ }+}++function hitHandle(crop: Rect, point: Point): Handle | null {+ for (const handle of HANDLES) {+ const at = handlePoint(crop, handle);+ if (+ Math.abs(point.x - at.x) <= HANDLE_HIT_PX &&+ Math.abs(point.y - at.y) <= HANDLE_HIT_PX+ ) {+ return handle;+ }+ }+ return null;+}++function resizeCrop(crop: Rect, handle: Handle, to: Point): Rect {+ let { x, y } = crop;+ let right = crop.x + crop.w;+ let bottom = crop.y + crop.h;+ if (handle.includes("w")) x = to.x;+ if (handle.includes("e")) right = to.x;+ if (handle.includes("n")) y = to.y;+ if (handle.includes("s")) bottom = to.y;+ return normalizeRect({ x, y }, { x: right, y: bottom });+}++function clampCrop(crop: Rect): Rect {+ const w = Math.min(crop.w, window.innerWidth);+ const h = Math.min(crop.h, window.innerHeight);+ return {+ x: Math.min(Math.max(crop.x, 0), window.innerWidth - w),+ y: Math.min(Math.max(crop.y, 0), window.innerHeight - h),+ w,+ h,+ };+}++function inside(rect: Rect, point: Point): boolean {+ return (+ point.x >= rect.x &&+ point.x <= rect.x + rect.w &&+ point.y >= rect.y &&+ point.y <= rect.y + rect.h+ );+}++/** Shapes with snapshot history, so delete/move/recolor undo cleanly. */+interface Doc {+ past: Shape[][];+ shapes: Shape[];+ future: Shape[][];+}++type Drag =+ | { mode: "select"; from: Point }+ | { mode: "draw"; from: Point }+ | { mode: "move"; from: Point; orig: Rect }+ | { mode: "resize"; handle: Handle }+ | {+ mode: "move-shape";+ from: Point;+ index: number;+ orig: Shape[];+ moved: boolean;+ }+ | {+ mode: "resize-shape";+ index: number;+ handle: string;+ orig: Shape[];+ moved: boolean;+ };++function pointOf(event: React.MouseEvent): Point {+ return { x: event.clientX, y: event.clientY };+}++/**+ * Wrap width for new text: the room left inside the selection, capped at a+ * readable line length so labels never run the full width of a large crop.+ */+function textWrapCap(x: number, crop: Rect, bg: boolean): number {+ const pads = bg ? TEXT_BG_PAD_X * 2 : 0;+ const room = Math.max(crop.x + crop.w, x + 160) - x - pads - 8;+ const readable = Math.max(260, Math.min(520, crop.w * 0.6));+ return Math.max(TEXT_MIN_WIDTH, Math.min(room, readable));+}++interface ShapeHandle {+ id: string;+ at: Point;+ cursor: string;+}++/** Resize handles: corners and edges for boxes, endpoints for arrows,+ * wrap-width side handles for text. */+function shapeHandles(shape: Shape): ShapeHandle[] {+ switch (shape.kind) {+ case "rect":+ case "ellipse":+ case "pixelate":+ return HANDLES.map((handle) => ({+ id: handle,+ at: handlePoint(shape.rect, handle),+ cursor: HANDLE_CURSORS[handle],+ }));+ case "arrow":+ return [+ { id: "from", at: shape.from, cursor: "move" },+ { id: "to", at: shape.to, cursor: "move" },+ ];+ case "text": {+ const box = shapeBBox(shape);+ const cy = box.y + box.h / 2;+ return [+ { id: "w", at: { x: box.x - 5, y: cy }, cursor: "ew-resize" },+ { id: "e", at: { x: box.x + box.w + 5, y: cy }, cursor: "ew-resize" },+ ];+ }+ default:+ return [];+ }+}++function hitShapeHandle(shape: Shape, point: Point): ShapeHandle | null {+ for (const handle of shapeHandles(shape)) {+ if (+ Math.abs(point.x - handle.at.x) <= HANDLE_HIT_PX &&+ Math.abs(point.y - handle.at.y) <= HANDLE_HIT_PX+ ) {+ return handle;+ }+ }+ return null;+}++/** A resize-handle drag applied to the shape that grabbed it. */+function resizeShape(shape: Shape, handle: string, to: Point): Shape {+ switch (shape.kind) {+ case "rect":+ case "ellipse":+ case "pixelate":+ return { ...shape, rect: resizeCrop(shape.rect, handle as Handle, to) };+ case "arrow":+ // Endpoint drags re-aim just that end of the line.+ return handle === "from" ? { ...shape, from: to } : { ...shape, to };+ case "text": {+ const pad = shape.bg ? TEXT_BG_PAD_X : 0;+ const box = shapeBBox(shape);+ const contentW = box.w - pad * 2;+ if (handle === "e") {+ const width = Math.max(to.x - 5 - pad - shape.at.x, TEXT_MIN_WIDTH);+ return { ...shape, width };+ }+ const right = shape.at.x + contentW;+ const x = Math.min(to.x + 5 + pad, right - TEXT_MIN_WIDTH);+ return { ...shape, at: { ...shape.at, x }, width: right - x };+ }+ default:+ return shape;+ }+}++export function Annotate(): React.JSX.Element {+ const [shot, setShot] = useState<HTMLImageElement | null>(null);+ const [crop, setCrop] = useState<Rect | null>(() => ({+ x: 0,+ y: 0,+ w: window.innerWidth,+ h: window.innerHeight,+ }));+ const [tool, setTool] = useState<Tool>("select");+ const [color, setColor] = useState(COLORS[0]);+ const [doc, setDoc] = useState<Doc>({ past: [], shapes: [], future: [] });+ const [selected, setSelected] = useState<number | null>(null);+ const [textBg, setTextBg] = useState(true);+ const [textSize, setTextSize] = useState(TEXT_SIZE);+ const [draft, setDraft] = useState<Shape | null>(null);+ const [textDraft, setTextDraft] = useState<Point | null>(null);+ const [cursor, setCursor] = useState("default");+ const [spaceHeld, setSpaceHeld] = useState(false);+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const textRef = useRef<HTMLTextAreaElement>(null);+ const drag = useRef<Drag | null>(null);++ const { shapes } = doc;++ // Focus the text editor once it mounts; autoFocus races the mousedown.+ useEffect(() => {+ if (textDraft) {+ requestAnimationFrame(() => textRef.current?.focus());+ }+ }, [textDraft]);++ useEffect(() => {+ void annotateHost()+ .shot()+ .then((dataUrl) => {+ if (!dataUrl) {+ annotateHost().cancel();+ return;+ }+ const image = new Image();+ image.onload = () => setShot(image);+ image.src = dataUrl;+ });+ }, []);++ const scaleX = shot ? shot.naturalWidth / window.innerWidth : 1;+ const scaleY = shot ? shot.naturalHeight / window.innerHeight : 1;++ const commit = useCallback((updater: (shapes: Shape[]) => Shape[]): void => {+ setDoc((current) => ({+ past: [...current.past, current.shapes],+ shapes: updater(current.shapes),+ future: [],+ }));+ }, []);++ const pushShape = useCallback(+ (shape: Shape): void => {+ commit((current) => [...current, shape]);+ setSelected(shapes.length);+ },+ [commit, shapes.length],+ );++ const deleteSelected = useCallback((): void => {+ if (selected === null) return;+ commit((current) => current.filter((_, index) => index !== selected));+ setSelected(null);+ }, [selected, commit]);++ // Builds the shape for the open text draft, or null when there is no draft+ // or its value is blank. Shared by commitText and the synchronous export in+ // finish, so the exported PNG and the committed shape can never diverge.+ const buildTextShape = useCallback((): Shape | null => {+ const at = textDraft;+ const value = textRef.current?.value ?? "";+ if (!at || !value.trim()) return null;+ const text = value.trimEnd();+ const cap = crop ? textWrapCap(at.x, crop, textBg) : undefined;+ const wraps = cap !== undefined && textNaturalWidth(text, textSize) > cap;+ return {+ kind: "text",+ at,+ text,+ color,+ bg: textBg,+ size: textSize,+ ...(wraps ? { width: cap } : {}),+ };+ }, [textDraft, crop, color, textBg, textSize]);++ const commitText = useCallback(+ (keep: boolean): void => {+ const shape = keep ? buildTextShape() : null;+ setTextDraft(null);+ if (shape) {+ pushShape(shape);+ // The usual next step is placing the label, so hand over the+ // select tool with the fresh label already selected.+ setTool("select");+ }+ },+ [buildTextShape, pushShape],+ );++ const undo = useCallback((): void => {+ setSelected(null);+ setDoc((current) => {+ const previous = current.past.at(-1);+ if (!previous) return current;+ return {+ past: current.past.slice(0, -1),+ shapes: previous,+ future: [...current.future, current.shapes],+ };+ });+ }, []);++ const redo = useCallback((): void => {+ setSelected(null);+ setDoc((current) => {+ const next = current.future.at(-1);+ if (!next) return current;+ return {+ past: [...current.past, current.shapes],+ shapes: next,+ future: current.future.slice(0, -1),+ };+ });+ }, []);++ // Swatches recolor the selection when there is one; either way they set+ // the ink for what comes next.+ const pickColor = useCallback(+ (value: string): void => {+ setColor(value);+ if (selected !== null && shapes[selected]?.kind !== "pixelate") {+ commit((current) =>+ current.map((shape, index) =>+ index === selected && shape.kind !== "pixelate"+ ? { ...shape, color: value }+ : shape,+ ),+ );+ }+ },+ [selected, shapes, commit],+ );++ const toggleTextBg = useCallback((): void => {+ setTextBg((current) => !current);+ if (selected !== null && shapes[selected]?.kind === "text") {+ commit((current) =>+ current.map((shape, index) =>+ index === selected && shape.kind === "text"+ ? { ...shape, bg: !shape.bg }+ : shape,+ ),+ );+ }+ }, [selected, shapes, commit]);++ // The slider's drag is one undo step: grab snapshots the pre-drag shapes and+ // release records them as a single entry. A keyboard change on the focused+ // slider fires onChange with no grab, so pickTextSize commits it on its own.+ const sizeDragOrig = useRef<Shape[] | null>(null);++ const pickTextSize = useCallback(+ (value: number): void => {+ setTextSize(value);+ if (selected === null || shapes[selected]?.kind !== "text") return;+ const applySize = (list: Shape[]): Shape[] =>+ list.map((shape, index) =>+ index === selected && shape.kind === "text"+ ? { ...shape, size: value }+ : shape,+ );+ if (sizeDragOrig.current) {+ // Mid-drag: fold into the single entry release will record.+ setDoc((current) => ({+ ...current,+ shapes: applySize(current.shapes),+ }));+ } else {+ // Keyboard: its own undo step, and clears redo like the sibling+ // color and background controls already do.+ commit(applySize);+ }+ },+ [selected, shapes, commit],+ );++ const grabTextSize = useCallback((): void => {+ sizeDragOrig.current =+ selected !== null && shapes[selected]?.kind === "text" ? shapes : null;+ }, [selected, shapes]);++ const releaseTextSize = useCallback((): void => {+ const orig = sizeDragOrig.current;+ sizeDragOrig.current = null;+ if (!orig) return;+ setDoc((current) =>+ current.shapes === orig+ ? current+ : { ...current, past: [...current.past, orig], future: [] },+ );+ }, []);++ const finish = useCallback((): void => {+ if (!shot) return;+ // Build the open draft synchronously: commitText only schedules a state+ // update, so `shapes` in this same tick would not yet hold the new label+ // and the export would drop it (e.g. clicking Attach without pressing+ // Enter first).+ const pending = textDraft ? buildTextShape() : null;+ if (textDraft) commitText(true);+ const exportShapes = pending ? [...shapes, pending] : shapes;+ const region = crop ?? {+ x: 0,+ y: 0,+ w: window.innerWidth,+ h: window.innerHeight,+ };+ const srcW = Math.max(1, Math.round(region.w * scaleX));+ const srcH = Math.max(1, Math.round(region.h * scaleY));+ const out = Math.min(1, EXPORT_MAX_EDGE / Math.max(srcW, srcH));+ const canvas = document.createElement("canvas");+ canvas.width = Math.max(1, Math.round(srcW * out));+ canvas.height = Math.max(1, Math.round(srcH * out));+ const ctx = canvas.getContext("2d");+ if (!ctx) return;+ ctx.drawImage(+ shot,+ region.x * scaleX,+ region.y * scaleY,+ srcW,+ srcH,+ 0,+ 0,+ canvas.width,+ canvas.height,+ );+ // Ink lives in view coordinates; the transform carries stroke widths and+ // text sizes into shot pixels so the export matches the preview.+ ctx.scale(scaleX * out, scaleY * out);+ ctx.translate(-region.x, -region.y);+ const env = { image: shot, sx: scaleX, sy: scaleY };+ for (const shape of exportShapes) {+ drawShape(ctx, shape, env);+ }+ annotateHost().done(canvas.toDataURL("image/png"));+ }, [+ shot,+ crop,+ shapes,+ scaleX,+ scaleY,+ textDraft,+ buildTextShape,+ commitText,+ ]);++ // Keyboard: tools, undo/redo, delete, nudge and resize, finish.+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent): void => {+ if (event.key === "Escape") {+ if (textDraft) {+ commitText(false);+ } else if (selected !== null) {+ setSelected(null);+ } else {+ annotateHost().cancel();+ }+ return;+ }+ // The text editor or a focused control owns every other key.+ if (textDraft) return;+ const target = event.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === "INPUT" || target.tagName === "TEXTAREA")+ ) {+ return;+ }+ if (event.key === "Enter") {+ finish();+ return;+ }+ // Shift makes the browser report the key as "Z"; lowercase it so the+ // redo half (Cmd/Ctrl+Shift+Z) reaches this branch at all.+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "z") {+ event.preventDefault();+ if (event.shiftKey) redo();+ else undo();+ return;+ }+ if (+ (event.key === "Backspace" || event.key === "Delete") &&+ selected !== null+ ) {+ event.preventDefault();+ deleteSelected();+ return;+ }+ if (event.key === " ") {+ setSpaceHeld(true);+ return;+ }+ if (event.key.startsWith("Arrow") && crop) {+ event.preventDefault();+ const step = event.altKey ? 10 : 1;+ const dx =+ event.key === "ArrowLeft"+ ? -step+ : event.key === "ArrowRight"+ ? step+ : 0;+ const dy =+ event.key === "ArrowUp"+ ? -step+ : event.key === "ArrowDown"+ ? step+ : 0;+ setCrop((current) => {+ if (!current) return current;+ if (event.shiftKey) {+ return clampCrop({+ ...current,+ w: Math.max(MIN_DRAG_PX, current.w + dx),+ h: Math.max(MIN_DRAG_PX, current.h + dy),+ });+ }+ return clampCrop({+ ...current,+ x: current.x + dx,+ y: current.y + dy,+ });+ });+ return;+ }+ const byKey = TOOLS.find(+ (entry) => entry.key.toLowerCase() === event.key.toLowerCase(),+ );+ if (byKey && !event.metaKey && !event.ctrlKey) {+ setTool(byKey.tool);+ }+ };+ const onKeyUp = (event: KeyboardEvent): void => {+ if (event.key === " ") setSpaceHeld(false);+ };+ window.addEventListener("keydown", onKeyDown);+ window.addEventListener("keyup", onKeyUp);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ window.removeEventListener("keyup", onKeyUp);+ };+ }, [+ crop,+ textDraft,+ selected,+ commitText,+ finish,+ undo,+ redo,+ deleteSelected,+ ]);++ // One overlay canvas repaints the dim, the selection frame, and the ink.+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || !shot) return;+ // Render at device resolution; 1x looks soft on Retina screens.+ const dpr = window.devicePixelRatio || 1;+ canvas.width = window.innerWidth * dpr;+ canvas.height = window.innerHeight * dpr;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;+ ctx.scale(dpr, dpr);+ ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);+ const draftCrop =+ !crop && drag.current?.mode === "select" && draft?.kind === "rect"+ ? draft.rect+ : null;+ const hole = crop ?? draftCrop;+ ctx.fillStyle = "rgba(6, 7, 10, 0.52)";+ ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);+ if (hole) {+ ctx.clearRect(hole.x, hole.y, hole.w, hole.h);+ }+ const env = { image: shot, sx: scaleX, sy: scaleY };+ for (const shape of shapes) {+ drawShape(ctx, shape, env);+ }+ if (crop && draft) {+ drawShape(ctx, draft, env);+ }+ const active = selected !== null ? shapes[selected] : null;+ if (active) {+ const box = shapeBBox(active);+ ctx.strokeStyle = "rgba(255, 255, 255, 0.85)";+ ctx.lineWidth = 1;+ ctx.setLineDash([5, 4]);+ ctx.strokeRect(box.x - 5, box.y - 5, box.w + 10, box.h + 10);+ ctx.setLineDash([]);+ for (const handle of shapeHandles(active)) {+ ctx.beginPath();+ ctx.arc(handle.at.x, handle.at.y, 4.5, 0, Math.PI * 2);+ ctx.fillStyle = "#ffffff";+ ctx.fill();+ ctx.strokeStyle = "rgba(0, 0, 0, 0.45)";+ ctx.lineWidth = 1;+ ctx.stroke();+ }+ }+ if (hole) {+ // Hairline light frame with a soft halo, readable on any content.+ ctx.strokeStyle = "rgba(0, 0, 0, 0.55)";+ ctx.lineWidth = 3;+ ctx.strokeRect(hole.x - 1, hole.y - 1, hole.w + 2, hole.h + 2);+ ctx.strokeStyle = "rgba(255, 255, 255, 0.95)";+ ctx.lineWidth = 1.5;+ ctx.strokeRect(hole.x - 0.75, hole.y - 0.75, hole.w + 1.5, hole.h + 1.5);+ }+ if (crop) {+ for (const handle of HANDLES) {+ const at = handlePoint(crop, handle);+ ctx.beginPath();+ ctx.arc(at.x, at.y, 4.5, 0, Math.PI * 2);+ ctx.fillStyle = "#ffffff";+ ctx.fill();+ ctx.strokeStyle = "rgba(0, 0, 0, 0.45)";+ ctx.lineWidth = 1;+ ctx.stroke();+ }+ }+ }, [shot, crop, shapes, draft, selected, scaleX, scaleY]);++ const topShapeAt = useCallback(+ (point: Point): number | null => {+ for (let index = shapes.length - 1; index >= 0; index--) {+ if (hitShape(shapes[index], point)) return index;+ }+ return null;+ },+ [shapes],+ );++ const onMouseDown = useCallback(+ (event: React.MouseEvent): void => {+ if (event.button !== 0) return;+ const from = pointOf(event);+ if (textDraft) {+ commitText(true);+ return;+ }+ if (!crop || tool === "crop") {+ drag.current = { mode: "select", from };+ setDraft({ kind: "rect", rect: normalizeRect(from, from), color });+ return;+ }+ const handle = hitHandle(crop, from);+ if (handle) {+ drag.current = { mode: "resize", handle };+ return;+ }+ if (spaceHeld && inside(crop, from)) {+ drag.current = { mode: "move", from, orig: crop };+ return;+ }+ if (tool === "select") {+ const active = selected !== null ? shapes[selected] : null;+ const handleHit = active ? hitShapeHandle(active, from) : null;+ if (handleHit && selected !== null) {+ drag.current = {+ mode: "resize-shape",+ index: selected,+ handle: handleHit.id,+ orig: shapes,+ moved: false,+ };+ return;+ }+ const index = topShapeAt(from);+ setSelected(index);+ if (index !== null) {+ drag.current = {+ mode: "move-shape",+ from,+ index,+ orig: shapes,+ moved: false,+ };+ }+ return;+ }+ setSelected(null);+ if (tool === "text") {+ // The mousedown's default focus handling would steal focus from the+ // editor right after it mounts.+ event.preventDefault();+ setTextDraft(from);+ return;+ }+ if (tool === "counter") {+ const next =+ Math.max(+ 0,+ ...shapes.map((shape) => (shape.kind === "counter" ? shape.n : 0)),+ ) + 1;+ pushShape({ kind: "counter", at: from, n: next, color });+ return;+ }+ drag.current = { mode: "draw", from };+ setDraft(+ tool === "pen"+ ? { kind: "pen", points: [from], color }+ : tool === "arrow"+ ? { kind: "arrow", from, to: from, color }+ : tool === "pixelate"+ ? { kind: "pixelate", rect: normalizeRect(from, from) }+ : { kind: tool, rect: normalizeRect(from, from), color },+ );+ },+ [+ crop,+ tool,+ color,+ spaceHeld,+ textDraft,+ shapes,+ selected,+ commitText,+ topShapeAt,+ pushShape,+ ],+ );++ const onMouseMove = useCallback(+ (event: React.MouseEvent): void => {+ const to = pointOf(event);+ const active = drag.current;+ if (!active) {+ // Hover feedback only: resize cursors on handles, move over shapes.+ if (crop) {+ const handle = hitHandle(crop, to);+ const activeShape = selected !== null ? shapes[selected] : null;+ const shapeHandleHit =+ tool === "select" && activeShape+ ? hitShapeHandle(activeShape, to)+ : null;+ setCursor(+ handle+ ? HANDLE_CURSORS[handle]+ : shapeHandleHit+ ? shapeHandleHit.cursor+ : spaceHeld && inside(crop, to)+ ? "grab"+ : tool === "select"+ ? topShapeAt(to) !== null+ ? "move"+ : "default"+ : tool === "text"+ ? "text"+ : "crosshair",+ );+ }+ return;+ }+ if (active.mode === "resize") {+ setCrop((current) =>+ current ? clampCrop(resizeCrop(current, active.handle, to)) : current,+ );+ return;+ }+ if (active.mode === "move") {+ setCrop(+ clampCrop({+ ...active.orig,+ x: active.orig.x + to.x - active.from.x,+ y: active.orig.y + to.y - active.from.y,+ }),+ );+ return;+ }+ if (active.mode === "move-shape") {+ active.moved = true;+ const dx = to.x - active.from.x;+ const dy = to.y - active.from.y;+ setDoc((current) => ({+ ...current,+ shapes: active.orig.map((shape, index) =>+ index === active.index ? translateShape(shape, dx, dy) : shape,+ ),+ }));+ return;+ }+ if (active.mode === "resize-shape") {+ active.moved = true;+ setDoc((current) => ({+ ...current,+ shapes: active.orig.map((shape, index) =>+ index === active.index+ ? resizeShape(shape, active.handle, to)+ : shape,+ ),+ }));+ return;+ }+ setDraft((current) => {+ if (!current) return current;+ if (current.kind === "pen") {+ return { ...current, points: [...current.points, to] };+ }+ if (current.kind === "arrow") {+ return { ...current, to };+ }+ if ("rect" in current) {+ return { ...current, rect: normalizeRect(active.from, to) };+ }+ return current;+ });+ },+ [crop, tool, spaceHeld, selected, shapes, topShapeAt],+ );++ const onMouseUp = useCallback((): void => {+ const active = drag.current;+ drag.current = null;+ if (!active) return;+ if (active.mode === "resize" || active.mode === "move") return;+ if (active.mode === "move-shape" || active.mode === "resize-shape") {+ // One history entry per completed move.+ if (active.moved) {+ setDoc((current) => ({+ past: [...current.past, active.orig],+ shapes: current.shapes,+ future: [],+ }));+ }+ return;+ }+ setDraft((current) => {+ if (!current) return null;+ if (active.mode === "select") {+ if (+ current.kind === "rect" &&+ (current.rect.w >= MIN_DRAG_PX || current.rect.h >= MIN_DRAG_PX)+ ) {+ setCrop(clampCrop(current.rect));+ setTool("select");+ }+ return null;+ }+ const tiny =+ "rect" in current &&+ current.rect.w < MIN_DRAG_PX &&+ current.rect.h < MIN_DRAG_PX;+ const short =+ current.kind === "arrow" &&+ Math.hypot(+ current.to.x - current.from.x,+ current.to.y - current.from.y,+ ) < MIN_DRAG_PX;+ if (!tiny && !short) {+ pushShape(current);+ // The usual next step is adjusting the fresh shape.+ setTool("select");+ }+ return null;+ });+ }, [pushShape]);++ const exportW = crop ? Math.round(crop.w * scaleX) : 0;+ const exportH = crop ? Math.round(crop.h * scaleY) : 0;+ const selectedShape = selected !== null ? shapes[selected] : null;+ const selectedText = selectedShape?.kind === "text" ? selectedShape : null;+ const showTextOptions = tool === "text" || selectedText !== null;+ const textBgOn = selectedText ? selectedText.bg : textBg;+ const textSizeOn = selectedText ? selectedText.size : textSize;+ // The editor wraps live at the same width the committed shape would get.+ const editorCap =+ textDraft && crop+ ? textWrapCap(textDraft.x, crop, textBg) ++ (textBg ? TEXT_BG_PAD_X * 2 : 0) ++ 6+ : null;++ return (+ <div+ role="application"+ aria-label="Screenshot annotator"+ className="an-root"+ style={{ cursor }}+ onMouseDown={onMouseDown}+ onMouseMove={onMouseMove}+ onMouseUp={onMouseUp}+ >+ {shot && <img className="an-shot" src={shot.src} alt="" />}+ <canvas ref={canvasRef} className="an-overlay" />++ {(!crop || tool === "crop") && (+ <div className="an-hint">+ Drag to select an area+ <span className="an-hint-keys">+ <kbd>esc</kbd> to cancel+ </span>+ </div>+ )}++ {crop && (+ <div+ role="toolbar"+ className="an-toolbar"+ onMouseDown={(event) => event.stopPropagation()}+ >+ {TOOLS.map((entry) => (+ <button+ key={entry.tool}+ type="button"+ aria-label={`${entry.label} (${entry.key})`}+ title={`${entry.label} — ${entry.key}`}+ className={tool === entry.tool ? "an-tool an-active" : "an-tool"}+ onClick={() => setTool(entry.tool)}+ >+ <ToolIcon tool={entry.tool} />+ </button>+ ))}+ <span className="an-sep" />+ {COLORS.map((value) => (+ <button+ key={value}+ type="button"+ aria-label={`Ink ${value}`}+ className={value === color ? "an-color an-color-on" : "an-color"}+ style={{ background: value }}+ onClick={() => pickColor(value)}+ />+ ))}+ <span className="an-sep" />+ {selectedShape && (+ <button+ type="button"+ aria-label="Delete (⌫)"+ title="Delete — ⌫"+ className="an-tool"+ onClick={deleteSelected}+ >+ <ToolIcon tool="trash" />+ </button>+ )}+ <button+ type="button"+ aria-label="Undo (⌘Z)"+ title="Undo — ⌘Z"+ className="an-tool"+ disabled={!doc.past.length}+ onClick={undo}+ >+ <ToolIcon tool="undo" />+ </button>+ <button+ type="button"+ aria-label="Redo (⇧⌘Z)"+ title="Redo — ⇧⌘Z"+ className="an-tool"+ disabled={!doc.future.length}+ onClick={redo}+ >+ <ToolIcon tool="redo" />+ </button>+ <span className="an-sep" />+ <span className="an-size">+ {exportW} × {exportH}+ </span>+ <span className="an-sep" />+ <button+ type="button"+ className="an-cancel"+ onClick={() => annotateHost().cancel()}+ >+ Cancel+ </button>+ <button type="button" className="an-attach" onClick={finish}>+ Attach+ <kbd>⏎</kbd>+ </button>+ </div>+ )}++ {crop && showTextOptions && (+ <div+ role="toolbar"+ className="an-subbar"+ onMouseDown={(event) => event.stopPropagation()}+ >+ <span className="an-sub-label">Text</span>+ <span className="an-sub-size" aria-hidden="true">+ A+ </span>+ <input+ type="range"+ aria-label="Text size"+ min={TEXT_MIN_SIZE}+ max={TEXT_MAX_SIZE}+ value={textSizeOn}+ onPointerDown={grabTextSize}+ onPointerUp={releaseTextSize}+ onPointerCancel={releaseTextSize}+ onChange={(event) => pickTextSize(Number(event.target.value))}+ />+ <span className="an-sub-size an-sub-size-big" aria-hidden="true">+ A+ </span>+ <span className="an-sub-value">{textSizeOn}</span>+ <span className="an-sep" />+ <button+ type="button"+ aria-label="Text background"+ title="Text background"+ className={textBgOn ? "an-tool an-active" : "an-tool"}+ onClick={toggleTextBg}+ >+ <ToolIcon tool="text-bg" />+ </button>+ </div>+ )}++ {textDraft && (+ <textarea+ ref={textRef}+ className={textBg ? "an-text-input an-text-solid" : "an-text-input"}+ style={{+ left: textBg ? textDraft.x - TEXT_BG_PAD_X : textDraft.x,+ top: textBg ? textDraft.y - TEXT_BG_PAD_Y : textDraft.y,+ font: textFont(textSize),+ lineHeight: TEXT_LINE,+ ...(editorCap !== null ? { maxWidth: editorCap } : {}),+ ...(textBg+ ? ({+ background: color,+ color: contrastInk(color),+ caretColor: contrastInk(color),+ padding: `${TEXT_BG_PAD_Y}px ${TEXT_BG_PAD_X}px`,+ // Placeholder and selection read against this ink.+ "--an-ph":+ contrastInk(color) === "#ffffff"+ ? "rgba(255, 255, 255, 0.55)"+ : "rgba(28, 29, 34, 0.45)",+ } as React.CSSProperties)+ : {+ color,+ caretColor: color,+ textShadow: "0 0 3px rgba(0,0,0,0.4)",+ }),+ }}+ rows={1}+ placeholder="Add text"+ // biome-ignore lint/a11y/noAutofocus: the tool just placed the caret+ autoFocus+ spellCheck={false}+ onMouseDown={(event) => event.stopPropagation()}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ commitText(true);+ }+ }}+ onInput={(event) => {+ // Width first: the height depends on how the text wraps.+ const el = event.currentTarget;+ el.style.width = "auto";+ el.style.width = `${Math.min(+ el.scrollWidth + 12,+ editorCap ?? window.innerWidth - textDraft.x - 10,+ )}px`;+ el.style.height = "auto";+ el.style.height = `${el.scrollHeight}px`;+ }}+ />+ )}+ </div>+ );+}diff --git a/products/desktop/packages/quick-ask/src/annotate/ToolIcon.tsx b/products/desktop/packages/quick-ask/src/annotate/ToolIcon.tsxnew file mode 100644index 000000000000..e36f63196395--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/ToolIcon.tsx@@ -0,0 +1,82 @@+import type React from "react";++const PATHS: Record<string, React.JSX.Element> = {+ select: <path d="M4 2.5l8 7-3.6.7 2 3.6-2 1-2-3.7-2.4 2.6z" />,+ crop: (+ <>+ <path d="M4.5 1.5v10h10" />+ <path d="M1.5 4.5h10v10" />+ </>+ ),+ counter: (+ <>+ <circle cx="8" cy="8" r="5.8" />+ <path d="M6.8 6.2L8.3 5.2v5.6" />+ </>+ ),+ "text-bg": (+ <>+ <rect x="2" y="2.5" width="12" height="11" rx="2.5" />+ <path d="M5.5 6V5h5v1M8 5v6M6.8 11h2.4" />+ </>+ ),+ trash: (+ <>+ <path d="M3 4.5h10" />+ <path d="M6.5 4.5V3h3v1.5" />+ <path d="M4.5 4.5l.7 8a1 1 0 0 0 1 .9h3.6a1 1 0 0 0 1-.9l.7-8" />+ <path d="M6.7 7v4M9.3 7v4" />+ </>+ ),+ arrow: (+ <>+ <path d="M3.5 12.5L12 4" />+ <path d="M6.5 4H12v5.5" />+ </>+ ),+ rect: <rect x="2.5" y="3.5" width="11" height="9" rx="1.5" />,+ ellipse: <ellipse cx="8" cy="8" rx="5.5" ry="4.5" />,+ pen: <path d="M2.5 13.5c3.5.5 3-6 5.5-6s1.5 5 3 5 1.5-2.5 2.5-4.5" />,+ text: (+ <>+ <path d="M3.5 4.5V3h9v1.5" />+ <path d="M8 3v10" />+ <path d="M6 13h4" />+ </>+ ),+ pixelate: (+ <>+ <path d="M3 3h3v3H3zM9 3h3v3H9zM6 6h3v3H6zM3 9h3v3H3zM9 9h3v3H9z" />+ </>+ ),+ undo: (+ <>+ <path d="M5.5 3.5L2.5 6.5l3 3" />+ <path d="M2.5 6.5H10a3.5 3.5 0 0 1 0 7H7" />+ </>+ ),+ redo: (+ <>+ <path d="M10.5 3.5l3 3-3 3" />+ <path d="M13.5 6.5H6a3.5 3.5 0 0 0 0 7h3" />+ </>+ ),+};++export function ToolIcon({ tool }: { tool: string }): React.JSX.Element {+ return (+ <svg+ width="16"+ height="16"+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ {PATHS[tool]}+ </svg>+ );+}diff --git a/products/desktop/packages/quick-ask/src/annotate/annotate.css b/products/desktop/packages/quick-ask/src/annotate/annotate.cssnew file mode 100644index 000000000000..b7c7d61be319--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/annotate.css@@ -0,0 +1,360 @@+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++html,+body,+#root {+ width: 100%;+ height: 100%;+ overflow: hidden;+ background: #101014;+}++:root {+ --an-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ --an-glass: rgba(24, 25, 30, 0.8);+ --an-hairline: rgba(255, 255, 255, 0.14);+ --an-fg: rgba(255, 255, 255, 0.92);+ --an-fg-dim: rgba(255, 255, 255, 0.6);+ --an-accent: #f7a501;+}++.an-root {+ position: fixed;+ inset: 0;+ user-select: none;+ font-family: var(--an-font);+ -webkit-font-smoothing: antialiased;+ text-rendering: optimizeLegibility;+}++.an-shot,+.an-overlay {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+}++/* ── Floating chrome ─────────────────────────────────── */++.an-hint,+.an-toolbar,+.an-subbar {+ position: fixed;+ background: var(--an-glass);+ backdrop-filter: blur(22px) saturate(1.4);+ -webkit-backdrop-filter: blur(22px) saturate(1.4);+ border: 1px solid var(--an-hairline);+ box-shadow:+ inset 0 1px 0 rgba(255, 255, 255, 0.1),+ 0 10px 34px rgba(0, 0, 0, 0.45);+}++.an-hint {+ top: 16px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 9px 16px;+ border-radius: 999px;+ font-size: 13px;+ color: var(--an-fg);+ animation: an-hint-rise 0.26s cubic-bezier(0.2, 0.8, 0.3, 1);+}++.an-hint-keys {+ font-size: 11.5px;+ color: var(--an-fg-dim);+}++.an-toolbar {+ top: 16px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 3px;+ padding: 6px;+ border-radius: 13px;+ cursor: default;+ animation: an-hint-rise 0.22s cubic-bezier(0.2, 0.8, 0.3, 1);+ max-width: calc(100vw - 24px);+}++.an-size {+ padding: 0 5px;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+ color: var(--an-fg-dim);+}++/* Contextual options row under the main toolbar. */+.an-subbar {+ top: 66px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ border-radius: 11px;+ cursor: default;+ animation: an-hint-rise 0.18s cubic-bezier(0.2, 0.8, 0.3, 1);+}++.an-sub-label {+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--an-fg-dim);+ margin-right: 2px;+}++.an-sub-size {+ font: 600 10px var(--an-font);+ color: var(--an-fg-dim);+}++.an-sub-size-big {+ font-size: 15px;+}++.an-sub-value {+ min-width: 20px;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+ text-align: right;+ color: var(--an-fg);+}++.an-subbar input[type="range"] {+ width: 120px;+ height: 3px;+ appearance: none;+ background: rgba(255, 255, 255, 0.22);+ border-radius: 2px;+ outline: none;+ cursor: pointer;+}++.an-subbar input[type="range"]::-webkit-slider-thumb {+ appearance: none;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: #ffffff;+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);+}++@keyframes an-hint-rise {+ from {+ opacity: 0;+ transform: translateX(-50%) translateY(5px);+ }+ to {+ transform: translateX(-50%);+ }+}++.an-sep {+ width: 1px;+ height: 20px;+ margin: 0 4px;+ background: var(--an-hairline);+}++/* ── Buttons ─────────────────────────────────────────── */++.an-tool {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ border: none;+ border-radius: 9px;+ background: transparent;+ color: var(--an-fg-dim);+ cursor: pointer;+ transition:+ color 0.1s,+ background 0.1s;+}++.an-tool:hover:not(:disabled) {+ color: var(--an-fg);+ background: rgba(255, 255, 255, 0.1);+}++.an-tool:active:not(:disabled) {+ transform: scale(0.92);+}++.an-tool,+.an-color,+.an-cancel,+.an-attach {+ transition:+ color 0.1s,+ background 0.1s,+ transform 0.12s cubic-bezier(0.2, 0.8, 0.3, 1);+}++.an-tool:focus-visible,+.an-color:focus-visible,+.an-cancel:focus-visible,+.an-attach:focus-visible {+ outline: 2px solid rgba(247, 165, 1, 0.8);+ outline-offset: 1px;+}++.an-tool:disabled {+ opacity: 0.32;+ cursor: default;+}++.an-active {+ color: var(--an-accent);+ background: rgba(247, 165, 1, 0.16);+}++.an-active:hover:not(:disabled) {+ color: var(--an-accent);+ background: rgba(247, 165, 1, 0.22);+}++.an-color {+ width: 16px;+ height: 16px;+ margin: 0 3px;+ border: none;+ border-radius: 50%;+ outline: 2px solid transparent;+ outline-offset: 2px;+ box-shadow:+ inset 0 0 0 1px rgba(255, 255, 255, 0.18),+ 0 1px 2px rgba(0, 0, 0, 0.25);+ cursor: pointer;+ transition:+ outline-color 0.1s,+ transform 0.1s;+}++.an-color:hover {+ transform: scale(1.15);+}++.an-color-on {+ outline-color: rgba(255, 255, 255, 0.85);+}++.an-cancel,+.an-attach {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ height: 32px;+ padding: 0 13px;+ border: none;+ border-radius: 9px;+ font: 600 12.5px var(--an-font);+ cursor: pointer;+ transition: background 0.1s;+}++.an-cancel {+ background: transparent;+ color: var(--an-fg-dim);+}++.an-cancel:hover {+ color: var(--an-fg);+ background: rgba(255, 255, 255, 0.09);+}++.an-attach {+ background: var(--an-accent);+ color: #1c1400;+ box-shadow:+ inset 0 1px 0 rgba(255, 255, 255, 0.3),+ 0 2px 8px rgba(0, 0, 0, 0.3);+}++.an-attach:hover {+ background: #ffb92e;+}++.an-attach:active {+ transform: scale(0.96);+}++.an-attach kbd {+ font: 600 10px var(--an-font);+ padding: 1px 4px;+ border-radius: 4px;+ background: rgba(0, 0, 0, 0.16);+}++.an-hint kbd {+ font: 600 10.5px var(--an-font);+ padding: 1.5px 5px;+ border-radius: 4px;+ border: 1px solid var(--an-hairline);+ background: rgba(255, 255, 255, 0.07);+ color: var(--an-fg-dim);+}++/* ── Text tool ───────────────────────────────────────── */++.an-text-input {+ position: fixed;+ min-width: 40px;+ max-width: 60vw;+ background: transparent;+ border: 1px dashed rgba(255, 255, 255, 0.45);+ border-radius: 4px;+ outline: none;+ resize: none;+ overflow: hidden;+ padding: 1px 3px;+ margin: -2px -4px;+ line-height: 1.25;+}++.an-text-input::placeholder {+ color: rgba(255, 255, 255, 0.35);+}++/* Background-on editing shows the pill exactly as it will export. */+.an-text-solid {+ margin: 0;+ border: none;+ border-radius: 7px;+ box-shadow:+ inset 0 1px 0 rgba(255, 255, 255, 0.18),+ 0 2px 8px rgba(0, 0, 0, 0.28);+}++.an-text-solid::placeholder {+ color: var(--an-ph, rgba(255, 255, 255, 0.55));+}++.an-text-solid::selection {+ background: var(--an-ph, rgba(255, 255, 255, 0.55));+}++@media (prefers-reduced-motion: reduce) {+ .an-hint,+ .an-toolbar,+ .an-subbar {+ animation: none;+ }+}diff --git a/products/desktop/packages/quick-ask/src/annotate/host-bridge.ts b/products/desktop/packages/quick-ask/src/annotate/host-bridge.tsnew file mode 100644index 000000000000..56805511a919--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/host-bridge.ts@@ -0,0 +1,15 @@+/**+ * The contract between the annotator and whatever hosts it. The Electron+ * host implements it in its preload (window.quickAskAnnotate).+ */+export interface QuickAskAnnotateHostBridge {+ /** The frozen screen as a PNG data URL; null when capture was lost. */+ shot: () => Promise<string | null>;+ done: (dataUrl: string) => void;+ cancel: () => void;+}++export function annotateHost(): QuickAskAnnotateHostBridge {+ return (window as unknown as { quickAskAnnotate: QuickAskAnnotateHostBridge })+ .quickAskAnnotate;+}diff --git a/products/desktop/packages/quick-ask/src/annotate/shapes.test.ts b/products/desktop/packages/quick-ask/src/annotate/shapes.test.tsnew file mode 100644index 000000000000..b4db19762438--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/shapes.test.ts@@ -0,0 +1,85 @@+import { beforeAll, describe, expect, it, vi } from "vitest";+import {+ arrowHead,+ hitShape,+ type Shape,+ shapeBBox,+ textLines,+} from "./shapes";++// Text measuring goes through a module-level canvas context; give the node+// environment a deterministic 10px-per-character measurer.+beforeAll(() => {+ vi.stubGlobal("document", {+ createElement: () => ({+ getContext: () => ({+ font: "",+ measureText: (text: string) => ({ width: text.length * 10 }),+ }),+ }),+ });+});++describe("annotator shape geometry", () => {+ // A long horizontal arrow: the head is 26px deep and its wings flare+ // vertically past the zero-height from->to box.+ const arrow: Shape = {+ kind: "arrow",+ from: { x: 0, y: 50 },+ to: { x: 200, y: 50 },+ color: "#fff",+ };++ it("includes the arrowhead wings in the bounding box", () => {+ const { wings } = arrowHead(arrow.from, arrow.to);+ const box = shapeBBox(arrow);+ for (const wing of wings) {+ expect(wing.y).toBeGreaterThanOrEqual(box.y);+ expect(wing.y).toBeLessThanOrEqual(box.y + box.h);+ }+ // The shaft alone would give a zero-height box.+ expect(box.h).toBeGreaterThan(0);+ });++ it("hits a click on an arrowhead wing, not just the shaft", () => {+ const { wings } = arrowHead(arrow.from, arrow.to);+ // The upper wing tip sits ~11px off the shaft, beyond the 6px slack.+ expect(Math.abs(wings[0].y - 50)).toBeGreaterThan(6);+ expect(hitShape(arrow, wings[0])).toBe(true);+ expect(hitShape(arrow, wings[1])).toBe(true);+ // Well off the head stays a miss.+ expect(hitShape(arrow, { x: 200, y: 80 })).toBe(false);+ });++ it("breaks a word wider than the wrap width instead of overflowing", () => {+ // 12 characters at 10px each against a 40px width: no line may exceed+ // the width, and nothing may be dropped.+ const lines = textLines("abcdefghijkl", 17, 40);+ expect(lines).toEqual(["abcd", "efgh", "ijkl"]);+ });++ it("still wraps at spaces before resorting to breaking words", () => {+ expect(textLines("ab cd efghijkl", 17, 50)).toEqual([+ "ab cd",+ "efghi",+ "jkl",+ ]);+ });++ it("keeps a click-only pen stroke selectable at its point", () => {+ const dot: Shape = {+ kind: "pen",+ points: [{ x: 30, y: 40 }],+ color: "#fff",+ };+ expect(hitShape(dot, { x: 33, y: 42 })).toBe(true);+ expect(hitShape(dot, { x: 45, y: 40 })).toBe(false);+ expect(shapeBBox(dot)).toEqual({ x: 30, y: 40, w: 0, h: 0 });+ });++ it("gives an empty pen shape a finite bounding box", () => {+ const empty: Shape = { kind: "pen", points: [], color: "#fff" };+ expect(shapeBBox(empty)).toEqual({ x: 0, y: 0, w: 0, h: 0 });+ expect(hitShape(empty, { x: 0, y: 0 })).toBe(false);+ });+});diff --git a/products/desktop/packages/quick-ask/src/annotate/shapes.ts b/products/desktop/packages/quick-ask/src/annotate/shapes.tsnew file mode 100644index 000000000000..aa6f93ebc5d8--- /dev/null+++ b/products/desktop/packages/quick-ask/src/annotate/shapes.ts@@ -0,0 +1,477 @@+export interface Point {+ x: number;+ y: number;+}++export interface Rect {+ x: number;+ y: number;+ w: number;+ h: number;+}++export type Tool =+ | "select"+ | "crop"+ | "arrow"+ | "rect"+ | "ellipse"+ | "pen"+ | "text"+ | "counter"+ | "pixelate";++export type Shape =+ | { kind: "rect"; rect: Rect; color: string }+ | { kind: "ellipse"; rect: Rect; color: string }+ | { kind: "arrow"; from: Point; to: Point; color: string }+ | { kind: "pen"; points: Point[]; color: string }+ | {+ kind: "text";+ at: Point;+ text: string;+ color: string;+ bg: boolean;+ size: number;+ /** Wrap width in view pixels; unset text stays on its typed lines. */+ width?: number;+ }+ | { kind: "counter"; at: Point; n: number; color: string }+ | { kind: "pixelate"; rect: Rect };++export const LINE_WIDTH = 3;+export const TEXT_SIZE = 17;+export const TEXT_MIN_SIZE = 12;+export const TEXT_MAX_SIZE = 48;+export const TEXT_MIN_WIDTH = 48;+export const TEXT_LINE = 1.25;+export const COUNTER_RADIUS = 14;+export const TEXT_BG_PAD_X = 8;+export const TEXT_BG_PAD_Y = 5;++export function textFont(size: number): string {+ return `600 ${size}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;+}+/** View pixels per pixelation block. */+const PIXEL_BLOCK = 12;++/**+ * Arrowhead geometry shared by drawing, bounds, and hit testing, so the+ * clickable and selectable area always matches the pixels on screen.+ */+export function arrowHead(+ from: Point,+ to: Point,+): { wings: [Point, Point]; shaftEnd: Point } {+ const angle = Math.atan2(to.y - from.y, to.x - from.x);+ const length = Math.hypot(to.x - from.x, to.y - from.y);+ const head = Math.min(Math.max(11, length * 0.22), 26);+ const wing = (offset: number): Point => ({+ x: to.x - head * Math.cos(angle + offset),+ y: to.y - head * Math.sin(angle + offset),+ });+ return {+ wings: [wing(-Math.PI / 7), wing(Math.PI / 7)],+ // The shaft stops short of the tip so it never pokes past the head.+ shaftEnd: {+ x: to.x - head * 0.6 * Math.cos(angle),+ y: to.y - head * 0.6 * Math.sin(angle),+ },+ };+}++export function normalizeRect(a: Point, b: Point): Rect {+ return {+ x: Math.min(a.x, b.x),+ y: Math.min(a.y, b.y),+ w: Math.abs(a.x - b.x),+ h: Math.abs(a.y - b.y),+ };+}++/** Ink readable on top of the given ink color: dark on light, white on dark. */+export function contrastInk(color: string): string {+ const hex = color.replace("#", "");+ if (hex.length !== 6) return "#ffffff";+ const r = Number.parseInt(hex.slice(0, 2), 16);+ const g = Number.parseInt(hex.slice(2, 4), 16);+ const b = Number.parseInt(hex.slice(4, 6), 16);+ return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? "#1c1d22" : "#ffffff";+}++let measureCtx: CanvasRenderingContext2D | null = null;++function measurer(size: number): CanvasRenderingContext2D | null {+ if (!measureCtx) {+ measureCtx = document.createElement("canvas").getContext("2d");+ }+ if (measureCtx) measureCtx.font = textFont(size);+ return measureCtx;+}++/** User-perceived characters, so a long word never splits inside an emoji+ * or a combining sequence. */+function graphemes(word: string): string[] {+ if (typeof Intl !== "undefined" && "Segmenter" in Intl) {+ return Array.from(+ new Intl.Segmenter().segment(word),+ (part) => part.segment,+ );+ }+ return Array.from(word);+}++/** Typed lines, word-wrapped to the shape's width when it has one. A word+ * wider than the width is broken at grapheme boundaries, so no rendered line+ * escapes the shape's background and selection box. */+export function textLines(+ text: string,+ size: number,+ width?: number,+): string[] {+ const ctx = measurer(size);+ const typed = text.split("\n");+ if (!ctx || width === undefined) return typed;+ const lines: string[] = [];+ for (const raw of typed) {+ let line = "";+ for (const word of raw.split(" ")) {+ const joined = line ? `${line} ${word}` : word;+ if (ctx.measureText(joined).width <= width) {+ line = joined;+ continue;+ }+ if (line) {+ lines.push(line);+ line = "";+ }+ if (ctx.measureText(word).width <= width) {+ line = word;+ continue;+ }+ for (const grapheme of graphemes(word)) {+ const candidate = line + grapheme;+ // A single grapheme wider than the width still gets its own line.+ if (line && ctx.measureText(candidate).width > width) {+ lines.push(line);+ line = grapheme;+ } else {+ line = candidate;+ }+ }+ }+ lines.push(line);+ }+ return lines;+}++/** Longest typed line, unwrapped. */+export function textNaturalWidth(text: string, size: number): number {+ const ctx = measurer(size);+ if (!ctx) return 0;+ return Math.max(+ ...text.split("\n").map((line) => ctx.measureText(line).width),+ );+}++function measureText(+ text: string,+ size: number,+ width?: number,+): { w: number; h: number } {+ const ctx = measurer(size);+ if (!ctx) return { w: 0, h: 0 };+ const lines = textLines(text, size, width);+ const maxLineWidth = Math.max(+ ...lines.map((line) => ctx.measureText(line).width),+ );+ // The requested width holds only while every rendered line fits it (a+ // single grapheme can still exceed it); otherwise report what will draw,+ // so the background and selection box cover the actual text.+ const w = width !== undefined && maxLineWidth <= width ? width : maxLineWidth;+ return { w, h: lines.length * size * TEXT_LINE };+}++export function shapeBBox(shape: Shape): Rect {+ switch (shape.kind) {+ case "rect":+ case "ellipse":+ case "pixelate":+ return shape.rect;+ case "arrow": {+ // The head's wings can stick out past the from->to box.+ const { wings } = arrowHead(shape.from, shape.to);+ const points = [shape.from, shape.to, ...wings];+ const xs = points.map((p) => p.x);+ const ys = points.map((p) => p.y);+ return normalizeRect(+ { x: Math.min(...xs), y: Math.min(...ys) },+ { x: Math.max(...xs), y: Math.max(...ys) },+ );+ }+ case "pen": {+ // Drawing always seeds one point, but guard the degenerate shape so+ // an empty array can never produce an infinite box.+ if (shape.points.length === 0) return { x: 0, y: 0, w: 0, h: 0 };+ const xs = shape.points.map((p) => p.x);+ const ys = shape.points.map((p) => p.y);+ return normalizeRect(+ { x: Math.min(...xs), y: Math.min(...ys) },+ { x: Math.max(...xs), y: Math.max(...ys) },+ );+ }+ case "text": {+ const size = measureText(shape.text, shape.size, shape.width);+ return shape.bg+ ? {+ x: shape.at.x - TEXT_BG_PAD_X,+ y: shape.at.y - TEXT_BG_PAD_Y,+ w: size.w + TEXT_BG_PAD_X * 2,+ h: size.h + TEXT_BG_PAD_Y * 2,+ }+ : { x: shape.at.x, y: shape.at.y, w: size.w, h: size.h };+ }+ case "counter":+ return {+ x: shape.at.x - COUNTER_RADIUS,+ y: shape.at.y - COUNTER_RADIUS,+ w: COUNTER_RADIUS * 2,+ h: COUNTER_RADIUS * 2,+ };+ }+}++function segmentDistance(p: Point, a: Point, b: Point): number {+ const abx = b.x - a.x;+ const aby = b.y - a.y;+ const lengthSq = abx * abx + aby * aby;+ const t = lengthSq+ ? Math.min(+ Math.max(((p.x - a.x) * abx + (p.y - a.y) * aby) / lengthSq, 0),+ 1,+ )+ : 0;+ return Math.hypot(p.x - (a.x + abx * t), p.y - (a.y + aby * t));+}++const HIT_SLACK = 6;++export function hitShape(shape: Shape, point: Point): boolean {+ switch (shape.kind) {+ case "arrow": {+ if (segmentDistance(point, shape.from, shape.to) <= HIT_SLACK) {+ return true;+ }+ // The arrowhead wings extend outside the shaft's slack; a click on+ // either head edge selects the arrow too.+ const { wings } = arrowHead(shape.from, shape.to);+ return wings.some(+ (wing) => segmentDistance(point, shape.to, wing) <= HIT_SLACK,+ );+ }+ case "pen":+ // A click-only stroke has a single point (drawn as a dot); it must+ // stay selectable or it could never be moved or deleted.+ if (shape.points.length === 1) {+ return (+ Math.hypot(+ point.x - shape.points[0].x,+ point.y - shape.points[0].y,+ ) <= HIT_SLACK+ );+ }+ return shape.points.some(+ (at, index) =>+ index > 0 &&+ segmentDistance(point, shape.points[index - 1], at) <= HIT_SLACK,+ );+ default: {+ const box = shapeBBox(shape);+ return (+ point.x >= box.x - HIT_SLACK &&+ point.x <= box.x + box.w + HIT_SLACK &&+ point.y >= box.y - HIT_SLACK &&+ point.y <= box.y + box.h + HIT_SLACK+ );+ }+ }+}++export function translateShape(shape: Shape, dx: number, dy: number): Shape {+ switch (shape.kind) {+ case "rect":+ case "ellipse":+ case "pixelate":+ return {+ ...shape,+ rect: { ...shape.rect, x: shape.rect.x + dx, y: shape.rect.y + dy },+ };+ case "arrow":+ return {+ ...shape,+ from: { x: shape.from.x + dx, y: shape.from.y + dy },+ to: { x: shape.to.x + dx, y: shape.to.y + dy },+ };+ case "pen":+ return {+ ...shape,+ points: shape.points.map((p) => ({ x: p.x + dx, y: p.y + dy })),+ };+ case "text":+ case "counter":+ return { ...shape, at: { x: shape.at.x + dx, y: shape.at.y + dy } };+ }+}++/** How shapes sample the underlying shot (for pixelate). */+export interface DrawEnv {+ image: HTMLImageElement;+ /** Shot pixels per view pixel, per axis. */+ sx: number;+ sy: number;+}++export function drawShape(+ ctx: CanvasRenderingContext2D,+ shape: Shape,+ env: DrawEnv,+): void {+ ctx.lineWidth = LINE_WIDTH;+ ctx.lineCap = "round";+ ctx.lineJoin = "round";+ switch (shape.kind) {+ case "rect": {+ const { x, y, w, h } = shape.rect;+ ctx.strokeStyle = shape.color;+ ctx.beginPath();+ ctx.roundRect(x, y, w, h, 4);+ ctx.stroke();+ return;+ }+ case "ellipse": {+ const { x, y, w, h } = shape.rect;+ ctx.strokeStyle = shape.color;+ ctx.beginPath();+ ctx.ellipse(x + w / 2, y + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);+ ctx.stroke();+ return;+ }+ case "arrow": {+ const { from, to } = shape;+ const { wings, shaftEnd } = arrowHead(from, to);+ ctx.strokeStyle = shape.color;+ ctx.fillStyle = shape.color;+ ctx.beginPath();+ ctx.moveTo(from.x, from.y);+ ctx.lineTo(shaftEnd.x, shaftEnd.y);+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(to.x, to.y);+ ctx.lineTo(wings[0].x, wings[0].y);+ ctx.lineTo(wings[1].x, wings[1].y);+ ctx.closePath();+ ctx.fill();+ return;+ }+ case "pen": {+ if (shape.points.length === 0) return;+ // A click without a drag leaves one point: draw the dot a round-capped+ // stroke of this width would leave, so the stroke doesn't vanish.+ if (shape.points.length === 1) {+ ctx.fillStyle = shape.color;+ ctx.beginPath();+ ctx.arc(+ shape.points[0].x,+ shape.points[0].y,+ LINE_WIDTH / 2,+ 0,+ Math.PI * 2,+ );+ ctx.fill();+ return;+ }+ ctx.strokeStyle = shape.color;+ ctx.beginPath();+ ctx.moveTo(shape.points[0].x, shape.points[0].y);+ for (const point of shape.points.slice(1)) {+ ctx.lineTo(point.x, point.y);+ }+ ctx.stroke();+ return;+ }+ case "text": {+ ctx.font = textFont(shape.size);+ ctx.textBaseline = "top";+ ctx.textAlign = "left";+ if (shape.bg) {+ const box = shapeBBox(shape);+ ctx.save();+ // Soft drop shadow lifts the pill off busy screenshots.+ ctx.shadowColor = "rgba(0, 0, 0, 0.28)";+ ctx.shadowBlur = 8;+ ctx.shadowOffsetY = 2;+ ctx.fillStyle = shape.color;+ ctx.beginPath();+ ctx.roundRect(box.x, box.y, box.w, box.h, 7);+ ctx.fill();+ ctx.restore();+ ctx.fillStyle = contrastInk(shape.color);+ } else {+ ctx.save();+ ctx.shadowColor = "rgba(0, 0, 0, 0.55)";+ ctx.shadowBlur = 3;+ ctx.fillStyle = shape.color;+ }+ let y = shape.at.y;+ for (const line of textLines(shape.text, shape.size, shape.width)) {+ ctx.fillText(line, shape.at.x, y);+ y += shape.size * TEXT_LINE;+ }+ if (!shape.bg) ctx.restore();+ return;+ }+ case "counter": {+ ctx.beginPath();+ ctx.arc(shape.at.x, shape.at.y, COUNTER_RADIUS, 0, Math.PI * 2);+ ctx.fillStyle = shape.color;+ ctx.fill();+ ctx.strokeStyle = "rgba(255, 255, 255, 0.85)";+ ctx.lineWidth = 1.5;+ ctx.stroke();+ ctx.font = `700 ${shape.n > 99 ? 11 : 13}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillStyle = contrastInk(shape.color);+ ctx.fillText(String(shape.n), shape.at.x, shape.at.y + 0.5);+ ctx.textAlign = "left";+ return;+ }+ case "pixelate": {+ const { x, y, w, h } = shape.rect;+ if (w < 2 || h < 2) return;+ const blocksW = Math.max(1, Math.round(w / PIXEL_BLOCK));+ const blocksH = Math.max(1, Math.round(h / PIXEL_BLOCK));+ const small = document.createElement("canvas");+ small.width = blocksW;+ small.height = blocksH;+ const smallCtx = small.getContext("2d");+ if (!smallCtx) return;+ smallCtx.drawImage(+ env.image,+ x * env.sx,+ y * env.sy,+ w * env.sx,+ h * env.sy,+ 0,+ 0,+ blocksW,+ blocksH,+ );+ const smoothing = ctx.imageSmoothingEnabled;+ ctx.imageSmoothingEnabled = false;+ ctx.drawImage(small, 0, 0, blocksW, blocksH, x, y, w, h);+ ctx.imageSmoothingEnabled = smoothing;+ return;+ }+ }+}diff --git a/products/desktop/packages/quick-ask/src/geometry/geometry.test.ts b/products/desktop/packages/quick-ask/src/geometry/geometry.test.tsnew file mode 100644index 000000000000..02821bde45ca--- /dev/null+++ b/products/desktop/packages/quick-ask/src/geometry/geometry.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";+import {+ computeGeometry,+ MENU_BAR_CLEARANCE,+ PILL_HEIGHT,+ PILL_TOP_TO_WINDOW_BOTTOM,+ PILL_TOP_TO_WINDOW_TOP,+ SCREEN_MARGIN,+} from "./geometry";++const AREA = { x: 0, y: 0, width: 1512, height: 950 };+const PILL = { width: 300, height: PILL_HEIGHT };++describe("computeGeometry", () => {+ it("anchors the window top at the pill and grows downward when there is room", () => {+ const geometry = computeGeometry(+ { x: 100, y: 200 },+ { width: 543, height: 600 },+ AREA,+ false,+ );+ expect(geometry).toMatchObject({+ x: 100,+ y: 200 - PILL_TOP_TO_WINDOW_TOP,+ width: 543,+ height: 600,+ flip: false,+ });+ expect(geometry.maxHeight).toBe(+ AREA.height - SCREEN_MARGIN - (200 - PILL_TOP_TO_WINDOW_TOP),+ );+ });++ it("flips upward when the content outgrows the room below a low anchor", () => {+ // The shipped bug: direction was decided at summon (pill-only content,+ // fits below), so an answer arriving later was crushed into the sliver.+ const anchor = { x: 100, y: 800 };+ const summoned = computeGeometry(anchor, PILL, AREA, false);+ expect(summoned.flip).toBe(false);++ const answered = computeGeometry(+ anchor,+ { width: 543, height: 500 },+ AREA,+ summoned.flip,+ );+ expect(answered.flip).toBe(true);+ // The pill keeps its on-screen position: window bottom sits just under it.+ expect(answered.y + answered.height).toBe(+ anchor.y + PILL_TOP_TO_WINDOW_BOTTOM,+ );+ expect(answered.height).toBe(500);+ });++ it("clamps to the roomier side when the content fits nowhere", () => {+ const anchor = { x: 100, y: 800 };+ const geometry = computeGeometry(+ anchor,+ { width: 543, height: 5000 },+ AREA,+ false,+ );+ expect(geometry.flip).toBe(true);+ const roomAbove = anchor.y + PILL_TOP_TO_WINDOW_BOTTOM - MENU_BAR_CLEARANCE;+ expect(geometry.height).toBe(roomAbove);+ expect(geometry.maxHeight).toBe(roomAbove);+ expect(geometry.y).toBe(anchor.y + PILL_TOP_TO_WINDOW_BOTTOM - roomAbove);+ });++ it("keeps the current direction while the content still fits there", () => {+ // No side-jumping mid-answer: shrinking content must not un-flip.+ const anchor = { x: 100, y: 500 };+ const geometry = computeGeometry(+ anchor,+ { width: 543, height: 300 },+ AREA,+ true,+ );+ expect(geometry.flip).toBe(true);+ });++ it("never reports less than pill height even with the anchor at the screen edge", () => {+ const geometry = computeGeometry(+ { x: 100, y: AREA.height - 20 },+ PILL,+ AREA,+ false,+ );+ expect(geometry.height).toBeGreaterThanOrEqual(PILL_HEIGHT);+ expect(geometry.maxHeight).toBeGreaterThanOrEqual(PILL_HEIGHT);+ });+});diff --git a/products/desktop/packages/quick-ask/src/geometry/geometry.ts b/products/desktop/packages/quick-ask/src/geometry/geometry.tsnew file mode 100644index 000000000000..c76b6dcac093--- /dev/null+++ b/products/desktop/packages/quick-ask/src/geometry/geometry.ts@@ -0,0 +1,79 @@+/**+ * Placement math for the quick-ask panel, kept free of electron imports so+ * the decisions are unit-testable.+ *+ * Everything about the panel's placement derives from one fact — where the+ * pill row's top-left corner sits on screen — plus the content size and the+ * display's work area. `computeGeometry` is that pure function, re-evaluated+ * on every content change, so the grow direction is a living decision: a+ * panel summoned low on the screen starts growing upward the moment the+ * answer needs the room, instead of being stuck with whatever direction+ * made sense when it was an empty pill.+ */++// Layout constants matching quick-ask.css: root padding top/bottom 10/14,+// pill row 46px, card gap 10px.+export const ROOT_PAD_TOP = 10;+export const ROOT_PAD_BOTTOM = 14;+export const PILL_ROW_HEIGHT = 46;+export const PILL_HEIGHT = ROOT_PAD_TOP + PILL_ROW_HEIGHT + ROOT_PAD_BOTTOM;+// Keep the panel clear of the menu bar and screen edges.+export const SCREEN_MARGIN = 16;+export const MENU_BAR_CLEARANCE = 40;+// Distance between the pill row's top edge and the window edge in each+// grow direction (root padding; plus the pill row itself when flipped).+export const PILL_TOP_TO_WINDOW_TOP = ROOT_PAD_TOP;+export const PILL_TOP_TO_WINDOW_BOTTOM = PILL_ROW_HEIGHT + ROOT_PAD_BOTTOM;++export interface Point {+ x: number;+ y: number;+}++export interface Size {+ width: number;+ height: number;+}++export interface Rect extends Point, Size {}++export interface QuickAskGeometry extends Rect {+ /** Card renders above the pill. */+ flip: boolean;+ /** Room between the pill's anchor and the screen edge, in CSS pixels. */+ maxHeight: number;+}++export function computeGeometry(+ anchor: Point,+ content: Size,+ workArea: Rect,+ prevFlip: boolean,+): QuickAskGeometry {+ const roomBelow =+ workArea.y ++ workArea.height -+ SCREEN_MARGIN -+ (anchor.y - PILL_TOP_TO_WINDOW_TOP);+ const roomAbove =+ anchor.y + PILL_TOP_TO_WINDOW_BOTTOM - (workArea.y + MENU_BAR_CLEARANCE);+ // Keep the current direction while the content fits there (no side+ // jumping mid-answer); otherwise grow toward the roomier side.+ let flip = prevFlip;+ if (content.height > (flip ? roomAbove : roomBelow)) {+ flip = roomAbove > roomBelow;+ }+ const maxHeight = Math.max(PILL_HEIGHT, flip ? roomAbove : roomBelow);+ const height = Math.max(PILL_HEIGHT, Math.min(content.height, maxHeight));+ const y = flip+ ? anchor.y + PILL_TOP_TO_WINDOW_BOTTOM - height+ : anchor.y - PILL_TOP_TO_WINDOW_TOP;+ return {+ x: anchor.x,+ y: Math.round(y),+ width: content.width,+ height,+ flip,+ maxHeight,+ };+}diff --git a/products/desktop/packages/quick-ask/src/gesture/shake.test.ts b/products/desktop/packages/quick-ask/src/gesture/shake.test.tsnew file mode 100644index 000000000000..f3f248e5aee5--- /dev/null+++ b/products/desktop/packages/quick-ask/src/gesture/shake.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { ShakeDetector } from "./shake";++/** Feeds a left-right zigzag of the given amplitude; returns first fire time. */+function zigzag(+ detector: ShakeDetector,+ amplitude: number,+ swings: number,+ stepMs = 60,+): number | null {+ let now = 0;+ for (let swing = 0; swing < swings; swing++) {+ const x = swing % 2 === 0 ? amplitude : 0;+ now += stepMs;+ if (detector.sample(x, now)) return now;+ }+ return null;+}++describe("ShakeDetector", () => {+ it("fires after enough fast wide swings and re-arms", () => {+ const detector = new ShakeDetector();+ expect(zigzag(detector, 40, 8)).not.toBeNull();+ // Re-armed: the same gesture fires again.+ detector.reset();+ expect(zigzag(detector, 40, 8)).not.toBeNull();+ });++ it("ignores small jitter", () => {+ const detector = new ShakeDetector();+ expect(zigzag(detector, 8, 40)).toBeNull();+ });++ it("ignores slow back-and-forth", () => {+ const detector = new ShakeDetector();+ expect(zigzag(detector, 40, 20, 600)).toBeNull();+ });++ it("a straight drag never fires", () => {+ const detector = new ShakeDetector();+ for (let i = 0; i < 100; i++) {+ expect(detector.sample(i * 20, i * 15)).toBe(false);+ }+ });+});diff --git a/products/desktop/packages/quick-ask/src/gesture/shake.ts b/products/desktop/packages/quick-ask/src/gesture/shake.tsnew file mode 100644index 000000000000..d9171ea25b8c--- /dev/null+++ b/products/desktop/packages/quick-ask/src/gesture/shake.ts@@ -0,0 +1,60 @@+/**+ * Shake gesture over a stream of cursor x positions: enough horizontal+ * direction reversals of a minimum swing, close enough together.+ */++/** A reversal counts only after the cursor swings back this many pixels. */+const SWING_PX = 14;+/** Reversals must all land inside this window. */+const WINDOW_MS = 900;+/** Reversals needed to call it a shake. */+const REVERSALS = 3;++export class ShakeDetector {+ private direction: 1 | -1 | 0 = 0;+ /** Furthest x reached in the current direction. */+ private extremeX = 0;+ private reversalTimes: number[] = [];+ private started = false;++ /** Feed one cursor sample; true when a shake completes (then re-arms). */+ sample(x: number, now: number): boolean {+ if (!this.started) {+ this.started = true;+ this.extremeX = x;+ return false;+ }+ if (this.direction >= 0 && x > this.extremeX) {+ this.direction = 1;+ this.extremeX = x;+ return false;+ }+ if (this.direction <= 0 && x < this.extremeX) {+ this.direction = -1;+ this.extremeX = x;+ return false;+ }+ if (Math.abs(x - this.extremeX) < SWING_PX) {+ return false;+ }+ // Swung back past the threshold: a reversal.+ this.direction = x > this.extremeX ? 1 : -1;+ this.extremeX = x;+ this.reversalTimes = this.reversalTimes.filter(+ (time) => now - time < WINDOW_MS,+ );+ this.reversalTimes.push(now);+ if (this.reversalTimes.length >= REVERSALS) {+ this.reversalTimes = [];+ return true;+ }+ return false;+ }++ reset(): void {+ this.direction = 0;+ this.extremeX = 0;+ this.reversalTimes = [];+ this.started = false;+ }+}diff --git a/products/desktop/packages/quick-ask/src/panel/QuickAsk.tsx b/products/desktop/packages/quick-ask/src/panel/QuickAsk.tsxnew file mode 100644index 000000000000..4d7b8f847a11--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/QuickAsk.tsx@@ -0,0 +1,584 @@+import {+ builderHog,+ explorerHog,+ happyHog,+ hogzillaHog,+ loopHog,+} from "@posthog/ui/assets/hedgehogs";+import type React from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import type { QuickAskEvent } from "../service/quick-ask";+import { AnswerCard, ErrorCard, ThinkingCard } from "./components/AnswerCard";+import { quickAskHost } from "./host-bridge";++type Phase = "idle" | "thinking" | "streaming" | "answered" | "error";++/** Double-clicking the hedgehog cycles through the crew. */+const HEDGEHOGS = [happyHog, builderHog, explorerHog, loopHog];++/** Sustained shaking summons (and later banishes) hogzilla. */+const HOGZILLA_SHAKES = 5;+/** Longest pause between shakes that still counts as one long shake. */+const HOGZILLA_GAP_MS = 1_500;++/** An empty, untouched panel folds into mini mode after this long. */+const IDLE_COLLAPSE_MS = Number(+ new URLSearchParams(window.location.search).get("idleCollapse") ?? 60_000,+);++const PILL_MIN_WIDTH = 176;+const PILL_MAX_WIDTH = 448;+const PILL_TEXT_EXTRA = 46; // pill padding + caret allowance around the text++interface TextPart {+ id: string;+ content: string;+ complete: boolean;+}++/**+ * Applies a streamed text snapshot: replace by id, or let a completed message+ * take over the trailing in-progress (`temp-` id) snapshot it finalizes.+ */+function applyTextEvent(+ parts: TextPart[],+ event: { id: string; content: string; complete: boolean },+): TextPart[] {+ const byId = parts.findIndex((part) => part.id === event.id);+ if (byId >= 0) {+ return parts.map((part, index) =>+ index === byId ? { ...part, ...event } : part,+ );+ }+ if (event.complete) {+ const lastIncomplete = parts.findLastIndex((part) => !part.complete);+ if (lastIncomplete >= 0) {+ return parts.map((part, index) =>+ index === lastIncomplete ? { ...event } : part,+ );+ }+ }+ return [...parts, { ...event }];+}++export function QuickAsk(): React.JSX.Element {+ const [phase, setPhase] = useState<Phase>("idle");+ const [thinkingLabel, setThinkingLabel] = useState("Thinking…");+ const [textParts, setTextParts] = useState<TextPart[]>([]);+ const [errorMessage, setErrorMessage] = useState("");+ const [pillWidth, setPillWidth] = useState(PILL_MIN_WIDTH);+ const [flip, setFlip] = useState(false);+ const [hedgehog, setHedgehog] = useState(0);+ const [mini, setMini] = useState(false);+ const [hogzilla, setHogzilla] = useState(false);+ const shakeStreak = useRef({ count: 0, last: 0 });+ const [attachment, setAttachment] = useState<string | null>(null);+ const [attachError, setAttachError] = useState<string | null>(null);+ const [canOpenSettings, setCanOpenSettings] = useState(false);+ const conversationIdRef = useRef<string | undefined>(undefined);+ const historyRef = useRef<string[]>([]);+ /** Position while walking history with the arrows; null = editing the draft. */+ const historyIndexRef = useRef<number | null>(null);+ const draftRef = useRef("");+ const inputRef = useRef<HTMLInputElement>(null);+ const measureRef = useRef<HTMLSpanElement>(null);+ const rootRef = useRef<HTMLDivElement>(null);++ const reset = useCallback((): void => {+ quickAskHost()?.reset();+ conversationIdRef.current = undefined;+ setAttachment(null);+ setAttachError(null);+ setPhase("idle");+ setThinkingLabel("Thinking…");+ setTextParts([]);+ setErrorMessage("");+ setPillWidth(PILL_MIN_WIDTH);+ if (inputRef.current) {+ inputRef.current.value = "";+ }+ // After the re-render: the click left focus on the new-chat button.+ requestAnimationFrame(() => inputRef.current?.focus());+ }, []);++ // Tell the main process how tall the window should be. Called on every+ // layout-relevant change: the ResizeObserver misses re-shows because the+ // content size does not change while hidden.+ const reportSize = useCallback((): void => {+ const root = rootRef.current;+ if (!root) return;+ // The window's bounds hug this measurement: everything outside the+ // content is not part of the window at all, so clicks land on whatever+ // is behind without any click-through machinery. +2 mirrors the -2+ // slack in the root's max-height so the reported height never exceeds+ // the space the main process said was available.+ const rect = root.getBoundingClientRect();+ quickAskHost()?.resize({+ width: Math.ceil(rect.width) + 2,+ height: Math.ceil(rect.height) + 2,+ });+ }, []);++ // The main process owns screen geometry: it pushes the room available at+ // the current position and decides whether the card sits above the pill+ // (summoned near the screen bottom). The root caps itself to that room and+ // flexbox shrinks the card into whatever is left, so the card cap never+ // depends on the measured height it feeds back.+ useEffect(() => {+ return quickAskHost()?.onLayout((layout) => {+ document.documentElement.style.setProperty(+ "--qa-root-max",+ `${Math.max(60, layout.maxHeight - 2)}px`,+ );+ setFlip(layout.flip);+ requestAnimationFrame(reportSize);+ });+ }, [reportSize]);++ const loading = phase === "thinking" || phase === "streaming";++ // Refocus on every summon. The previous session is kept — "New chat" or a+ // new question clears it — so reopening restores the last answer.+ useEffect(() => {+ const unsubscribe = quickAskHost()?.onShown(() => {+ // Summoning is an intent to type; leave mini mode.+ setMini(false);+ inputRef.current?.focus();+ reportSize();+ // Re-report once the flipped layout has settled.+ requestAnimationFrame(reportSize);+ });+ return () => unsubscribe?.();+ }, [reportSize]);++ // Esc dismisses from anywhere.+ useEffect(() => {+ const onKey = (event: KeyboardEvent): void => {+ if (event.key === "Escape") {+ quickAskHost()?.hide();+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ // Answer stream from the main process.+ useEffect(() => {+ return quickAskHost()?.onEvent((raw) => {+ const event = raw as QuickAskEvent;+ switch (event.type) {+ case "conversation":+ conversationIdRef.current = event.conversationId;+ break;+ case "reasoning":+ setThinkingLabel(event.content || "Thinking…");+ break;+ case "text":+ setTextParts((parts) => applyTextEvent(parts, event));+ setPhase((current) =>+ current === "thinking" || current === "idle"+ ? "streaming"+ : current,+ );+ break;+ case "error":+ setErrorMessage(event.message);+ setPhase("error");+ break;+ case "done":+ setPhase((current) => (current === "error" ? current : "answered"));+ break;+ }+ });+ }, []);++ // Drive the BrowserWindow height from the rendered content.+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ const observer = new ResizeObserver(reportSize);+ observer.observe(root);+ return () => observer.disconnect();+ }, [reportSize]);++ // Screenshot lifecycle: the main process owns the bytes and reports the+ // chip preview (or why capture failed) here.+ useEffect(() => {+ return quickAskHost()?.onAttachment((payload) => {+ const { previewDataUrl, error, canOpenSettings } = (payload ?? {}) as {+ previewDataUrl?: string | null;+ error?: string;+ canOpenSettings?: boolean;+ };+ setAttachment(previewDataUrl ?? null);+ setAttachError(error ?? null);+ setCanOpenSettings(canOpenSettings ?? false);+ });+ }, []);++ useEffect(() => {+ if (!attachError) return;+ // A permission miss carries a settings link; leave it up until acted on.+ if (canOpenSettings) return;+ const timer = setTimeout(() => setAttachError(null), 5000);+ return () => clearTimeout(timer);+ }, [attachError, canOpenSettings]);++ // The hedgehog is the drag handle. Native `-webkit-app-region: drag`+ // swallows the mousedown that click-through relies on, so the panel moves+ // itself: report a grab offset and the main process follows the cursor.+ const startDrag = useCallback((event: React.MouseEvent): void => {+ if (event.button !== 0) return;+ event.preventDefault();+ quickAskHost()?.dragStart({+ dx: event.screenX - window.screenX,+ dy: event.screenY - window.screenY,+ });+ const endDrag = (): void => {+ quickAskHost()?.dragEnd();+ document.removeEventListener("mouseup", endDrag);+ };+ document.addEventListener("mouseup", endDrag);+ }, []);++ // Figma-style pill: width hugs the typed text.+ const syncPillWidth = useCallback((): void => {+ const measure = measureRef.current;+ const input = inputRef.current;+ if (!measure || !input) return;+ measure.textContent = input.value || input.placeholder;+ const width = Math.min(+ Math.max(measure.offsetWidth + PILL_TEXT_EXTRA, PILL_MIN_WIDTH),+ PILL_MAX_WIDTH,+ );+ setPillWidth(width);+ }, []);++ const submit = useCallback((): void => {+ // A turn is already streaming: ignore type-ahead so a second question can't+ // relay onto the live run and corrupt turn attribution. The input is also+ // disabled, but this closes the click-race before React applies that.+ if (loading) return;+ const question = inputRef.current?.value.trim();+ if (!question) return;+ // Shell-style history for the up/down arrows.+ const history = historyRef.current;+ if (history[history.length - 1] !== question) {+ history.push(question);+ }+ historyIndexRef.current = null;+ draftRef.current = "";+ if (inputRef.current) {+ inputRef.current.value = "";+ }+ syncPillWidth();+ setTextParts([]);+ setErrorMessage("");+ setThinkingLabel("Thinking…");+ setPhase("thinking");+ // The main process folds the pending screenshot into this ask.+ setAttachment(null);+ quickAskHost()?.ask(question, conversationIdRef.current);+ }, [syncPillWidth, loading]);++ // Up/down arrows recall previously sent questions, shell-style: up walks+ // back through history, down walks forward and lands on the unsent draft.+ const recallHistory = useCallback(+ (direction: -1 | 1): void => {+ const input = inputRef.current;+ if (!input) return;+ const history = historyRef.current;+ if (history.length === 0) return;+ let index = historyIndexRef.current;+ if (index === null) {+ if (direction === 1) return; // Nothing newer than the draft.+ draftRef.current = input.value;+ index = history.length - 1;+ } else {+ index += direction;+ }+ if (index >= history.length) {+ historyIndexRef.current = null;+ input.value = draftRef.current;+ } else {+ historyIndexRef.current = Math.max(0, index);+ input.value = history[historyIndexRef.current];+ }+ input.setSelectionRange(input.value.length, input.value.length);+ syncPillWidth();+ },+ [syncPillWidth],+ );++ const onKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLInputElement>): void => {+ if (event.key === "Enter") {+ submit();+ } else if (event.key === "ArrowUp") {+ event.preventDefault();+ recallHistory(-1);+ } else if (event.key === "ArrowDown") {+ event.preventDefault();+ recallHistory(1);+ }+ },+ [submit, recallHistory],+ );++ const openInApp = useCallback((): void => {+ quickAskHost()?.openInApp();+ }, []);++ const nextHedgehog = useCallback((): void => {+ setHedgehog((current) => (current + 1) % HEDGEHOGS.length);+ }, []);++ // Shaking the panel while dragging it cycles the hedgehog. Keeping the+ // shake going summons hogzilla; another long shake calms it back down.+ const onShake = useCallback((): void => {+ const now = Date.now();+ const streak = shakeStreak.current;+ streak.count = now - streak.last < HOGZILLA_GAP_MS ? streak.count + 1 : 1;+ streak.last = now;+ if (streak.count >= HOGZILLA_SHAKES) {+ streak.count = 0;+ setHogzilla((current) => !current);+ return;+ }+ if (!hogzilla) {+ nextHedgehog();+ }+ }, [hogzilla, nextHedgehog]);++ useEffect(() => {+ const unsubscribe = quickAskHost()?.onShake(onShake);+ return () => unsubscribe?.();+ }, [onShake]);++ const toggleMini = useCallback((): void => {+ setMini((current) => !current);+ }, []);++ // Left open, empty, and untouched, the panel folds itself into mini mode.+ useEffect(() => {+ if (mini || hogzilla || phase !== "idle") return;+ let timer: number;+ const schedule = (): void => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ if (inputRef.current?.value) {+ schedule();+ } else {+ setMini(true);+ }+ }, IDLE_COLLAPSE_MS);+ };+ schedule();+ window.addEventListener("keydown", schedule);+ window.addEventListener("mousedown", schedule);+ window.addEventListener("mousemove", schedule);+ return () => {+ window.clearTimeout(timer);+ window.removeEventListener("keydown", schedule);+ window.removeEventListener("mousedown", schedule);+ window.removeEventListener("mousemove", schedule);+ };+ }, [mini, hogzilla, phase]);++ // Put the caret back in the pill when leaving mini mode, and when a turn+ // settles and re-enables the input (a disabled input drops focus and the+ // browser does not restore it).+ useEffect(() => {+ if (!mini && !loading) {+ inputRef.current?.focus();+ }+ }, [mini, loading]);++ const status = loading+ ? "busy"+ : phase === "answered"+ ? "ready"+ : phase === "error"+ ? "error"+ : "idle";++ return (+ <div+ ref={rootRef}+ className={[+ "qa-root",+ flip && "qa-flip",+ mini && "qa-mini",+ hogzilla && "qa-zilla",+ ]+ .filter(Boolean)+ .join(" ")}+ >+ <div className="qa-pill-row">+ <button+ type="button"+ aria-label={+ hogzilla+ ? "Hogzilla — shake to calm it down"+ : mini+ ? "Expand the panel"+ : "Drag to move the panel"+ }+ onMouseDown={startDrag}+ onDoubleClick={hogzilla ? undefined : toggleMini}+ className={phase === "thinking" ? "qa-hog qa-hog-thinking" : "qa-hog"}+ >+ <img+ src={hogzilla ? hogzillaHog : HEDGEHOGS[hedgehog]}+ alt=""+ draggable={false}+ />+ <span+ className={`qa-status qa-status-${status}`}+ aria-hidden="true"+ />+ </button>+ {mini && loading && (+ <span key={thinkingLabel} className="qa-mini-label">+ {thinkingLabel}+ </span>+ )}+ <div className="qa-pill" style={{ width: pillWidth }}>+ <input+ ref={inputRef}+ type="text"+ placeholder={+ phase === "answered" ? "Ask a follow-up…" : "Ask PostHog"+ }+ autoComplete="off"+ spellCheck={false}+ disabled={loading}+ onKeyDown={onKeyDown}+ onInput={syncPillWidth}+ />+ </div>+ {phase !== "idle" && (+ <button+ type="button"+ aria-label="New chat"+ title="New chat"+ className="qa-new"+ onClick={reset}+ >+ <svg+ width="13"+ height="13"+ viewBox="0 0 10 10"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ aria-hidden="true"+ >+ <path d="M5 1.5V8.5M1.5 5H8.5" />+ </svg>+ </button>+ )}+ <button+ type="button"+ aria-label="Capture screen"+ title="Capture and annotate the screen"+ className="qa-shot"+ onClick={() => quickAskHost()?.capture()}+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 14 14"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.3"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ <path d="M1.5 4.5a1 1 0 0 1 1-1h1.6l1-1.5h3.8l1 1.5h1.6a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1z" />+ <circle cx="7" cy="7.2" r="2.2" />+ </svg>+ </button>+ <button+ type="button"+ aria-label="Close"+ title="Close"+ className="qa-close"+ onClick={() => quickAskHost()?.hide()}+ >+ <svg+ width="13"+ height="13"+ viewBox="0 0 10 10"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ aria-hidden="true"+ >+ <path d="M1.5 1.5L8.5 8.5M8.5 1.5L1.5 8.5" />+ </svg>+ </button>+ {/* Hidden mirror used to measure the typed text for the pill width. */}+ <span ref={measureRef} className="qa-measure" aria-hidden="true" />+ </div>++ {(attachment || attachError) && (+ <div className="qa-attach">+ {attachment ? (+ <>+ <img src={attachment} alt="Screenshot to attach" />+ <span className="qa-attach-label">Screenshot attached</span>+ <button+ type="button"+ aria-label="Remove screenshot"+ onClick={() => {+ quickAskHost()?.discardAttachment();+ setAttachment(null);+ }}+ >+ ×+ </button>+ </>+ ) : (+ <>+ <span className="qa-attach-error">{attachError}</span>+ {canOpenSettings && (+ <button+ type="button"+ className="qa-attach-settings"+ onClick={() => {+ quickAskHost()?.openScreenSettings();+ setAttachError(null);+ }}+ >+ Open settings+ </button>+ )}+ <button+ type="button"+ aria-label="Dismiss"+ onClick={() => setAttachError(null)}+ >+ ×+ </button>+ </>+ )}+ </div>+ )}++ {phase === "thinking" && <ThinkingCard label={thinkingLabel} />}+ {phase === "error" && <ErrorCard message={errorMessage} />}+ {(phase === "streaming" || phase === "answered") && (+ <AnswerCard+ parts={textParts}+ streaming={phase === "streaming"}+ statusLabel={phase === "streaming" ? thinkingLabel : null}+ onOpenInApp={openInApp}+ />+ )}+ </div>+ );+}diff --git a/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx b/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsxnew file mode 100644index 000000000000..cbc21de0cc46--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx@@ -0,0 +1,263 @@+import { EvidenceRefChip } from "@posthog/ui/features/editor/components/EvidenceRefChip";+import {+ baseComponents,+ MarkdownRenderer,+} from "@posthog/ui/features/editor/components/MarkdownRenderer";+import { useCopy } from "@posthog/ui/primitives/useCopy";+import {+ chartBlockKey,+ isGeneratedChartBlock,+ parseChartBlock,+} from "@posthog/ui/utils/chartBlocks";+import {+ type EvidenceLinkTarget,+ parseEvidenceLink,+} from "@posthog/ui/utils/evidenceLinks";+import type React from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import type { Components } from "react-markdown";+import { PanelChartCard } from "./PanelChartCard";++const AUTOSCROLL_SLACK_PX = 48;++/**+ * The shared reference chip with its live hover preview. The chip's own+ * click-out is suppressed: in the panel the hover card is the destination,+ * and its "open" affordance still links out.+ */+function PanelChip({+ target,+ children,+}: {+ target: EvidenceLinkTarget;+ children: React.ReactNode;+}): React.JSX.Element {+ return (+ <span+ className="qa-ref"+ onClickCapture={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ >+ <EvidenceRefChip target={target}>{children}</EvidenceRefChip>+ </span>+ );+}++const BaseAnchor = baseComponents.a as React.ComponentType<{+ href?: string;+ children?: React.ReactNode;+}>;+const BaseCode = baseComponents.code as React.ComponentType<{+ className?: string;+ children?: React.ReactNode;+}>;+/** Panel rendering for the shared tag pipeline: compact charts, plain chips. */+const panelComponents: Partial<Components> = {+ a: ({ href, children }) => {+ const target = parseEvidenceLink(href);+ if (target) {+ return <PanelChip target={target}>{children}</PanelChip>;+ }+ return <BaseAnchor href={href}>{children}</BaseAnchor>;+ },+ code: ({ className, children, node }) => {+ // The AST marker is the trust boundary: only plugin-generated blocks+ // resolve to live queries; a hand-authored fence stays a code block.+ if (isGeneratedChartBlock(node)) {+ const spec = parseChartBlock(String(children).replace(/\n$/, ""));+ if (!spec) return null;+ return (+ <PanelChartCard key={chartBlockKey(String(children))} spec={spec} />+ );+ }+ return <BaseCode className={className}>{children}</BaseCode>;+ },+ pre: (props) => {+ // A chart block renders as a card, not inside a code block shell.+ if (isGeneratedChartBlock(props.node?.children[0])) {+ return props.children;+ }+ return <pre className="qa-pre">{props.children}</pre>;+ },+};++export function ThinkingCard({ label }: { label: string }): React.JSX.Element {+ return (+ <div className="qa-card qa-card-thinking">+ <div className="qa-thinking-header">+ <span className="qa-thinking-dots" aria-hidden="true">+ <span />+ <span />+ <span />+ </span>+ {/* Keyed so a new reasoning step slides in instead of just swapping. */}+ <span key={label} className="qa-thinking-label">+ {label}+ </span>+ </div>+ <div className="qa-skeleton qa-skeleton-line-wide" />+ <div className="qa-skeleton qa-skeleton-line" />+ <div className="qa-skeleton qa-skeleton-line-short" />+ </div>+ );+}++export function ErrorCard({ message }: { message: string }): React.JSX.Element {+ return (+ <div className="qa-card">+ <div className="qa-error">{message}</div>+ </div>+ );+}++export interface AnswerPart {+ id: string;+ content: string;+ complete: boolean;+}++interface AnswerCardProps {+ /** Answer segments: text stretches separated by tool activity. */+ parts: AnswerPart[];+ /** Still receiving tokens: show the streaming caret, hold the actions. */+ streaming: boolean;+ /** Latest agent activity, shown above the answer until the turn is done. */+ statusLabel: string | null;+ onOpenInApp: () => void;+}++export function AnswerCard({+ parts,+ streaming,+ statusLabel,+ onOpenInApp,+}: AnswerCardProps): React.JSX.Element {+ // Sets `copied` only after the clipboard write resolves, so the button+ // never reports a success that didn't happen (unfocused panel, blocked+ // permission).+ const { copied, copy } = useCopy(1400);+ // null follows the newest segment; a number pins an earlier one.+ const [pinned, setPinned] = useState<number | null>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const pinnedToBottom = useRef(true);++ const shownIndex =+ pinned === null+ ? Math.max(parts.length - 1, 0)+ : Math.min(pinned, parts.length - 1);+ const shown = parts[shownIndex];+ const text = shown?.content ?? "";++ const copyAnswer = useCallback((): void => {+ copy(parts.map((part) => part.content).join("\n\n"));+ }, [copy, parts]);++ const page = useCallback(+ (direction: -1 | 1): void => {+ setPinned((current) => {+ const base = current === null ? parts.length - 1 : current;+ const next = Math.min(Math.max(base + direction, 0), parts.length - 1);+ return next === parts.length - 1 ? null : next;+ });+ },+ [parts.length],+ );++ // Follow the stream, but stop if the user scrolled up to read.+ const onScroll = useCallback((): void => {+ const el = scrollRef.current;+ if (!el) return;+ pinnedToBottom.current =+ el.scrollHeight - el.scrollTop - el.clientHeight < AUTOSCROLL_SLACK_PX;+ }, []);++ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll on every text growth+ useEffect(() => {+ const el = scrollRef.current;+ if (el && streaming && pinnedToBottom.current) {+ el.scrollTop = el.scrollHeight;+ }+ }, [text, streaming]);++ const pager =+ parts.length > 1 ? (+ <span className="qa-pager">+ <button+ type="button"+ aria-label="Previous part"+ disabled={shownIndex === 0}+ onClick={() => page(-1)}+ >+ ‹+ </button>+ {shownIndex + 1}/{parts.length}+ <button+ type="button"+ aria-label="Next part"+ disabled={shownIndex === parts.length - 1}+ onClick={() => page(1)}+ >+ ›+ </button>+ </span>+ ) : null;++ const streamingShown = streaming && shownIndex === parts.length - 1;++ return (+ <div className="qa-card">+ {/* The pager lives up here: the card is top-anchored, so paging between+ segments of different heights never moves it. */}+ {(streaming || pager) && (+ <div className="qa-status-row">+ {streaming && (+ <>+ <span className="qa-thinking-dots" aria-hidden="true">+ <span />+ <span />+ <span />+ </span>+ <span key={statusLabel} className="qa-thinking-label">+ {statusLabel || "Working…"}+ </span>+ </>+ )}+ {pager}+ </div>+ )}+ <div ref={scrollRef} className="qa-card-scroll" onScroll={onScroll}>+ <div+ key={shown?.id ?? "empty"}+ className={+ streamingShown+ ? "qa-answer qa-streaming qa-seg-in"+ : "qa-answer qa-seg-in"+ }+ >+ <MarkdownRenderer+ content={text}+ renderObjectTags+ componentsOverride={panelComponents}+ />+ </div>+ </div>++ {!streaming && (+ <div className="qa-actions">+ <button type="button" className="qa-button" onClick={copyAnswer}>+ {copied ? "Copied" : "Copy"}+ </button>+ <button+ type="button"+ className="qa-button qa-primary"+ onClick={onOpenInApp}+ >+ Open in PostHog+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/products/desktop/packages/quick-ask/src/panel/components/PanelChartCard.tsx b/products/desktop/packages/quick-ask/src/panel/components/PanelChartCard.tsxnew file mode 100644index 000000000000..e0c9b363a434--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/components/PanelChartCard.tsx@@ -0,0 +1,242 @@+import {+ planReportChart,+ type ReportChartData,+ reportChartOpenTarget,+ shapeReportChartData,+} from "@posthog/core/inbox/reportCharts";+import { getCloudUrlFromRegion } from "@posthog/shared";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";+import type { ChartBlockSpec } from "@posthog/ui/utils/chartBlocks";+import type React from "react";+import { useMemo } from "react";+import { Chart, type QuickAskChart } from "./charts";++/**+ * The panel's rendering of a block-display object tag. Data resolves through+ * the same live pipeline as the shared chart card; only the drawing differs:+ * the compact SVG chart sized for a cursor panel.+ */++function useOpenOptions(): { cloudUrl: string; projectId: number } | null {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);+ if (!projectId || !cloudRegion) return null;+ return { cloudUrl: getCloudUrlFromRegion(cloudRegion), projectId };+}++function Frame({+ title,+ openUrl,+ children,+}: {+ title: string;+ openUrl: string | null;+ children: React.ReactNode;+}): React.JSX.Element {+ return (+ <div className="qa-chart">+ <div className="qa-chart-header">+ {openUrl ? (+ <button+ type="button"+ className="qa-chart-title qa-chart-title-link"+ onClick={() => openExternalUrl(openUrl)}+ title="Open in PostHog"+ >+ {title}+ </button>+ ) : (+ <span className="qa-chart-title">{title}</span>+ )}+ </div>+ {children}+ </div>+ );+}++function Skeleton(): React.JSX.Element {+ return (+ <>+ <div className="qa-skeleton qa-skeleton-line-wide" />+ <div className="qa-skeleton qa-skeleton-line" />+ </>+ );+}++function toChart(data: ReportChartData, title: string): QuickAskChart | null {+ if (data.type !== "series" || data.series.length === 0) return null;+ return {+ kind: data.render,+ title,+ labels: data.labels,+ series: data.series.map((series) => ({+ name: series.label,+ points: series.data,+ })),+ };+}++function ChartBody({+ data,+ title,+ openUrl,+}: {+ data: ReportChartData;+ title: string;+ openUrl: string | null;+}): React.JSX.Element {+ const chart = toChart(data, title);+ if (chart) {+ // The compact chart draws its own header with the headline stat.+ return (+ <Chart+ chart={chart}+ onOpen={openUrl ? () => openExternalUrl(openUrl) : undefined}+ />+ );+ }+ if (data.type === "number") {+ return (+ <Frame title={title} openUrl={openUrl}>+ <div className="qa-chart-number">{data.value.toLocaleString()}</div>+ </Frame>+ );+ }+ if (data.type === "table") {+ return (+ <Frame title={title} openUrl={openUrl}>+ <table className="qa-chart-table">+ <thead>+ <tr>+ {data.columns.map((column) => (+ <th key={column}>{column}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {data.rows.slice(0, 8).map((row, rowIndex) => (+ <tr key={`${rowIndex}:${String(row[0])}`}>+ {row.map((cell, cellIndex) => (+ <td key={`${cellIndex}:${String(cell)}`}>{String(cell)}</td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </Frame>+ );+ }+ return (+ <Frame title={title} openUrl={openUrl}>+ <div className="qa-chart-note">Open in PostHog to see this one.</div>+ </Frame>+ );+}++function openUrlFor(+ node: unknown,+ options: { cloudUrl: string; projectId: number } | null,+): string | null {+ if (!options) return null;+ return reportChartOpenTarget(node, options)?.url ?? null;+}++function HogqlCard({+ spec,+}: {+ spec: Extract<ChartBlockSpec, { mode: "hogql" }>;+}): React.JSX.Element {+ const openOptions = useOpenOptions();+ const node = useMemo(+ () => ({+ kind: "DataVisualizationNode",+ source: { kind: "HogQLQuery", query: spec.query },+ }),+ [spec.query],+ );+ const plan = useMemo(() => planReportChart(node), [node]);+ const title = spec.title ?? "Query result";+ const query = useAuthenticatedQuery<ReportChartData>(+ ["quick-ask-chart", spec.query],+ async (client) => {+ if (plan.kind !== "run") return { type: "empty" };+ const response = await client.runQuery(plan.source);+ return shapeReportChartData(response, plan);+ },+ { staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },+ );+ const openUrl = openUrlFor(node, openOptions);+ if (query.isPending) {+ return (+ <Frame title={title} openUrl={openUrl}>+ <Skeleton />+ </Frame>+ );+ }+ if (query.isError || !query.data) {+ return (+ <Frame title={title} openUrl={openUrl}>+ <div className="qa-chart-note">+ The query behind this chart failed. Open it in PostHog.+ </div>+ </Frame>+ );+ }+ return <ChartBody data={query.data} title={title} openUrl={openUrl} />;+}++function InsightCard({+ spec,+}: {+ spec: Extract<ChartBlockSpec, { mode: "insight" }>;+}): React.JSX.Element {+ const openOptions = useOpenOptions();+ const query = useAuthenticatedQuery<{+ name: string | null;+ data: ReportChartData | null;+ } | null>(+ ["quick-ask-chart-insight", spec.shortId],+ async (client) => {+ const insight = await client.getInsightDefinition(spec.shortId);+ if (!insight) return null;+ const plan = planReportChart(insight.query);+ if (plan.kind !== "run") return { name: insight.name, data: null };+ const response = await client.runQuery(plan.source);+ return { name: insight.name, data: shapeReportChartData(response, plan) };+ },+ { staleTime: 5 * 60 * 1000, refetchOnWindowFocus: false, retry: 1 },+ );+ const title = spec.title ?? query.data?.name ?? "Insight";+ const openUrl = openUrlFor(+ { kind: "SavedInsightNode", shortId: spec.shortId },+ openOptions,+ );+ if (query.isPending) {+ return (+ <Frame title={title} openUrl={openUrl}>+ <Skeleton />+ </Frame>+ );+ }+ if (query.isError || !query.data?.data) {+ return (+ <Frame title={title} openUrl={openUrl}>+ <div className="qa-chart-note">Open in PostHog to see this one.</div>+ </Frame>+ );+ }+ return <ChartBody data={query.data.data} title={title} openUrl={openUrl} />;+}++export function PanelChartCard({+ spec,+}: {+ spec: ChartBlockSpec;+}): React.JSX.Element | null {+ if (spec.mode === "hogql") return <HogqlCard spec={spec} />;+ if (spec.mode === "insight") return <InsightCard spec={spec} />;+ // Replay cards need the full player surface; the chip already links out.+ return null;+}diff --git a/products/desktop/packages/quick-ask/src/panel/components/charts.tsx b/products/desktop/packages/quick-ask/src/panel/components/charts.tsxnew file mode 100644index 000000000000..0d03a64ead4a--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/components/charts.tsx@@ -0,0 +1,476 @@+import type React from "react";+import { useCallback, useMemo, useState } from "react";++/** A compact chart: series over shared x-axis labels. */+export interface QuickAskChart {+ kind: "line" | "bar";+ title: string;+ labels: string[];+ series: { name: string; points: number[] }[];+}++/** Normalized plot space; the SVG stretches to fill the card. */+const WIDTH = 100;+const HEIGHT = 48;+const TOP_PAD = 5;+const MAX_X_TICKS = 7;+/** Fixed categorical order; one distinct color per renderable series. */+const SERIES_COLORS = [+ "var(--qa-accent)",+ "var(--qa-series-2)",+ "var(--qa-series-3)",+ "var(--qa-series-4)",+ "var(--qa-series-5)",+ "var(--qa-series-6)",+];+/**+ * The palette is the ceiling: past it, series would share colors and become+ * indistinguishable in the plot, tooltip, and legend alike. Extra series are+ * dropped consistently everywhere and the legend states how many.+ */+const MAX_SERIES = SERIES_COLORS.length;++const MONTHS = [+ "Jan",+ "Feb",+ "Mar",+ "Apr",+ "May",+ "Jun",+ "Jul",+ "Aug",+ "Sep",+ "Oct",+ "Nov",+ "Dec",+];++/** "8/14" (the axis short form) reads as "Aug 14" in the tooltip. */+function tooltipLabel(label: string): string {+ const match = label.match(/^(\d{1,2})\/(\d{1,2})$/);+ if (!match) return label;+ const month = MONTHS[Number(match[1]) - 1];+ return month ? `${month} ${Number(match[2])}` : label;+}++/** 87342 -> "87.3K"; keeps small numbers plain. */+function compactValue(value: number): string {+ const abs = Math.abs(value);+ const format = (scaled: number, suffix: string): string => {+ const rounded =+ scaled >= 100 ? Math.round(scaled) : Number(scaled.toFixed(1));+ return `${rounded}${suffix}`;+ };+ if (abs >= 1e9) return format(value / 1e9, "B");+ if (abs >= 1e6) return format(value / 1e6, "M");+ if (abs >= 1e3) return format(value / 1e3, "K");+ return Number.isInteger(value) ? String(value) : value.toFixed(1);+}++/** Rounds up to 1/1.5/2/2.5/3/4/5/6/8 × 10^k so gridlines land on round values. */+function niceCeil(value: number): number {+ if (value <= 0) return 1;+ const magnitude = 10 ** Math.floor(Math.log10(value));+ for (const factor of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) {+ if (factor * magnitude >= value) return factor * magnitude;+ }+ return 10 * magnitude;+}++interface PlotScale {+ lo: number;+ hi: number;+ /** Round values, bottom to top, for gridlines and their labels. */+ ticks: number[];+ x: (index: number, count: number) => number;+ y: (value: number) => number;+}++function buildScale(series: { points: number[] }[]): PlotScale {+ const all = series.flatMap((entry) => entry.points);+ const hi = niceCeil(Math.max(...all));+ const lo = Math.min(0, ...all);+ const range = hi - lo || 1;+ return {+ lo,+ hi,+ ticks: [lo, (lo + hi) / 2, hi],+ x: (index, count) =>+ count > 1 ? (index / (count - 1)) * WIDTH : WIDTH / 2,+ y: (value) => HEIGHT - ((value - lo) / range) * (HEIGHT - TOP_PAD),+ };+}++function Gridlines({ scale }: { scale: PlotScale }): React.JSX.Element {+ return (+ <g>+ {scale.ticks.map((tick) => (+ <line+ key={tick}+ x1={0}+ x2={WIDTH}+ y1={scale.y(tick)}+ y2={scale.y(tick)}+ stroke="rgba(255, 255, 255, 0.07)"+ strokeWidth={1}+ vectorEffect="non-scaling-stroke"+ />+ ))}+ </g>+ );+}++function LinePlot({+ chart,+ scale,+}: {+ chart: QuickAskChart;+ scale: PlotScale;+}): React.JSX.Element {+ return (+ <>+ {chart.series.map((series, seriesIndex) => {+ const line = series.points+ .map(+ (point, index) =>+ `${index === 0 ? "M" : "L"}${scale.x(index, series.points.length).toFixed(1)} ${scale.y(point).toFixed(1)}`,+ )+ .join(" ");+ const color = SERIES_COLORS[seriesIndex] ?? SERIES_COLORS[0];+ return (+ <g key={series.name}>+ {seriesIndex === 0 && (+ <path+ className="qa-chart-area"+ d={`${line} L${WIDTH} ${HEIGHT} L0 ${HEIGHT} Z`}+ fill="url(#qa-line-fill)"+ />+ )}+ <path+ className="qa-chart-line"+ d={line}+ pathLength={1}+ fill="none"+ stroke={color}+ strokeWidth={2}+ strokeLinejoin="round"+ strokeLinecap="round"+ vectorEffect="non-scaling-stroke"+ />+ </g>+ );+ })}+ </>+ );+}++function BarPlot({+ chart,+ scale,+ hoverIndex,+}: {+ chart: QuickAskChart;+ scale: PlotScale;+ hoverIndex: number | null;+}): React.JSX.Element {+ // Bars draw a single series; Chart renders multi-series data as lines.+ const points = chart.series[0].points;+ const slot = WIDTH / points.length;+ const barWidth = slot * 0.62;+ const baseline = scale.y(Math.max(scale.lo, 0));+ return (+ <>+ {points.map((point, index) => {+ const top = scale.y(point);+ return (+ <rect+ key={`${index}:${point}`}+ className="qa-chart-bar"+ style={{ animationDelay: `${Math.min(index * 24, 300)}ms` }}+ x={(index * slot + (slot - barWidth) / 2).toFixed(1)}+ y={Math.min(top, baseline).toFixed(1)}+ width={barWidth.toFixed(1)}+ height={Math.max(Math.abs(baseline - top), 0.5).toFixed(1)}+ rx={1.2}+ fill="var(--qa-accent)"+ opacity={+ hoverIndex === null ? 0.82 : hoverIndex === index ? 1 : 0.4+ }+ />+ );+ })}+ </>+ );+}++/**+ * Thins x-axis labels to at most MAX_X_TICKS. Spaced backwards from the last+ * label so the newest one always shows and kept labels never sit adjacent.+ */+function tickLabels(labels: string[]): string[] {+ if (labels.length <= MAX_X_TICKS) return labels;+ const step = Math.ceil(labels.length / MAX_X_TICKS);+ return labels.map((label, index) =>+ (labels.length - 1 - index) % step === 0 ? label : "",+ );+}++/** Latest value plus its change from the previous point, for the header. */+function LatestStat({+ chart,+}: {+ chart: QuickAskChart;+}): React.JSX.Element | null {+ const points = chart.series[0].points;+ const last = points[points.length - 1];+ // Empty query results are valid (e.g. a total-value insight has labels but no+ // points); with no last value there is no headline stat to show. Mirrors the+ // shared `chartHeadlineStat` guard so the header does not read `undefined`.+ if (typeof last !== "number" || !Number.isFinite(last)) return null;+ const previous = points.length > 1 ? points[points.length - 2] : null;+ const deltaPct =+ previous != null && previous !== 0+ ? ((last - previous) / Math.abs(previous)) * 100+ : null;+ return (+ <span className="qa-chart-stat">+ <span className="qa-chart-stat-value">{compactValue(last)}</span>+ {deltaPct != null && Math.abs(deltaPct) >= 0.5 && (+ <span+ className={+ deltaPct >= 0+ ? "qa-chart-delta qa-delta-up"+ : "qa-chart-delta qa-delta-down"+ }+ >+ {deltaPct >= 0 ? "▲" : "▼"}+ {Math.abs(deltaPct) >= 10+ ? Math.round(Math.abs(deltaPct))+ : Math.abs(deltaPct).toFixed(1)}+ %+ </span>+ )}+ </span>+ );+}++interface HoverState {+ index: number;+ /** Fraction across the plot, 0..1, for positioning the crosshair/tooltip. */+ frac: number;+}++export function Chart({+ chart: chartProp,+ onOpen,+}: {+ chart: QuickAskChart;+ /** Makes the title a link into PostHog. */+ onOpen?: () => void;+}): React.JSX.Element {+ // BarPlot draws a single series; a multi-series bar would plot the first+ // series while the tooltip and legend list them all. Lines carry every+ // series, so multi-series bar data renders as a line chart instead.+ const chart: QuickAskChart = useMemo(() => {+ const kind =+ chartProp.kind === "bar" && chartProp.series.length > 1+ ? "line"+ : chartProp.kind;+ return {+ ...chartProp,+ kind,+ series: chartProp.series.slice(0, MAX_SERIES),+ };+ }, [chartProp]);+ const omittedSeries = chartProp.series.length - chart.series.length;+ const [hover, setHover] = useState<HoverState | null>(null);+ const scale = useMemo(() => buildScale(chart.series), [chart.series]);+ const pointCount = chart.series[0].points.length;++ const onPointerMove = useCallback(+ (event: React.PointerEvent<HTMLDivElement>): void => {+ const rect = event.currentTarget.getBoundingClientRect();+ if (rect.width === 0 || pointCount === 0) return;+ const frac = Math.min(+ Math.max((event.clientX - rect.left) / rect.width, 0),+ 1,+ );+ const index =+ chart.kind === "bar"+ ? Math.min(Math.floor(frac * pointCount), pointCount - 1)+ : Math.round(frac * (pointCount - 1));+ setHover({+ index,+ frac: pointCount > 1 ? index / (pointCount - 1) : 0.5,+ });+ },+ [chart.kind, pointCount],+ );++ const onPointerLeave = useCallback((): void => setHover(null), []);++ const hoverRows =+ hover === null+ ? []+ : chart.series+ .map((series, seriesIndex) => ({+ name: series.name,+ color: SERIES_COLORS[seriesIndex] ?? SERIES_COLORS[0],+ value: series.points[hover.index],+ }))+ .filter((row) => row.value != null);++ return (+ <div className="qa-chart">+ <div className="qa-chart-header">+ {onOpen ? (+ <button+ type="button"+ className="qa-chart-title qa-chart-title-link"+ onClick={onOpen}+ title="Open in PostHog"+ >+ {chart.title}+ </button>+ ) : (+ <span className="qa-chart-title">{chart.title}</span>+ )}+ <LatestStat chart={chart} />+ </div>++ <div+ className="qa-chart-plot"+ onPointerMove={onPointerMove}+ onPointerLeave={onPointerLeave}+ >+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ preserveAspectRatio="none"+ className="qa-chart-svg"+ role="img"+ aria-label={chart.kind === "line" ? "Line chart" : "Bar chart"}+ >+ <defs>+ <linearGradient id="qa-line-fill" x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="0%"+ stopColor="var(--qa-accent)"+ stopOpacity={0.22}+ />+ <stop+ offset="100%"+ stopColor="var(--qa-accent)"+ stopOpacity={0.02}+ />+ </linearGradient>+ </defs>+ <Gridlines scale={scale} />+ {chart.kind === "line" ? (+ <LinePlot chart={chart} scale={scale} />+ ) : (+ <BarPlot+ chart={chart}+ scale={scale}+ hoverIndex={hover?.index ?? null}+ />+ )}+ </svg>++ {/* Round-value tick labels sit over the gridlines, out of the SVG so+ they keep their aspect under preserveAspectRatio="none". */}+ {scale.ticks+ .filter((tick) => tick !== scale.lo)+ .map((tick) => (+ <span+ key={tick}+ className="qa-chart-ytick"+ style={{ top: `${(scale.y(tick) / HEIGHT) * 100}%` }}+ >+ {compactValue(tick)}+ </span>+ ))}++ {hover !== null && (+ <>+ <div+ className="qa-chart-crosshair"+ style={{ left: `${hover.frac * 100}%` }}+ />+ {chart.kind === "line" &&+ chart.series.map((series, seriesIndex) => {+ const value = series.points[hover.index];+ if (value == null) return null;+ return (+ <div+ key={series.name}+ className="qa-chart-hover-dot"+ style={{+ left: `${hover.frac * 100}%`,+ top: `${(scale.y(value) / HEIGHT) * 100}%`,+ background:+ SERIES_COLORS[seriesIndex] ?? SERIES_COLORS[0],+ }}+ />+ );+ })}+ <div+ className={+ hover.frac > 0.55+ ? "qa-chart-tip qa-chart-tip-left"+ : "qa-chart-tip"+ }+ style={{ left: `${hover.frac * 100}%` }}+ >+ {chart.labels[hover.index] != null && (+ <div className="qa-chart-tip-label">+ {tooltipLabel(chart.labels[hover.index])}+ </div>+ )}+ {hoverRows.map((row) => (+ <div key={row.name} className="qa-chart-tip-row">+ <span+ className="qa-chart-dot"+ style={{ background: row.color }}+ />+ <span className="qa-chart-tip-name">{row.name}</span>+ <span className="qa-chart-tip-value">+ {compactValue(row.value)}+ </span>+ </div>+ ))}+ </div>+ </>+ )}+ </div>++ {chart.labels.length > 0 && (+ <div className="qa-chart-labels">+ {tickLabels(chart.labels).map((label, index) => (+ <span key={`${index}:${label}`}>{label}</span>+ ))}+ </div>+ )}++ {chart.series.length > 1 && (+ <div className="qa-chart-legend">+ {chart.series.map((series, seriesIndex) => (+ <span key={series.name} className="qa-chart-legend-item">+ <span+ className="qa-chart-dot"+ style={{+ background: SERIES_COLORS[seriesIndex] ?? SERIES_COLORS[0],+ }}+ />+ {series.name}+ </span>+ ))}+ {omittedSeries > 0 && (+ <span className="qa-chart-legend-item">+ +{omittedSeries} more in PostHog+ </span>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/products/desktop/packages/quick-ask/src/panel/host-bridge.ts b/products/desktop/packages/quick-ask/src/panel/host-bridge.tsnew file mode 100644index 000000000000..9c0199ae8295--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/host-bridge.ts@@ -0,0 +1,44 @@+/**+ * The contract between the panel and whatever hosts it. The Electron host+ * implements it in its preload (window.quickAsk); tests stub it the same way.+ */++/** Geometry pushed by the host after every layout change. */+export interface QuickAskLayout {+ /** Card renders above the pill (summoned near the bottom of the screen). */+ flip: boolean;+ /** Max window height: pill anchor to screen edge, in CSS pixels. */+ maxHeight: number;+}++export interface QuickAskHostBridge {+ hide: () => void;+ /** Reports the content's bounding box; the window's bounds hug it. */+ resize: (size: { width: number; height: number }) => void;+ openInApp: () => void;+ /** Native app-region dragging fights click-through; the panel drags itself. */+ dragStart: (offset: { dx: number; dy: number }) => void;+ dragEnd: () => void;+ ask: (question: string, conversationId?: string) => void;+ cancel: () => void;+ /** Drops the thread and pre-warms the next one. */+ reset: () => void;+ /** Events are `QuickAskEvent`s from ../service/quick-ask. */+ onEvent: (callback: (event: unknown) => void) => () => void;+ onLayout: (callback: (layout: QuickAskLayout) => void) => () => void;+ onShown: (callback: () => void) => () => void;+ /** Fired when the panel is shaken while dragged. */+ onShake: (callback: () => void) => () => void;+ /** Hides the panel, freezes the screen, and opens the annotator. */+ capture: () => void;+ discardAttachment: () => void;+ /** Opens the OS pane that grants screen-recording permission. */+ openScreenSettings: () => void;+ /** Payloads are `QuickAskAttachmentPayload`s from the host's constants. */+ onAttachment: (callback: (payload: unknown) => void) => () => void;+}++/** The bridge the host installed, if any (absent in bare component tests). */+export function quickAskHost(): QuickAskHostBridge | undefined {+ return (window as { quickAsk?: QuickAskHostBridge }).quickAsk;+}diff --git a/products/desktop/packages/quick-ask/src/panel/quick-ask.css b/products/desktop/packages/quick-ask/src/panel/quick-ask.cssnew file mode 100644index 000000000000..45e49fbe641e--- /dev/null+++ b/products/desktop/packages/quick-ask/src/panel/quick-ask.css@@ -0,0 +1,1173 @@+/* Quick-ask cursor pill + answer card. Color values mirror the quill dark+ * theme tokens (packages/quill/packages/tokens) so it matches the app. */++/* The app's global styles paint opaque page backgrounds; the panel window is+ * transparent outside its content, so neutralize them. This file loads after+ * globals.css, so equal-specificity rules here win. */+.radix-themes {+ min-height: 0;+ background: transparent;+}++:root {+ /* Opaque like Figma's cursor chat: no translucency, no blur, no shadow.+ * (backdrop-filter also renders as a grey slab in a transparent window.) */+ --qa-surface: #1e1f25;+ --qa-surface-raised: rgba(255, 255, 255, 0.04);+ --qa-border: rgba(255, 255, 255, 0.14);+ --qa-fg: #f2f2f5;+ --qa-fg-muted: #a1a1aa;+ --qa-fg-subtle: #77777e;+ --qa-accent: #f1a82c; /* quill primary (dark) */+ /* Chart series 2-6 (series 1 is the accent). 2 and 3 are CVD-validated+ * against --qa-surface with the dataviz palette checker; 4-6 extend the+ * ramp with hue + lightness separation from their neighbors. */+ --qa-series-2: #5b86de;+ --qa-series-3: #3aa658;+ --qa-series-4: #a875e8;+ --qa-series-5: #de5b9c;+ --qa-series-6: #3fb8c9;+ --qa-up: #6bcf7e;+ --qa-down: #ff7b6b;+ /* Hover-card sparklines pick up the panel's accent. */+ --evidence-spark-color: var(--qa-accent);+ --qa-hover: rgba(255, 255, 255, 0.08);+ --qa-glass: rgba(30, 31, 37, 0.92);+ --qa-glass-card: rgba(30, 31, 37, 0.94);+ --qa-sheen: rgba(255, 255, 255, 0.07);+ --qa-hairline: rgba(255, 255, 255, 0.06);+ --qa-raised-solid: #2a2b33;+ --qa-elevated: #26272e;+ --qa-backdrop: rgba(30, 31, 37, 0.75);+ --qa-fg-soft: #d6d6dc;+ --qa-scroll: rgba(255, 255, 255, 0.14);+ --qa-scroll-hover: rgba(255, 255, 255, 0.24);+ --qa-crosshair: rgba(255, 255, 255, 0.22);+ --qa-dot-idle: rgba(255, 255, 255, 0.4);+ --qa-shimmer-lo: rgba(255, 255, 255, 0.05);+ --qa-shimmer-hi: rgba(255, 255, 255, 0.11);+ --qa-font:+ -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Helvetica,+ Arial, sans-serif;+ --qa-mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, monospace;+}++/* Light palette; the theme store toggles .dark on <html>. */+html:not(.dark) {+ --qa-surface: #ffffff;+ --qa-surface-raised: rgba(0, 0, 0, 0.045);+ --qa-border: rgba(0, 0, 0, 0.16);+ --qa-fg: #1c1d22;+ --qa-fg-muted: #5c5c66;+ --qa-fg-subtle: #8a8a93;+ --qa-accent: #d97706;+ --qa-series-2: #3560c4;+ --qa-series-3: #2a8a47;+ --qa-series-4: #7c4fd0;+ --qa-series-5: #b8437e;+ --qa-series-6: #22869a;+ --qa-up: #2f9e54;+ --qa-down: #d64545;+ --qa-hover: rgba(0, 0, 0, 0.06);+ --qa-glass: rgba(255, 255, 255, 0.93);+ --qa-glass-card: rgba(255, 255, 255, 0.95);+ --qa-sheen: rgba(255, 255, 255, 0.85);+ --qa-hairline: rgba(0, 0, 0, 0.08);+ --qa-raised-solid: #e9e9ee;+ --qa-elevated: #ffffff;+ --qa-backdrop: rgba(255, 255, 255, 0.78);+ --qa-fg-soft: #33343c;+ --qa-scroll: rgba(0, 0, 0, 0.18);+ --qa-scroll-hover: rgba(0, 0, 0, 0.3);+ --qa-crosshair: rgba(0, 0, 0, 0.25);+ --qa-dot-idle: rgba(0, 0, 0, 0.35);+ --qa-shimmer-lo: rgba(0, 0, 0, 0.045);+ --qa-shimmer-hi: rgba(0, 0, 0, 0.09);+}++/* box-sizing everywhere. Un-layered, but border-box is the default every+ * element wants, so winning over utilities is harmless. */+* {+ box-sizing: border-box;+}++/* Reset panel-tree margins/padding in `base` — below Tailwind's `utilities`+ * layer — so shared components (MarkdownRenderer, reference chips) keep their+ * spacing utilities inside #root. An un-layered reset outranks every layer+ * regardless of specificity, which would zero those utilities. :where(#root …)+ * keeps the reset off the portalled overlays that render outside #root. */+@layer base {+ :where(#root, #root *) {+ margin: 0;+ padding: 0;+ }+}++/* `html body` outranks the app globals' plain `body` background rules. */+html,+html body {+ background: transparent;+ overflow: hidden;+ font-family: var(--qa-font);+ user-select: none;+}++.qa-root {+ display: inline-flex;+ flex-direction: column;+ align-items: flex-start;+ padding: 10px 14px 14px 10px;+ /* Pushed by the main process: the room between the pill's anchor and the+ * screen edge. Flexbox shrinks the card into it; the window then matches+ * the measured result. */+ max-height: var(--qa-root-max, none);+}++/* Summoned close to the screen bottom: the card renders above the pill+ * (class toggles the root's direction; card overrides live below `.qa-card`). */+.qa-root.qa-flip {+ flex-direction: column-reverse;+}++/* ── Cursor pill ─────────────────────────────────────── */++.qa-pill-row {+ display: flex;+ flex-shrink: 0;+ align-items: flex-end;+ gap: 7px;+ position: relative;+}++.qa-hog {+ position: relative;+ width: 46px;+ height: 46px;+ padding: 0;+ border: 0;+ background: transparent;+ /* The hedgehog is the drag handle for moving the panel around. */+ cursor: grab;+ animation: qa-hog-in 0.28s cubic-bezier(0.34, 1.56, 0.64, 1);+ transform-origin: bottom center;+}++.qa-hog img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ pointer-events: none;+}++.qa-hog:active {+ cursor: grabbing;+}++.qa-hog-thinking {+ animation: qa-hog-bob 0.9s ease-in-out infinite;+}++@keyframes qa-hog-in {+ from {+ transform: scale(0.3) translateY(10px);+ opacity: 0;+ }+ to {+ transform: scale(1) translateY(0);+ opacity: 1;+ }+}++@keyframes qa-hog-bob {+ 0%,+ 100% {+ transform: translateY(0) rotate(0deg);+ }+ 30% {+ transform: translateY(-4px) rotate(-3deg);+ }+ 60% {+ transform: translateY(0) rotate(2deg);+ }+}++.qa-pill {+ height: 42px;+ display: flex;+ align-items: center;+ padding: 0 18px;+ border-radius: 21px;+ border-bottom-left-radius: 6px;+ background: var(--qa-glass);+ border: 1px solid var(--qa-border);+ box-shadow: inset 0 1px 0 var(--qa-sheen);+ transition: width 0.12s ease-out;+ animation: qa-pill-in 0.22s cubic-bezier(0.2, 0.9, 0.3, 1.1);+ transform-origin: left bottom;+}++@keyframes qa-pill-in {+ from {+ transform: scale(0.6);+ opacity: 0;+ }+ to {+ transform: scale(1);+ opacity: 1;+ }+}++.qa-pill input {+ width: 100%;+ background: transparent;+ border: 0;+ outline: 0;+ font: 500 14.5px var(--qa-font);+ color: var(--qa-fg);+ caret-color: var(--qa-accent);+}++.qa-pill input::placeholder {+ color: var(--qa-fg-subtle);+}++/* Hidden mirror of the input text, used to size the pill. */+/* Mini mode: only the hedgehog and its status dot stay on screen. */+.qa-mini > :not(.qa-pill-row),+.qa-mini .qa-pill-row > :not(.qa-hog) {+ display: none;+}++/* Hogzilla: a long shake grows the hedgehog and takes the panel hostage;+ only another long shake shrinks it back. */+.qa-zilla > :not(.qa-pill-row),+.qa-zilla .qa-pill-row > :not(.qa-hog) {+ display: none;+}++.qa-zilla .qa-hog {+ width: 156px;+ height: 156px;+ animation: qa-zilla-in 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);+}++.qa-mini-label {+ display: none;+ align-self: center;+ max-width: 240px;+ padding: 4px 10px;+ font-size: 11px;+ color: var(--qa-fg-muted);+ background: var(--qa-glass);+ border: 1px solid var(--qa-border);+ border-radius: 999px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ animation: qa-label-in 0.28s cubic-bezier(0.2, 0.8, 0.3, 1);+ box-shadow: inset 0 1px 0 var(--qa-sheen);+}++:where(.qa-mini) .qa-mini-label {+ display: inline-block;+}++/* Status dot on the hedgehog's shoulder, mini mode only. */+.qa-status {+ display: none;+ position: absolute;+ right: 0;+ bottom: 2px;+ width: 11px;+ height: 11px;+ border-radius: 50%;+ border: 2px solid var(--qa-surface);+}++.qa-mini .qa-status {+ display: block;+}++.qa-status-idle {+ background: var(--qa-dot-idle);+}++.qa-status-busy {+ background: var(--qa-accent);+ animation: qa-status-pulse 1.1s ease-in-out infinite;+}++.qa-status-ready {+ background: var(--qa-up);+}++.qa-status-error {+ background: var(--qa-down);+}++@keyframes qa-zilla-in {+ 0% {+ transform: scale(0.3);+ }+ 60% {+ transform: scale(1.12) rotate(-3deg);+ }+ 80% {+ transform: scale(0.96) rotate(2deg);+ }+ 100% {+ transform: scale(1);+ }+}++@keyframes qa-status-pulse {+ 50% {+ opacity: 0.35;+ }+}++/* Pill-height circles so the controls read as part of the input row. */+.qa-close,+.qa-shot,+.qa-new {+ width: 42px;+ height: 42px;+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: 1px solid var(--qa-border);+ border-radius: 50%;+ background: var(--qa-surface);+ color: var(--qa-fg-subtle);+ cursor: pointer;+ transition:+ color 0.12s,+ background 0.12s;+}++.qa-close:hover,+.qa-shot:hover,+.qa-new:hover {+ color: var(--qa-fg);+ background: var(--qa-raised-solid);+}++.qa-measure {+ position: absolute;+ visibility: hidden;+ white-space: pre;+ font: 500 14.5px var(--qa-font);+}++/* Pending screenshot chip between the pill and the card. */+.qa-attach {+ display: flex;+ align-items: center;+ gap: 9px;+ width: max-content;+ max-width: 464px;+ margin: 8px 0 0 53px;+ padding: 6px 10px 6px 6px;+ border-radius: 10px;+ background: var(--qa-glass);+ border: 1px solid var(--qa-border);+ box-shadow: inset 0 1px 0 var(--qa-sheen);+ animation: qa-label-in 0.28s cubic-bezier(0.2, 0.8, 0.3, 1);+}++.qa-attach img {+ display: block;+ height: 36px;+ max-width: 120px;+ object-fit: cover;+ border-radius: 6px;+ border: 1px solid var(--qa-border);+}++.qa-attach-label {+ font-size: 11.5px;+ color: var(--qa-fg-muted);+}++.qa-attach-error {+ flex: 1;+ min-width: 0;+ padding: 2px 4px;+ font-size: 11.5px;+ color: var(--qa-down);+ overflow-wrap: anywhere;+}++/* Controls keep their size; the message is what gives way. */+.qa-attach .qa-attach-settings,+.qa-attach button {+ flex-shrink: 0;+}++.qa-attach .qa-attach-settings {+ font: 600 11.5px var(--qa-font);+ color: var(--qa-accent);+ background: rgba(247, 165, 1, 0.12);+ border: 1px solid rgba(247, 165, 1, 0.3);+ border-radius: 7px;+ padding: 3px 9px;+ cursor: pointer;+ white-space: nowrap;+}++.qa-attach .qa-attach-settings:hover {+ background: rgba(247, 165, 1, 0.2);+}++.qa-attach button {+ width: 18px;+ height: 18px;+ border: none;+ border-radius: 50%;+ background: transparent;+ color: var(--qa-fg-subtle);+ font-size: 14px;+ line-height: 1;+ cursor: pointer;+}++.qa-attach button:hover {+ color: var(--qa-fg);+ background: var(--qa-hover);+}++/* ── Answer card ─────────────────────────────────────── */++.qa-card {+ width: 464px;+ margin: 10px 0 0 53px;+ border-radius: 14px;+ background: var(--qa-glass-card);+ border: 1px solid var(--qa-border);+ box-shadow: inset 0 1px 0 var(--qa-sheen);+ animation: qa-card-in 0.24s cubic-bezier(0.2, 0.9, 0.3, 1.05);+ transform-origin: top left;+ overflow: hidden;+ /* Shrinks into the root's max-height; long answers scroll inside. */+ min-height: 0;+ display: flex;+ flex-direction: column;+}++/* Flipped: the card grows upward with the pill anchored to its summon point. */+.qa-flip .qa-card {+ margin: 0 0 10px 53px;+ transform-origin: bottom left;+}++.qa-card-scroll {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 16px 16px 12px;+}++.qa-card-scroll::-webkit-scrollbar {+ width: 8px;+}++.qa-card-scroll::-webkit-scrollbar-thumb {+ background: var(--qa-scroll);+ border-radius: 4px;+ border: 2px solid transparent;+ background-clip: content-box;+}++.qa-card-scroll::-webkit-scrollbar-thumb:hover {+ background: var(--qa-scroll-hover);+ border: 2px solid transparent;+ background-clip: content-box;+}++@keyframes qa-card-in {+ from {+ transform: translateY(-6px) scale(0.98);+ opacity: 0;+ }+ to {+ transform: translateY(0) scale(1);+ opacity: 1;+ }+}++/* Answer prose */++.qa-answer {+ font-size: 13px;+ line-height: 1.55;+ color: var(--qa-fg-soft);+ user-select: text;+ cursor: text;+}++.qa-answer p + p {+ margin-top: 7px;+}++.qa-answer strong {+ color: var(--qa-fg);+ font-weight: 650;+}++.qa-answer .qa-num {+ color: var(--qa-accent);+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}++/* Actions */++.qa-actions {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: flex-end;+ gap: 8px;+ padding: 10px 16px 12px;+ border-top: 1px solid var(--qa-hairline);+}++.qa-button {+ font: 600 12px var(--qa-font);+ border-radius: 8px;+ padding: 5px 11px;+ border: 1px solid var(--qa-border);+ background: var(--qa-surface-raised);+ color: var(--qa-fg);+ cursor: pointer;+ transition: background 0.12s;+}++.qa-button:hover {+ background: var(--qa-hover);+}++.qa-button.qa-primary {+ background: var(--qa-accent);+ border-color: transparent;+ color: #1d1f27;+}++.qa-button.qa-primary:hover {+ filter: brightness(1.06);+}++.qa-answer code {+ font-family: var(--qa-mono);+ font-size: 12px;+ background: var(--qa-surface-raised);+ border: 1px solid var(--qa-hairline);+ border-radius: 4px;+ padding: 1px 4px;+}++.qa-answer table {+ margin: 9px 0;+ border-collapse: collapse;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+}++.qa-answer th,+.qa-answer td {+ padding: 4px 10px;+ text-align: left;+ border-bottom: 1px solid var(--qa-hairline);+}++.qa-answer th {+ font-size: 10.5px;+ font-weight: 650;+ color: var(--qa-fg-subtle);+ text-transform: uppercase;+ letter-spacing: 0.03em;+}++.qa-answer td:not(:first-child),+.qa-answer th:not(:first-child) {+ text-align: right;+}++.qa-answer tbody tr:last-child td {+ border-bottom: 0;+}++.qa-answer ul {+ margin: 7px 0;+ padding-left: 18px;+}++.qa-answer li + li {+ margin-top: 3px;+}++/* Streaming caret, drawn inline at the end of the last rendered block so it+ * never opens a stray line of its own. */+.qa-streaming > :last-child::after {+ content: "";+ display: inline-block;+ width: 3px;+ height: 13px;+ margin-left: 3px;+ vertical-align: -2px;+ border-radius: 1px;+ background: var(--qa-accent);+ animation: qa-caret-blink 1s steps(1) infinite;+}++@keyframes qa-caret-blink {+ 50% {+ opacity: 0;+ }+}++.qa-error {+ font-size: 13px;+ line-height: 1.5;+ color: var(--qa-down);+}++/* Chart */++.qa-chart {+ margin: 12px 0;+ padding: 11px 12px 9px;+ background: var(--qa-surface-raised);+ border: 1px solid var(--qa-border);+ border-radius: 10px;+}++.qa-chart-header {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ gap: 12px;+ margin-bottom: 9px;+}++.qa-chart-title {+ font-size: 11px;+ font-weight: 600;+ color: var(--qa-fg-muted);+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}++.qa-chart-stat {+ display: flex;+ align-items: baseline;+ gap: 6px;+ flex-shrink: 0;+}++.qa-chart-stat-value {+ font-size: 15px;+ font-weight: 650;+ color: var(--qa-fg);+ font-variant-numeric: tabular-nums;+}++.qa-chart-delta {+ font-size: 10px;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}++.qa-delta-up {+ color: var(--qa-up);+}++.qa-delta-down {+ color: var(--qa-down);+}++.qa-chart-plot {+ position: relative;+ /* Room for the tooltip; hover geometry maps onto this box. */+ touch-action: none;+}++.qa-chart-svg {+ display: block;+ width: 100%;+ height: 104px;+}++.qa-chart-line {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: qa-line-draw 0.7s cubic-bezier(0.3, 0.6, 0.3, 1) forwards;+}++.qa-chart-area {+ opacity: 0;+ animation: qa-fade-in 0.5s ease-out 0.35s forwards;+}++.qa-chart-bar {+ transform-box: fill-box;+ transform-origin: bottom;+ animation: qa-bar-grow 0.4s cubic-bezier(0.2, 0.8, 0.3, 1) backwards;+}++@keyframes qa-line-draw {+ to {+ stroke-dashoffset: 0;+ }+}++@keyframes qa-fade-in {+ to {+ opacity: 1;+ }+}++@keyframes qa-bar-grow {+ from {+ transform: scaleY(0);+ }+}++.qa-chart-ytick {+ position: absolute;+ left: 0;+ transform: translateY(-110%);+ font-size: 9px;+ color: var(--qa-fg-subtle);+ font-variant-numeric: tabular-nums;+ pointer-events: none;+ background: var(--qa-backdrop);+ padding: 0 3px;+ border-radius: 3px;+}++.qa-chart-crosshair {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 1px;+ background: var(--qa-crosshair);+ pointer-events: none;+}++.qa-chart-hover-dot {+ position: absolute;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ border: 1.5px solid var(--qa-surface);+ transform: translate(-50%, -50%);+ pointer-events: none;+}++.qa-chart-tip {+ position: absolute;+ top: -4px;+ transform: translateX(10px);+ min-width: 92px;+ max-width: 190px;+ padding: 6px 9px;+ border-radius: 8px;+ background: var(--qa-elevated);+ border: 1px solid var(--qa-border);+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);+ pointer-events: none;+ z-index: 1;+}++.qa-chart-tip-left {+ transform: translateX(calc(-100% - 10px));+}++.qa-chart-tip-label {+ font-size: 10px;+ font-weight: 650;+ color: var(--qa-fg);+ margin-bottom: 3px;+}++.qa-chart-tip-row {+ display: flex;+ align-items: center;+ gap: 5px;+ font-size: 10px;+ color: var(--qa-fg-muted);+}++.qa-chart-tip-row + .qa-chart-tip-row {+ margin-top: 2px;+}++.qa-chart-tip-name {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}++.qa-chart-tip-value {+ margin-left: auto;+ color: var(--qa-fg);+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}++.qa-chart-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ flex-shrink: 0;+}++.qa-chart-labels {+ display: flex;+ justify-content: space-between;+ margin-top: 5px;+ font-size: 9.5px;+ color: var(--qa-fg-subtle);+ font-variant-numeric: tabular-nums;+}++.qa-chart-labels span {+ flex: 1 1 0;+ min-width: 0;+ padding: 0 2px;+ text-align: center;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}++.qa-chart-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 4px 12px;+ margin-top: 7px;+}++.qa-chart-legend-item {+ display: flex;+ align-items: center;+ gap: 5px;+ font-size: 10px;+ color: var(--qa-fg-muted);+}++.qa-chart-title-link {+ border: 0;+ padding: 0;+ background: transparent;+ text-align: left;+ cursor: pointer;+ /* Buttons don't inherit typography; .qa-chart-title supplies size/weight. */+ font-family: var(--qa-font);+ color: inherit;+}++.qa-chart-title-link:hover {+ color: var(--qa-fg);+ text-decoration: underline;+}++.qa-chart-number {+ font-size: 22px;+ font-weight: 650;+ color: var(--qa-fg);+ font-variant-numeric: tabular-nums;+ padding: 4px 0 6px;+}++.qa-chart-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 11px;+}++.qa-chart-table th,+.qa-chart-table td {+ padding: 3px 8px 3px 0;+ text-align: left;+ color: var(--qa-fg-muted);+ border-bottom: 1px solid var(--qa-hairline);+ font-variant-numeric: tabular-nums;+}++.qa-chart-table th {+ font-weight: 600;+ color: var(--qa-fg-subtle);+ text-transform: uppercase;+ font-size: 9.5px;+ letter-spacing: 0.05em;+}++.qa-chart-table tbody tr:last-child td {+ border-bottom: 0;+}++.qa-chart-note {+ font-size: 12px;+ color: var(--qa-fg-muted);+ padding: 2px 0 4px;+}++/* Wrapper for the shared reference chip; hover previews live inside it. */+.qa-ref {+ cursor: default;+}++/* The shared markdown components render at app sizes; tighten to the+ * panel's 13px rhythm. */+.qa-answer .rt-Text {+ font-size: 13px;+ line-height: 1.55;+ margin-bottom: 7px;+}++.qa-answer .rt-Text:last-child {+ margin-bottom: 0;+}++.qa-answer .rt-Code {+ font-size: 11.5px;+}++.qa-pre {+ margin: 8px 0;+ padding: 9px 11px;+ background: var(--qa-surface-raised);+ border: 1px solid var(--qa-border);+ border-radius: 9px;+ overflow-x: auto;+ font: 11.5px var(--qa-mono);+ color: var(--qa-fg-muted);+}++.qa-status-row {+ display: flex;+ align-items: center;+ gap: 9px;+ min-height: 28px;+ padding: 10px 16px 0;+ overflow: hidden;+}++:where(.qa-status-row) .qa-thinking-label {+ flex: 1;+ min-width: 0;+}++:where(.qa-status-row) .qa-pager {+ margin-left: auto;+}++.qa-pager {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ flex-shrink: 0;+ font-size: 10.5px;+ color: var(--qa-fg-subtle);+ font-variant-numeric: tabular-nums;+}++.qa-pager button {+ width: 18px;+ height: 18px;+ border: 1px solid var(--qa-border);+ border-radius: 50%;+ background: transparent;+ color: var(--qa-fg-muted);+ font-size: 12px;+ line-height: 1;+ cursor: pointer;+}++.qa-pager button:hover:not(:disabled) {+ color: var(--qa-fg);+ background: var(--qa-hover);+}++.qa-pager button:disabled {+ opacity: 0.35;+ cursor: default;+}++.qa-seg-in {+ animation: qa-seg-in 0.22s cubic-bezier(0.2, 0.8, 0.3, 1);+}++@keyframes qa-seg-in {+ from {+ opacity: 0;+ transform: translateY(4px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++/* ── Thinking skeleton ───────────────────────────────── */++.qa-card-thinking {+ padding: 16px;+}++.qa-thinking-header {+ display: flex;+ align-items: center;+ gap: 9px;+ margin-bottom: 13px;+ overflow: hidden;+}++.qa-thinking-dots {+ display: inline-flex;+ gap: 3px;+ flex-shrink: 0;+}++.qa-thinking-dots span {+ width: 4.5px;+ height: 4.5px;+ border-radius: 50%;+ background: var(--qa-accent);+ animation: qa-dot-bounce 1.1s ease-in-out infinite;+}++.qa-thinking-dots span:nth-child(2) {+ animation-delay: 0.14s;+}++.qa-thinking-dots span:nth-child(3) {+ animation-delay: 0.28s;+}++@keyframes qa-dot-bounce {+ 0%,+ 55%,+ 100% {+ transform: translateY(0);+ opacity: 0.45;+ }+ 27% {+ transform: translateY(-3.5px);+ opacity: 1;+ }+}++.qa-thinking-label {+ font-size: 12px;+ color: var(--qa-fg-muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ /* Each new reasoning step (keyed) slides up into place. */+ animation: qa-label-in 0.28s cubic-bezier(0.2, 0.8, 0.3, 1);+}++@keyframes qa-label-in {+ from {+ transform: translateY(80%);+ opacity: 0;+ }+ to {+ transform: translateY(0);+ opacity: 1;+ }+}++.qa-skeleton {+ border-radius: 8px;+ background: linear-gradient(+ 100deg,+ var(--qa-shimmer-lo) 40%,+ var(--qa-shimmer-hi) 50%,+ var(--qa-shimmer-lo) 60%+ );+ background-size: 200% 100%;+ animation: qa-shimmer 1.4s linear infinite;+}++.qa-skeleton-line-wide {+ width: 92%;+ height: 12px;+ margin-bottom: 8px;+}++.qa-skeleton-line {+ width: 68%;+ height: 12px;+ margin-bottom: 8px;+ animation-delay: 0.12s;+}++.qa-skeleton-line-short {+ width: 42%;+ height: 12px;+ animation-delay: 0.24s;+}++@keyframes qa-shimmer {+ from {+ background-position: 200% 0;+ }+ to {+ background-position: -200% 0;+ }+}++/* ── Motion preferences ──────────────────────────────── */++[data-testid="evidence-hover-card"] {+ animation: qa-pop-in 0.16s cubic-bezier(0.2, 0.8, 0.3, 1);+}++[data-testid="evidence-hover-card"] svg rect {+ transform-box: fill-box;+ transform-origin: bottom;+ animation: qa-bar-grow 0.4s cubic-bezier(0.2, 0.8, 0.3, 1) backwards;+}++@keyframes qa-pop-in {+ from {+ opacity: 0;+ transform: scale(0.97) translateY(2px);+ }+}++@media (prefers-reduced-motion: reduce) {+ .qa-hog,+ .qa-hog-thinking,+ .qa-pill,+ .qa-card,+ .qa-skeleton,+ .qa-thinking-dots span,+ .qa-thinking-label,+ .qa-streaming > :last-child::after,+ .qa-status-busy,+ .qa-zilla .qa-hog,+ .qa-seg-in,+ .qa-mini-label,+ .qa-attach,+ .qa-chart-line,+ .qa-chart-area,+ .qa-chart-bar,+ [data-testid="evidence-hover-card"],+ [data-testid="evidence-hover-card"] svg rect {+ animation: none;+ }+ .qa-chart-line {+ stroke-dasharray: none;+ stroke-dashoffset: 0;+ }+ .qa-chart-area {+ opacity: 1;+ }+}diff --git a/products/desktop/packages/quick-ask/src/service/quick-ask.integration.test.ts b/products/desktop/packages/quick-ask/src/service/quick-ask.integration.test.tsnew file mode 100644index 000000000000..6fde7f17a0e8--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/quick-ask.integration.test.ts@@ -0,0 +1,162 @@+// @vitest-environment node+// The S3 upload posts real multipart FormData, which jsdom's FormData+// polyfill cannot feed into undici's fetch.+import type { AuthService } from "@posthog/core/auth/auth";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { type QuickAskEvent, QuickAskService } from "./quick-ask";+import {+ REPLAY_ANSWER,+ REPLAY_FOLLOW_UP,+ REPLAY_FOLLOW_UP_ANSWER,+ REPLAY_FOLLOW_UP_PRELUDE,+ REPLAY_QUESTION,+ REPLAY_STRAY_ANSWER,+ type ReplayServer,+ startReplayServer,+} from "./replay-fixture";++/**+ * The whole transport against a real HTTP server replaying a production run's+ * stream: warm, task creation activating the warm run, the boot-time+ * description prompt whose turn must be skipped, a mid-answer stream rotation+ * resumed via Last-Event-ID, and a follow-up over the command relay.+ */++function authFor(origin: string): AuthService {+ return {+ getValidAccessToken: async () => ({ accessToken: "t", apiHost: origin }),+ getState: () => ({ currentProjectId: 2 }),+ authenticatedFetch: (+ fetchImpl: typeof fetch,+ url: string,+ init: RequestInit,+ ) => fetchImpl(url, init),+ } as unknown as AuthService;+}++async function collect(+ service: QuickAskService,+ question: string,+ conversationId?: string,+ attachments?: { name: string; base64: string; mimeType: string }[],+): Promise<QuickAskEvent[]> {+ const events: QuickAskEvent[] = [];+ for await (const event of service.ask({+ question,+ conversationId,+ attachments,+ })) {+ events.push(event);+ }+ return events;+}++describe("quick-ask against a replayed production stream", () => {+ let server: ReplayServer;+ let service: QuickAskService;++ beforeEach(async () => {+ server = await startReplayServer();+ service = new QuickAskService(authFor(server.origin));+ });++ afterEach(async () => {+ await server.close();+ });++ it("warms, asks, and renders only its own turn's answer", async () => {+ await service.warm();+ const events = await collect(service, REPLAY_QUESTION);++ const finalText = events.findLast((event) => event.type === "text");+ expect(finalText).toEqual({+ type: "text",+ id: "turn-1",+ content: REPLAY_ANSWER,+ complete: true,+ });+ expect(events.at(-1)).toEqual({ type: "done" });+ expect(events.some((event) => event.type === "error")).toBe(false);+ // The description turn's output stays out of the panel.+ const allText = events+ .filter((event) => event.type === "text")+ .map((event) => event.content)+ .join("");+ expect(allText).not.toContain(REPLAY_STRAY_ANSWER);+ // Its tool activity stays out too; only the answering turn's shows.+ const reasoning = events.filter((event) => event.type === "reasoning");+ expect(reasoning).toContainEqual({+ type: "reasoning",+ content: "Running execute-sql…",+ });++ // The rotation forced a resume with the cursor.+ expect(server.streamRequests.length).toBeGreaterThanOrEqual(2);+ expect(server.streamRequests[1].lastEventId).toMatch(/^\d+-0$/);++ // The create call opted into warm reuse and carried the message.+ const create = server.requests.find((r) => r.path.endsWith("/tasks/"));+ const body = create?.body as Record<string, unknown>;+ expect(body.description).toBe(REPLAY_QUESTION);+ expect(body).toHaveProperty("branch", null);+ expect(String(body.pending_user_message)).toContain(+ "<posthog_trusted_context>",+ );+ });++ it("continues the thread with a follow-up over the command relay", async () => {+ const first = await collect(service, REPLAY_QUESTION);+ const conversation = first.find((event) => event.type === "conversation");+ if (conversation?.type !== "conversation") throw new Error("no thread id");++ const events = await collect(+ service,+ REPLAY_FOLLOW_UP,+ conversation.conversationId,+ );+ // Text on both sides of the tool call arrives as two segments.+ expect(events).toContainEqual({+ type: "text",+ id: "turn-2",+ content: REPLAY_FOLLOW_UP_PRELUDE,+ complete: true,+ });+ const finalText = events.findLast((event) => event.type === "text");+ expect(finalText).toEqual({+ type: "text",+ id: "turn-2.2",+ content: REPLAY_FOLLOW_UP_ANSWER,+ complete: true,+ });+ expect(events.at(-1)).toEqual({ type: "done" });++ const command = server.requests.find((r) => r.path.endsWith("/command/"));+ expect((command?.body as { method?: string }).method).toBe("user_message");+ });++ it("uploads a screenshot and references it on the follow-up", async () => {+ const first = await collect(service, REPLAY_QUESTION);+ const conversation = first.find((event) => event.type === "conversation");+ if (conversation?.type !== "conversation") throw new Error("no thread id");++ const events = await collect(+ service,+ REPLAY_FOLLOW_UP,+ conversation.conversationId,+ [{ name: "screenshot.png", base64: btoa("png"), mimeType: "image/png" }],+ );+ expect(events.at(-1)).toEqual({ type: "done" });++ const prepare = server.requests.find((r) =>+ r.path.endsWith("/prepare_upload/"),+ );+ expect(prepare?.path).toContain("/runs/run-1/artifacts/");+ const upload = server.requests.find((r) => r.path.endsWith("/s3-upload/"));+ expect(String(upload?.body)).toContain("screenshot.png");+ const command = server.requests.find((r) => r.path.endsWith("/command/"));+ expect(+ (command?.body as { params?: { artifact_ids?: string[] } }).params+ ?.artifact_ids,+ ).toEqual(["art-1"]);+ });+});diff --git a/products/desktop/packages/quick-ask/src/service/quick-ask.module.ts b/products/desktop/packages/quick-ask/src/service/quick-ask.module.tsnew file mode 100644index 000000000000..bd5b8f2a9b98--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/quick-ask.module.ts@@ -0,0 +1,7 @@+import { ContainerModule } from "inversify";+import { QUICK_ASK_SERVICE, QuickAskService } from "./quick-ask";++export const quickAskCoreModule = new ContainerModule(({ bind }) => {+ bind(QuickAskService).toSelf().inSingletonScope();+ bind(QUICK_ASK_SERVICE).toService(QuickAskService);+});diff --git a/products/desktop/packages/quick-ask/src/service/quick-ask.test.ts b/products/desktop/packages/quick-ask/src/service/quick-ask.test.tsnew file mode 100644index 000000000000..76cbe8a2fa1b--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/quick-ask.test.ts@@ -0,0 +1,1027 @@+import type { AuthService } from "@posthog/core/auth/auth";+import { describe, expect, it, vi } from "vitest";+import {+ PANEL_STEERING,+ parseSseChunk,+ type QuickAskEvent,+ type QuickAskRunDefaults,+ QuickAskService,+ reasoningLabel,+ translateFrame,+} from "./quick-ask";++function sseResponse(frames: string[]): Response {+ const encoder = new TextEncoder();+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ for (const frame of frames) {+ controller.enqueue(encoder.encode(frame));+ }+ controller.close();+ },+ });+ return new Response(body, { status: 200 });+}++function taskResponse(+ taskId = "task-1",+ runId: string | null = "run-1",+): Response {+ return new Response(+ JSON.stringify({+ id: taskId,+ latest_run: runId ? { id: runId, status: "in_progress" } : null,+ }),+ { status: 200 },+ );+}++function notification(method: string, params: unknown): string {+ return JSON.stringify({+ type: "notification",+ notification: { method, params },+ });+}++function sessionUpdate(update: unknown): string {+ return notification("session/update", { update });+}++function agentText(text: string): string {+ return sessionUpdate({+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text },+ });+}++/** The complete-snapshot frame ACP sends to close a run of chunks. */+function agentMessage(text: string): string {+ return sessionUpdate({+ sessionUpdate: "agent_message",+ content: { type: "text", text },+ });+}++function promptEcho(text: string): string {+ return notification("session/prompt", {+ prompt: [{ type: "text", text }],+ });+}++const QUESTION = "how many signups?";+const FIRST_TURN_CONTENT = `${QUESTION}\n\n${PANEL_STEERING}`;+/** Echo of the first question as the run logs it (question + steering). */+const USER_ECHO = promptEcho(FIRST_TURN_CONTENT);+const TURN_COMPLETE = notification("_posthog/turn_complete", {});+const SIMPLE_TURN = [`data: ${USER_ECHO}\n\ndata: ${TURN_COMPLETE}\n\n`];++interface MockedAuth {+ service: QuickAskService;+ fetchMock: ReturnType<typeof vi.fn>;+ s3Mock: ReturnType<typeof vi.fn>;+}++interface MockRoutes {+ /** Responses for `POST /tasks/warm/`, consumed in order. */+ warm?: Response[];+ /** Responses for `POST /tasks/`, consumed in order. */+ createTask?: Response[];+ /** Responses for `POST .../runs/` (run creation), consumed in order. */+ createRun?: Response[];+ /** Responses for `POST .../runs/{id}/start/`, consumed in order. */+ startRun?: Response[];+ /** Responses for `POST .../runs/{id}/command/`, consumed in order. */+ command?: Response[];+ /** Responses for `GET .../stream/`, consumed in order. */+ stream?: Response[];+ /** Responses for `POST .../prepare_upload/`, consumed in order. */+ prepare?: Response[];+ /** Responses for `POST .../finalize_upload/`, consumed in order. */+ finalize?: Response[];+}++/** URL-routed fetch mock - the warm call runs detached from ask generators. */+function serviceWith(+ routes: MockRoutes,+ runDefaults?: () => QuickAskRunDefaults,+): MockedAuth {+ const queues = {+ warm: [...(routes.warm ?? [])],+ createTask: [...(routes.createTask ?? [])],+ createRun: [...(routes.createRun ?? [])],+ startRun: [...(routes.startRun ?? [])],+ command: [...(routes.command ?? [])],+ stream: [...(routes.stream ?? [])],+ prepare: [...(routes.prepare ?? [])],+ finalize: [...(routes.finalize ?? [])],+ };+ const route = (url: string): keyof typeof queues => {+ if (url.endsWith("/tasks/warm/")) return "warm";+ if (url.endsWith("/tasks/")) return "createTask";+ if (url.endsWith("/runs/")) return "createRun";+ if (url.endsWith("/start/")) return "startRun";+ if (url.endsWith("/command/")) return "command";+ if (url.includes("/stream/")) return "stream";+ if (url.endsWith("/prepare_upload/")) return "prepare";+ if (url.endsWith("/finalize_upload/")) return "finalize";+ throw new Error(`unrouted url: ${url}`);+ };+ const fetchMock = vi.fn(+ async (_fetch: unknown, url: string): Promise<Response> => {+ return (+ queues[route(url)].shift() ?? new Response("exhausted", { status: 500 })+ );+ },+ );+ // Presigned S3 uploads bypass authenticatedFetch.+ const s3Mock = vi.fn(+ async (): Promise<Response> => new Response(null, { status: 204 }),+ );+ const authService = {+ getValidAccessToken: vi.fn().mockResolvedValue({+ accessToken: "t",+ apiHost: "https://us.posthog.com",+ }),+ getState: vi.fn().mockReturnValue({ currentProjectId: 2 }),+ authenticatedFetch: fetchMock,+ } as unknown as AuthService;+ return {+ service: new QuickAskService(+ authService,+ s3Mock as unknown as typeof fetch,+ runDefaults,+ ),+ fetchMock,+ s3Mock,+ };+}++function preparedResponse(ids: string[]): Response {+ return new Response(+ JSON.stringify({+ artifacts: ids.map((id) => ({+ id,+ presigned_post: { url: "https://s3.local/upload", fields: { k: "v" } },+ })),+ }),+ { status: 200 },+ );+}++const SHOT = {+ name: "screenshot.png",+ base64: btoa("png-bytes"),+ mimeType: "image/png",+};++function callsTo(fetchMock: ReturnType<typeof vi.fn>, suffix: string) {+ return fetchMock.mock.calls.filter((call) =>+ String(call[1]).endsWith(suffix),+ );+}++async function collect(+ service: QuickAskService,+ question = "how many signups?",+ conversationId?: string,+ attachments?: { name: string; base64: string; mimeType: string }[],+): Promise<QuickAskEvent[]> {+ const events: QuickAskEvent[] = [];+ for await (const event of service.ask({+ question,+ conversationId,+ attachments,+ })) {+ events.push(event);+ }+ return events;+}++function conversationIdOf(events: QuickAskEvent[]): string {+ const event = events[0];+ if (event.type !== "conversation") throw new Error("no conversation event");+ return event.conversationId;+}++describe("QuickAskService", () => {+ it("parses SSE blocks into event/id/data frames", () => {+ const blocks = [+ ...parseSseChunk(+ 'id: 1-0\ndata: {"a":1}\n\nevent: stream-end\ndata: {"status":"complete"}',+ ),+ ];+ expect(blocks).toEqual([+ { event: "message", id: "1-0", data: '{"a":1}' },+ {+ event: "stream-end",+ id: undefined,+ data: '{"status":"complete"}',+ },+ ]);+ });++ it("streams a turn: echo gate, growing text snapshots, turn complete", async () => {+ const stream = sseResponse([+ // Boot noise before the user's echo is skipped.+ `id: 1-0\ndata: ${notification("_posthog/console", { message: "boot" })}\n\n`,+ `id: 2-0\ndata: ${USER_ECHO}\n\nid: 3-0\ndata: ${agentText("Signups are ")}\n\n`,+ // A frame split across two network reads.+ `id: 4-0\ndata: ${agentText("up 12%.")}`.slice(0, 40),+ `${`id: 4-0\ndata: ${agentText("up 12%.")}`.slice(40)}\n\nid: 5-0\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ await expect(collect(service)).resolves.toEqual([+ { type: "conversation", conversationId: expect.any(String) },+ { type: "text", id: "turn-1", content: "Signups are ", complete: false },+ {+ type: "text",+ id: "turn-1",+ content: "Signups are up 12%.",+ complete: false,+ },+ {+ type: "text",+ id: "turn-1",+ content: "Signups are up 12%.",+ complete: true,+ },+ { type: "done" },+ ]);+ });++ it("a closing agent_message replaces its chunks instead of duplicating them", async () => {+ const stream = sseResponse([+ `id: 1-0\ndata: ${USER_ECHO}\n\n` ++ `id: 2-0\ndata: ${agentText("Signups are ")}\n\n` ++ `id: 3-0\ndata: ${agentText("up 12%.")}\n\n` ++ // ACP closes the message with the full snapshot, not another delta.+ `id: 4-0\ndata: ${agentMessage("Signups are up 12%.")}\n\n` ++ `id: 5-0\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const texts = (await collect(service)).filter((e) => e.type === "text");+ // The snapshot supersedes the chunks; the answer is a single copy, not+ // "Signups are up 12%.Signups are up 12%.".+ expect(texts.at(-1)).toEqual({+ type: "text",+ id: "turn-1",+ content: "Signups are up 12%.",+ complete: true,+ });+ });++ it("cancels the stream reader when the turn ends", async () => {+ let cancelled = false;+ const encoder = new TextEncoder();+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ `data: ${USER_ECHO}\n\ndata: ${agentText("hi")}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ),+ );+ // Left open on purpose: only reader.cancel() should release it, so the+ // spy fires exactly when the turn tears its connection down.+ },+ cancel() {+ cancelled = true;+ },+ });+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [new Response(body, { status: 200 })],+ });+ await collect(service);+ expect(cancelled).toBe(true);+ });++ it("creates the task with the question as description and warm-matching fields", async () => {+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ await collect(service);+ const body = JSON.parse(callsTo(fetchMock, "/tasks/")[0][2].body as string);+ // The description becomes the task title; steering rides only the message.+ expect(body.description).toBe("how many signups?");+ expect(body.pending_user_message).toMatch(+ /^how many signups\?\n\n<posthog_trusted_context>/,+ );+ expect(body.pending_user_message).toContain('<hogql display="block"');+ // `branch` present (null) opts into the backend's warm-run lookup; the+ // repo-less shape matches what `warm()` provisioned.+ expect(body).toMatchObject({ branch: null, repositories: [] });+ });++ it("follow-ups ride the command relay without the steering block", async () => {+ const followUpTurn = [+ `data: ${promptEcho("and yesterday?")}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ];+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ command: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN), sseResponse(followUpTurn)],+ });+ const first = await collect(service);+ await collect(service, "and yesterday?", conversationIdOf(first));++ const commandCalls = callsTo(fetchMock, "/command/");+ expect(commandCalls).toHaveLength(1);+ expect(commandCalls[0][1]).toContain("/tasks/task-1/runs/run-1/command/");+ const body = JSON.parse(commandCalls[0][2].body as string);+ expect(body.method).toBe("user_message");+ expect(body.params).toEqual({ content: "and yesterday?" });+ });++ it("cold-starts a run when no warm sandbox matched", async () => {+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse("task-1", null)],+ createRun: [+ new Response(JSON.stringify({ id: "run-9" }), { status: 200 }),+ ],+ startRun: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ const events = await collect(service);+ expect(events.at(-1)).toEqual({ type: "done" });+ const createRun = JSON.parse(+ callsTo(fetchMock, "/runs/")[0][2].body as string,+ );+ expect(createRun).toMatchObject({+ environment: "cloud",+ mode: "interactive",+ initial_permission_mode: "auto",+ });+ const start = JSON.parse(+ callsTo(fetchMock, "/start/")[0][2].body as string,+ );+ expect(start.pending_user_message).toContain("how many signups?");+ expect(callsTo(fetchMock, "/stream/")[0][1]).toContain("/runs/run-9/");+ });++ it("stages an attachment onto a cold start", async () => {+ const { service, fetchMock, s3Mock } = serviceWith({+ createTask: [taskResponse("task-1", null)],+ prepare: [preparedResponse(["art-1"])],+ finalize: [preparedResponse(["art-1"])],+ createRun: [+ new Response(JSON.stringify({ id: "run-9" }), { status: 200 }),+ ],+ startRun: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ const events = await collect(service, QUESTION, undefined, [SHOT]);+ expect(events.at(-1)).toEqual({ type: "done" });+ const prepareCall = callsTo(fetchMock, "/prepare_upload/")[0];+ expect(prepareCall[1]).toContain("/tasks/task-1/staged_artifacts/");+ expect(JSON.parse(prepareCall[2].body as string).artifacts[0]).toEqual({+ name: "screenshot.png",+ type: "user_attachment",+ source: "posthog_code",+ size: 9,+ content_type: "image/png",+ });+ expect(s3Mock).toHaveBeenCalledWith(+ "https://s3.local/upload",+ expect.objectContaining({ method: "POST" }),+ );+ const start = JSON.parse(+ callsTo(fetchMock, "/start/")[0][2].body as string,+ );+ expect(start.pending_user_artifact_ids).toEqual(["art-1"]);+ });++ it("uploads an attachment to the warm run before creating the task", async () => {+ const { service, fetchMock } = serviceWith({+ warm: [+ new Response(JSON.stringify({ task_id: "task-w", run_id: "run-w" }), {+ status: 200,+ }),+ ],+ command: [new Response("{}", { status: 200 })],+ prepare: [preparedResponse(["art-1"])],+ finalize: [preparedResponse(["art-1"])],+ createTask: [taskResponse("task-w", "run-w")],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ await service.warm();+ await collect(service, QUESTION, undefined, [SHOT]);+ expect(callsTo(fetchMock, "/prepare_upload/")[0][1]).toContain(+ "/tasks/task-w/runs/run-w/artifacts/",+ );+ const create = JSON.parse(+ callsTo(fetchMock, "/tasks/")[0][2].body as string,+ );+ expect(create.pending_user_artifact_ids).toEqual(["art-1"]);+ });++ it("skips warm reuse and re-stages when the warm upload fails", async () => {+ const { service, fetchMock } = serviceWith({+ warm: [+ new Response(JSON.stringify({ task_id: "task-w", run_id: "run-w" }), {+ status: 200,+ }),+ ],+ command: [new Response("{}", { status: 200 })],+ // The warm-run upload fails; the retry on the cold path succeeds.+ prepare: [+ new Response("nope", { status: 500 }),+ preparedResponse(["art-1"]),+ ],+ finalize: [preparedResponse(["art-1"])],+ createTask: [taskResponse("task-1", null)],+ createRun: [+ new Response(JSON.stringify({ id: "run-9" }), { status: 200 }),+ ],+ startRun: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ await service.warm();+ const events = await collect(service, QUESTION, undefined, [SHOT]);+ expect(events.at(-1)).toEqual({ type: "done" });+ // No `branch` key: the backend's warm-run lookup must not fire, or the+ // question would ride the warm run without its screenshot.+ const create = JSON.parse(+ callsTo(fetchMock, "/tasks/")[0][2].body as string,+ );+ expect("branch" in create).toBe(false);+ expect(create.pending_user_artifact_ids).toEqual([]);+ // The attachment went up through the fresh task's staged path instead.+ const prepareCalls = callsTo(fetchMock, "/prepare_upload/");+ expect(prepareCalls[1][1]).toContain("/tasks/task-1/staged_artifacts/");+ const start = JSON.parse(+ callsTo(fetchMock, "/start/")[0][2].body as string,+ );+ expect(start.pending_user_artifact_ids).toEqual(["art-1"]);+ });++ it("errors the turn when the staged retry upload also fails", async () => {+ const { service } = serviceWith({+ warm: [+ new Response(JSON.stringify({ task_id: "task-w", run_id: "run-w" }), {+ status: 200,+ }),+ ],+ command: [new Response("{}", { status: 200 })],+ prepare: [+ new Response("nope", { status: 500 }),+ new Response("nope", { status: 500 }),+ ],+ createTask: [taskResponse("task-1", null)],+ });+ await service.warm();+ const events = await collect(service, QUESTION, undefined, [SHOT]);+ expect(events.at(-1)).toMatchObject({ type: "error" });+ });++ it("attaches run artifacts to a follow-up user_message", async () => {+ const followUpTurn = [+ `data: ${promptEcho("and yesterday?")}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ];+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ command: [new Response("{}", { status: 200 })],+ prepare: [preparedResponse(["art-2"])],+ finalize: [preparedResponse(["art-2"])],+ stream: [sseResponse(SIMPLE_TURN), sseResponse(followUpTurn)],+ });+ const first = await collect(service);+ await collect(service, "and yesterday?", conversationIdOf(first), [SHOT]);+ expect(callsTo(fetchMock, "/prepare_upload/")[0][1]).toContain(+ "/tasks/task-1/runs/run-1/artifacts/",+ );+ const command = JSON.parse(+ callsTo(fetchMock, "/command/")[0][2].body as string,+ );+ expect(command.params).toEqual({+ content: "and yesterday?",+ artifact_ids: ["art-2"],+ });+ });++ it("falls back to a fresh run when the live run rejects a follow-up", async () => {+ const followUpTurn = [+ `data: ${promptEcho("and yesterday?")}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ];+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ command: [new Response("no active sandbox", { status: 400 })],+ createRun: [+ new Response(JSON.stringify({ id: "run-2" }), { status: 200 }),+ ],+ startRun: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN), sseResponse(followUpTurn)],+ });+ const first = await collect(service);+ const events = await collect(+ service,+ "and yesterday?",+ conversationIdOf(first),+ );+ expect(events.at(-1)).toEqual({ type: "done" });+ // The successor run is created on the same task and streamed from scratch.+ expect(callsTo(fetchMock, "/runs/")[0][1]).toContain("/tasks/task-1/");+ expect(callsTo(fetchMock, "/stream/")[1][1]).toContain("/runs/run-2/");+ });++ it("splits text around tool activity into segments and surfaces tool labels", async () => {+ const stream = sseResponse([+ `data: ${USER_ECHO}\n\n`,+ `data: ${agentText("Checking.")}\n\n`,+ `data: ${sessionUpdate({ sessionUpdate: "tool_call", title: "execute-sql" })}\n\n`,+ `data: ${agentText("1,204 signups this week.")}\n\n`,+ `data: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ expect(events).toContainEqual({+ type: "reasoning",+ content: "Running execute-sql…",+ });+ // The first segment completes when tool activity starts a second one.+ expect(events).toContainEqual({+ type: "text",+ id: "turn-1",+ content: "Checking.",+ complete: true,+ });+ expect(events).toContainEqual({+ type: "text",+ id: "turn-1.2",+ content: "1,204 signups this week.",+ complete: true,+ });+ });++ it("boot progress surfaces as a status label before the turn starts", async () => {+ const stream = sseResponse([+ `data: ${notification("_posthog/progress", { label: "Setting up sandbox", status: "in_progress", step: "sandbox" })}\n\n`,+ `data: ${USER_ECHO}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ expect(events).toContainEqual({+ type: "reasoning",+ content: "Setting up sandbox",+ });+ });++ it("shows the latest thought line as the reasoning label", async () => {+ const stream = sseResponse([+ `data: ${USER_ECHO}\n\n`,+ `data: ${sessionUpdate({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "Looking at signups\nby day" } })}\n\n`,+ `data: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ expect(events).toContainEqual({ type: "reasoning", content: "by day" });+ });++ it("reconnects from the cursor when the stream connection errors mid-read", async () => {+ const encoder = new TextEncoder();+ // Pull-based: erroring a stream discards queued chunks, so the frame must+ // deliver on the first read and the error on the second.+ let pulls = 0;+ const broken = new Response(+ new ReadableStream<Uint8Array>({+ pull(streamController) {+ pulls += 1;+ if (pulls === 1) {+ streamController.enqueue(+ encoder.encode(`id: 3-0\ndata: ${USER_ECHO}\n\n`),+ );+ return;+ }+ streamController.error(+ new TypeError("net::ERR_HTTP2_PROTOCOL_ERROR"),+ );+ },+ }),+ { status: 200 },+ );+ const second = sseResponse([+ `id: 4-0\ndata: ${agentText("Recovered.")}\n\nid: 5-0\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ stream: [broken, second],+ });+ const events = await collect(service);+ expect(events).toContainEqual({+ type: "text",+ id: "turn-1",+ content: "Recovered.",+ complete: true,+ });+ expect(events.some((event) => event.type === "error")).toBe(false);+ const streamCalls = fetchMock.mock.calls.filter((call) =>+ String(call[1]).includes("/stream/"),+ );+ expect(streamCalls[1][2].headers["Last-Event-ID"]).toBe("3-0");+ });++ it("retries a stream connection that fails to open, then errors past the budget", async () => {+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [+ new Response("bad gateway", { status: 502 }),+ sseResponse([`data: ${USER_ECHO}\n\ndata: ${TURN_COMPLETE}\n\n`]),+ ],+ });+ const events = await collect(service);+ expect(events.at(-1)).toEqual({ type: "done" });+ expect(events.some((event) => event.type === "error")).toBe(false);+ });++ it("resumes across a stream rotation with the last event id", async () => {+ const first = sseResponse([+ `id: 7-0\ndata: ${USER_ECHO}\n\nevent: end\ndata: {"type":"rotated"}\n\n`,+ ]);+ const second = sseResponse([+ `id: 8-0\ndata: ${agentText("Done.")}\n\nid: 9-0\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse()],+ stream: [first, second],+ });+ const events = await collect(service);+ expect(events).toContainEqual({+ type: "text",+ id: "turn-1",+ content: "Done.",+ complete: true,+ });+ const streamCalls = fetchMock.mock.calls.filter((call) =>+ String(call[1]).includes("/stream/"),+ );+ expect(streamCalls).toHaveLength(2);+ expect(streamCalls[1][2].headers["Last-Event-ID"]).toBe("7-0");+ });++ it("takes only its own turn when the boot prompts the task description first", async () => {+ // The workflow prompts the task description at boot; prompt queueing logs+ // our prompt before that turn completes. The panel must skip the first+ // turn's output and completion, and take the second turn's.+ const stream = sseResponse([+ `data: ${promptEcho(QUESTION)}\n\n`,+ `data: ${USER_ECHO}\n\n`,+ `data: ${agentText("Description-turn answer.")}\n\n`,+ `data: ${TURN_COMPLETE}\n\n`,+ `data: ${agentText("Steered answer.")}\n\ndata: ${TURN_COMPLETE}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ const texts = events.filter((event) => event.type === "text");+ expect(texts).toEqual([+ {+ type: "text",+ id: "turn-1",+ content: "Steered answer.",+ complete: false,+ },+ {+ type: "text",+ id: "turn-1",+ content: "Steered answer.",+ complete: true,+ },+ ]);+ expect(events.at(-1)).toEqual({ type: "done" });+ });++ it("ends the turn when the run reaches a terminal status", async () => {+ const stream = sseResponse([+ `data: ${USER_ECHO}\n\ndata: ${agentText("Partial answer.")}\n\n`,+ `data: ${JSON.stringify({ type: "task_run_state", status: "completed" })}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ expect(events.at(-1)).toEqual({ type: "done" });+ });++ it("surfaces a failed run as an error", async () => {+ const stream = sseResponse([+ `data: ${USER_ECHO}\n\n`,+ `data: ${JSON.stringify({ type: "task_run_state", status: "failed", error_message: "sandbox died" })}\n\n`,+ ]);+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [stream],+ });+ const events = await collect(service);+ expect(events.at(-1)).toEqual({+ type: "error",+ message: "PostHog AI hit an error. Try asking again.",+ detail: "sandbox died",+ });+ });++ it("maps task creation failures: usage limits, access, and everything else", async () => {+ const cases: [number, string][] = [+ [402, "Your organization is out of PostHog task credits."],+ [429, "Your organization is out of PostHog task credits."],+ [403, "Your account can't run PostHog tasks in this project."],+ [503, "PostHog AI is unavailable right now (503)."],+ ];+ for (const [status, message] of cases) {+ const { service } = serviceWith({+ createTask: [new Response("nope", { status })],+ });+ const events = await collect(service);+ expect(events[1]).toEqual({+ type: "error",+ message,+ detail: "nope",+ });+ }+ });++ it("never calls the API when signed out", async () => {+ const fetchMock = vi.fn();+ const authService = {+ getValidAccessToken: vi+ .fn()+ .mockResolvedValue({ accessToken: "t", apiHost: "https://x" }),+ getState: vi.fn().mockReturnValue({ currentProjectId: null }),+ authenticatedFetch: fetchMock,+ } as unknown as AuthService;+ const service = new QuickAskService(authService);+ const events = await collect(service);+ expect(events).toEqual([+ { type: "error", message: "Sign in to PostHog to ask questions." },+ ]);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("warm posts a repo-less warm request and swallows every outcome", async () => {+ const { service, fetchMock } = serviceWith({+ // Flag off / pool full: the endpoint returns an empty 200 body.+ warm: [new Response("", { status: 200 })],+ });+ await expect(service.warm()).resolves.toBeUndefined();+ const body = JSON.parse(+ callsTo(fetchMock, "/tasks/warm/")[0][2].body as string,+ );+ expect(body).toEqual({+ repository: null,+ repositories: [],+ github_integration: null,+ branch: null,+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,+ });++ const failing = serviceWith({+ warm: [new Response("boom", { status: 500 })],+ });+ await expect(failing.service.warm()).resolves.toBeUndefined();+ });++ it("switches a warmed run to auto mode before activating it", async () => {+ const { service, fetchMock } = serviceWith({+ warm: [+ new Response(JSON.stringify({ task_id: "task-w", run_id: "run-w" }), {+ status: 200,+ }),+ ],+ command: [new Response("{}", { status: 200 })],+ createTask: [taskResponse("task-w", "run-w")],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ await service.warm();+ await collect(service);+ const commandCalls = callsTo(fetchMock, "/command/");+ expect(commandCalls).toHaveLength(1);+ expect(commandCalls[0][1]).toContain("/runs/run-w/");+ expect(JSON.parse(commandCalls[0][2].body as string)).toMatchObject({+ method: "set_config_option",+ params: { configId: "mode", value: "auto" },+ });+ // The mode switch lands before the message-delivering create call.+ const commandIndex = fetchMock.mock.calls.findIndex((call) =>+ String(call[1]).endsWith("/command/"),+ );+ const createIndex = fetchMock.mock.calls.findIndex((call) =>+ String(call[1]).endsWith("/tasks/"),+ );+ expect(commandIndex).toBeLessThan(createIndex);+ });++ it("goes cold instead of reusing a warm run whose auto-mode switch failed", async () => {+ const { service, fetchMock } = serviceWith({+ warm: [+ new Response(JSON.stringify({ task_id: "task-w", run_id: "run-w" }), {+ status: 200,+ }),+ ],+ // The set_config_option command fails (e.g. the run is still booting).+ command: [new Response("boot", { status: 400 })],+ createTask: [taskResponse("task-1", null)],+ createRun: [+ new Response(JSON.stringify({ id: "run-9" }), { status: 200 }),+ ],+ startRun: [new Response("{}", { status: 200 })],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ await service.warm();+ const events = await collect(service);+ expect(events.at(-1)).toEqual({ type: "done" });+ // No `branch` key: a warm run left in default mode would park the+ // question on an approval the panel cannot answer.+ const create = JSON.parse(+ callsTo(fetchMock, "/tasks/")[0][2].body as string,+ );+ expect("branch" in create).toBe(false);+ // The cold run sets auto mode server-side in its create body.+ const run = JSON.parse(callsTo(fetchMock, "/runs/")[0][2].body as string);+ expect(run.initial_permission_mode).toBe("auto");+ });++ it("exposes the thread's task id for open-in-app, cleared on reset", async () => {+ const { service } = serviceWith({+ createTask: [taskResponse()],+ stream: [sseResponse(SIMPLE_TURN)],+ });+ expect(service.currentTaskId).toBeNull();+ await collect(service);+ expect(service.currentTaskId).toBe("task-1");+ service.reset();+ expect(service.currentTaskId).toBeNull();+ });++ it("applies run defaults to warm and task creation", async () => {+ const { service, fetchMock } = serviceWith(+ {+ warm: [new Response("", { status: 200 })],+ createTask: [taskResponse()],+ stream: [sseResponse(SIMPLE_TURN)],+ },+ () => ({+ channelId: "chan-7",+ repositories: ["posthog/posthog"],+ githubIntegrationId: 42,+ adapter: "codex",+ model: "gpt-5.5",+ reasoningEffort: "high",+ }),+ );+ await service.warm();+ await collect(service);++ const warmBody = JSON.parse(+ callsTo(fetchMock, "/tasks/warm/")[0][2].body as string,+ );+ expect(warmBody).toMatchObject({+ repository: "posthog/posthog",+ repositories: ["posthog/posthog"],+ github_integration: 42,+ runtime_adapter: "codex",+ model: "gpt-5.5",+ reasoning_effort: "high",+ });+ const createBody = JSON.parse(+ callsTo(fetchMock, "/tasks/")[0][2].body as string,+ );+ expect(createBody).toMatchObject({+ channel: "chan-7",+ repositories: ["posthog/posthog"],+ github_integration: 42,+ runtime_adapter: "codex",+ model: "gpt-5.5",+ reasoning_effort: "high",+ });+ });++ it("a space default without repos leaves repositories to the space", async () => {+ const { service, fetchMock } = serviceWith(+ {+ createTask: [taskResponse()],+ stream: [sseResponse(SIMPLE_TURN)],+ },+ () => ({+ channelId: "chan-7",+ repositories: [],+ githubIntegrationId: null,+ adapter: null,+ model: null,+ reasoningEffort: null,+ }),+ );+ await collect(service);+ const createBody = JSON.parse(+ callsTo(fetchMock, "/tasks/")[0][2].body as string,+ );+ expect(createBody.channel).toBe("chan-7");+ expect(createBody).not.toHaveProperty("repositories");+ });++ it("reset drops the session so the next ask creates a new task", async () => {+ const { service, fetchMock } = serviceWith({+ createTask: [taskResponse(), taskResponse("task-2", "run-2")],+ stream: [sseResponse(SIMPLE_TURN), sseResponse(SIMPLE_TURN)],+ });+ await collect(service);+ service.reset();+ await collect(service);+ const creates = callsTo(fetchMock, "/tasks/");+ expect(creates).toHaveLength(2);+ // A fresh thread carries the steering block again.+ const secondBody = JSON.parse(creates[1][2].body as string);+ expect(secondBody.pending_user_message).toContain(+ "<posthog_trusted_context>",+ );+ });+});++describe("translateFrame", () => {+ it.each([+ [+ "agent text chunk",+ agentText("hi"),+ { kind: "agent-text", text: "hi", final: false },+ ],+ [+ "agent message snapshot",+ agentMessage("hi"),+ { kind: "agent-text", text: "hi", final: true },+ ],+ ["prompt echo", promptEcho("hello"), { kind: "prompt", text: "hello" }],+ ["turn complete", TURN_COMPLETE, { kind: "turn-complete" }],+ [+ "tool call falls back to claudeCode tool name",+ sessionUpdate({+ sessionUpdate: "tool_call",+ _meta: { claudeCode: { toolName: "Bash" } },+ }),+ { kind: "tool", label: "Bash" },+ ],+ [+ "posthog error",+ notification("_posthog/error", { message: "crash" }),+ { kind: "run-terminal", status: "failed", errorMessage: "crash" },+ ],+ [+ "non-terminal run state",+ JSON.stringify({ type: "task_run_state", status: "in_progress" }),+ { kind: "ignore", detail: "run state in_progress" },+ ],+ [+ "keepalive frame",+ JSON.stringify({ type: "keepalive" }),+ { kind: "ignore" },+ ],+ [+ "user message chunk",+ sessionUpdate({+ sessionUpdate: "user_message_chunk",+ content: { type: "text", text: "hi" },+ }),+ { kind: "ignore", detail: "user_message_chunk" },+ ],+ // Permission waits are status signals so repeats replace the label+ // instead of accreting into the thought buffer.+ [+ "permission request",+ JSON.stringify({ type: "permission_request", requestId: "r1" }),+ { kind: "status", text: "Waiting for a tool approval…" },+ ],+ [+ "permission request over the session",+ notification("session/request_permission", { toolCallId: "t1" }),+ { kind: "status", text: "Waiting for a tool approval…" },+ ],+ ])("%s", (_name, frame, expected) => {+ expect(translateFrame(JSON.parse(frame))).toEqual(expected);+ });+});++describe("reasoningLabel", () => {+ it("returns the last non-empty line", () => {+ expect(reasoningLabel("Analyzing signups\n\nby weekday ")).toBe(+ "by weekday",+ );+ expect(reasoningLabel("")).toBe("");+ });+});diff --git a/products/desktop/packages/quick-ask/src/service/quick-ask.ts b/products/desktop/packages/quick-ask/src/service/quick-ask.tsnew file mode 100644index 000000000000..186be235b53c--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/quick-ask.ts@@ -0,0 +1,1156 @@+import type { AuthService, FetchLike } from "@posthog/core/auth/auth";+import { AUTH_SERVICE } from "@posthog/core/auth/auth.module";+import { inject, injectable, optional } from "inversify";+import { PANEL_STEERING } from "./steering";++export const QUICK_ASK_SERVICE = Symbol.for("posthog.core.quickAsk.service");+/**+ * Fetch implementation for quick-ask HTTP. Hosts may bind a transport that is+ * more reliable than Node's global fetch (the Electron main process binds+ * Chromium's `net.fetch`, which honors system proxies/VPNs undici trips over).+ */+export const QUICK_ASK_FETCH = Symbol.for("posthog.core.quickAsk.fetch");++/** Where new quick-ask threads run: the space they file into and the repos+ * their sandbox clones. Empty values mean the personal space and no repos. */+export interface QuickAskRunDefaults {+ channelId: string | null;+ repositories: string[];+ githubIntegrationId: number | null;+ adapter: string | null;+ model: string | null;+ reasoningEffort: string | null;+}++export const QUICK_ASK_RUN_DEFAULTS = Symbol.for(+ "posthog.core.quickAsk.runDefaults",+);++/**+ * Events the quick-ask panel renders, distilled from the task run's SSE+ * stream. Text arrives as growing snapshots keyed by a per-turn id; the+ * renderer replaces by id.+ */+export type QuickAskEvent =+ | { type: "conversation"; conversationId: string }+ | { type: "reasoning"; content: string }+ | { type: "text"; id: string; content: string; complete: boolean }+ | { type: "error"; message: string; detail?: string }+ | { type: "done" };++export interface QuickAskInput {+ question: string;+ /** Continues an existing thread; omitted for the first question. */+ conversationId?: string;+ /** Annotated screenshots to attach to this message. */+ attachments?: QuickAskAttachment[];+}++export interface QuickAskAttachment {+ name: string;+ base64: string;+ mimeType: string;+}++export { PANEL_STEERING } from "./steering";++/** One parsed SSE event: name, optional resume id, joined data lines. */+export interface SseFrame {+ event: string;+ id?: string;+ data: string;+}++/** Minimal SSE parser: collects `event:`/`id:`/`data:` lines per blank-line-delimited block. */+export function* parseSseChunk(buffer: string): Generator<SseFrame> {+ for (const block of buffer.split("\n\n")) {+ let event = "message";+ let id: string | undefined;+ const dataLines: string[] = [];+ for (const line of block.split("\n")) {+ if (line.startsWith("event:")) {+ event = line.slice(6).trim();+ } else if (line.startsWith("id:")) {+ id = line.slice(3).trim();+ } else if (line.startsWith("data:")) {+ dataLines.push(line.slice(5).trimStart());+ }+ }+ if (dataLines.length > 0) {+ yield { event, id, data: dataLines.join("\n") };+ }+ }+}++interface SessionUpdate {+ sessionUpdate?: string;+ content?: { type?: string; text?: string };+ title?: string;+ _meta?: { claudeCode?: { toolName?: string } };+}++interface NotificationFrame {+ type?: string;+ notification?: {+ method?: string;+ params?: {+ update?: SessionUpdate;+ message?: unknown;+ status?: string;+ prompt?: { type?: string; text?: string }[];+ };+ };+ status?: string;+ error_message?: string | null;+}++interface TaskResponse {+ id?: string;+ latest_run?: { id?: string; status?: string } | null;+}++interface RunResponse {+ id?: string;+}++interface WarmHandle {+ taskId: string;+ runId: string;+}++interface PrepareUploadResponse {+ artifacts?: {+ id: string;+ presigned_post: { url: string; fields: Record<string, string> };+ }[];+}++/** Terminal run statuses on `task_run_state` frames. */+const TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "cancelled"]);++/**+ * Consecutive stream connection failures tolerated without any frame+ * arriving. Long-lived SSE connections drop routinely (proxies reset HTTP/2+ * streams), so drops reconnect from the cursor; progress resets the budget.+ */+const MAX_STREAM_ATTEMPTS = 8;++function reconnectDelay(attempts: number): Promise<void> {+ return new Promise((resolve) =>+ setTimeout(resolve, Math.min(500 * attempts, 5000)),+ );+}++/**+ * Deadline for the non-stream task calls and attachment uploads. Passing the+ * turn signal to AuthService replaces its own default deadline, so a stalled+ * proxy or half-open socket would otherwise wedge the panel in "Thinking…"+ * with no error. The SSE stream is deliberately left unbounded.+ */+const REQUEST_TIMEOUT_MS = 30_000;++/**+ * Bounds a request by both the turn signal and a timeout, so cancelling the+ * turn or a stall each abort it. Used for every non-stream call; the SSE fetch+ * keeps the raw turn signal.+ */+function withRequestTimeout(signal?: AbortSignal): AbortSignal {+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);+ return signal ? AbortSignal.any([signal, timeout]) : timeout;+}++/**+ * Per-thread state. `conversationId` is a client-minted key the renderer+ * echoes back so follow-ups land on the same task; `cursor` is the stream id+ * of the last ingested event, carried across turns and reconnects so no frame+ * is re-rendered or missed.+ */+interface QuickAskSession {+ conversationId: string;+ taskId: string | null;+ runId: string | null;+ cursor: string | null;+ /** Number of questions sent (the first carries the steering block). */+ turns: number;+}++/** What one stream frame means for the current turn. */+export type TurnSignal =+ | { kind: "prompt"; text: string }+ | { kind: "agent-text"; text: string; final: boolean }+ | { kind: "reasoning"; text: string }+ | { kind: "tool"; label: string }+ | { kind: "status"; text: string }+ | { kind: "turn-complete" }+ | { kind: "run-terminal"; status: string; errorMessage?: string }+ | { kind: "ignore"; detail?: string };++export function translateFrame(parsed: unknown): TurnSignal {+ const frame = parsed as NotificationFrame;+ if (frame.type === "permission_request") {+ return { kind: "status", text: "Waiting for a tool approval…" };+ }+ if (frame.type === "task_run_state") {+ const status = frame.status ?? "";+ if (TERMINAL_RUN_STATUSES.has(status)) {+ return {+ kind: "run-terminal",+ status,+ errorMessage: frame.error_message ?? undefined,+ };+ }+ return { kind: "ignore", detail: `run state ${status}` };+ }+ if (frame.type !== "notification" || !frame.notification) {+ return { kind: "ignore" };+ }+ const method = frame.notification.method ?? "";+ if (method === "_posthog/turn_complete") {+ return { kind: "turn-complete" };+ }+ // The harness logs every prompt as a `session/prompt` request; the run can+ // carry prompts besides ours (the workflow prompts the task description at+ // boot), so the caller matches the text to find its own turn.+ if (method === "session/prompt") {+ const text = (frame.notification.params?.prompt ?? [])+ .map((block) => block.text ?? "")+ .join("");+ return { kind: "prompt", text };+ }+ if (method === "_posthog/error") {+ const message = frame.notification.params?.message;+ return {+ kind: "run-terminal",+ status: "failed",+ errorMessage: typeof message === "string" ? message : undefined,+ };+ }+ if (method === "session/request_permission") {+ return { kind: "status", text: "Waiting for a tool approval…" };+ }+ if (method === "_posthog/progress") {+ const params = frame.notification.params as+ | { label?: unknown; status?: unknown }+ | undefined;+ return typeof params?.label === "string" && params.status !== "completed"+ ? { kind: "status", text: params.label }+ : { kind: "ignore" };+ }+ if (method !== "session/update") {+ return { kind: "ignore", detail: method || undefined };+ }+ const update = frame.notification.params?.update;+ switch (update?.sessionUpdate) {+ case "agent_message_chunk":+ case "agent_message":+ // `agent_message_chunk` frames are deltas; the `agent_message` that+ // closes them carries the complete snapshot, so the consumer must+ // replace rather than append (else the answer text lands twice).+ return update.content?.type === "text" && update.content.text+ ? {+ kind: "agent-text",+ text: update.content.text,+ final: update.sessionUpdate === "agent_message",+ }+ : { kind: "ignore" };+ case "agent_thought_chunk":+ return update.content?.type === "text" && update.content.text+ ? { kind: "reasoning", text: update.content.text }+ : { kind: "ignore" };+ case "tool_call": {+ const label =+ update.title || update._meta?.claudeCode?.toolName || "a tool";+ return { kind: "tool", label };+ }+ default:+ return { kind: "ignore", detail: update?.sessionUpdate };+ }+}++/** Last non-empty line of the accumulated thought text, shown as the live status label. */+export function reasoningLabel(thoughtBuffer: string): string {+ const lines = thoughtBuffer+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+ return lines[lines.length - 1] ?? "";+}++/** Surfaces `error.cause` too: undici hides the real network error there. */+function describeError(error: unknown): string {+ if (!(error instanceof Error)) {+ return String(error);+ }+ const cause = error.cause instanceof Error ? ` (${error.cause.message})` : "";+ return `${error.message}${cause}`;+}++const UNAVAILABLE_MESSAGE =+ "PostHog AI tasks are unavailable right now. Try again.";++/**+ * Streams quick-ask answers through prewarmed cloud task runs: summoning the+ * panel warms a repo-less sandbox, each question is a turn on the thread's+ * run, and the answer streams from the run's SSE endpoint. Business logic+ * only; the host forwards events over IPC.+ */+@injectable()+export class QuickAskService {+ private controller: AbortController | null = null;+ private warmPromise: Promise<void> | null = null;+ private warmHandle: WarmHandle | null = null;+ private session: QuickAskSession | null = null;+ private readonly fetchImpl: FetchLike;++ constructor(+ @inject(AUTH_SERVICE)+ private readonly authService: AuthService,+ @inject(QUICK_ASK_FETCH) @optional() fetchImpl?: FetchLike,+ @inject(QUICK_ASK_RUN_DEFAULTS)+ @optional()+ private readonly runDefaults?: () => QuickAskRunDefaults,+ ) {+ this.fetchImpl = fetchImpl ?? fetch;+ }++ private defaults(): QuickAskRunDefaults {+ return (+ this.runDefaults?.() ?? {+ channelId: null,+ repositories: [],+ githubIntegrationId: null,+ adapter: null,+ model: null,+ reasoningEffort: null,+ }+ );+ }++ cancel(): void {+ this.controller?.abort();+ this.controller = null;+ }++ /** Task backing the current thread, for opening it in the app. */+ get currentTaskId(): string | null {+ return this.session?.taskId ?? null;+ }++ private async context(): Promise<{+ apiHost: string;+ projectId: number;+ } | null> {+ const { apiHost } = await this.authService.getValidAccessToken();+ const projectId = this.authService.getState().currentProjectId;+ return projectId == null ? null : { apiHost, projectId };+ }++ private ensureSession(conversationId?: string): QuickAskSession {+ if (+ this.session &&+ (!conversationId || this.session.conversationId === conversationId)+ ) {+ return this.session;+ }+ this.session = {+ conversationId: conversationId ?? globalThis.crypto.randomUUID(),+ taskId: null,+ runId: null,+ cursor: null,+ turns: 0,+ };+ return this.session;+ }++ /** Drops the current thread so the next question starts a fresh task. */+ reset(): void {+ this.cancel();+ this.session = null;+ }++ private post(+ apiHost: string,+ path: string,+ body: unknown,+ signal?: AbortSignal,+ ): Promise<Response> {+ return this.authService.authenticatedFetch(+ this.fetchImpl,+ `${apiHost}${path}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal: withRequestTimeout(signal),+ },+ );+ }++ /**+ * Boots a repo-less sandbox on panel summon, so the first ask starts at+ * model speed. Best-effort: failures are swallowed and a cold ask still+ * works.+ */+ warm(): Promise<void> {+ if (this.warmPromise) return this.warmPromise;+ if (this.session?.runId) return Promise.resolve();+ this.warmPromise = (async () => {+ const context = await this.context();+ if (!context) return;+ const defaults = this.defaults();+ const response = await this.post(+ context.apiHost,+ `/api/projects/${context.projectId}/tasks/warm/`,+ {+ repository: defaults.repositories[0] ?? null,+ repositories: defaults.repositories,+ github_integration: defaults.githubIntegrationId,+ branch: null,+ runtime_adapter: defaults.adapter,+ model: defaults.model,+ reasoning_effort: defaults.reasoningEffort,+ },+ );+ if (!response.ok) return;+ // An empty body means warming is off or the pool is full.+ const text = await response.text().catch(() => "");+ if (!text) return;+ const handle = JSON.parse(text) as { task_id?: string; run_id?: string };+ if (handle.task_id && handle.run_id) {+ this.warmHandle = { taskId: handle.task_id, runId: handle.run_id };+ }+ })()+ .catch(() => undefined)+ .finally(() => {+ this.warmPromise = null;+ });+ return this.warmPromise;+ }++ /**+ * Creates the thread's task. The backend's warm-run lookup triggers only+ * when `branch` is present (null): a matching idle sandbox is activated+ * with the pending message. `reuseWarm: false` omits the key entirely, so+ * the task returns runless and the caller starts a cold run — the safe+ * route when the warm run couldn't be prepared for this message. Repo-less+ * user-created tasks file into the personal channel.+ */+ private async createTask(+ apiHost: string,+ projectId: number,+ question: string,+ content: string,+ pendingArtifactIds: string[],+ reuseWarm: boolean,+ signal: AbortSignal,+ ): Promise<Response> {+ const defaults = this.defaults();+ return this.post(+ apiHost,+ `/api/projects/${projectId}/tasks/`,+ {+ description: question,+ ...(reuseWarm ? { branch: null } : {}),+ pending_user_message: content,+ pending_user_artifact_ids: pendingArtifactIds,+ ...(defaults.channelId ? { channel: defaults.channelId } : {}),+ // Explicit repos win; a space brings its own; otherwise none. Omitting+ // the key lets the space's repositories apply server-side.+ ...(defaults.repositories.length+ ? {+ repositories: defaults.repositories,+ github_integration: defaults.githubIntegrationId,+ }+ : defaults.channelId+ ? {}+ : { repositories: [] }),+ ...(defaults.adapter ? { runtime_adapter: defaults.adapter } : {}),+ ...(defaults.model ? { model: defaults.model } : {}),+ ...(defaults.reasoningEffort+ ? { reasoning_effort: defaults.reasoningEffort }+ : {}),+ },+ signal,+ );+ }++ /** Creates and starts an interactive cloud run carrying the message. */+ private async startRun(+ apiHost: string,+ projectId: number,+ taskId: string,+ content: string,+ artifactIds: string[],+ signal: AbortSignal,+ ): Promise<string | null> {+ const defaults = this.defaults();+ const createResponse = await this.post(+ apiHost,+ `/api/projects/${projectId}/tasks/${taskId}/runs/`,+ {+ environment: "cloud",+ mode: "interactive",+ runtime_adapter: defaults.adapter ?? "claude",+ ...(defaults.model ? { model: defaults.model } : {}),+ ...(defaults.reasoningEffort+ ? { reasoning_effort: defaults.reasoningEffort }+ : {}),+ // "auto" lets the agent use safe tools without approval prompts the+ // panel has no surface for.+ initial_permission_mode: "auto",+ },+ signal,+ );+ if (!createResponse.ok) return null;+ const run = (await createResponse.json()) as RunResponse;+ if (!run.id) return null;+ const startResponse = await this.post(+ apiHost,+ `/api/projects/${projectId}/tasks/${taskId}/runs/${run.id}/start/`,+ {+ pending_user_message: content,+ pending_user_artifact_ids: artifactIds,+ },+ signal,+ );+ return startResponse.ok ? run.id : null;+ }++ /**+ * Warm runs boot in the "default" permission mode, which holds every tool+ * call for an approval the panel has no surface for; switch the agent to+ * "auto" before the first message reaches it. Returns whether the switch+ * landed — a warm run left in default mode must not receive the question,+ * or the turn parks forever on an approval prompt the panel can't answer.+ */+ private async setAutoMode(+ apiHost: string,+ projectId: number,+ handle: WarmHandle,+ signal: AbortSignal,+ ): Promise<boolean> {+ try {+ const response = await this.post(+ apiHost,+ `/api/projects/${projectId}/tasks/${handle.taskId}/runs/${handle.runId}/command/`,+ {+ jsonrpc: "2.0",+ id: globalThis.crypto.randomUUID(),+ method: "set_config_option",+ params: { configId: "mode", value: "auto" },+ },+ signal,+ );+ return response.ok;+ } catch {+ return false;+ }+ }++ /** Signals a follow-up question onto the live run. */+ private async sendUserMessage(+ apiHost: string,+ projectId: number,+ taskId: string,+ runId: string,+ content: string,+ artifactIds: string[],+ signal: AbortSignal,+ ): Promise<boolean> {+ const response = await this.post(+ apiHost,+ `/api/projects/${projectId}/tasks/${taskId}/runs/${runId}/command/`,+ {+ jsonrpc: "2.0",+ id: globalThis.crypto.randomUUID(),+ method: "user_message",+ params: artifactIds.length+ ? { content, artifact_ids: artifactIds }+ : { content },+ },+ signal,+ );+ return response.ok;+ }++ /** Route one question onto the session's task, minting runs as needed. */+ private async placeTurn(+ apiHost: string,+ projectId: number,+ session: QuickAskSession,+ question: string,+ content: string,+ attachments: QuickAskAttachment[],+ signal: AbortSignal,+ ): Promise<{ ok: true } | { ok: false; status: number; detail: string }> {+ // A run that died since the last turn rejects the command; fall through+ // to a successor run.+ if (session.taskId && session.runId) {+ const artifactIds = await this.uploadAttachments(+ apiHost,+ projectId,+ `tasks/${session.taskId}/runs/${session.runId}/artifacts`,+ attachments,+ signal,+ );+ if (artifactIds) {+ const sent = await this.sendUserMessage(+ apiHost,+ projectId,+ session.taskId,+ session.runId,+ content,+ artifactIds,+ signal,+ );+ if (sent) return { ok: true };+ }+ session.runId = null;+ session.cursor = null;+ }++ if (session.taskId) {+ const runId = await this.startStagedRun(+ apiHost,+ projectId,+ session.taskId,+ content,+ attachments,+ signal,+ );+ if (!runId) {+ return { ok: false, status: 0, detail: "starting a run failed" };+ }+ session.runId = runId;+ session.cursor = null;+ return { ok: true };+ }++ let warmArtifactIds: string[] = [];+ // Reusing a warm run forwards the pending message as-is, so it is only+ // safe when any attachments are already uploaded to that run. When the+ // upload fails — or attachments exist with no warm run to carry them —+ // the task is created without the warm lookup, and the cold staged path+ // below re-uploads them (or fails the turn); riding a warm run anyway+ // would silently answer without the screenshots.+ let reuseWarm = attachments.length === 0;+ if (this.warmHandle) {+ const handle = this.warmHandle;+ this.warmHandle = null;+ // A warm run stuck in default mode would park the question on an+ // approval the panel can't answer; decline the reuse and go cold (the+ // cold run sets auto mode server-side in its create body).+ const autoReady = await this.setAutoMode(+ apiHost,+ projectId,+ handle,+ signal,+ );+ if (!autoReady) {+ reuseWarm = false;+ }+ if (autoReady && attachments.length > 0) {+ const uploaded = await this.uploadAttachments(+ apiHost,+ projectId,+ `tasks/${handle.taskId}/runs/${handle.runId}/artifacts`,+ attachments,+ signal,+ );+ if (uploaded) {+ warmArtifactIds = uploaded;+ reuseWarm = true;+ }+ }+ }+ const response = await this.createTask(+ apiHost,+ projectId,+ question,+ content,+ warmArtifactIds,+ reuseWarm,+ signal,+ );+ if (!response.ok) {+ const detail = await response+ .text()+ .then((text) => text.slice(0, 500))+ .catch(() => "");+ return { ok: false, status: response.status, detail };+ }+ const task = (await response.json()) as TaskResponse;+ if (!task.id) {+ return { ok: false, status: 0, detail: "task creation returned no id" };+ }+ session.taskId = task.id;+ if (task.latest_run?.id) {+ session.runId = task.latest_run.id;+ session.cursor = null;+ return { ok: true };+ }+ const runId = await this.startStagedRun(+ apiHost,+ projectId,+ task.id,+ content,+ attachments,+ signal,+ );+ if (!runId) {+ return { ok: false, status: 0, detail: "starting a run failed" };+ }+ session.runId = runId;+ session.cursor = null;+ return { ok: true };+ }++ /**+ * Uploads attachments through the tasks artifact store: prepare presigned+ * S3 posts, upload the bytes, finalize. `basePath` picks run artifacts+ * (live/warm run) or staged task artifacts (cold start). Returns the+ * artifact ids, or null when any step fails.+ */+ private async uploadAttachments(+ apiHost: string,+ projectId: number,+ basePath: string,+ attachments: QuickAskAttachment[],+ signal: AbortSignal,+ ): Promise<string[] | null> {+ if (!attachments.length) return [];+ const files = attachments.map((attachment) => ({+ bytes: Uint8Array.from(atob(attachment.base64), (c) => c.charCodeAt(0)),+ name: attachment.name,+ mimeType: attachment.mimeType,+ }));+ const prefix = `/api/projects/${projectId}/${basePath}`;+ const prepareResponse = await this.post(+ apiHost,+ `${prefix}/prepare_upload/`,+ {+ artifacts: files.map((file) => ({+ name: file.name,+ type: "user_attachment",+ source: "posthog_code",+ size: file.bytes.byteLength,+ content_type: file.mimeType,+ })),+ },+ signal,+ );+ if (!prepareResponse.ok) return null;+ const prepared = ((await prepareResponse.json()) as PrepareUploadResponse)+ .artifacts;+ if (!prepared || prepared.length !== files.length) return null;+ for (const [index, artifact] of prepared.entries()) {+ const file = files[index];+ const form = new FormData();+ for (const [key, value] of Object.entries(+ artifact.presigned_post.fields,+ )) {+ form.append(key, value);+ }+ form.append(+ "file",+ new Blob([file.bytes], { type: file.mimeType }),+ file.name,+ );+ const uploadResponse = await this.fetchImpl(artifact.presigned_post.url, {+ method: "POST",+ body: form,+ signal: withRequestTimeout(signal),+ });+ if (!uploadResponse.ok) return null;+ }+ const finalizeResponse = await this.post(+ apiHost,+ `${prefix}/finalize_upload/`,+ { artifacts: prepared },+ signal,+ );+ if (!finalizeResponse.ok) return null;+ const finalized = ((await finalizeResponse.json()) as PrepareUploadResponse)+ .artifacts;+ if (!finalized || finalized.length !== files.length) return null;+ return finalized.map((artifact) => artifact.id);+ }++ /** Stages attachments on the task, then creates and starts a cold run. */+ private async startStagedRun(+ apiHost: string,+ projectId: number,+ taskId: string,+ content: string,+ attachments: QuickAskAttachment[],+ signal: AbortSignal,+ ): Promise<string | null> {+ const artifactIds = await this.uploadAttachments(+ apiHost,+ projectId,+ `tasks/${taskId}/staged_artifacts`,+ attachments,+ signal,+ );+ if (!artifactIds) return null;+ return this.startRun(+ apiHost,+ projectId,+ taskId,+ content,+ artifactIds,+ signal,+ );+ }++ async *ask(input: QuickAskInput): AsyncGenerator<QuickAskEvent> {+ this.cancel();+ const controller = new AbortController();+ this.controller = controller;++ const context = await this.context();+ if (!context) {+ yield { type: "error", message: "Sign in to PostHog to ask questions." };+ return;+ }+ const { apiHost, projectId } = context;++ // The create call must see the idling sandbox, not race its provisioning.+ if (this.warmPromise) {+ await this.warmPromise;+ }+ const session = this.ensureSession(input.conversationId);+ yield { type: "conversation", conversationId: session.conversationId };++ const firstTurn = session.turns === 0;+ const content = firstTurn+ ? `${input.question}\n\n${PANEL_STEERING}`+ : input.question;++ let placed: Awaited<ReturnType<typeof this.placeTurn>>;+ try {+ placed = await this.placeTurn(+ apiHost,+ projectId,+ session,+ input.question,+ content,+ input.attachments ?? [],+ controller.signal,+ );+ } catch (error) {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: describeError(error),+ };+ return;+ }+ if (!placed.ok) {+ yield {+ type: "error",+ message:+ placed.status === 402 || placed.status === 429+ ? "Your organization is out of PostHog task credits."+ : placed.status === 403+ ? "Your account can't run PostHog tasks in this project."+ : `PostHog AI is unavailable right now (${placed.status || "no run"}).`,+ detail: placed.detail,+ };+ return;+ }+ session.turns += 1;++ yield* this.streamTurn(apiHost, projectId, session, content, controller);+ }++ /**+ * Reads the run's SSE stream from the session cursor until the turn+ * completes. `event: end` (server-side connection rotation) reconnects with+ * the cursor; `event: stream-end` means the run itself finished.+ */+ private async *streamTurn(+ apiHost: string,+ projectId: number,+ session: QuickAskSession,+ content: string,+ controller: AbortController,+ ): AsyncGenerator<QuickAskEvent> {+ const turnId = `turn-${session.turns}`;+ // Text between stretches of tool activity forms its own segment; the+ // panel pages through them.+ let segment = 0;+ let segmentText = "";+ const segmentId = (): string =>+ segment === 0 ? turnId : `${turnId}.${segment + 1}`;+ let thoughtBuffer = "";+ let toolSinceText = false;+ // The run can carry prompts besides ours (the workflow prompts the task+ // description at boot), and prompt queueing logs a prompt when queued, so+ // ordering alone cannot attribute frames. Find our prompt by text, count+ // the prompts still unanswered ahead of it, and take only the output+ // between their completions and ours. A stream with no logged prompts+ // falls back to treating all agent activity as ours.+ const target = content.trim();+ let promptsBefore = 0;+ let completionsBefore = 0;+ let matched = false;+ let turnsAhead = 0;+ let completionsAfter = 0;+ const freshStream = session.cursor == null;+ const inOurTurn = (): boolean =>+ matched+ ? completionsAfter === turnsAhead+ : freshStream && promptsBefore === 0;++ const finish = (): QuickAskEvent[] =>+ segmentText+ ? [+ {+ type: "text",+ id: segmentId(),+ content: segmentText,+ complete: true,+ },+ { type: "done" },+ ]+ : [{ type: "done" }];++ try {+ let attempts = 0;+ while (true) {+ let response: Response;+ try {+ response = await this.authService.authenticatedFetch(+ this.fetchImpl,+ `${apiHost}/api/projects/${projectId}/tasks/${session.taskId}/runs/${session.runId}/stream/`,+ {+ method: "GET",+ headers: {+ Accept: "text/event-stream",+ ...(session.cursor+ ? { "Last-Event-ID": session.cursor }+ : undefined),+ },+ signal: controller.signal,+ },+ );+ } catch (error) {+ if (controller.signal.aborted) return;+ attempts += 1;+ if (attempts > MAX_STREAM_ATTEMPTS) {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: describeError(error),+ };+ return;+ }+ await reconnectDelay(attempts);+ if (controller.signal.aborted) return;+ continue;+ }+ if (!response.ok || !response.body) {+ attempts += 1;+ if (attempts > MAX_STREAM_ATTEMPTS) {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: `stream failed with ${response.status}`,+ };+ return;+ }+ await reconnectDelay(attempts);+ if (controller.signal.aborted) return;+ continue;+ }++ let rotated = false;+ let dropped = false;+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ const frames = async function* (): AsyncGenerator<SseFrame> {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ // Process complete SSE blocks; keep the trailing partial block.+ const lastDelimiter = buffer.lastIndexOf("\n\n");+ if (lastDelimiter === -1) continue;+ const complete = buffer.slice(0, lastDelimiter);+ buffer = buffer.slice(lastDelimiter + 2);+ yield* parseSseChunk(complete);+ }+ yield* parseSseChunk(buffer);+ };++ try {+ for await (const frame of frames()) {+ if (frame.id) {+ session.cursor = frame.id;+ attempts = 0; // Progress restores the reconnect budget.+ }+ if (frame.event === "end") {+ rotated = true; // Server rotates long connections; resume below.+ break;+ }+ if (frame.event === "stream-end") {+ yield* finish();+ return;+ }+ if (frame.event === "error") {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: frame.data.slice(0, 500),+ };+ return;+ }+ if (frame.event !== "message") {+ continue; // keepalive and other named events carry nothing to fold.+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(frame.data);+ } catch {+ continue;+ }+ const signal = translateFrame(parsed);+ switch (signal.kind) {+ case "prompt":+ if (matched) break; // Queued behind ours; not our concern.+ if (signal.text.trim() === target) {+ matched = true;+ turnsAhead = Math.max(0, promptsBefore - completionsBefore);+ } else {+ promptsBefore += 1;+ }+ break;+ case "agent-text":+ if (!inOurTurn()) break;+ if (toolSinceText && segmentText) {+ yield {+ type: "text",+ id: segmentId(),+ content: segmentText,+ complete: true,+ };+ segment += 1;+ segmentText = "";+ }+ toolSinceText = false;+ // A closing `agent_message` supersedes the chunks it followed;+ // replace so the snapshot does not double its own text.+ segmentText = signal.final+ ? signal.text+ : segmentText + signal.text;+ yield {+ type: "text",+ id: segmentId(),+ content: segmentText,+ complete: false,+ };+ break;+ case "reasoning": {+ if (!inOurTurn()) break;+ thoughtBuffer += signal.text;+ const label = reasoningLabel(thoughtBuffer);+ if (label) {+ yield { type: "reasoning", content: label };+ }+ break;+ }+ case "tool":+ if (!inOurTurn()) break;+ toolSinceText = true;+ yield {+ type: "reasoning",+ content: `Running ${signal.label}…`,+ };+ break;+ case "status":+ yield { type: "reasoning", content: signal.text };+ break;+ case "turn-complete":+ if (matched) {+ completionsAfter += 1;+ if (completionsAfter > turnsAhead) {+ yield* finish();+ return;+ }+ break;+ }+ if (freshStream && promptsBefore === 0) {+ yield* finish();+ return;+ }+ completionsBefore += 1;+ break;+ case "run-terminal":+ // The sandbox ended; the next question starts a successor run.+ session.runId = null;+ session.cursor = null;+ if (signal.status === "failed") {+ yield {+ type: "error",+ message: "PostHog AI hit an error. Try asking again.",+ detail: signal.errorMessage,+ };+ } else {+ yield* finish();+ }+ return;+ case "ignore":+ break;+ }+ }+ } catch (error) {+ // A mid-read network failure (proxies reset long HTTP/2 streams);+ // reconnect from the cursor like a rotation.+ if (controller.signal.aborted) return;+ dropped = true;+ attempts += 1;+ if (attempts > MAX_STREAM_ATTEMPTS) {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: describeError(error),+ };+ return;+ }+ } finally {+ // Release this connection on every exit — terminal return, rotation,+ // or retry — so the server is not left holding an idle SSE stream+ // (and its Redis reader) until its 900s cap. cancel() closes the+ // socket; an already-errored reader rejects, so swallow that.+ await reader.cancel().catch(() => {});+ }++ if (rotated) continue;+ if (!dropped) {+ // Clean EOF without the stream-end sentinel: connection dropped.+ attempts += 1;+ if (attempts > MAX_STREAM_ATTEMPTS) {+ yield {+ type: "error",+ message: UNAVAILABLE_MESSAGE,+ detail: "stream kept dropping",+ };+ return;+ }+ }+ await reconnectDelay(attempts);+ if (controller.signal.aborted) return;+ }+ } finally {+ // The turn is over; abort so the fetch/socket is torn down even if a+ // reader cancel did not fully propagate, and so this turn's controller+ // cannot linger past it.+ controller.abort();+ if (this.controller === controller) {+ this.controller = null;+ }+ }+ }+}diff --git a/products/desktop/packages/quick-ask/src/service/replay-fixture.ts b/products/desktop/packages/quick-ask/src/service/replay-fixture.tsnew file mode 100644index 000000000000..7aee43b58dca--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/replay-fixture.ts@@ -0,0 +1,277 @@+import http from "node:http";+import type { AddressInfo } from "node:net";+import { PANEL_STEERING } from "./steering";++/**+ * Replay of a production quick-ask run's stream, for the integration test and+ * the panel end-to-end script (`scripts/quick-ask-e2e.mts`). The+ * frame ordering is the part that matters and is taken from a real run: the+ * workflow prompts the task description at boot, prompt queueing logs the+ * panel's prompt before that turn completes, and the answer arrives in the+ * second turn. Frame contents are invented.+ */++export const REPLAY_QUESTION = "How many signups this week?";+export const REPLAY_FIRST_TURN_CONTENT = `${REPLAY_QUESTION}\n\n${PANEL_STEERING}`;+export const REPLAY_FOLLOW_UP = "And the week before?";++export const REPLAY_ANSWER = [+ "Signups held steady this week. The <hogql label=\"Tuesday spike\">SELECT count() FROM events WHERE event = 'signed_up' AND toDayOfWeek(timestamp) = 2</hogql> matches the launch email.",+ "",+ '<hogql display="block" title="Signups per day, last 7 days">SELECT toDate(timestamp) AS day, count() FROM events WHERE event = \'signed_up\' GROUP BY day ORDER BY day</hogql>',+].join("\n");+export const REPLAY_FOLLOW_UP_PRELUDE = "Comparing against last week.";+export const REPLAY_FOLLOW_UP_ANSWER = "About 1,100, a touch below this week.";+/** Output of the description turn; the panel must never show it. */+export const REPLAY_STRAY_ANSWER = "Looking into signups now.";++function notification(method: string, params: unknown): object {+ return {+ type: "notification",+ notification: { jsonrpc: "2.0", method, params },+ };+}++function console_(message: string): object {+ return notification("_posthog/console", { level: "debug", message });+}++function sessionUpdate(update: object): object {+ return notification("session/update", { sessionId: "s1", update });+}++function agentText(text: string): object {+ return sessionUpdate({+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text },+ });+}++function prompt(text: string): object {+ return notification("session/prompt", {+ sessionId: "s1",+ prompt: [{ type: "text", text }],+ });+}++const TURN_COMPLETE = notification("_posthog/turn_complete", {+ sessionId: "s1",+ stopReason: "end_turn",+});++/** First-turn frames, in the production order. */+export const REPLAY_FRAMES: object[] = [+ { type: "task_run_state", status: "queued" },+ console_("Setting up sandbox"),+ console_("Sandbox provisioned"),+ { type: "task_run_state", status: "in_progress" },+ notification("initialize", { protocolVersion: 1 }),+ notification("session/new", { cwd: "/tmp/workspace" }),+ notification("_posthog/run_started", { sessionId: "s1" }),+ sessionUpdate({+ sessionUpdate: "available_commands_update",+ availableCommands: [],+ }),+ // The workflow prompts the task description; the panel's prompt is queued+ // behind it and logged before the first turn completes.+ prompt(REPLAY_QUESTION),+ prompt(REPLAY_FIRST_TURN_CONTENT),+ sessionUpdate({+ sessionUpdate: "tool_call",+ toolCallId: "t0",+ title: "execute-sql",+ }),+ sessionUpdate({+ sessionUpdate: "tool_call_update",+ toolCallId: "t0",+ status: "completed",+ }),+ agentText(REPLAY_STRAY_ANSWER),+ TURN_COMPLETE,+ sessionUpdate({+ sessionUpdate: "agent_thought_chunk",+ content: { type: "text", text: "Charting signups by day" },+ }),+ sessionUpdate({+ sessionUpdate: "tool_call",+ toolCallId: "t1",+ title: "execute-sql",+ }),+ agentText(REPLAY_ANSWER.slice(0, 40)),+ agentText(REPLAY_ANSWER.slice(40)),+ TURN_COMPLETE,+];++/** Frame index after which the first stream connection rotates. */+export const REPLAY_ROTATE_AFTER = 15;++/**+ * Follow-up turn frames, appended once the follow-up command arrives. Text+ * lands on both sides of the tool call, so the turn produces two segments.+ */+export const REPLAY_FOLLOW_UP_FRAMES: object[] = [+ prompt(REPLAY_FOLLOW_UP),+ agentText(REPLAY_FOLLOW_UP_PRELUDE),+ sessionUpdate({+ sessionUpdate: "tool_call",+ toolCallId: "t2",+ title: "execute-sql",+ }),+ agentText(REPLAY_FOLLOW_UP_ANSWER),+ TURN_COMPLETE,+];++export interface ReplayServer {+ origin: string;+ /** Request bodies seen, keyed by route suffix. */+ requests: { path: string; body: unknown }[];+ streamRequests: { lastEventId: string | null }[];+ close(): Promise<void>;+}++function sseFrame(id: number, data: object): string {+ return `id: ${id}-0\ndata: ${JSON.stringify(data)}\n\n`;+}++/**+ * Serves the tasks API surface quick-ask speaks: warm, create (returning an+ * activated run), the command relay, and the run's SSE stream. The stream+ * rotates once mid-answer, so resuming with `Last-Event-ID` is exercised on+ * every run of the fixture. Follow-up frames start streaming once a+ * `user_message` command arrives.+ */+export async function startReplayServer(): Promise<ReplayServer> {+ const requests: { path: string; body: unknown }[] = [];+ const streamRequests: { lastEventId: string | null }[] = [];+ let followUpRequested = false;++ const allFrames = (): object[] =>+ followUpRequested+ ? [...REPLAY_FRAMES, ...REPLAY_FOLLOW_UP_FRAMES]+ : REPLAY_FRAMES;++ const server = http.createServer((request, response) => {+ const url = request.url ?? "";+ let raw = "";+ request.on("data", (chunk) => {+ raw += chunk;+ });+ request.on("end", () => {+ // The presigned S3 upload posts multipart form data, not JSON.+ let body: unknown = null;+ try {+ body = raw ? JSON.parse(raw) : null;+ } catch {+ body = raw;+ }+ requests.push({ path: url, body });++ if (url.endsWith("/prepare_upload/")) {+ const artifacts = (+ (body as { artifacts?: object[] } | null)?.artifacts ?? []+ ).map((artifact, index) => ({+ ...artifact,+ id: `art-${index + 1}`,+ presigned_post: {+ url: `http://${request.headers.host}/s3-upload/`,+ fields: { key: `uploads/art-${index + 1}` },+ },+ }));+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(JSON.stringify({ artifacts }));+ return;+ }+ if (url.endsWith("/s3-upload/")) {+ response.writeHead(204);+ response.end();+ return;+ }+ if (url.endsWith("/finalize_upload/")) {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(+ JSON.stringify({+ artifacts: (body as { artifacts?: object[] }).artifacts ?? [],+ }),+ );+ return;+ }++ if (url.endsWith("/tasks/warm/")) {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(JSON.stringify({ task_id: "task-1", run_id: "run-1" }));+ return;+ }+ if (url.endsWith("/tasks/")) {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(+ JSON.stringify({+ id: "task-1",+ latest_run: { id: "run-1", status: "in_progress" },+ }),+ );+ return;+ }+ if (url.endsWith("/command/")) {+ const method = (body as { method?: string } | null)?.method;+ if (method === "user_message") {+ followUpRequested = true;+ }+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(JSON.stringify({ success: true }));+ return;+ }+ if (url.includes("/stream/")) {+ const lastEventId = request.headers["last-event-id"];+ const cursor =+ typeof lastEventId === "string"+ ? Number.parseInt(lastEventId, 10)+ : -1;+ streamRequests.push({+ lastEventId: typeof lastEventId === "string" ? lastEventId : null,+ });+ response.writeHead(200, { "Content-Type": "text/event-stream" });++ const frames = allFrames();+ // The first connection rotates mid-answer; resumed connections send+ // the rest and stay open (like the real stream between turns).+ const rotate = cursor < 0 && frames.length > REPLAY_ROTATE_AFTER;+ const end = rotate ? REPLAY_ROTATE_AFTER + 1 : frames.length;+ for (let index = cursor + 1; index < end; index++) {+ response.write(sseFrame(index, frames[index]));+ }+ if (rotate) {+ response.write('event: end\ndata: {"type":"rotated"}\n\n');+ response.end();+ return;+ }+ const poll = setInterval(() => {+ const grown = allFrames();+ for (let index = end; index < grown.length; index++) {+ response.write(sseFrame(index, grown[index]));+ }+ if (grown.length > end) {+ clearInterval(poll);+ response.end();+ }+ }, 20);+ request.on("close", () => clearInterval(poll));+ return;+ }+ response.writeHead(404);+ response.end();+ });+ });++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const { port } = server.address() as AddressInfo;+ return {+ origin: `http://127.0.0.1:${port}`,+ requests,+ streamRequests,+ close: () =>+ new Promise((resolve) => {+ server.closeAllConnections();+ server.close(() => resolve());+ }),+ };+}diff --git a/products/desktop/packages/quick-ask/src/service/steering.ts b/products/desktop/packages/quick-ask/src/service/steering.tsnew file mode 100644index 000000000000..72abe7fea793--- /dev/null+++ b/products/desktop/packages/quick-ask/src/service/steering.ts@@ -0,0 +1,14 @@+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";++/**+ * Sent after the user's first question, so the task title stays the question.+ * The tag vocabulary is the shared block the renderer's object-tag pipeline+ * parses.+ */+export const PANEL_STEERING = `<posthog_trusted_context>+This question was asked from PostHog Desktop's compact quick-ask panel. For this whole conversation:+- Answer from PostHog data using the PostHog MCP tools. Do not clone repositories or modify code.+- Keep the text answer short - a few sentences at most.+- Never ask a blocking question; make reasonable assumptions and state them briefly.+- Rich output: ${RICH_OUTPUT_TAGS_PROMPT}+</posthog_trusted_context>`;diff --git a/products/desktop/packages/quick-ask/tsconfig.json b/products/desktop/packages/quick-ask/tsconfig.jsonnew file mode 100644index 000000000000..2bdd7e87dcc2--- /dev/null+++ b/products/desktop/packages/quick-ask/tsconfig.json@@ -0,0 +1,8 @@+{+ "extends": "@posthog/tsconfig/react-package.json",+ "compilerOptions": {+ "experimentalDecorators": true,+ "emitDecoratorMetadata": true+ },+ "include": ["src/**/*"]+}diff --git a/products/desktop/packages/quick-ask/vitest.config.ts b/products/desktop/packages/quick-ask/vitest.config.tsnew file mode 100644index 000000000000..bed14b24e079--- /dev/null+++ b/products/desktop/packages/quick-ask/vitest.config.ts@@ -0,0 +1,23 @@+import { defineConfig } from "vitest/config";+import { trunkTestOptions } from "../../vitest.config.base";++export default defineConfig({+ oxc: false,+ esbuild: {+ tsconfigRaw: {+ compilerOptions: {+ experimentalDecorators: true,+ target: "ES2022",+ useDefineForClassFields: false,+ verbatimModuleSyntax: true,+ },+ },+ },+ test: {+ globals: true,+ ...trunkTestOptions,+ environment: "node",+ include: ["src/**/*.test.ts", "src/**/*.test.tsx"],+ exclude: ["**/node_modules/**", "**/dist/**"],+ },+});diff --git a/products/desktop/packages/shared/package.json b/products/desktop/packages/shared/package.jsonindex 59caea2b31f4..96077e001f5e 100644--- a/products/desktop/packages/shared/package.json+++ b/products/desktop/packages/shared/package.json@@ -44,6 +44,14 @@"types": "./dist/mcp-sandbox-proxy.d.ts","import": "./dist/mcp-sandbox-proxy.js"},+ "./quick-ask-shortcuts": {+ "types": "./dist/quick-ask-shortcuts.d.ts",+ "import": "./dist/quick-ask-shortcuts.js"+ },+ "./rich-output-prompt": {+ "types": "./dist/rich-output-prompt.d.ts",+ "import": "./dist/rich-output-prompt.js"+ },"./posthog-property-headers": {"types": "./dist/posthog-property-headers.d.ts","import": "./dist/posthog-property-headers.js"diff --git a/products/desktop/packages/shared/src/quick-ask-shortcuts.ts b/products/desktop/packages/shared/src/quick-ask-shortcuts.tsnew file mode 100644index 000000000000..b6d90264a96d--- /dev/null+++ b/products/desktop/packages/shared/src/quick-ask-shortcuts.ts@@ -0,0 +1,112 @@+/**+ * Global shortcut handling for the quick-ask panel: a free-form recorder in+ * settings, validated here against Electron's accelerator grammar, with+ * presets kept for defaults and fallbacks.+ */++export interface QuickAskShortcutPreset {+ /** Electron accelerator string (Alt = Option on macOS). */+ accelerator: string;+ /** Label shown on macOS. */+ macLabel: string;+ /** Label shown on Windows/Linux. */+ otherLabel: string;+}++export const QUICK_ASK_SHORTCUT_PRESETS: readonly QuickAskShortcutPreset[] = [+ {+ accelerator: "CommandOrControl+Alt+P",+ macLabel: "⌘ ⌥ P",+ otherLabel: "Ctrl+Alt+P",+ },+ {+ accelerator: "Alt+Space",+ macLabel: "⌥ Space",+ otherLabel: "Alt+Space",+ },+ {+ accelerator: "Control+Space",+ macLabel: "⌃ Space",+ otherLabel: "Ctrl+Space",+ },+ {+ accelerator: "Alt+P",+ macLabel: "⌥ P",+ otherLabel: "Alt+P",+ },+ {+ accelerator: "CommandOrControl+Shift+Space",+ macLabel: "⌘ ⇧ Space",+ otherLabel: "Ctrl+Shift+Space",+ },+];++export const QUICK_ASK_DEFAULT_SHORTCUT =+ QUICK_ASK_SHORTCUT_PRESETS[0].accelerator;++export function isQuickAskShortcut(accelerator: string): boolean {+ return QUICK_ASK_SHORTCUT_PRESETS.some(+ (preset) => preset.accelerator === accelerator,+ );+}++const ACCELERATOR_MODIFIERS = new Set([+ "Command",+ "Cmd",+ "Control",+ "Ctrl",+ "CommandOrControl",+ "CmdOrCtrl",+ "Alt",+ "Option",+ "Shift",+ "Super",+ "Meta",+]);++const ACCELERATOR_KEY_RE =+ /^([A-Z0-9]|F([1-9]|1\d|2[0-4])|Space|Tab|Return|Up|Down|Left|Right|Home|End|PageUp|PageDown|[`\-=[\];',./\\])$/;++/**+ * A recordable accelerator: known modifiers plus one key. A bare or+ * shift-only key would swallow normal typing system-wide, so those pass only+ * for function keys.+ */+export function isValidQuickAskAccelerator(accelerator: string): boolean {+ const parts = accelerator.split("+");+ const key = parts[parts.length - 1];+ const modifiers = parts.slice(0, -1);+ if (!key || !ACCELERATOR_KEY_RE.test(key)) return false;+ if (!modifiers.every((part) => ACCELERATOR_MODIFIERS.has(part))) {+ return false;+ }+ const hasRealModifier = modifiers.some((part) => part !== "Shift");+ return hasRealModifier || /^F\d+$/.test(key);+}++const MAC_MODIFIER_GLYPHS: Record<string, string> = {+ Command: "\u2318",+ Cmd: "\u2318",+ CommandOrControl: "\u2318",+ CmdOrCtrl: "\u2318",+ Control: "\u2303",+ Ctrl: "\u2303",+ Alt: "\u2325",+ Option: "\u2325",+ Shift: "\u21e7",+ Super: "\u2318",+ Meta: "\u2318",+};++/** "CommandOrControl+Shift+Space" -> "\u2318 \u21e7 Space" (mac) or "Ctrl+Shift+Space". */+export function formatAccelerator(accelerator: string, mac: boolean): string {+ const parts = accelerator.split("+");+ if (!mac) {+ return parts+ .map((part) =>+ part === "CommandOrControl" || part === "CmdOrCtrl" ? "Ctrl" : part,+ )+ .join("+");+ }+ return parts.map((part) => MAC_MODIFIER_GLYPHS[part] ?? part).join(" ");+}diff --git a/products/desktop/packages/shared/src/rich-output-prompt.ts b/products/desktop/packages/shared/src/rich-output-prompt.tsnew file mode 100644index 000000000000..8635a3376f18--- /dev/null+++ b/products/desktop/packages/shared/src/rich-output-prompt.ts@@ -0,0 +1,11 @@+/**+ * Prompt block teaching an agent the object-tag vocabulary the desktop+ * renders as live references (chips, hover previews, chart cards). Embedded+ * by the local agent's system prompt and the quick-ask steering, so the+ * taught syntax stays in sync with what `remarkObjectTags` parses.+ */+export const RICH_OUTPUT_TAGS_PROMPT = `Embed the PostHog objects behind your conclusions as XML tags, the same convention as \`<file path="..."/>\` attachments. Every tag is a live reference the app resolves when shown - never restate the object's data in your text, and never put tags inside code fences.+- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.+- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.+- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.+- Recording card: \`<replay id="<session_id>" display="block"/>\` renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;diff --git a/products/desktop/packages/shared/tsup.config.ts b/products/desktop/packages/shared/tsup.config.tsindex cf58a4fc65e2..5f7c08e3dbea 100644--- a/products/desktop/packages/shared/tsup.config.ts+++ b/products/desktop/packages/shared/tsup.config.ts@@ -12,6 +12,8 @@ export default defineConfig({"src/domain-types.ts","src/mcp-sandbox-proxy.ts","src/posthog-property-headers.ts",+ "src/quick-ask-shortcuts.ts",+ "src/rich-output-prompt.ts","src/types.ts",],format: ["esm"],diff --git a/products/desktop/packages/ui/src/assets/hedgehogs.ts b/products/desktop/packages/ui/src/assets/hedgehogs.tsindex ab4c5f219989..307b5d078d52 100644--- a/products/desktop/packages/ui/src/assets/hedgehogs.ts+++ b/products/desktop/packages/ui/src/assets/hedgehogs.ts@@ -1,4 +1,5 @@export { default as builderHog } from "./hedgehogs/builder-hog-03.png";+export { default as hogzillaHog } from "./hedgehogs/driving-hogzilla.png";export { default as explorerHog } from "./hedgehogs/explorer-hog.png";export { default as happyHog } from "./hedgehogs/happy-hog.png";export { default as loopHog } from "./hedgehogs/loop-hog.svg";diff --git a/products/desktop/packages/ui/src/assets/hedgehogs/driving-hogzilla.png b/products/desktop/packages/ui/src/assets/hedgehogs/driving-hogzilla.pngnew file mode 100644index 000000000000..ea93a1880ad5Binary files /dev/null and b/products/desktop/packages/ui/src/assets/hedgehogs/driving-hogzilla.png differdiff --git a/products/desktop/packages/ui/src/features/command/KeyboardShortcutsSheet.tsx b/products/desktop/packages/ui/src/features/command/KeyboardShortcutsSheet.tsxindex e95780c08540..3b89068b8f0d 100644--- a/products/desktop/packages/ui/src/features/command/KeyboardShortcutsSheet.tsx+++ b/products/desktop/packages/ui/src/features/command/KeyboardShortcutsSheet.tsx@@ -1,3 +1,4 @@+import { PencilSimple } from "@phosphor-icons/react";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import {CATEGORY_LABELS,@@ -5,6 +6,7 @@ import {getShortcutsByCategory,type ShortcutCategory,} from "@posthog/ui/features/command/keyboard-shortcuts";+import { useQuickAskShortcut } from "@posthog/ui/features/quick-ask/useQuickAskShortcut";import { Box, Dialog, Flex, Text } from "@radix-ui/themes";import { useMemo, useState } from "react";import { useHotkeys } from "react-hotkeys-hook";@@ -54,6 +56,7 @@ export function KeyboardShortcutsSheet({open,onOpenChange,}: KeyboardShortcutsSheetProps) {+ const quickAsk = useQuickAskShortcut();useHotkeys("escape", () => onOpenChange(false), {enabled: open,enableOnContentEditable: true,@@ -80,7 +83,9 @@ export function KeyboardShortcutsSheet({</Flex><Box className="max-h-[calc(80vh-120px)] overflow-y-auto pr-[8px]">- <KeyboardShortcutsList />+ <KeyboardShortcutsList+ leadingGeneralShortcuts={quickAsk ? [quickAsk] : []}+ /></Box></Dialog.Content></Dialog.Root>@@ -109,7 +114,20 @@ function ShortcutsHeader() {);}-export function KeyboardShortcutsList() {+export interface LeadingShortcutRow {+ id: string;+ description: string;+ /** Hotkey format ("alt+space"), same as the static shortcut table. */+ keys: string;+ onEdit?: () => void;+}++export function KeyboardShortcutsList({+ leadingGeneralShortcuts = [],+}: {+ /** Dynamic rows (the quick-ask shortcut) shown first under General. */+ leadingGeneralShortcuts?: LeadingShortcutRow[];+} = {}) {// Several keys change owner with the layout, so the sheet has to know which// one is on rather than listing keys nothing handles.const channelsLayout = useChannelsLayout();@@ -150,6 +168,32 @@ export function KeyboardShortcutsList() {{CATEGORY_LABELS[category]}</Text><Box className="overflow-hidden rounded-(--radius-2) border border-(--gray-5)">+ {category === "general" &&+ leadingGeneralShortcuts.map((shortcut) => (+ <Flex+ key={shortcut.id}+ align="center"+ justify="between"+ px="3"+ className="group border-b border-b-(--gray-4) pt-[6px] pb-[6px] last:border-b-0 odd:bg-(--gray-2) even:bg-(--gray-1)"+ >+ <Text className="text-sm">{shortcut.description}</Text>+ <Flex gap="2" align="center">+ <ShortcutKeys keys={shortcut.keys} />+ {shortcut.onEdit && (+ <button+ type="button"+ aria-label={`Change ${shortcut.description}`}+ title={`Change ${shortcut.description}`}+ onClick={shortcut.onEdit}+ className="text-(--gray-9) opacity-0 transition-opacity hover:text-(--gray-12) focus-visible:opacity-100 group-hover:opacity-100"+ >+ <PencilSimple size={14} />+ </button>+ )}+ </Flex>+ </Flex>+ ))}{uniqueShortcuts.map((shortcut) => (<Flexkey={shortcut.id}diff --git a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.tsindex cf29f36601c6..52bd370fb1ac 100644--- a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts+++ b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts@@ -360,6 +360,7 @@ function formatKey(key: string): string {if (k === "=") return "+";if (k === "-") return "-";if (k === "tab") return "Tab";+ if (k === "space") return "Space";return k.toUpperCase();}diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsxindex 5f34613f71ed..d1f58765b056 100644--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx@@ -41,10 +41,11 @@ import {const SPARK_W = 100;const SPARK_H = 30;const SPARK_PAD = 2;-// PostHog's first data-viz color, same source quill-charts reads; the hex-// fallback keeps the spark on-brand where the theme variable isn't defined-// (the tooltip portals outside the theme root).-const SPARK_COLOR = "var(--data-color-1, #1d4aff)";+// Surfaces with their own palette (the quick-ask panel) set+// --evidence-spark-color; everywhere else PostHog's first data-viz color+// applies, with a hex fallback because the tooltip portals outside the+// theme root.+const SPARK_COLOR = "var(--evidence-spark-color, var(--data-color-1, #1d4aff))";/** Mini chart of the preview's primary series: a line for time series, columns for categories. */function Sparkline({@@ -63,7 +64,7 @@ function Sparkline({if (render === "bar") {const step = SPARK_W / points.length;- const gap = Math.min(step * 0.25, 2);+ const barWidth = step * 0.62;// Bars grow from the zero line, so a negative point extends below it.// Measuring to the chart bottom instead would shrink or invert them once// any point is negative (min drops below 0 and lifts the zero line).@@ -72,7 +73,7 @@ function Sparkline({<svgviewBox={`0 0 ${SPARK_W} ${SPARK_H}`}preserveAspectRatio="none"- className="h-9 w-full"+ className="my-1 h-8 w-full"role="img"aria-label="Column sparkline"data-testid="evidence-sparkline"@@ -83,12 +84,13 @@ function Sparkline({<rect// biome-ignore lint/suspicious/noArrayIndexKey: static series, never reorderskey={index}- x={index * step + gap / 2}- width={step - gap}- y={Math.min(y, baseline)}- height={Math.max(Math.abs(y - baseline), 0.5)}+ x={(index * step + (step - barWidth) / 2).toFixed(1)}+ width={barWidth.toFixed(1)}+ y={Math.min(y, baseline).toFixed(1)}+ height={Math.max(Math.abs(y - baseline), 0.5).toFixed(1)}+ rx={1.2}fill={SPARK_COLOR}- fillOpacity={0.85}+ fillOpacity={0.82}/>);})}@@ -114,7 +116,7 @@ function Sparkline({<svgviewBox={`0 0 ${SPARK_W} ${SPARK_H}`}preserveAspectRatio="none"- className="h-9 w-full"+ className="my-1 h-8 w-full"role="img"aria-label="Trend sparkline"data-testid="evidence-sparkline"@@ -407,6 +409,7 @@ export function EvidenceRefChip({loaded on every surface that renders chips (see ChatMarkdown). */}<Popover.Positioner side="top" sideOffset={8} className="z-[9999]"><Popover.Popup+ data-testid="evidence-hover-card"className="dark rounded-[6px] border border-(--gray-4) bg-(--gray-2) text-(--gray-12) outline-none"style={{ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.25)" }}>diff --git a/products/desktop/packages/ui/src/features/quick-ask/identifiers.ts b/products/desktop/packages/ui/src/features/quick-ask/identifiers.tsnew file mode 100644index 000000000000..05064239a5cc--- /dev/null+++ b/products/desktop/packages/ui/src/features/quick-ask/identifiers.ts@@ -0,0 +1,47 @@+/**+ * UI-side port for the quick-ask panel's settings. The global shortcut is+ * registered by the host (`apps/code` main process); this is the thin,+ * host-neutral surface the settings UI talks to. The desktop host binds a+ * tRPC-backed adapter; hosts without a quick-ask panel leave it unbound and+ * the settings card hides itself.+ */++export interface QuickAskState {+ /** Whether the quick-ask panel is available in this build. */+ enabled: boolean;+ /** The user toggle; off unregisters the shortcut and drops the panel. */+ active: boolean;+ /** The configured Electron accelerator. */+ shortcut: string;+ /** False when another app owns the accelerator. */+ registered: boolean;+ /** Space new threads file into; empty means the personal space. */+ defaultChannelId: string;+ /** Repos the sandbox clones; empty defers to the space's repositories. */+ defaultRepositories: string[];+ defaultGithubIntegrationId: number;+ /** Empty strings follow the adapter/model defaults. */+ defaultAdapter: string;+ defaultModel: string;+ defaultEffort: string;+}++export interface QuickAskSettingsPatch {+ active?: boolean;+ defaultChannelId?: string;+ defaultRepositories?: string[];+ defaultGithubIntegrationId?: number;+ defaultAdapter?: string;+ defaultModel?: string;+ defaultEffort?: string;+}++export interface QuickAskSettingsClient {+ getState(): Promise<QuickAskState>;+ setShortcut(accelerator: string): Promise<QuickAskState>;+ setSettings(patch: QuickAskSettingsPatch): Promise<QuickAskState>;+}++export const QUICK_ASK_SETTINGS_CLIENT = Symbol.for(+ "posthog.ui.quickAsk.settingsClient",+);diff --git a/products/desktop/packages/ui/src/features/quick-ask/useQuickAskAvailable.ts b/products/desktop/packages/ui/src/features/quick-ask/useQuickAskAvailable.tsnew file mode 100644index 000000000000..4e658e09517d--- /dev/null+++ b/products/desktop/packages/ui/src/features/quick-ask/useQuickAskAvailable.ts@@ -0,0 +1,34 @@+import { useServiceOptional } from "@posthog/di/react";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+ type QuickAskState,+} from "@posthog/ui/features/quick-ask/identifiers";+import { useEffect, useState } from "react";++/**+ * True only when this host binds a quick-ask client and the build exposes the+ * panel. Web (client unbound) and packaged desktop without the prototype gate+ * both read false, so the settings page can hide itself instead of rendering a+ * dead end. Defaults to false until the async state resolves, so the entry+ * appears once availability is confirmed rather than flashing out.+ */+export function useQuickAskAvailable(): boolean {+ const client = useServiceOptional<QuickAskSettingsClient>(+ QUICK_ASK_SETTINGS_CLIENT,+ );+ const [state, setState] = useState<QuickAskState | null>(null);++ useEffect(() => {+ if (!client) return;+ let active = true;+ client.getState().then((next) => {+ if (active) setState(next);+ });+ return () => {+ active = false;+ };+ }, [client]);++ return !!client && !!state?.enabled;+}diff --git a/products/desktop/packages/ui/src/features/quick-ask/useQuickAskShortcut.ts b/products/desktop/packages/ui/src/features/quick-ask/useQuickAskShortcut.tsnew file mode 100644index 000000000000..1ddb867f93c3--- /dev/null+++ b/products/desktop/packages/ui/src/features/quick-ask/useQuickAskShortcut.ts@@ -0,0 +1,61 @@+import { useServiceOptional } from "@posthog/di/react";+import type { LeadingShortcutRow } from "@posthog/ui/features/command/KeyboardShortcutsSheet";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+ type QuickAskState,+} from "@posthog/ui/features/quick-ask/identifiers";+import { useEffect, useState } from "react";++const ACCELERATOR_HOTKEYS: Record<string, string> = {+ CommandOrControl: "mod",+ CmdOrCtrl: "mod",+ Command: "mod",+ Cmd: "mod",+ Meta: "mod",+ Super: "mod",+ Control: "ctrl",+ Ctrl: "ctrl",+ Alt: "alt",+ Option: "alt",+ Shift: "shift",+};++/** "Alt+Space" (Electron accelerator) -> "alt+space" (the sheet's format). */+function acceleratorToHotkey(accelerator: string): string {+ return accelerator+ .split("+")+ .map((part) => ACCELERATOR_HOTKEYS[part] ?? part.toLowerCase())+ .join("+");+}++/**+ * The quick-ask global shortcut as a shortcut-list row, or null when the panel+ * is unavailable or switched off. Shared by the Shortcuts settings page and the+ * mod+/ shortcut sheet so the two surfaces list the same shortcut. Callers add+ * an `onEdit` affordance if they want one.+ */+export function useQuickAskShortcut(): LeadingShortcutRow | null {+ const client = useServiceOptional<QuickAskSettingsClient>(+ QUICK_ASK_SETTINGS_CLIENT,+ );+ const [state, setState] = useState<QuickAskState | null>(null);++ useEffect(() => {+ if (!client) return;+ let active = true;+ client.getState().then((next) => {+ if (active) setState(next);+ });+ return () => {+ active = false;+ };+ }, [client]);++ if (!client || !state?.enabled || !state.active) return null;+ return {+ id: "quick-ask",+ description: "Ask PostHog anywhere",+ keys: acceleratorToHotkey(state.shortcut),+ };+}diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsxindex 7fe1866dad7f..58443b754c95 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx@@ -9,6 +9,7 @@ import { HarnessSettings } from "@posthog/ui/features/settings/sections/HarnessSimport { NotificationsSettings } from "@posthog/ui/features/settings/sections/NotificationsSettings";import { PersonalizationSettings } from "@posthog/ui/features/settings/sections/PersonalizationSettings";import { PlanUsageSettings } from "@posthog/ui/features/settings/sections/PlanUsageSettings";+import { QuickAskSettings } from "@posthog/ui/features/settings/sections/QuickAskSettings";import { ShortcutsSettings } from "@posthog/ui/features/settings/sections/ShortcutsSettings";import { SignalSourcesSettings } from "@posthog/ui/features/settings/sections/SignalSourcesSettings";import { SlackSettings } from "@posthog/ui/features/settings/sections/SlackSettings";@@ -72,6 +73,7 @@ const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {terminal: defineSettingsPage("Terminal", TerminalSettings),harness: defineSettingsPage("Harness", HarnessSettings),shortcuts: defineSettingsPage("Shortcuts", ShortcutsSettings),+ "quick-ask": defineSettingsPage("Quick ask", QuickAskSettings),github: defineSettingsPage("GitHub", GitHubSettings),slack: defineSettingsPage("Slack integration", SlackSettings),discord: defineSettingsPage("Discord", DiscordSettings),diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsxindex 4c7c84605dd5..323cfbb67019 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx@@ -11,6 +11,7 @@ import {GithubLogo,Keyboard,Lightbulb,+ Lightning,MagnifyingGlass,Palette,Plugs,@@ -32,6 +33,7 @@ import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";+import { useQuickAskAvailable } from "@posthog/ui/features/quick-ask/useQuickAskAvailable";import { SettingsPageContent } from "@posthog/ui/features/settings/components/SettingsPageContent";import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import {@@ -73,6 +75,7 @@ const SIDEBAR_GROUPS: SidebarGroup[] = [{ id: "personalization", icon: <Palette size={16} /> },{ id: "sidebar", icon: <SidebarSimple size={16} /> },{ id: "shortcuts", icon: <Keyboard size={16} /> },+ { id: "quick-ask", icon: <Lightning size={16} /> },],},{@@ -149,6 +152,7 @@ export function SettingsPanel({const channelsLayout = useChannelsLayout();const { localWorkspaces } = useHostCapabilities();const logoutMutation = useLogoutMutation();+ const quickAskAvailable = useQuickAskAvailable();const spendAnalysisEnabled = useSpendAnalysisEnabled();const hiddenCategories = getHiddenSettingsCategories({@@ -156,6 +160,7 @@ export function SettingsPanel({spendAnalysisEnabled,localWorkspaces,channelsLayout,+ quickAskAvailable,});const sidebarGroups = SIDEBAR_GROUPS.map((group) => ({...group,diff --git a/products/desktop/packages/ui/src/features/settings/sections/QuickAskSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/QuickAskSettings.tsxnew file mode 100644index 000000000000..601c06775013--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/QuickAskSettings.tsx@@ -0,0 +1,235 @@+import { isValidConfigValue } from "@posthog/core/task-detail/configOptions";+import { useServiceOptional } from "@posthog/di/react";+import { Switch } from "@posthog/quill";+import type { Adapter } from "@posthog/shared";+import { isSupportedReasoningEffort } from "@posthog/shared";+import { RepositoriesField } from "@posthog/ui/features/canvas/components/RepositoriesField";+import { SpaceSelect } from "@posthog/ui/features/canvas/components/SpaceSelect";+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+ type QuickAskSettingsPatch,+ type QuickAskState,+} from "@posthog/ui/features/quick-ask/identifiers";+import { ReasoningLevelSelector } from "@posthog/ui/features/sessions/components/ReasoningLevelSelector";+import { SettingRow } from "@posthog/ui/features/settings/SettingRow";+import { QuickAskShortcutSetting } from "@posthog/ui/features/settings/sections/QuickAskShortcutSetting";+import { usePreviewConfig } from "@posthog/ui/features/task-detail/hooks/usePreviewConfig";+import { Flex, Text } from "@radix-ui/themes";+import { useCallback, useEffect, useRef, useState } from "react";++/** The new-task model pill, wired to the persisted quick-ask defaults. */+function AgentDefaults({+ state,+ apply,+ disabled,+}: {+ state: QuickAskState;+ apply: (patch: QuickAskSettingsPatch) => void;+ disabled: boolean;+}) {+ const adapter: Adapter =+ state.defaultAdapter === "codex" ? "codex" : "claude";+ const { modelOption, thoughtOption, isLoading, setConfigOption } =+ usePreviewConfig(adapter);++ // Reflect the persisted defaults into the fetched options once per load.+ const seeded = useRef(false);+ useEffect(() => {+ if (seeded.current || isLoading) return;+ seeded.current = true;+ if (+ state.defaultModel &&+ modelOption &&+ isValidConfigValue(modelOption, state.defaultModel)+ ) {+ setConfigOption(modelOption.id, state.defaultModel);+ }+ if (+ state.defaultEffort &&+ thoughtOption &&+ isValidConfigValue(thoughtOption, state.defaultEffort)+ ) {+ setConfigOption(thoughtOption.id, state.defaultEffort);+ }+ }, [+ isLoading,+ modelOption,+ thoughtOption,+ setConfigOption,+ state.defaultModel,+ state.defaultEffort,+ ]);++ const handleModelChange = useCallback(+ (value: string) => {+ if (!modelOption) return;+ setConfigOption(modelOption.id, value);+ const effort =+ state.defaultEffort &&+ isSupportedReasoningEffort(adapter, value, state.defaultEffort)+ ? state.defaultEffort+ : "";+ apply({ defaultModel: value, defaultEffort: effort });+ },+ [modelOption, setConfigOption, adapter, state.defaultEffort, apply],+ );++ const handleThoughtChange = useCallback(+ (value: string) => {+ if (!thoughtOption) return;+ setConfigOption(thoughtOption.id, value);+ apply({ defaultEffort: value });+ },+ [thoughtOption, setConfigOption, apply],+ );++ const handleConfigOptionChange = useCallback(+ (configId: string, value: string) => {+ if (modelOption && configId === modelOption.id) {+ handleModelChange(value);+ return;+ }+ if (thoughtOption && configId === thoughtOption.id) {+ handleThoughtChange(value);+ }+ },+ [modelOption, thoughtOption, handleModelChange, handleThoughtChange],+ );++ return (+ <ReasoningLevelSelector+ thoughtOption={thoughtOption}+ modelOption={modelOption}+ adapter={adapter}+ onChange={handleThoughtChange}+ onModelChange={handleModelChange}+ onAdapterChange={(next) => {+ seeded.current = true;+ apply({+ defaultAdapter: next === "claude" ? "" : next,+ defaultModel: "",+ defaultEffort: "",+ });+ }}+ onConfigOptionChange={handleConfigOptionChange}+ disabled={disabled}+ isLoading={isLoading}+ />+ );+}++export function QuickAskSettings() {+ const client = useServiceOptional<QuickAskSettingsClient>(+ QUICK_ASK_SETTINGS_CLIENT,+ );+ const [state, setState] = useState<QuickAskState | null>(null);+ const { channels } = useChannels();++ useEffect(() => {+ if (!client) return;+ let active = true;+ client.getState().then((next) => {+ if (active) setState(next);+ });+ return () => {+ active = false;+ };+ }, [client]);++ if (!client || !state?.enabled) {+ return (+ <Text className="text-(--gray-11) text-sm">+ The quick-ask panel is not available in this build.+ </Text>+ );+ }++ const apply = (patch: QuickAskSettingsPatch): void => {+ void client.setSettings(patch).then(setState);+ };++ const personal = channels.find(+ (channel) => channel.channelType === "personal",+ );+ // The stored empty id means the personal space (the backend's default).+ const selectedSpaceId = state.defaultChannelId || (personal?.id ?? "");+ const selectedSpace = channels.find(+ (channel) => channel.id === selectedSpaceId,+ );+ const spaceRepositories =+ state.defaultChannelId && selectedSpace?.channelType !== "personal"+ ? (selectedSpace?.repositories ?? [])+ : [];+ const off = !state.active;++ return (+ <Flex direction="column">+ <SettingRow+ label="Enable quick ask"+ description="The floating panel and its global shortcut. Turning this off frees the shortcut."+ >+ <Switch+ size="sm"+ checked={state.active}+ onCheckedChange={(checked) => apply({ active: checked })}+ aria-label="Enable quick ask"+ />+ </SettingRow>++ <div className={off ? "pointer-events-none opacity-50" : undefined}>+ <QuickAskShortcutSetting disabled={off} />++ <SettingRow+ label="Default space"+ description="New quick-ask threads file into this space."+ >+ <SpaceSelect+ value={selectedSpaceId}+ disabled={off}+ onChange={(channelId) => {+ const picked = channels.find(+ (channel) => channel.id === channelId,+ );+ apply({+ defaultChannelId:+ picked?.channelType === "personal" ? "" : channelId,+ });+ }}+ />+ </SettingRow>++ <SettingRow+ label="Default repositories"+ description={+ state.defaultRepositories.length === 0 &&+ spaceRepositories.length > 0+ ? `None of your own; the space brings ${spaceRepositories.join(", ")}.`+ : "Cloned into the sandbox for every new thread. Leave empty for data-only answers, or to use the space's repositories."+ }+ >+ <RepositoriesField+ selected={state.defaultRepositories}+ integrationId={state.defaultGithubIntegrationId || null}+ disabled={off}+ onChange={(repositories, integrationId) =>+ apply({+ defaultRepositories: repositories,+ defaultGithubIntegrationId: integrationId ?? 0,+ })+ }+ />+ </SettingRow>++ <SettingRow+ label="Agent"+ description="The harness, model, and effort quick-ask answers run with."+ noBorder+ >+ <AgentDefaults state={state} apply={apply} disabled={off} />+ </SettingRow>+ </div>+ </Flex>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.test.ts b/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.test.tsnew file mode 100644index 000000000000..75af91787571--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import { acceleratorFromEvent } from "./QuickAskShortcutSetting";++describe("acceleratorFromEvent", () => {+ it.each([+ // Each physical modifier keeps its own identity instead of collapsing into+ // CommandOrControl, which Electron would resolve to the wrong key.+ [+ "macOS Control stays Control",+ { code: "Space", ctrlKey: true },+ true,+ "Control+Space",+ ],+ [+ "macOS Command stays Command",+ { code: "Space", metaKey: true },+ true,+ "Command+Space",+ ],+ [+ "macOS Command+Control keeps both",+ { code: "Space", metaKey: true, ctrlKey: true },+ true,+ "Command+Control+Space",+ ],+ [+ "non-mac Meta becomes Super",+ { code: "Space", metaKey: true },+ false,+ "Super+Space",+ ],+ [+ "non-mac Control stays Control",+ { code: "Space", ctrlKey: true },+ false,+ "Control+Space",+ ],+ ["Alt keeps its key", { code: "KeyP", altKey: true }, true, "Alt+P"],+ ] as const)("%s", (_name, init, isMac, expected) => {+ const event = new KeyboardEvent("keydown", init);+ expect(acceleratorFromEvent(event, isMac)).toBe(expected);+ });+});diff --git a/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.tsx b/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.tsxnew file mode 100644index 000000000000..926fafbf9ed5--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/QuickAskShortcutSetting.tsx@@ -0,0 +1,173 @@+import { useServiceOptional } from "@posthog/di/react";+import { Button } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import {+ formatAccelerator,+ isValidQuickAskAccelerator,+} from "@posthog/shared/quick-ask-shortcuts";+import {+ QUICK_ASK_SETTINGS_CLIENT,+ type QuickAskSettingsClient,+ type QuickAskState,+} from "@posthog/ui/features/quick-ask/identifiers";+import { SettingRow } from "@posthog/ui/features/settings/SettingRow";+import { track } from "@posthog/ui/shell/analytics";+import { useEffect, useState } from "react";++const IS_MAC = globalThis.navigator?.platform.startsWith("Mac") ?? false;++const CODE_KEYS: Record<string, string> = {+ Space: "Space",+ Comma: ",",+ Period: ".",+ Slash: "/",+ Backslash: "\\",+ Semicolon: ";",+ Quote: "'",+ BracketLeft: "[",+ BracketRight: "]",+ Minus: "-",+ Equal: "=",+ Backquote: "`",+ ArrowUp: "Up",+ ArrowDown: "Down",+ ArrowLeft: "Left",+ ArrowRight: "Right",+ Enter: "Return",+ Tab: "Tab",+ Home: "Home",+ End: "End",+ PageUp: "PageUp",+ PageDown: "PageDown",+};++export function acceleratorFromEvent(+ event: KeyboardEvent,+ isMac: boolean,+): string | null {+ let key: string | null = null;+ if (event.code.startsWith("Key")) key = event.code.slice(3);+ else if (event.code.startsWith("Digit")) key = event.code.slice(5);+ else if (/^F\d+$/.test(event.code)) key = event.code;+ else key = CODE_KEYS[event.code] ?? null;+ if (!key) return null;++ const modifiers: string[] = [];+ // Map each physical modifier to its own Electron accelerator. Collapsing+ // Meta and Control into CommandOrControl records a different shortcut than+ // pressed — on macOS a Control+Space would become Command+Space and collide+ // with Spotlight.+ if (event.metaKey) modifiers.push(isMac ? "Command" : "Super");+ if (event.ctrlKey) modifiers.push("Control");+ if (event.altKey) modifiers.push("Alt");+ if (event.shiftKey) modifiers.push("Shift");+ const accelerator = [...modifiers, key].join("+");+ return isValidQuickAskAccelerator(accelerator) ? accelerator : null;+}++function ShortcutRecorder({+ value,+ disabled,+ onRecord,+}: {+ value: string;+ disabled: boolean;+ onRecord: (accelerator: string) => void;+}) {+ const [recording, setRecording] = useState(false);++ useEffect(() => {+ if (!recording) return;+ const onKeyDown = (event: KeyboardEvent): void => {+ event.preventDefault();+ event.stopPropagation();+ if (event.key === "Escape") {+ setRecording(false);+ return;+ }+ const accelerator = acceleratorFromEvent(event, IS_MAC);+ if (accelerator) {+ setRecording(false);+ onRecord(accelerator);+ }+ };+ const cancel = (): void => setRecording(false);+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("blur", cancel);+ return () => {+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("blur", cancel);+ };+ }, [recording, onRecord]);++ return (+ <Button+ variant="outline"+ size="sm"+ disabled={disabled}+ onClick={() => setRecording((current) => !current)}+ aria-label="Record shortcut"+ className="min-w-[160px] font-mono"+ >+ {recording+ ? "Press a shortcut… (Esc cancels)"+ : formatAccelerator(value, IS_MAC)}+ </Button>+ );+}++/**+ * Records any modifier+key combination as the panel's global shortcut.+ * Renders nothing on hosts without the panel.+ */+export function QuickAskShortcutSetting({+ disabled = false,+}: {+ disabled?: boolean;+}) {+ const client = useServiceOptional<QuickAskSettingsClient>(+ QUICK_ASK_SETTINGS_CLIENT,+ );+ const [state, setState] = useState<QuickAskState | null>(null);++ useEffect(() => {+ if (!client) return;+ let active = true;+ client.getState().then((next) => {+ if (active) setState(next);+ });+ return () => {+ active = false;+ };+ }, [client]);++ if (!client || !state?.enabled) {+ return null;+ }++ const handleRecord = (accelerator: string): void => {+ track(ANALYTICS_EVENTS.SETTING_CHANGED, {+ setting_name: "quick_ask_shortcut",+ new_value: accelerator,+ old_value: state.shortcut,+ });+ void client.setShortcut(accelerator).then(setState);+ };++ return (+ <SettingRow+ label="Ask PostHog anywhere"+ description={+ state.active && !state.registered+ ? "Another app owns this shortcut. Record a different one."+ : "Click, then press the keys you want to summon the panel with."+ }+ >+ <ShortcutRecorder+ value={state.shortcut}+ disabled={disabled}+ onRecord={handleRecord}+ />+ </SettingRow>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/ShortcutsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/ShortcutsSettings.tsxindex 90b475185331..fa3ece4c6316 100644--- a/products/desktop/packages/ui/src/features/settings/sections/ShortcutsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/ShortcutsSettings.tsx@@ -1,5 +1,15 @@-import { KeyboardShortcutsList } from "@posthog/ui/features/command/KeyboardShortcutsSheet";+import {+ KeyboardShortcutsList,+ type LeadingShortcutRow,+} from "@posthog/ui/features/command/KeyboardShortcutsSheet";+import { useQuickAskShortcut } from "@posthog/ui/features/quick-ask/useQuickAskShortcut";+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";export function ShortcutsSettings() {- return <KeyboardShortcutsList />;+ const quickAsk = useQuickAskShortcut();+ const quickAskRows: LeadingShortcutRow[] = quickAsk+ ? [{ ...quickAsk, onEdit: () => openSettings("quick-ask") }]+ : [];++ return <KeyboardShortcutsList leadingGeneralShortcuts={quickAskRows} />;}diff --git a/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts b/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.tsindex 88f3e8fa8853..375715f72603 100644--- a/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts@@ -9,6 +9,7 @@ describe("getHiddenSettingsCategories", () => {billingEnabled: true,spendAnalysisEnabled: true,localWorkspaces: true,+ quickAskAvailable: true,},expected: [],},@@ -18,6 +19,7 @@ describe("getHiddenSettingsCategories", () => {billingEnabled: false,spendAnalysisEnabled: false,localWorkspaces: true,+ quickAskAvailable: true,},expected: ["plan-usage"],},@@ -27,6 +29,7 @@ describe("getHiddenSettingsCategories", () => {billingEnabled: true,spendAnalysisEnabled: true,localWorkspaces: false,+ quickAskAvailable: true,},expected: ["workspaces", "worktrees", "terminal", "harness", "discord"],},@@ -39,9 +42,22 @@ describe("getHiddenSettingsCategories", () => {spendAnalysisEnabled: true,localWorkspaces: true,channelsLayout: true,+ quickAskAvailable: true,},expected: ["sidebar"],},+ {+ // The page's only content when the panel is unavailable is a dead-end+ // "not available in this build" message, so hide it (web hosts and+ // packaged desktop without the prototype gate).+ name: "hides quick-ask when the panel is unavailable",+ input: {+ billingEnabled: true,+ spendAnalysisEnabled: true,+ localWorkspaces: true,+ },+ expected: ["quick-ask"],+ },])("$name", ({ input, expected }) => {expect([...getHiddenSettingsCategories(input)]).toEqual(expected);});diff --git a/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts b/products/desktop/packages/ui/src/features/settings/settingsVisibility.tsindex 6afbcac9d05f..e2b78753603f 100644--- a/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts@@ -20,6 +20,12 @@ interface SettingsVisibility {* Sidebar page's controls have nothing to act on there.*/channelsLayout?: boolean;+ /**+ * The quick-ask panel exists on this host and build. Off (web, and packaged+ * desktop without the prototype gate) hides its settings page, whose only+ * content otherwise is an "unavailable" message.+ */+ quickAskAvailable?: boolean;}export function getHiddenSettingsCategories({@@ -27,6 +33,7 @@ export function getHiddenSettingsCategories({spendAnalysisEnabled,localWorkspaces,channelsLayout = false,+ quickAskAvailable = false,}: SettingsVisibility): ReadonlySet<SettingsCategory> {const hiddenCategories = new Set<SettingsCategory>();@@ -44,6 +51,9 @@ export function getHiddenSettingsCategories({if (channelsLayout) {hiddenCategories.add("sidebar");}+ if (!quickAskAvailable) {+ hiddenCategories.add("quick-ask");+ }return hiddenCategories;}diff --git a/products/desktop/packages/ui/src/features/settings/types.ts b/products/desktop/packages/ui/src/features/settings/types.tsindex cf759c86f32f..1c5558e1e600 100644--- a/products/desktop/packages/ui/src/features/settings/types.ts+++ b/products/desktop/packages/ui/src/features/settings/types.ts@@ -14,6 +14,7 @@ export type SettingsCategory =| "terminal"| "harness"| "shortcuts"+ | "quick-ask"| "github"| "slack"| "signals"@@ -36,6 +37,7 @@ export const SETTINGS_CATEGORIES: readonly SettingsCategory[] = ["terminal","harness","shortcuts",+ "quick-ask","github","slack","signals",@@ -66,6 +68,7 @@ export const SETTINGS_PAGE_LABELS: Record<SettingsCategory, string> = {terminal: "Terminal",harness: "Harness",shortcuts: "Shortcuts",+ "quick-ask": "Quick ask",github: "GitHub",slack: "Slack",signals: "Self-driving",diff --git a/products/desktop/packages/ui/src/primitives/ThemeWrapper.tsx b/products/desktop/packages/ui/src/primitives/ThemeWrapper.tsxindex 0d706781c352..b36c96e6d132 100644--- a/products/desktop/packages/ui/src/primitives/ThemeWrapper.tsx+++ b/products/desktop/packages/ui/src/primitives/ThemeWrapper.tsx@@ -9,8 +9,19 @@ export function getPortalContainer(): HTMLElement {return portalContainer ?? document.body;}-export function ThemeWrapper({ children }: { children: React.ReactNode }) {- const isDarkMode = useThemeStore((state) => state.isDarkMode);+export function ThemeWrapper({+ children,+ appearance,+}: {+ children: React.ReactNode;+ /**+ * Fixed appearance for surfaces with a hard-coded palette; defaults to the+ * user's theme preference.+ */+ appearance?: "light" | "dark";+}) {+ const storeIsDarkMode = useThemeStore((state) => state.isDarkMode);+ const isDarkMode = appearance ? appearance === "dark" : storeIsDarkMode;const portalRef = useRef<HTMLDivElement>(null);useEffect(() => {diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex b0ef03d637b0..b6745de4c019 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -74,6 +74,7 @@ import {serializeError,TypedEventEmitter,} from "@posthog/shared";+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";import { inject, injectable, preDestroy } from "inversify";import { WORKSPACE_REPOSITORY } from "../../db/identifiers";import type { IWorkspaceRepository } from "../../db/repositories/workspace-repository";@@ -665,11 +666,7 @@ Optimize for the fewest shell round trips.- Never rerun a command solely to reproduce output you already have.## Rich output in replies-Embed the PostHog objects behind your conclusions as XML tags, the same convention as \`<file path="..."/>\` attachments. Every tag is a live reference the app resolves when shown - never restate the object's data in your text, and never put tags inside code fences.-- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.-- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.-- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.-- Recording card: \`<replay id="<session_id>" display="block"/>\` renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;+${RICH_OUTPUT_TAGS_PROMPT}`;if (channelMode) {prompt += `diff --git a/products/desktop/pnpm-lock.yaml b/products/desktop/pnpm-lock.yamlindex 50586fdace45..93a7eed9327a 100644--- a/products/desktop/pnpm-lock.yaml+++ b/products/desktop/pnpm-lock.yaml@@ -210,6 +210,9 @@ importers:'@posthog/platform':specifier: workspace:*version: link:../../packages/platform+ '@posthog/quick-ask':+ specifier: workspace:*+ version: link:../../packages/quick-ask'@posthog/quill':specifier: 'catalog:'version: 0.3.0-beta.26(@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -1204,6 +1207,37 @@ importers:specifier: ^5.5.0version: 5.9.3+ packages/quick-ask:+ dependencies:+ '@posthog/core':+ specifier: workspace:*+ version: link:../core+ '@posthog/shared':+ specifier: workspace:*+ version: link:../shared+ '@posthog/ui':+ specifier: workspace:*+ version: link:../ui+ inversify:+ specifier: 'catalog:'+ version: 7.11.0([email protected])+ react:+ specifier: 19.2.6+ version: 19.2.6+ react-markdown:+ specifier: ^10.1.0+ version: 10.1.0(@types/[email protected])([email protected])+ devDependencies:+ '@posthog/tsconfig':+ specifier: workspace:*+ version: link:../../tooling/typescript+ typescript:+ specifier: 'catalog:'+ version: 5.9.3+ vitest:+ specifier: ^4.1.8+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages/shared:dependencies:zod:@@ -7068,8 +7102,8 @@ packages:'@types/react-dom':optional: true- '@react-grab/[email protected]':- resolution: {integrity: sha512-Px/Hwhhyk2PubCA4ZaRFsfvwxhbxXsetJyvqC6aFFi8WhJhA+oVC33aTzuAeWmM3fhb4/8ce8YsHXI1d6ChcKg==}+ '@react-grab/[email protected]':+ resolution: {integrity: sha512-LVfA+j5cFT0Szd958WRD8W/B8ucCtz4ViiveDKWLqAwBkZFW9VRW1ZvwOUhp/M3SmVPtjDaRkW12GvAuTArP+Q==}hasBin: true'@react-native-async-storage/[email protected]':@@ -14142,8 +14176,8 @@ packages:peerDependencies:react: 19.2.6- resolution: {integrity: sha512-zRkHKq/8a1msCpEOp8BDROeQZT50m0OH2XPrP6jk5op+JAHrlsm3pj7eAQMOsct87EZDeGNnu4r+sGsJJzyw1Q==}+ resolution: {integrity: sha512-ohhsfXD4qN0j6cMQd56aaVJBPDF3kUdviF/Od1Eak/rEIXQ3svQ4gjkwTfuTZwTBnxHRL16p9JqdlVQO5nUHqA==}hasBin: truepeerDependencies:react: 19.2.6@@ -21853,7 +21887,7 @@ snapshots:'@types/react': 19.2.17'@types/react-dom': 19.2.3(@types/[email protected])- '@react-grab/[email protected]':+ '@react-grab/[email protected]':dependencies:agent-install: 0.0.6commander: 14.0.3@@ -26846,7 +26880,7 @@ snapshots:dependencies:- '@types/estree': 1.0.8+ '@types/estree': 1.0.9'@types/hast': 3.0.4'@types/unist': 3.0.3comma-separated-tokens: 2.0.3@@ -30295,9 +30329,9 @@ snapshots:dependencies:react: 19.2.6dependencies:- '@react-grab/cli': 0.1.50+ '@react-grab/cli': 0.2.0bippy: 0.6.1([email protected])optionalDependencies:react: 19.2.6@@ -30563,7 +30597,7 @@ snapshots:react: 19.2.6react-doctor: 0.9.12(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))react-dom: 19.2.6([email protected])- react-grab: 0.1.50([email protected])+ react-grab: 0.2.0([email protected])optionalDependencies:esbuild: 0.27.7unplugin: 3.0.0