Skip to content

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

feat(desktop/canvas): give sessions and spaces one hover card (#82035)

Adam Leithf8f21274c71b
diff --git a/products/desktop/packages/core/src/sessions/latestTurnMessage.test.ts b/products/desktop/packages/core/src/sessions/latestTurnMessage.test.ts
new file mode 100644
index 000000000000..8276d7c069d5
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/latestTurnMessage.test.ts
@@ -0,0 +1,92 @@
+import type { AcpMessage } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import { latestAgentMessage, persistedTurnMessage } from "./latestTurnMessage";
+
+function update(sessionUpdate: string, text?: string): AcpMessage {
+ return {
+ type: "acp_message",
+ ts: 0,
+ message: {
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate,
+ content: text === undefined ? undefined : { type: "text", text },
+ },
+ },
+ },
+ };
+}
+
+function agent(text: string): AcpMessage {
+ return update("agent_message_chunk", text);
+}
+
+describe("latestTurnMessage", () => {
+ it("joins the chunks the last message streamed in as", () => {
+ expect(
+ latestAgentMessage([
+ agent("Ignore "),
+ update("tool_call"),
+ agent("Renamed "),
+ agent("the column."),
+ ]),
+ ).toBe("Renamed the column.");
+ });
+
+ it.each([
+ ["nothing at all", []],
+ ["a run with no agent prose", [update("tool_call"), update("plan")]],
+ ["prose that is only whitespace", [agent(" \n ")]],
+ ])("says nothing about %s", (_case, events: AcpMessage[]) => {
+ expect(latestAgentMessage(events)).toBeNull();
+ });
+
+ it("reads past a user turn to the message before it, not into it", () => {
+ expect(
+ latestAgentMessage([
+ agent("First answer."),
+ update("user_message_chunk", "and now this"),
+ ]),
+ ).toBe("First answer.");
+ });
+
+ // A streaming session holds tens of thousands of events and this runs while
+ // the card is open, so the scan is bounded rather than proportional.
+ it("gives up rather than walking an entire transcript", () => {
+ const stale = agent("Said this a long time ago.");
+ const filler = Array.from({ length: 600 }, () => update("tool_call"));
+
+ expect(latestAgentMessage([stale, ...filler])).toBeNull();
+ });
+
+ it("collapses a long message onto one line and cuts it on a word", () => {
+ const message = latestAgentMessage([
+ agent(`Rewrote\n the importer.\n${"word ".repeat(120)}`),
+ ]);
+
+ expect(message?.startsWith("Rewrote the importer. word")).toBe(true);
+ expect(message?.endsWith("…")).toBe(true);
+ expect(message).not.toContain("\n");
+ expect(message?.length).toBeLessThanOrEqual(241);
+ });
+
+ it.each([
+ [
+ "the run's closing prose",
+ { final_message: "Opened the PR." },
+ "Opened the PR.",
+ ],
+ [
+ "a run that wrote nothing",
+ { pr_url: "https://example.com/pull/1" },
+ null,
+ ],
+ ["a non-string value", { final_message: 42 }, null],
+ ["no output at all", null, null],
+ ])("takes %s off the run", (_case, output, expected) => {
+ expect(persistedTurnMessage(output as Record<string, unknown> | null)).toBe(
+ expected,
+ );
+ });
+});
diff --git a/products/desktop/packages/core/src/sessions/latestTurnMessage.ts b/products/desktop/packages/core/src/sessions/latestTurnMessage.ts
new file mode 100644
index 000000000000..6d49d55b26c9
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/latestTurnMessage.ts
@@ -0,0 +1,103 @@
+import type { AcpMessage, JsonRpcMessage } from "@posthog/shared";
+import { isJsonRpcNotification } from "@posthog/shared";
+
+/**
+ * The last thing the agent actually said, for surfaces that show a task without
+ * opening it.
+ *
+ * Two sources, because neither covers every task on its own: a session loaded
+ * in this window has the live events, and a cloud run persists the text of each
+ * finished turn on the run itself. A task you have never opened only has the
+ * second; a turn streaming right now only has the first.
+ */
+
+/** The key the cloud relay writes each finished turn's closing prose under. */
+const FINAL_MESSAGE_KEY = "final_message";
+
+/**
+ * How far back a scan walks before giving up. A long session holds tens of
+ * thousands of events and this runs while a card is open on a streaming turn,
+ * so the scan is bounded rather than proportional to the transcript. An agent
+ * message that is further back than this is old enough that the run's persisted
+ * text is the better answer anyway.
+ */
+const MAX_SCANNED_EVENTS = 500;
+
+/** Longer than this and the card is a transcript. Cut on a word boundary. */
+const MAX_MESSAGE_CHARS = 240;
+
+/**
+ * The text of a `session/update` carrying agent prose, or null for anything
+ * else — a thought, a tool call, a user chunk, a response.
+ */
+function agentMessageText(message: JsonRpcMessage): string | null {
+ if (!isJsonRpcNotification(message) || message.method !== "session/update") {
+ return null;
+ }
+ const update = (message.params as { update?: unknown } | undefined)?.update as
+ | {
+ sessionUpdate?: string;
+ content?: { type?: string; text?: string };
+ }
+ | undefined;
+ if (update?.sessionUpdate !== "agent_message_chunk") return null;
+ if (update.content?.type !== "text") return null;
+ return update.content.text ?? null;
+}
+
+/**
+ * The agent's most recent message, assembled from the streamed chunks it came
+ * in as.
+ *
+ * Chunks of one message arrive consecutively, so the message is the run of
+ * chunks ending at the last one: walking back from there stops at the first
+ * event that isn't prose (a tool call, a thought, the user's turn), which is
+ * where that message began.
+ */
+export function latestAgentMessage(
+ events: readonly AcpMessage[] | undefined,
+): string | null {
+ if (!events?.length) return null;
+ const floor = Math.max(0, events.length - MAX_SCANNED_EVENTS);
+ let end = -1;
+ for (let i = events.length - 1; i >= floor; i--) {
+ if (agentMessageText(events[i].message) != null) {
+ end = i;
+ break;
+ }
+ }
+ if (end === -1) return null;
+
+ const chunks: string[] = [];
+ for (let i = end; i >= floor; i--) {
+ const text = agentMessageText(events[i].message);
+ if (text == null) break;
+ chunks.unshift(text);
+ }
+ return condenseTurnMessage(chunks.join(""));
+}
+
+/**
+ * The closing message of the last turn a cloud run finished, which the relay
+ * persists on the run as it ends.
+ */
+export function persistedTurnMessage(
+ output: Record<string, unknown> | null | undefined,
+): string | null {
+ const message = output?.[FINAL_MESSAGE_KEY];
+ return typeof message === "string" ? condenseTurnMessage(message) : null;
+}
+
+/**
+ * One line of prose out of a message that may be many. Markdown is left as
+ * typed — stripping it half-way reads worse than the source does, and the
+ * surfaces that show this clamp to a couple of lines anyway.
+ */
+export function condenseTurnMessage(text: string): string | null {
+ const collapsed = text.replace(/\s+/g, " ").trim();
+ if (!collapsed) return null;
+ if (collapsed.length <= MAX_MESSAGE_CHARS) return collapsed;
+ const cut = collapsed.slice(0, MAX_MESSAGE_CHARS);
+ const lastSpace = cut.lastIndexOf(" ");
+ return `${(lastSpace > MAX_MESSAGE_CHARS / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
index fbfdc70216c8..6e0152872879 100644
--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
@@ -77,7 +77,8 @@ The root `AGENTS.md` architecture rules still apply.
`TaskRowMenuProps`, so the facts and the actions can't drift.
Rename is the one item the tree drops, because it edits in place and there is
no inline editor on a row the keyboard is walking.
- The card also opens on the keyboard's highlight, 350ms after it lands.
+ The card also opens on the keyboard's highlight, 350ms after it lands — on a space row as well as a session one, so walking the tree shows the same card whichever kind of row the highlight lands on.
+ The row that opened it is the only one that may take it away (`openFromKeyboard` / `closeFromKeyboard` on the provider, released the moment a pointer enters any row): the pointer moves the same popup between rows without telling the row that opened it, so an unconditional close on the next keypress reached across and shut a card the pointer was on.
Rows read that highlight from `spaceTreeStore` as a boolean
(`highlightedValue === item.key`) so a keypress re-renders two rows, and the
list still writes it to a ref as well, because the arrow handlers read the
@@ -89,6 +90,39 @@ The root `AGENTS.md` architecture rules still apply.
whole list and passed through `SpaceTaskActionsProvider`, which keeps one pin
and one archive mutation for the tree instead of one per row and keeps them
out of the memo comparisons.
+- **There is one card, not one per row.** `ChannelItemPreviewCardProvider`,
+ mounted once around the whole sidebar, owns the popup; a row is only a
+ `PreviewCard.Trigger` on its handle, carrying what the card should say as the
+ trigger's payload.
+ So the card's queries and derivations run for the row being pointed at rather
+ than once per row in the list, and Base UI skips the open delay when the
+ pointer crosses to another trigger of a card that is already open — which is
+ the point: sliding down the list moves one card instead of re-waiting 400ms
+ on every row.
+ Two things keep that working: a row's payload has to stay referentially stable
+ (memoize the `menu`), and a surface that lists rows has to sit under the
+ provider, or its rows get no card at all.
+- **A space has a card too, on the same handle.** `SpaceHoverCard` is a trigger on the one popup the session rows use, so crossing from a space to a session under it swaps the card's contents instead of closing one popup and opening another. The payload is a discriminated union (`ChannelPreviewPayload`), and `kind` picks `SpacePreview` or `ChannelItemPreview`.
+ It shows who has been working in the space, what it is wired to, and the counts the row draws as dots: the creator leads the avatar group wearing a crown, then whoever ran the newest sessions.
+ The people are not a membership list — the backend has none. They come from `useSpaceOverview`, off the same `space-tree-tasks` page the tree's rows are built from, which the row's own hover prefetch has already warmed, so the card costs no request.
+ The group is `reverse`d, so each face tucks behind the one after it — which puts the creator's right corner under its neighbour, so the crown goes on its left corner instead.
+ `useChannelActions` memoizes its action list, and `ChannelSection` memoizes the payload, because both travel to the card's store on every identity change. Its memo comparator also compares `repositories` by content — the channel list is polled and hands out a new array each time.
+- **The card names the row's marks rather than inventing a second scale.**
+ It spells out the dot's own label and the badges' (`taskDot`, `taskBadges`),
+ and shows the last thing the agent said.
+ It used to show the run's raw status ("Ready", "In progress"), a vocabulary
+ the rows dropped when the dot took over, which left a quiet row sitting under
+ a green "Ready".
+ The message comes from `useLatestTurnMessage`: the live session's events where
+ this window has the session, otherwise the closing prose a cloud run persists
+ to `latest_run.output.final_message`.
+ Neither costs a request.
+- **The card's badges are buttons where they point somewhere; the row's never are.** A row is a `<button>`, so its badges stay spans — the card isn't, so a badge carrying a `url` opens it externally and is underlined, dotted, to say so.
+ `taskBadges` sets the url on the PR badges, and on the origin badge for Slack — the one origin that hands back a place to go (`slack_thread_url` off the run's state), rather than just naming itself.
+ A PR's url reaches the badge by two routes: a cloud run's `pr_url`, or the one the host cached against the task, which `getTaskPrStatus` returns alongside the state so a local PR is clickable too.
+- **The card's `Item`s are `flex-nowrap`, and neither card has a gutter.** quill's `Item` wraps, and a message with a url in it has a min-content wider than the card, which dropped the whole text column onto a line of its own and out past the card's edge.
+ `min-w-0` on the `ItemContent` and `break-words` on the message keep it inside. The `Crowded` story is that case.
+ A row's mark rides beside the title rather than in an `ItemMedia` column: one glyph on one line does not earn an indent down the whole height of the card.
- **A row's own colour utilities outrank quill's highlight styling.** quill
brings a highlighted option's contents to `--foreground` with
`.quill-autocomplete__item[data-highlighted] *`, but that rule lives in the
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx
new file mode 100644
index 000000000000..42e577b98d52
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx
@@ -0,0 +1,191 @@
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import type { Task } from "@posthog/shared/domain-types";
+import type { TaskStatusInput } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+import { Theme } from "@radix-ui/themes";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// The card's status comes from live session/workspace state and a per-task tRPC
+// query, none of which a unit test has. Stubbed at the module boundary, as
+// ChannelItemRow.test.tsx does for the same reason.
+const mocks = vi.hoisted(() => ({ status: null as TaskStatusInput | null }));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskStatus", () => ({
+ useChannelTaskStatus: () => mocks.status,
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
+ useChannels: () => ({ channels: [] }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
+ useFileTaskToChannel: () => vi.fn(),
+}));
+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
+ useFeatureFlag: () => true,
+}));
+
+import {
+ ChannelItemHoverCard,
+ ChannelItemPreviewCardProvider,
+} from "./ChannelItemHoverCard";
+import type { TaskRowMenuProps } from "./TaskRowMenu";
+
+function item(title: string, overrides: Partial<ChannelItemModel> = {}) {
+ return {
+ key: `task:${title}`,
+ kind: "task",
+ id: title,
+ title,
+ ts: Date.parse("2026-07-17T12:00:00.000Z"),
+ createdAt: Date.parse("2026-07-16T12:00:00.000Z"),
+ pinned: false,
+ rawStatus: "completed",
+ environment: "cloud",
+ source: null,
+ needsInput: false,
+ unread: false,
+ authorUser: null,
+ authorName: null,
+ authorUuid: "user-uuid",
+ templateId: null,
+ task: null,
+ ...overrides,
+ } satisfies ChannelItemModel;
+}
+
+function menuFor(model: ChannelItemModel): TaskRowMenuProps {
+ return {
+ kind: "task",
+ id: model.id,
+ title: model.title,
+ isPinned: false,
+ onTogglePin: () => {},
+ };
+}
+
+/** A cloud run that finished a turn, which persists its closing prose. */
+function taskWithFinalMessage(text: string): Task {
+ return {
+ id: "task-1",
+ task_number: 1,
+ slug: "task-1",
+ title: "Investigate signup drop-off",
+ description: "",
+ created_at: "2026-07-16T12:00:00.000Z",
+ updated_at: "2026-07-17T12:00:00.000Z",
+ origin_product: "user_created",
+ latest_run: {
+ id: "run-1",
+ task: "task-1",
+ team: 1,
+ branch: null,
+ status: "completed",
+ log_url: "",
+ error_message: null,
+ output: { final_message: text },
+ state: {},
+ created_at: "2026-07-16T12:00:00.000Z",
+ updated_at: "2026-07-17T12:00:00.000Z",
+ completed_at: "2026-07-17T12:00:00.000Z",
+ },
+ };
+}
+
+function renderRows(models: ChannelItemModel[]) {
+ return render(
+ <Theme>
+ <ChannelItemPreviewCardProvider>
+ {models.map((model) => (
+ <ChannelItemHoverCard
+ key={model.key}
+ item={model}
+ menu={menuFor(model)}
+ >
+ <button type="button">{model.title}</button>
+ </ChannelItemHoverCard>
+ ))}
+ </ChannelItemPreviewCardProvider>
+ </Theme>,
+ );
+}
+
+async function openCardOn(title: string) {
+ await userEvent.hover(screen.getByRole("button", { name: title }));
+ return screen.findByRole("button", { name: "Pin" }, { timeout: 2000 });
+}
+
+beforeEach(() => {
+ mocks.status = null;
+});
+
+describe("ChannelItemHoverCard", () => {
+ it("names the state in the row's own vocabulary, not the run's status", async () => {
+ // `rawStatus: "completed"` — the card used to read this as a green "Ready"
+ // badge while the row's dot said the opposite.
+ mocks.status = { needsPermission: true };
+ renderRows([item("Investigate signup drop-off")]);
+
+ await openCardOn("Investigate signup drop-off");
+
+ expect(screen.getByText("Needs your input")).not.toBeNull();
+ expect(screen.queryByText("Ready")).toBeNull();
+ });
+
+ it("names what the row's badges mean", async () => {
+ mocks.status = { prState: "merged", originProduct: "slack" };
+ renderRows([item("Investigate signup drop-off")]);
+
+ await openCardOn("Investigate signup drop-off");
+
+ expect(screen.getByText("Merged")).not.toBeNull();
+ expect(screen.getByText("Source: Slack")).not.toBeNull();
+ });
+
+ it("shows the last thing the agent said", async () => {
+ mocks.status = {};
+ renderRows([
+ item("Investigate signup drop-off", {
+ task: taskWithFinalMessage("Dropped the retry loop and opened a PR."),
+ }),
+ ]);
+
+ await openCardOn("Investigate signup drop-off");
+
+ expect(
+ screen.getByText("Dropped the retry loop and opened a PR."),
+ ).not.toBeNull();
+ });
+
+ // The point of the shared card: one popup for the whole list, so crossing to
+ // another row moves it rather than opening a second one behind the delay.
+ it("moves to the next row without waiting to open again", async () => {
+ mocks.status = {};
+ renderRows([item("First session"), item("Second session")]);
+ await openCardOn("First session");
+
+ await userEvent.hover(
+ screen.getByRole("button", { name: "Second session" }),
+ );
+
+ // No `findBy`: the card is already showing the second row by the time the
+ // pointer has arrived, which is what "already open" buys.
+ const titles = screen.getAllByText("Second session");
+ expect(titles).toHaveLength(2);
+ expect(screen.getAllByText("First session")).toHaveLength(1);
+ });
+
+ it("leaves a row usable where no list is hosting a card", async () => {
+ mocks.status = {};
+ const model = item("Investigate signup drop-off");
+ render(
+ <Theme>
+ <ChannelItemHoverCard item={model} menu={menuFor(model)}>
+ <button type="button">{model.title}</button>
+ </ChannelItemHoverCard>
+ </Theme>,
+ );
+
+ await userEvent.hover(screen.getByRole("button", { name: model.title }));
+
+ expect(screen.queryByRole("button", { name: "Pin" })).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx
index d19690ea4528..2a43dc8b1267 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx
@@ -1,53 +1,35 @@
import { PreviewCard } from "@base-ui/react/preview-card";
-import { ChatCircleIcon } from "@phosphor-icons/react";
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import { Card } from "@posthog/quill";
import {
- runStatusLabel,
- runStatusVariant,
-} from "@posthog/core/canvas/runStatus";
+ ChannelItemPreview,
+ type ChannelItemPreviewPayload,
+} from "@posthog/ui/features/canvas/components/ChannelItemPreview";
import {
- Avatar,
- AvatarFallback,
- Badge,
- Card,
- Item,
- ItemContent,
- ItemDescription,
- ItemGroup,
- ItemMedia,
- ItemSeparator,
- ItemTitle,
-} from "@posthog/quill";
-import { formatRelativeTimeShort } from "@posthog/shared";
-import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
-import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+ SpacePreview,
+ type SpacePreviewPayload,
+} from "@posthog/ui/features/canvas/components/SpacePreview";
+import type { TaskRowMenuProps } from "@posthog/ui/features/canvas/components/TaskRowMenu";
import {
- TaskRowMenuList,
- type TaskRowMenuProps,
-} from "@posthog/ui/features/canvas/components/TaskRowMenu";
-import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
-import { type ReactNode, useCallback, useEffect, useState } from "react";
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
/**
- * What the card leads with. A canvas gets its template glyph in canvas violet; a
- * task gets the chat glyph the sidebar uses for a task with nothing going on —
- * before this, a task was shown wearing a canvas's icon.
+ * How long the pointer has to rest on a row before its card opens — the first
+ * time. Once a card is open, moving to another row swaps it with no delay at
+ * all (Base UI treats triggers that share a handle as one popup being moved),
+ * which is the whole reason the list shares one card.
*/
-function previewGlyph(item: ChannelItemModel): ReactNode {
- if (item.kind !== "canvas") {
- return <ChatCircleIcon size={15} className="text-gray-10" />;
- }
- // Matches the schema's own default for boards saved before templating.
- return iconForTemplate(item.templateId ?? "freeform", {
- size: 15,
- className: "text-violet-9",
- });
-}
-
-function authorLabel(item: ChannelItemModel): string | null {
- if (item.authorUser) return userDisplayName(item.authorUser);
- return item.authorName;
-}
+const OPEN_DELAY_MS = 400;
+const CLOSE_DELAY_MS = 100;
/**
* How long the keyboard has to rest on a row before its card opens. Long enough
@@ -56,9 +38,179 @@ function authorLabel(item: ChannelItemModel): string | null {
const KEYBOARD_OPEN_DELAY_MS = 350;
/**
- * The row's hover card: what the thing is, who made it, and what you can do to
- * it. Shared by the channel sidebar's rows and the space tree's session rows so
- * the two can't drift into showing different facts or actions for one task.
+ * What the sidebar's one card can be showing. A space and a session are
+ * different cards, but they are the same popup being moved between rows: the
+ * pointer crosses from a space to a session inside it without either card
+ * re-waiting its open delay, which is the whole reason the handle is shared.
+ */
+export type ChannelPreviewPayload =
+ | ({ kind: "item" } & ChannelItemPreviewPayload)
+ | ({ kind: "space" } & SpacePreviewPayload);
+
+/**
+ * The shared card, and who currently owns it.
+ *
+ * Ownership matters because the card is one popup and two things move it. A
+ * keyboard-opened card belongs to the row the highlight is on, and that row
+ * takes it away again when the highlight leaves — but only while it still owns
+ * it. Without that, arrowing on after the pointer had moved the card elsewhere
+ * closed the card out from under the pointer.
+ */
+interface ChannelPreviewCard {
+ handle: PreviewCard.Handle<ChannelPreviewPayload>;
+ /** Open on a row the keyboard has settled on, and claim the card for it. */
+ openFromKeyboard: (triggerId: string) => void;
+ /** Close, but only if the keyboard's card is still this row's. */
+ closeFromKeyboard: (triggerId: string) => void;
+ /** The pointer is driving now; the keyboard no longer owns what it opened. */
+ releaseKeyboard: () => void;
+}
+
+const ChannelItemPreviewHandleContext =
+ createContext<ChannelPreviewCard | null>(null);
+
+/**
+ * One hover card for every session row in the sidebar, rather than one per row.
+ *
+ * Rows are cheap and there are hundreds of them across an expanded tree; a
+ * preview card each meant hundreds of popup roots, each with its own floating
+ * context and open state, built while the list rendered and thrown away when it
+ * scrolled. Here the rows are only triggers on a shared handle, and the card —
+ * with the queries and derivations behind its contents — is built once, for
+ * whichever row is being pointed at.
+ *
+ * Sharing the handle is also what makes sliding down the list feel like one
+ * card moving: Base UI skips the open delay when the pointer crosses to another
+ * trigger of an already-open popup.
+ */
+export function ChannelItemPreviewCardProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const [handle] = useState(() =>
+ PreviewCard.createHandle<ChannelPreviewPayload>(),
+ );
+ const [open, setOpen] = useState(false);
+ const [submenuOpen, setSubmenuOpen] = useState(false);
+ const close = useCallback(() => {
+ setSubmenuOpen(false);
+ handle.close();
+ }, [handle]);
+
+ // Which row's keypress the open card belongs to, if any.
+ const keyboardTrigger = useRef<string | null>(null);
+ const card = useMemo<ChannelPreviewCard>(
+ () => ({
+ handle,
+ openFromKeyboard: (triggerId) => {
+ keyboardTrigger.current = triggerId;
+ handle.open(triggerId);
+ },
+ closeFromKeyboard: (triggerId) => {
+ if (keyboardTrigger.current !== triggerId) return;
+ keyboardTrigger.current = null;
+ handle.close();
+ },
+ releaseKeyboard: () => {
+ keyboardTrigger.current = null;
+ },
+ }),
+ [handle],
+ );
+
+ return (
+ <ChannelItemPreviewHandleContext.Provider value={card}>
+ {children}
+ {/* Controlled so the card survives its own submenu: "File to…" opens in a
+ portal outside the card, and the pointer moving there reads as leaving
+ the card, which would take the menu down with it. */}
+ <PreviewCard.Root
+ handle={handle}
+ open={open || submenuOpen}
+ onOpenChange={setOpen}
+ >
+ {({ payload }) =>
+ payload ? (
+ <PreviewCard.Portal>
+ <PreviewCard.Positioner
+ side="right"
+ align="start"
+ sideOffset={10}
+ className="z-50"
+ >
+ {/* The card is quill's `Card` and `Item` parts throughout — the
+ popup itself carries no surface styling, so this window's
+ hover card matches every other card in the app rather than a
+ hand-tuned shadow of its own. The card's own padding is off
+ (`gap-0 py-0`): each section pays for its own inset, which is
+ what lets the rules run edge to edge and the action rows
+ highlight full width. */}
+ <PreviewCard.Popup
+ render={
+ <Card
+ size="sm"
+ className="w-72 gap-0 border border-border py-0 shadow-md"
+ />
+ }
+ >
+ {payload.kind === "space" ? (
+ <SpacePreview payload={payload} onAction={close} />
+ ) : (
+ <ChannelItemPreview
+ // Keyed on the row, so crossing to another one unmounts
+ // the card rather than reusing it — which is what lowers
+ // the submenu flag. Base UI reports no close on unmount,
+ // and a flag left raised pins `open || submenuOpen` true
+ // on a card nothing can then dismiss.
+ key={payload.item.key}
+ payload={payload}
+ onAction={close}
+ onSubmenuOpenChange={setSubmenuOpen}
+ />
+ )}
+ </PreviewCard.Popup>
+ </PreviewCard.Positioner>
+ </PreviewCard.Portal>
+ ) : null
+ }
+ </PreviewCard.Root>
+ </ChannelItemPreviewHandleContext.Provider>
+ );
+}
+
+/**
+ * Opens the shared card on a row the keyboard has settled on, and takes it away
+ * again the moment the highlight moves — a card still open once the highlight
+ * has gone points at the wrong row.
+ *
+ * "Takes it away" only where the keyboard's card is still this row's. The
+ * pointer moves the same popup between rows without telling the row that opened
+ * it, so a highlight leaving after that would otherwise close a card the
+ * pointer is sitting on.
+ */
+function useKeyboardPreview(
+ card: ChannelPreviewCard | null,
+ triggerId: string,
+ highlighted: boolean,
+): void {
+ useEffect(() => {
+ if (!card || !highlighted) return;
+ const timer = setTimeout(
+ () => card.openFromKeyboard(triggerId),
+ KEYBOARD_OPEN_DELAY_MS,
+ );
+ return () => {
+ clearTimeout(timer);
+ card.closeFromKeyboard(triggerId);
+ };
+ }, [card, highlighted, triggerId]);
+}
+
+/**
+ * A row that shows the shared preview card while it is pointed at. Shared by
+ * the channel sidebar's rows and the space tree's session rows so the two can't
+ * drift into showing different facts or actions for one task.
*
* `children` is the row itself, handed to the trigger.
*/
@@ -74,123 +226,87 @@ export function ChannelItemHoverCard({
highlighted?: boolean;
children: ReactNode;
}) {
- const [cardOpen, setCardOpen] = useState(false);
- const [submenuOpen, setSubmenuOpen] = useState(false);
- const [keyboardOpen, setKeyboardOpen] = useState(false);
- // Stable: `TaskRowMenuList` builds its item components from these, so a new
- // identity each render would remount every button in the card.
- const closeCard = useCallback(() => setCardOpen(false), []);
- const statusLabel = runStatusLabel(item.rawStatus);
- const author = authorLabel(item);
+ const card = useContext(ChannelItemPreviewHandleContext);
+ // The card reads the row it is over off the active trigger, so what the row
+ // has to say travels as the trigger's payload. Kept stable, because a new
+ // identity writes it to the card's store again.
+ const payload = useMemo(
+ () => ({ kind: "item" as const, item, menu }),
+ [item, menu],
+ );
+ // Ours rather than Base UI's own, because opening from the keyboard means
+ // naming the trigger to open.
+ const triggerId = useId();
+ useKeyboardPreview(card, triggerId, highlighted);
+ const row = (
+ // Pointing at any row hands the card to the pointer, so the row the
+ // keyboard opened it on stops trying to close it.
+ <div className="flex min-w-0" onPointerEnter={card?.releaseKeyboard}>
+ {children}
+ </div>
+ );
- // Closing is immediate: once the highlight has moved, a card still open
- // points at the wrong row.
- useEffect(() => {
- if (!highlighted) {
- setKeyboardOpen(false);
- return;
- }
- const timer = setTimeout(
- () => setKeyboardOpen(true),
- KEYBOARD_OPEN_DELAY_MS,
- );
- return () => clearTimeout(timer);
- }, [highlighted]);
+ // No provider, no card. A row still has its right-click menu, and every fact
+ // the card names is on the row itself.
+ if (!card) return row;
+
+ return (
+ <PreviewCard.Trigger
+ handle={card.handle}
+ payload={payload}
+ id={triggerId}
+ delay={OPEN_DELAY_MS}
+ closeDelay={CLOSE_DELAY_MS}
+ render={row}
+ />
+ );
+}
+
+/**
+ * A space row that shows the shared preview card while it is pointed at, with
+ * the space's own card in it rather than a session's.
+ *
+ * The same handle as the session rows on purpose: a space and the sessions
+ * under it are one list to the pointer, so crossing between them swaps the
+ * card's contents instead of closing one popup and opening another. It opens on
+ * the keyboard's highlight the way they do, too — walking the tree shows the
+ * same card whichever kind of row the highlight lands on.
+ */
+export function SpaceHoverCard({
+ space,
+ highlighted = false,
+ children,
+}: {
+ space: SpacePreviewPayload;
+ /** The keyboard is on this row, which opens the card as hovering does. */
+ highlighted?: boolean;
+ children: ReactNode;
+}) {
+ const card = useContext(ChannelItemPreviewHandleContext);
+ // Stable for the reason a session row's is: a new identity writes the payload
+ // to the card's store again. The caller memoizes what it passes.
+ const payload = useMemo(
+ () => ({ kind: "space" as const, ...space }),
+ [space],
+ );
+ const triggerId = useId();
+ useKeyboardPreview(card, triggerId, highlighted);
+ const row = (
+ <div className="flex min-w-0" onPointerEnter={card?.releaseKeyboard}>
+ {children}
+ </div>
+ );
+
+ if (!card) return row;
return (
- // Controlled so the card survives its own submenu: "File to…" opens in a
- // portal outside the card, and the pointer moving there reads as leaving the
- // card, which would take the menu down with it.
- <PreviewCard.Root
- open={cardOpen || submenuOpen || keyboardOpen}
- onOpenChange={setCardOpen}
- >
- <PreviewCard.Trigger
- delay={400}
- closeDelay={100}
- render={<div className="flex min-w-0">{children}</div>}
- />
- <PreviewCard.Portal>
- <PreviewCard.Positioner
- side="right"
- align="start"
- sideOffset={10}
- className="z-50"
- >
- {/* The card is quill's `Card` and `Item` parts throughout — the popup
- itself carries no surface styling, so this window's hover card
- matches every other card in the app rather than a hand-tuned
- shadow of its own. The card's own padding is off (`gap-0 py-0`):
- each section pays for its own inset, which is what lets the rules
- run edge to edge and the action rows highlight full width. */}
- <PreviewCard.Popup
- render={
- <Card
- size="sm"
- className="w-64 gap-0 border border-border py-0 shadow-md"
- />
- }
- >
- <ItemGroup className="gap-0!">
- <Item size="xs" className="p-2">
- <ItemMedia variant="icon" className="size-5">
- {previewGlyph(item)}
- </ItemMedia>
- <ItemContent>
- <ItemTitle>{item.title}</ItemTitle>
- <ItemDescription>
- {item.kind === "canvas" ? "Canvas" : "Task"} · updated{" "}
- {formatRelativeTimeShort(item.ts)}
- </ItemDescription>
- </ItemContent>
- </Item>
- {statusLabel && (
- <div className="px-2 pb-2">
- <Badge variant={runStatusVariant(item.rawStatus)}>
- {statusLabel}
- </Badge>
- </div>
- )}
- {author && (
- <>
- {/* Every section of the card gets the rule above it, canvases
- included — the author is a different fact from the thing's
- identity whether or not there are actions under it. */}
- <ItemSeparator className="my-0" />
- <Item size="xs" className="p-2">
- <ItemMedia variant="icon">
- {item.authorUser ? (
- <UserAvatar size="xs" user={item.authorUser} />
- ) : (
- <Avatar size="xs">
- <AvatarFallback>
- {author.charAt(0).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- )}
- </ItemMedia>
- <ItemContent className="gap-0">
- <ItemTitle>{author}</ItemTitle>
- <ItemDescription>Created by</ItemDescription>
- </ItemContent>
- </Item>
- </>
- )}
- {/* The row's actions live here now: a row at rest shows its
- status, and the card is already the surface you're pointing at
- when you want to do something to it. */}
- <ItemSeparator className="my-0" />
- <div className="p-1">
- <TaskRowMenuList
- menu={menu}
- onAction={closeCard}
- onSubmenuOpenChange={setSubmenuOpen}
- />
- </div>
- </ItemGroup>
- </PreviewCard.Popup>
- </PreviewCard.Positioner>
- </PreviewCard.Portal>
- </PreviewCard.Root>
+ <PreviewCard.Trigger
+ handle={card.handle}
+ payload={payload}
+ id={triggerId}
+ delay={OPEN_DELAY_MS}
+ closeDelay={CLOSE_DELAY_MS}
+ render={row}
+ />
);
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx
new file mode 100644
index 000000000000..0062dfe88701
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx
@@ -0,0 +1,169 @@
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import { Card } from "@posthog/quill";
+import type { Task, TaskRun } from "@posthog/shared/domain-types";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ChannelItemPreview } from "./ChannelItemPreview";
+import type { TaskRowMenuProps } from "./TaskRowMenu";
+
+/**
+ * The card as the list shows it — the popup itself carries no styling of its
+ * own, so the story supplies the same quill `Card` the shared preview card
+ * renders it into.
+ */
+function CardFrame({
+ item,
+ menu,
+}: {
+ item: ChannelItemModel;
+ menu: TaskRowMenuProps;
+}) {
+ return (
+ <div className="p-4">
+ <Card
+ size="sm"
+ className="w-72 gap-0 border border-border py-0 shadow-md"
+ >
+ <ChannelItemPreview
+ payload={{ item, menu }}
+ onAction={() => {}}
+ onSubmenuOpenChange={() => {}}
+ />
+ </Card>
+ </div>
+ );
+}
+
+function run(overrides: Partial<TaskRun>): TaskRun {
+ return {
+ id: "run-1",
+ task: "task-1",
+ team: 1,
+ branch: null,
+ environment: "cloud",
+ status: "completed",
+ log_url: "",
+ error_message: null,
+ output: null,
+ state: {},
+ created_at: "2026-07-16T12:00:00.000Z",
+ updated_at: "2026-07-17T12:00:00.000Z",
+ completed_at: "2026-07-17T12:00:00.000Z",
+ ...overrides,
+ };
+}
+
+function task(latestRun: TaskRun, overrides: Partial<Task> = {}): Task {
+ return {
+ id: "task-1",
+ task_number: 41,
+ slug: "clean-up-the-importer",
+ title: "Clean up the importer",
+ description: "",
+ created_at: "2026-07-16T12:00:00.000Z",
+ updated_at: "2026-07-17T12:00:00.000Z",
+ origin_product: "user_created",
+ latest_run: latestRun,
+ ...overrides,
+ };
+}
+
+function item(
+ latestRun: TaskRun,
+ overrides: Partial<ChannelItemModel> = {},
+ taskOverrides: Partial<Task> = {},
+): ChannelItemModel {
+ return {
+ key: "task:task-1",
+ kind: "task",
+ id: "task-1",
+ title: "Clean up the importer",
+ ts: Date.parse("2026-07-17T12:00:00.000Z"),
+ createdAt: Date.parse("2026-07-16T12:00:00.000Z"),
+ pinned: false,
+ rawStatus: latestRun.status,
+ environment: "cloud",
+ source: null,
+ needsInput: false,
+ unread: false,
+ authorUser: {
+ id: 1,
+ uuid: "user-uuid",
+ first_name: "Ada",
+ last_name: "Lovelace",
+ email: "[email protected]",
+ },
+ authorName: null,
+ authorUuid: "user-uuid",
+ templateId: null,
+ task: task(latestRun, taskOverrides),
+ ...overrides,
+ };
+}
+
+const menu: TaskRowMenuProps = {
+ kind: "task",
+ id: "task-1",
+ title: "Clean up the importer",
+ isPinned: false,
+ channelId: "channel-1",
+ onRename: () => {},
+ onAddToCommandCenter: () => {},
+ onTogglePin: () => {},
+ onArchive: () => {},
+};
+
+const meta = {
+ title: "Canvas/ChannelItemPreview",
+ component: CardFrame,
+ args: { menu },
+} satisfies Meta<typeof CardFrame>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** A finished run: the quiet dot, what the agent signed off with, and its PR. */
+export const Finished: Story = {
+ args: {
+ item: item(
+ run({
+ output: {
+ final_message:
+ "Dropped the retry loop, moved the backfill behind a flag, and opened a PR. The importer now fails closed on a bad row instead of skipping it.",
+ pr_url: "https://github.com/posthog/posthog/pull/1",
+ },
+ }),
+ ),
+ },
+};
+
+/** A sandbox coming up: the dot spins and there is nothing said yet. */
+export const Starting: Story = {
+ args: { item: item(run({ status: "queued", output: null })) },
+};
+
+/**
+ * The widest the card gets: a title that wraps, a full message, and both an
+ * origin and a PR badge, each pointing somewhere. Every line still has to start
+ * in the title's column.
+ */
+export const Crowded: Story = {
+ args: {
+ item: item(
+ run({
+ output: {
+ // Written to exercise the card, not transcribed from anywhere: long
+ // enough to clamp at three lines, and carrying a url whose unbroken
+ // width is what used to push the text column out of the card.
+ final_message:
+ "Swapped the retry loop for a bounded backoff, so the importer now fails closed on a bad row instead of skipping it. The remaining cleanup is tracked in https://github.com/PostHog/posthog/pull/12345 for a follow-up.",
+ pr_url: "https://github.com/posthog/posthog/pull/1",
+ },
+ state: {
+ slack_thread_url: "https://example.slack.com/archives/C1/p1",
+ },
+ }),
+ { title: "Clean up the importer's retry handling" },
+ { origin_product: "slack" },
+ ),
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx
new file mode 100644
index 000000000000..935cc72471e5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx
@@ -0,0 +1,284 @@
+import { ChatCircleIcon } from "@phosphor-icons/react";
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import {
+ Avatar,
+ AvatarFallback,
+ cn,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemSeparator,
+ ItemTitle,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@posthog/quill";
+import { formatRelativeTimeShort } from "@posthog/shared";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+import {
+ TaskRowMenuList,
+ type TaskRowMenuProps,
+} from "@posthog/ui/features/canvas/components/TaskRowMenu";
+import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
+import { useLatestTurnMessage } from "@posthog/ui/features/canvas/hooks/useLatestTurnMessage";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { TaskDotMark } from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";
+import {
+ type TaskBadge,
+ type TaskDot,
+ TONE_ICON_VAR,
+ taskBadges,
+ taskDot,
+} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { type ReactNode, useEffect } from "react";
+
+/** Matches the rows' own tooltip delay, so the card doesn't feel slower. */
+const TOOLTIP_DELAY_MS = 200;
+
+/** What the card is about: the row that is being pointed at. */
+export interface ChannelItemPreviewPayload {
+ item: ChannelItemModel;
+ menu: TaskRowMenuProps;
+}
+
+/**
+ * The mark the row it came from leads with, which the card wears beside the
+ * title rather than in a gutter of its own.
+ *
+ * A session's mark is its state dot rather than a generic chat glyph, which
+ * said nothing the title didn't. A canvas has no run behind it and keeps its
+ * template glyph in canvas violet; a session with no run to read falls back to
+ * the chat glyph rather than inventing a state.
+ */
+function previewGlyph(item: ChannelItemModel, dot: TaskDot | null): ReactNode {
+ if (item.kind === "canvas") {
+ // Matches the schema's own default for boards saved before templating.
+ return iconForTemplate(item.templateId ?? "freeform", {
+ size: 15,
+ className: "text-violet-9",
+ });
+ }
+ if (!dot) return <ChatCircleIcon size={15} className="text-gray-10" />;
+ return <TaskDotMark dot={dot} />;
+}
+
+function authorLabel(item: ChannelItemModel): string | null {
+ if (item.authorUser) return userDisplayName(item.authorUser);
+ return item.authorName;
+}
+
+/**
+ * Who made it, as the avatar alone. The name is worth a line of the card only
+ * where the avatar can't carry it, so it goes to the label and a tooltip
+ * instead of a row of its own.
+ */
+function AuthorAvatar({ item }: { item: ChannelItemModel }) {
+ const author = authorLabel(item);
+ if (!author) return null;
+ const label = `Created by ${author}`;
+ return (
+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>
+ {/* `disableHoverablePopup` and `pointer-events-none` for the reason the
+ rows' tooltips take them: a popup the pointer can hold open sits over
+ the card and swallows what is under it. */}
+ <Tooltip disableHoverablePopup>
+ <TooltipTrigger
+ render={
+ // `role="img"` for the same reason the row's badges take one: the
+ // avatar is a fact about the item, and it needs a name a screen
+ // reader can read.
+ // `flex`: quill's avatar is an inline-flex box, so an inline
+ // wrapper carries the line box's descender space with it and the
+ // avatar sits high in a taller container.
+ <span aria-label={label} role="img" className="flex shrink-0">
+ {item.authorUser ? (
+ <UserAvatar size="xs" user={item.authorUser} />
+ ) : (
+ <Avatar size="xs">
+ <AvatarFallback>
+ {author.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ )}
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="pointer-events-none select-none">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
+
+/**
+ * One of the row's badges. A badge that points somewhere — a PR — is a button
+ * that opens it, which the row itself can't offer: a row is a `<button>`, so its
+ * badges have to stay spans. The card is the surface where they can be clicked.
+ */
+function Badge({ badge: { Icon, label, tone, url } }: { badge: TaskBadge }) {
+ const glyph = (
+ // An explicit `color` (an SVG fill) rather than a text-* class, the same way
+ // the row's badges are drawn.
+ <Icon
+ aria-hidden
+ size={11}
+ weight={tone ? "fill" : "regular"}
+ color={tone ? TONE_ICON_VAR[tone] : undefined}
+ />
+ );
+ const className = "flex items-center gap-1 text-muted-foreground text-xs";
+ if (!url) {
+ return (
+ <span className={className}>
+ {glyph}
+ {label}
+ </span>
+ );
+ }
+ return (
+ <button
+ type="button"
+ title={url}
+ className={cn(
+ className,
+ // Underlined at rest, dotted, so the badge that can be clicked is
+ // marked as such without shouting over the badges that can't.
+ "cursor-pointer rounded-xs underline decoration-dotted underline-offset-2 hover:text-foreground hover:decoration-solid focus-visible:outline-2 focus-visible:outline-ring",
+ )}
+ onClick={() => openExternalUrl(url)}
+ >
+ {glyph}
+ {label}
+ </button>
+ );
+}
+
+/**
+ * What the row's marks mean, in words: the dot's own label, the last thing the
+ * agent said, then the badges'.
+ *
+ * The card is where the sidebar's vocabulary gets spelled out, so it says
+ * exactly what the row says rather than a second opinion — it used to show the
+ * run's raw status ("Ready", "In progress"), a scale the rows stopped using
+ * when the dot took over, so a quiet row could sit under a green "Ready" badge
+ * and a working one under nothing at all.
+ *
+ * Laid out as the same `Item` as the header above it, and like it carries no
+ * gutter: the dot the state belongs to is already up beside the title, and
+ * drawing it twice would make one state look like two.
+ */
+function ItemSignals({
+ dot,
+ badges,
+ message,
+}: {
+ dot: TaskDot;
+ badges: TaskBadge[];
+ message: string | null;
+}) {
+ return (
+ <>
+ <ItemSeparator className="my-0" />
+ {/* `flex-nowrap`: quill's `Item` wraps, and a message with a url in it has
+ a min-content wider than the card, which dropped this column onto a
+ line of its own and out past the card's edge. */}
+ <Item size="xs" className="flex-nowrap items-start p-2">
+ <ItemContent className="min-w-0 gap-1.5">
+ <span className="text-xs">{dot.label}</span>
+ {message && (
+ // Three lines: enough for the agent's closing sentence, short of
+ // turning the card into a transcript you have to read.
+ <p className="line-clamp-3 break-words text-muted-foreground text-xs leading-snug">
+ {message}
+ </p>
+ )}
+ {badges.length > 0 && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {badges.map((badge) => (
+ <Badge key={badge.key} badge={badge} />
+ ))}
+ </div>
+ )}
+ </ItemContent>
+ </Item>
+ </>
+ );
+}
+
+/**
+ * The contents of a row's hover card: what the thing is, what its marks mean,
+ * the last thing the agent said, who made it, and what you can do to it.
+ *
+ * Rendered by the one card the list shares, from the payload of whichever
+ * trigger is active — so the hooks in here run for the row being pointed at,
+ * once, rather than once per row in the list.
+ */
+export function ChannelItemPreview({
+ payload,
+ onAction,
+ onSubmenuOpenChange,
+}: {
+ payload: ChannelItemPreviewPayload;
+ onAction: () => void;
+ onSubmenuOpenChange: (open: boolean) => void;
+}) {
+ const { item, menu } = payload;
+ // The submenu flag lives on the provider, and Base UI reports no close when
+ // the menu goes away with its card. Lower it here, so a card left with
+ // "File to…" open cannot pin the shared popup open behind it.
+ useEffect(() => () => onSubmenuOpenChange(false), [onSubmenuOpenChange]);
+ // The PR lookup runs here even where the row skipped it (the space tree does,
+ // to stay off the host): a hover is one row at a time and a deliberate ask,
+ // and the card is the surface that should be able to say "merged".
+ const status = useChannelTaskStatus(item);
+ const message = useLatestTurnMessage(item.task);
+ const dot = status ? taskDot(status) : null;
+
+ return (
+ <ItemGroup className="gap-0!">
+ <Item size="xs" className="flex-nowrap p-2">
+ <ItemContent className="min-w-0">
+ {/* No gutter: the mark is one glyph on one line, and a column for it
+ indents everything under it for the whole height of the card. */}
+ <ItemTitle className="flex items-baseline gap-2 break-words">
+ <span className="flex size-4 shrink-0 translate-y-0.5 items-center justify-center">
+ {previewGlyph(item, dot)}
+ </span>
+ <span className="min-w-0">{item.title}</span>
+ </ItemTitle>
+ <ItemDescription>
+ {item.kind === "canvas" ? "Canvas" : "Task"} · updated{" "}
+ {formatRelativeTimeShort(item.ts)}
+ </ItemDescription>
+ </ItemContent>
+ {/* Who made it rides on the identity row rather than taking a row of
+ its own — the card is a glance, and a line of chrome for a name is
+ a line the agent's own words could have had. Top-aligned: it belongs
+ to the title, not to the block of text under it. */}
+ <ItemActions className="self-start">
+ <AuthorAvatar item={item} />
+ </ItemActions>
+ </Item>
+ {dot && status && (
+ <ItemSignals dot={dot} badges={taskBadges(status)} message={message} />
+ )}
+ {/* The row's actions live here now: a row at rest shows its status, and
+ the card is already the surface you're pointing at when you want to do
+ something to it. */}
+ <ItemSeparator className="my-0" />
+ <div className="p-1">
+ <TaskRowMenuList
+ menu={menu}
+ onAction={onAction}
+ onSubmenuOpenChange={onSubmenuOpenChange}
+ />
+ </div>
+ </ItemGroup>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
index 9be41f4fee5f..6dfd96448803 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
@@ -4,6 +4,7 @@ import type { TaskStatusInput } from "@posthog/ui/features/sidebar/components/it
import { Theme } from "@radix-ui/themes";
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
+import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
// The row's status comes from live session/workspace state and a per-task tRPC
@@ -25,6 +26,7 @@ vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
}));
import { usePendingCanvasDeleteStore } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";
+import { ChannelItemPreviewCardProvider } from "./ChannelItemHoverCard";
import { ChannelItemRow } from "./ChannelItemRow";
const actions = {
@@ -57,14 +59,24 @@ function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {
};
}
-function renderRow(model: ChannelItemModel) {
+/**
+ * The list's rows share one preview card, hung off a provider above them, so a
+ * row on its own has no card to open — every hover assertion here needs it.
+ */
+function renderInList(row: ReactNode) {
return render(
<Theme>
- <ChannelItemRow actions={actions} isActive={false} item={model} />
+ <ChannelItemPreviewCardProvider>{row}</ChannelItemPreviewCardProvider>
</Theme>,
);
}
+function renderRow(model: ChannelItemModel) {
+ return renderInList(
+ <ChannelItemRow actions={actions} isActive={false} item={model} />,
+ );
+}
+
beforeEach(() => {
mocks.status = null;
usePendingCanvasDeleteStore.setState({ pending: {} });
@@ -283,16 +295,14 @@ describe("ChannelItemRow", () => {
onRename?: () => void;
onAddToCommandCenter?: () => void;
}) {
- return render(
- <Theme>
- <ChannelItemRow
- actions={actions}
- isActive={false}
- item={item()}
- onRename={overrides.onRename ?? (() => {})}
- onAddToCommandCenter={overrides.onAddToCommandCenter}
- />
- </Theme>,
+ return renderInList(
+ <ChannelItemRow
+ actions={actions}
+ isActive={false}
+ item={item()}
+ onRename={overrides.onRename ?? (() => {})}
+ onAddToCommandCenter={overrides.onAddToCommandCenter}
+ />,
);
}
@@ -366,10 +376,8 @@ describe("ChannelItemRow", () => {
id: "c1",
title: "Web analytics overview",
});
- render(
- <Theme>
- <ChannelItemRow actions={actions} isActive={false} item={canvas} />
- </Theme>,
+ renderInList(
+ <ChannelItemRow actions={actions} isActive={false} item={canvas} />,
);
await userEvent.hover(screen.getByText("Web analytics overview"));
@@ -393,14 +401,12 @@ describe("ChannelItemRow", () => {
id: "c1",
title: "Web analytics overview",
});
- render(
- <Theme>
- <ChannelItemRow
- actions={{ ...actions, remove }}
- isActive={false}
- item={canvas}
- />
- </Theme>,
+ renderInList(
+ <ChannelItemRow
+ actions={{ ...actions, remove }}
+ isActive={false}
+ item={canvas}
+ />,
);
await userEvent.hover(screen.getByText("Web analytics overview"));
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index 4def1ad4702b..d8bb19d4dd0b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -37,7 +37,13 @@ import {
} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";
import { SESSION_ROW_ATTRIBUTE } from "@posthog/ui/features/sidebar/useMarqueeSelection";
-import { type DragEvent, type ReactNode, useCallback, useState } from "react";
+import {
+ type DragEvent,
+ type ReactNode,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
/**
* What a row can do. One object per channel rather than closures per item, so
@@ -189,29 +195,35 @@ export function ChannelItemRow({
// A canvas gets the same menu with the items it actually has: pin, and delete
// instead of archive. Filing and command-centre cells are task-shaped, and the
// menu drops them rather than showing them dead.
- const menu: TaskRowMenuProps =
- item.kind === "canvas"
- ? {
- kind: "canvas",
- id: item.id,
- title: item.title,
- isPinned: item.pinned,
- onTogglePin: () => actions.togglePin(item),
- // Confirm first, like the canvas menus in the artifacts grid and the
- // canvas header: the canvas and its history go for everyone.
- onDelete: () => setConfirmDeleteOpen(true),
- }
- : {
- kind: "task",
- id: item.id,
- title: item.title,
- isPinned: item.pinned,
- channelId,
- onAddToCommandCenter,
- onRename,
- onTogglePin: () => actions.togglePin(item),
- onArchive: () => actions.archive(item),
- };
+ //
+ // Memoized because it travels to the shared preview card as the trigger's
+ // payload, which is written to the card's store whenever its identity changes.
+ const menu: TaskRowMenuProps = useMemo(
+ () =>
+ item.kind === "canvas"
+ ? {
+ kind: "canvas",
+ id: item.id,
+ title: item.title,
+ isPinned: item.pinned,
+ onTogglePin: () => actions.togglePin(item),
+ // Confirm first, like the canvas menus in the artifacts grid and
+ // the canvas header: the canvas and its history go for everyone.
+ onDelete: () => setConfirmDeleteOpen(true),
+ }
+ : {
+ kind: "task",
+ id: item.id,
+ title: item.title,
+ isPinned: item.pinned,
+ channelId,
+ onAddToCommandCenter,
+ onRename,
+ onTogglePin: () => actions.togglePin(item),
+ onArchive: () => actions.archive(item),
+ },
+ [item, channelId, actions, onAddToCommandCenter, onRename],
+ );
if (isEditing) {
return (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
index ceef53dce551..7aa2d40e068a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
@@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({
name: string;
channelType: "public" | "personal";
starred: boolean;
+ repositories: string[];
+ createdBy: null;
}[],
tasks: [] as {
id: string;
@@ -130,18 +132,24 @@ const ME = {
name: "me",
channelType: "personal" as const,
starred: false,
+ repositories: [],
+ createdBy: null,
};
const ENG = {
id: "eng-id",
name: "engineering",
channelType: "public" as const,
starred: false,
+ repositories: [],
+ createdBy: null,
};
const DESIGN = {
id: "design-id",
name: "design",
channelType: "public" as const,
starred: false,
+ repositories: [],
+ createdBy: null,
};
function renderList() {
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index b01597aca909..eb038941a4f1 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -49,9 +49,14 @@ import {
TooltipTrigger,
} from "@posthog/quill";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
-import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
+import {
+ ChannelItemHoverCard,
+ SpaceHoverCard,
+} from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
+import type { ChannelActionItem } from "@posthog/ui/features/canvas/components/channelActions";
import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";
import { RenameChannelModal } from "@posthog/ui/features/canvas/components/RenameChannelModal";
+import type { SpacePreviewPayload } from "@posthog/ui/features/canvas/components/SpacePreview";
import {
TaskRowContextMenu,
type TaskRowMenuProps,
@@ -453,17 +458,23 @@ const SpaceTaskRow = memo(function SpaceTaskRow({
// The tree only lists sessions, so this is always the task menu. Rename is
// the one item the space's own list has and this doesn't, because it edits in
// place and there is no inline editor on a row the keyboard is walking.
- const menu: TaskRowMenuProps = {
- kind: "task",
- id: item.id,
- title: item.title,
- isPinned: item.pinned,
- // Ticks the space the session is already in, inside "File to…".
- channelId: spaceId,
- onAddToCommandCenter: actions.commandCenterAssigner(item.id),
- onTogglePin: () => actions.togglePin(item),
- onArchive: () => actions.archive(item),
- };
+ //
+ // Memoized because it travels to the shared preview card as the trigger's
+ // payload, which is written to the card's store whenever its identity changes.
+ const menu: TaskRowMenuProps = useMemo(
+ () => ({
+ kind: "task",
+ id: item.id,
+ title: item.title,
+ isPinned: item.pinned,
+ // Ticks the space the session is already in, inside "File to…".
+ channelId: spaceId,
+ onAddToCommandCenter: actions.commandCenterAssigner(item.id),
+ onTogglePin: () => actions.togglePin(item),
+ onArchive: () => actions.archive(item),
+ }),
+ [item, spaceId, actions],
+ );
const row = (
<SpaceRowSurface
@@ -667,19 +678,6 @@ function SpaceTaskRows({
);
}
-// One actionable entry in a channel's menu, rendered the same whether it
-// surfaces in the hover "..." dropdown or the right-click context menu.
-type ChannelActionItem = {
- key: string;
- label: string;
- icon: ReactNode;
- onSelect: () => void;
- variant?: "destructive";
- disabled?: boolean;
- // Draw a divider above this item to separate it from the previous group.
- separatorBefore?: boolean;
-};
-
// The channel actions (star, copy link, rename, delete) plus the rename-modal
// state they drive. Single source of truth so the dropdown and context menus
// stay in lockstep — add an action here and both surfaces pick it up.
@@ -757,41 +755,47 @@ function useChannelActions(channel: Channel): {
}
};
- const actions: ChannelActionItem[] = [
- {
- key: "star",
- label: isStarred ? `Unstar ${noun}` : `Star ${noun}`,
- icon: <StarIcon size={14} weight={isStarred ? "fill" : "regular"} />,
- onSelect: () => {
- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
- action_type: isStarred ? "unstar" : "star",
- surface: "sidebar",
- channel_id: channel.id,
- });
- toggleStar();
+ // Memoized because it travels to the shared preview card as the space
+ // trigger's payload, which is written to the card's store whenever its
+ // identity changes.
+ const actions: ChannelActionItem[] = useMemo(
+ () => [
+ {
+ key: "star",
+ label: isStarred ? `Unstar ${noun}` : `Star ${noun}`,
+ icon: <StarIcon size={14} weight={isStarred ? "fill" : "regular"} />,
+ onSelect: () => {
+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
+ action_type: isStarred ? "unstar" : "star",
+ surface: "sidebar",
+ channel_id: channel.id,
+ });
+ toggleStar();
+ },
+ },
+ {
+ key: "copy-link",
+ label: "Copy link",
+ icon: <LinkIcon size={14} />,
+ onSelect: () => void copyChannelLink(channel.id, "sidebar"),
+ },
+ {
+ key: "rename",
+ label: `Rename ${noun}…`,
+ icon: <PencilSimpleIcon size={14} />,
+ separatorBefore: true,
+ onSelect: () => setRenameOpen(true),
+ },
+ {
+ key: "delete",
+ label: `Delete ${noun}…`,
+ icon: <TrashIcon size={14} />,
+ variant: "destructive",
+ onSelect: () => setConfirmDeleteOpen(true),
},
- },
- {
- key: "copy-link",
- label: "Copy link",
- icon: <LinkIcon size={14} />,
- onSelect: () => void copyChannelLink(channel.id, "sidebar"),
- },
- {
- key: "rename",
- label: `Rename ${noun}…`,
- icon: <PencilSimpleIcon size={14} />,
- separatorBefore: true,
- onSelect: () => setRenameOpen(true),
- },
- {
- key: "delete",
- label: `Delete ${noun}…`,
- icon: <TrashIcon size={14} />,
- variant: "destructive",
- onSelect: () => setConfirmDeleteOpen(true),
- },
- ];
+ ],
+ [channel.id, isStarred, noun, toggleStar],
+ );
return {
actions,
@@ -960,6 +964,26 @@ const ChannelSection = memo(
isDeleting,
} = useChannelActions(channel);
+ // A boolean rather than the value itself, so a keypress re-renders only the
+ // two rows whose answer changed. The row's autocomplete value is the space
+ // id, which is what the keyboard's highlight holds.
+ const isHighlighted = useSpaceTreeStore(
+ (s) => s.highlightedValue === channel.id,
+ );
+
+ // What the shared card says about this space. Memoized because a new
+ // identity is written to the card's store again, and the counts change on
+ // every feed poll.
+ const preview: SpacePreviewPayload = useMemo(
+ () => ({
+ channel,
+ unreadSessions,
+ blockedSessions,
+ actions,
+ }),
+ [channel, unreadSessions, blockedSessions, actions],
+ );
+
const glyph = channelGlyph(channel.name, {
size: 14,
space: spacesLayout,
@@ -997,94 +1021,106 @@ const ChannelSection = memo(
>
{/* The "# name" opens the channel sidebar; the glyph doubles as the
caret that opens the space's recent tasks below it. Right-clicking
- opens the same actions as the "..." menu. */}
- <ContextMenu>
- <ContextMenuTrigger
- render={
- <SpaceRowSurface
- asOption={spacesLayout}
- optionValue={channel.id}
- // An open space hands the fill to the session under it: the row
- // you are in is the one the fill is for, and two of them stacked
- // reads as two selections.
- data-selected={(isActive && !expanded) || undefined}
- onClick={() => openChannel(channel)}
- {...focusProps}
- className={spacesLayout ? "pl-2" : undefined}
- >
- {onToggleExpanded && (
- <SpaceDisclosure
- expanded={expanded}
- spaceName={channel.name}
- onToggle={() => onToggleExpanded(channel.id)}
- />
- )}
- {glyph}
- <OverflowTickerText
- reveal={reveal}
- className={cn(
- "text-[13px]",
- // mr-11 clears the two icon-xs hover buttons pinned at
- // right-1. It belongs on whatever ends the row's content —
- // put it on the name while the dot is there and the gap
- // opens between them, carrying the dot off to the buttons.
- !hasAttention && "group-hover/chan:mr-11",
- // Bold is unread's alone; full contrast is shared with the
- // channel you're in. Either way there's no hover brighten
- // left to do, so those rows skip it.
- isUnread ? "font-bold" : "font-medium",
- isUnread || isActive ? "text-foreground" : ROW_LABEL_TONE,
- menuOpen && !hasAttention && "mr-11",
- )}
+ opens the same actions as the "..." menu, and resting on it opens
+ the space's card — the same popup the sessions under it use, so
+ crossing between them swaps contents rather than reopening. */}
+ {/* Not on the space you are already in: opening it leaves the
+ highlight where it was, so the card would sit over the space it
+ just opened. */}
+ <SpaceHoverCard
+ space={preview}
+ highlighted={isHighlighted && !isActive}
+ >
+ <ContextMenu>
+ <ContextMenuTrigger
+ render={
+ <SpaceRowSurface
+ asOption={spacesLayout}
+ optionValue={channel.id}
+ // An open space hands the fill to the session under it: the row
+ // you are in is the one the fill is for, and two of them stacked
+ // reads as two selections.
+ data-selected={(isActive && !expanded) || undefined}
+ onClick={() => openChannel(channel)}
+ {...focusProps}
+ className={spacesLayout ? "pl-2" : undefined}
>
- {channel.name}
- </OverflowTickerText>
- {/* Both dots in one slot, so the hover margin belongs to the
- pair rather than to whichever of them happens to end the
- row. */}
- {hasAttention && (
- <span
+ {onToggleExpanded && (
+ <SpaceDisclosure
+ expanded={expanded}
+ spaceName={channel.name}
+ onToggle={() => onToggleExpanded(channel.id)}
+ />
+ )}
+ {glyph}
+ <OverflowTickerText
+ reveal={reveal}
className={cn(
- "flex shrink-0 items-center gap-1",
- "group-hover/chan:mr-11",
- menuOpen && "mr-11",
+ "text-[13px]",
+ // mr-11 clears the two icon-xs hover buttons pinned at
+ // right-1. It belongs on whatever ends the row's content —
+ // put it on the name while the dot is there and the gap
+ // opens between them, carrying the dot off to the buttons.
+ !hasAttention && "group-hover/chan:mr-11",
+ // Bold is unread's alone; full contrast is shared with the
+ // channel you're in. Either way there's no hover brighten
+ // left to do, so those rows skip it.
+ isUnread ? "font-bold" : "font-medium",
+ isUnread || isActive
+ ? "text-foreground"
+ : ROW_LABEL_TONE,
+ menuOpen && !hasAttention && "mr-11",
)}
>
- {/* Blue first, because the rows below are sorted with
+ {channel.name}
+ </OverflowTickerText>
+ {/* Both dots in one slot, so the hover margin belongs to the
+ pair rather than to whichever of them happens to end the
+ row. */}
+ {hasAttention && (
+ <span
+ className={cn(
+ "flex shrink-0 items-center gap-1",
+ "group-hover/chan:mr-11",
+ menuOpen && "mr-11",
+ )}
+ >
+ {/* Blue first, because the rows below are sorted with
what wants you at the top — the pair reads as a
summary of that list, in its order. */}
- <SpaceAttentionDot
- count={blockedSessions}
- tone="blocked"
- faded={expanded}
- />
- <SpaceAttentionDot
- count={unreadSessions}
- faded={expanded}
- />
- </span>
- )}
- {/* `!mr-0` undoes quill's `.quill-button kbd { margin-right: -4px }`,
+ <SpaceAttentionDot
+ count={blockedSessions}
+ tone="blocked"
+ faded={expanded}
+ />
+ <SpaceAttentionDot
+ count={unreadSessions}
+ faded={expanded}
+ />
+ </span>
+ )}
+ {/* `!mr-0` undoes quill's `.quill-button kbd { margin-right: -4px }`,
which is meant to let a shortcut hang into a button's own
padding. Here `ml-auto` takes every pixel of slack, so the
hang had nowhere to go and cut off the last 4px of the hint. */}
- {/* Dropped from the row rather than faded on hover: the label
+ {/* Dropped from the row rather than faded on hover: the label
already reserves mr-11 for the buttons that replace the hint,
and a hint still taking part in the row's width and its gap
there is what cut a starred name shorter than an unstarred
one. */}
- {hotkeySlot != null && (
- <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:hidden">
- {formatHotkey(`mod+${hotkeySlot}`)}
- </Kbd>
- )}
- </SpaceRowSurface>
- }
- />
- <ContextMenuContent>
- <ChannelActionItems actions={actions} kind="context" />
- </ContextMenuContent>
- </ContextMenu>
+ {hotkeySlot != null && (
+ <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:hidden">
+ {formatHotkey(`mod+${hotkeySlot}`)}
+ </Kbd>
+ )}
+ </SpaceRowSurface>
+ }
+ />
+ <ContextMenuContent>
+ <ChannelActionItems actions={actions} kind="context" />
+ </ContextMenuContent>
+ </ContextMenu>
+ </SpaceHoverCard>
{/* Hover actions: the "+" dropdown (New task / New canvas) and the
options menu. Stay visible while either is open. */}
<div className="absolute top-1 right-1">
@@ -1237,7 +1273,14 @@ const ChannelSection = memo(
prev.channel.id === next.channel.id &&
prev.channel.name === next.channel.name &&
prev.channel.starred === next.channel.starred &&
- prev.channel.channelType === next.channel.channelType,
+ prev.channel.channelType === next.channel.channelType &&
+ prev.channel.createdBy?.uuid === next.channel.createdBy?.uuid &&
+ // By content: the poll hands out a new array even when the repos are the
+ // same, and the space's card draws them.
+ prev.channel.repositories.length === next.channel.repositories.length &&
+ prev.channel.repositories.every(
+ (repo, index) => repo === next.channel.repositories[index],
+ ),
);
// The user's private "#me" channel, pinned above the shared channel list.
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
index b5f13dc1236e..cb0de025f396 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
@@ -2,6 +2,7 @@ import { ArchiveIcon } from "@phosphor-icons/react";
import { cn, Separator } from "@posthog/quill";
import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
+import { ChannelItemPreviewCardProvider } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { ChannelNav } from "@posthog/ui/features/canvas/components/ChannelNav";
import { ChannelSidebar } from "@posthog/ui/features/canvas/components/ChannelSidebar";
import { ChannelsFab } from "@posthog/ui/features/canvas/components/ChannelsFab";
@@ -38,7 +39,6 @@ import { ErrorBoundary } from "@posthog/ui/primitives/ErrorBoundary";
import { useSidebarEdgeHoverPeek } from "@posthog/ui/primitives/hooks/useSidebarEdgeHoverPeek";
import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";
import { navigateToArchived } from "@posthog/ui/router/navigationBridge";
-import { Box, Flex } from "@radix-ui/themes";
import { useParams } from "@tanstack/react-router";
import { useDeferredValue, useEffect, useRef } from "react";
@@ -71,7 +71,7 @@ function ChannelPanes({
});
return (
- <Box ref={panesRef} className="min-h-0 flex-1 overflow-hidden">
+ <div ref={panesRef} className="min-h-0 flex-1 overflow-hidden">
<div
className={cn(
"flex h-full w-[200%] transition-transform duration-200 ease-out motion-reduce:transition-none",
@@ -94,7 +94,7 @@ function ChannelPanes({
)}
</div>
</div>
- </Box>
+ </div>
);
}
export function ChannelsSidebar() {
@@ -225,65 +225,69 @@ export function ChannelsSidebar() {
onPeekLeave={() => endSidebarPeek()}
onPeekDismiss={cancelSidebarPeek}
>
- <Flex direction="column" className="h-full bg-chrome">
- {!channelsLayout && (
- <>
- <SidebarNavSection />
- <TasksHeader />
- </>
- )}
+ {/* One preview card for every row in here — the channel's own list and
+ the space tree both draw their rows as triggers on it. */}
+ <ChannelItemPreviewCardProvider>
+ <div className="flex h-full flex-col bg-chrome">
+ {!channelsLayout && (
+ <>
+ <SidebarNavSection />
+ <TasksHeader />
+ </>
+ )}
- {channelsLayout ? (
- <>
- {/* Which project you're in is the outermost thing about this window,
- so under the layout it sits above the nav row rather than in the
- footer. Its menu opens downward, which is the right direction
- from the top of a sidebar. */}
- <Box className="shrink-0 px-2 pb-1">
- <ProjectSwitcher />
- </Box>
- <ChannelNav />
- <ChannelPanes channelId={currentChannelId} showList={showList} />
- </>
- ) : bodyChannelsWorld ? (
- <>
- <Separator />
- <Box className="relative min-h-0 flex-1">
- <ChannelsList />
- <ChannelsFab />
- </Box>
- </>
- ) : (
- <Box className="min-h-0 flex-1">
- <SidebarMenu />
- </Box>
- )}
+ {channelsLayout ? (
+ <>
+ {/* Which project you're in is the outermost thing about this
+ window, so under the layout it sits above the nav row rather
+ than in the footer. Its menu opens downward, which is the
+ right direction from the top of a sidebar. */}
+ <div className="shrink-0 px-2 pb-1">
+ <ProjectSwitcher />
+ </div>
+ <ChannelNav />
+ <ChannelPanes channelId={currentChannelId} showList={showList} />
+ </>
+ ) : bodyChannelsWorld ? (
+ <>
+ <Separator />
+ <div className="relative min-h-0 flex-1">
+ <ChannelsList />
+ <ChannelsFab />
+ </div>
+ </>
+ ) : (
+ <div className="min-h-0 flex-1">
+ <SidebarMenu />
+ </div>
+ )}
- <UpdateBanner />
+ <UpdateBanner />
- {showArchivedRow && archivedTaskIds.size > 0 && (
- <Box className="shrink-0 border-border border-t">
- <button
- type="button"
- className="flex w-full items-center gap-1 bg-transparent px-2 py-1.5 text-left text-[13px] text-gray-11 transition-colors hover:bg-gray-3"
- onClick={navigateToArchived}
- >
- <span className="flex h-[18px] w-[18px] shrink-0 items-center justify-center text-gray-10">
- <ArchiveIcon size={14} />
- </span>
- <span className="text-gray-11">Archived</span>
- </button>
- </Box>
- )}
+ {showArchivedRow && archivedTaskIds.size > 0 && (
+ <div className="shrink-0 border-border border-t">
+ <button
+ type="button"
+ className="flex w-full items-center gap-1 bg-transparent px-2 py-1.5 text-left text-[13px] text-gray-11 transition-colors hover:bg-gray-3"
+ onClick={navigateToArchived}
+ >
+ <span className="flex h-[18px] w-[18px] shrink-0 items-center justify-center text-gray-10">
+ <ArchiveIcon size={14} />
+ </span>
+ <span className="text-gray-11">Archived</span>
+ </button>
+ </div>
+ )}
- {/* The code layout keeps it in the footer: that sidebar's top is the nav
+ {/* The code layout keeps it in the footer: that sidebar's top is the nav
section and task header, and there's no nav row to sit above. */}
- {!channelsLayout && (
- <Box className="shrink-0 px-2 pb-2">
- <ProjectSwitcher />
- </Box>
- )}
- </Flex>
+ {!channelsLayout && (
+ <div className="shrink-0 px-2 pb-2">
+ <ProjectSwitcher />
+ </div>
+ )}
+ </div>
+ </ChannelItemPreviewCardProvider>
</ResizableSidebar>
);
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx
new file mode 100644
index 000000000000..dd479b6968c2
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx
@@ -0,0 +1,121 @@
+import { LinkIcon, StarIcon, TrashIcon } from "@phosphor-icons/react";
+import { Card } from "@posthog/quill";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type { ChannelActionItem } from "./channelActions";
+import { SpacePreviewContent, type SpacePreviewPayload } from "./SpacePreview";
+
+/**
+ * The card as the sidebar shows it — the popup itself carries no styling of its
+ * own, so the story supplies the same quill `Card` the shared preview card
+ * renders it into.
+ */
+function CardFrame({
+ people,
+ total,
+ ...payload
+}: SpacePreviewPayload & { people: UserBasic[]; total: number | null }) {
+ return (
+ <div className="p-4">
+ <Card
+ size="sm"
+ className="w-72 gap-0 border border-border py-0 shadow-md"
+ >
+ <SpacePreviewContent
+ payload={payload}
+ people={people}
+ total={total}
+ onAction={() => {}}
+ />
+ </Card>
+ </div>
+ );
+}
+
+function user(id: number, first: string, last: string): UserBasic {
+ return {
+ id,
+ uuid: `user-${id}`,
+ first_name: first,
+ last_name: last,
+ email: `${first.toLowerCase()}@example.com`,
+ };
+}
+
+const actions: ChannelActionItem[] = [
+ {
+ key: "star",
+ label: "Star space",
+ icon: <StarIcon size={14} />,
+ onSelect: () => {},
+ },
+ {
+ key: "copy-link",
+ label: "Copy link",
+ icon: <LinkIcon size={14} />,
+ onSelect: () => {},
+ },
+ {
+ key: "delete",
+ label: "Delete space…",
+ icon: <TrashIcon size={14} />,
+ variant: "destructive",
+ onSelect: () => {},
+ },
+];
+
+const meta = {
+ title: "Canvas/SpacePreview",
+ component: CardFrame,
+ args: {
+ channel: {
+ id: "channel-1",
+ name: "growth-engineering",
+ channelType: "public" as const,
+ starred: true,
+ repositories: ["PostHog/posthog", "PostHog/posthog.com"],
+ createdBy: user(1, "Ada", "Lovelace"),
+ },
+ unreadSessions: 0,
+ blockedSessions: 0,
+ actions,
+ total: 14,
+ people: [
+ user(1, "Ada", "Lovelace"),
+ user(2, "Grace", "Hopper"),
+ user(3, "Alan", "Turing"),
+ user(4, "Katherine", "Johnson"),
+ ],
+ },
+} satisfies Meta<typeof CardFrame>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** Nothing owed: the gutter stays empty and the card is who and what. */
+export const Quiet: Story = {};
+
+/** Both dots the row can show, spelled out. */
+export const WantsYou: Story = {
+ args: { unreadSessions: 3, blockedSessions: 2 },
+};
+
+/** More repos than the card names, and no creator on the record. */
+export const ManyRepos: Story = {
+ args: {
+ people: [user(2, "Grace", "Hopper"), user(3, "Alan", "Turing")],
+ channel: {
+ id: "channel-2",
+ name: "platform",
+ channelType: "public",
+ starred: false,
+ repositories: [
+ "PostHog/posthog",
+ "PostHog/posthog.com",
+ "PostHog/charts",
+ "PostHog/vector",
+ ],
+ createdBy: null,
+ },
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx
new file mode 100644
index 000000000000..f2fef446f4f6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx
@@ -0,0 +1,309 @@
+import { CrownSimpleIcon, GitBranchIcon } from "@phosphor-icons/react";
+import {
+ AvatarGroup,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemSeparator,
+ ItemTitle,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@posthog/quill";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import {
+ type ChannelActionItem,
+ ChannelActionList,
+} from "@posthog/ui/features/canvas/components/channelActions";
+import type { Channel } from "@posthog/ui/features/canvas/hooks/useChannels";
+import { useSpaceOverview } from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { DOT_TONE_VAR } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+
+/** What the card is about: the space that is being pointed at. */
+export interface SpacePreviewPayload {
+ channel: Channel;
+ /** Sessions inside with something unread, as the row already counted them. */
+ unreadSessions: number;
+ /** Sessions inside waiting on an answer from you. */
+ blockedSessions: number;
+ actions: ChannelActionItem[];
+}
+
+/** Matches the rows' own tooltip delay, so the card doesn't feel slower. */
+const TOOLTIP_DELAY_MS = 200;
+
+/**
+ * How many faces the group shows. Past this the stack stops reading as people
+ * and starts reading as texture, and the card is a glance.
+ */
+const MAX_PEOPLE = 5;
+
+/** Repos past this are counted rather than named — the card has one line. */
+const MAX_REPOS = 3;
+
+/**
+ * One person in the space, as their avatar. The creator wears a crown, because
+ * "who made this" is the one thing about a space's people the space itself
+ * knows — everyone else in the stack is there for having run something lately.
+ */
+function Person({ user, isCreator }: { user: UserBasic; isCreator: boolean }) {
+ const name = userDisplayName(user);
+ const label = isCreator ? `${name} created this space` : name;
+ return (
+ <Tooltip disableHoverablePopup>
+ <TooltipTrigger
+ render={
+ // `flex`, not `block`: quill's avatar is an inline-flex box, so a
+ // block wrapper adds the line box's descender space under it and the
+ // avatar rides at the top of a taller container — enough to knock one
+ // face out of line with its neighbours.
+ <span
+ aria-label={label}
+ role="img"
+ className="relative flex shrink-0"
+ >
+ <UserAvatar size="xs" user={user} />
+ {isCreator && (
+ // Top-left rather than top-right: the stack tucks each face
+ // behind the one after it, so the creator's right corner is
+ // under its neighbour and a crown there is a sliver of gold
+ // nobody can read. Its left corner is the one nothing covers.
+ <span className="-top-1 -left-1 absolute rounded-full bg-background p-px">
+ <CrownSimpleIcon
+ size={9}
+ weight="fill"
+ className="block text-primary"
+ />
+ </span>
+ )}
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="pointer-events-none select-none">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * The space's people, stacked so each face tucks behind the one after it —
+ * which is what `reverse` gives, and why the creator's crown sits on the left
+ * corner of its avatar rather than the right.
+ */
+function SpacePeople({
+ people,
+ creatorUuid,
+}: {
+ people: UserBasic[];
+ creatorUuid: string | undefined;
+}) {
+ if (people.length === 0) return null;
+ return (
+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>
+ <AvatarGroup stacked reverse size="xs">
+ {people.map((user) => (
+ <Person
+ key={user.uuid}
+ user={user}
+ isCreator={user.uuid === creatorUuid}
+ />
+ ))}
+ </AvatarGroup>
+ </TooltipProvider>
+ );
+}
+
+/** A counted signal, drawn as the dot the row shows for it plus the words. */
+function CountSignal({
+ count,
+ tone,
+ label,
+}: {
+ count: number;
+ tone: "blocked" | "attention";
+ label: string;
+}) {
+ if (count === 0) return null;
+ return (
+ <span className="flex items-center gap-1 text-muted-foreground text-xs">
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full"
+ style={{
+ backgroundColor:
+ tone === "blocked" ? DOT_TONE_VAR.blue : "var(--primary)",
+ }}
+ />
+ {count} {label}
+ </span>
+ );
+}
+
+/**
+ * What the space is asking of you and what it is wired to.
+ *
+ * Only what it has to say: a space with nothing owed and no repos gets no
+ * section at all rather than a line telling it so. "All caught up" is the
+ * sessions' own vocabulary, and a space is not a session.
+ */
+function SpaceSignals({
+ unreadSessions,
+ blockedSessions,
+ repositories,
+}: {
+ unreadSessions: number;
+ blockedSessions: number;
+ repositories: string[];
+}) {
+ const shown = repositories.slice(0, MAX_REPOS);
+ const rest = repositories.length - shown.length;
+ const hasCounts = blockedSessions > 0 || unreadSessions > 0;
+ if (!hasCounts && shown.length === 0) return null;
+ return (
+ <>
+ <ItemSeparator className="my-0" />
+ <Item size="xs" className="flex-nowrap items-start p-2">
+ <ItemContent className="min-w-0 gap-1.5">
+ {hasCounts && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {/* Blue first, the way the row's pair is ordered: the sessions
+ you can clear from here come before the ones to read. */}
+ <CountSignal
+ count={blockedSessions}
+ tone="blocked"
+ label="waiting on you"
+ />
+ <CountSignal
+ count={unreadSessions}
+ tone="attention"
+ label="unread"
+ />
+ </div>
+ )}
+ {shown.length > 0 && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {shown.map((repo) => (
+ <span
+ key={repo}
+ className="flex min-w-0 items-center gap-1 text-muted-foreground text-xs"
+ >
+ <GitBranchIcon aria-hidden size={11} className="shrink-0" />
+ <span className="truncate">{repo}</span>
+ </span>
+ ))}
+ {rest > 0 && (
+ <span className="text-muted-foreground text-xs">
+ +{rest} more
+ </span>
+ )}
+ </div>
+ )}
+ </ItemContent>
+ </Item>
+ </>
+ );
+}
+
+/**
+ * The card itself, given everything it draws. Split from the hook below so it
+ * can be rendered from a story: the space's people come from a query, and a
+ * query resolves to nothing in Storybook.
+ */
+export function SpacePreviewContent({
+ payload,
+ people,
+ total,
+ onAction,
+}: {
+ payload: SpacePreviewPayload;
+ people: UserBasic[];
+ /** Sessions in the space, or `null` while the page hasn't arrived. */
+ total: number | null;
+ onAction: () => void;
+}) {
+ const { channel, unreadSessions, blockedSessions, actions } = payload;
+ const hasAttention = unreadSessions > 0 || blockedSessions > 0;
+
+ return (
+ <ItemGroup className="gap-0!">
+ <Item size="xs" className="flex-nowrap p-2">
+ <ItemContent className="min-w-0">
+ {/* The row's own mark rides with the name rather than in a gutter of
+ its own: a quiet space has no mark, and a column that is empty on
+ most cards is an indent nothing pays for. */}
+ <ItemTitle className="flex items-center gap-2 break-words">
+ {hasAttention && (
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full"
+ style={{
+ backgroundColor:
+ blockedSessions > 0 ? DOT_TONE_VAR.blue : "var(--primary)",
+ }}
+ />
+ )}
+ {channel.name}
+ </ItemTitle>
+ <ItemDescription>
+ {/* No count until the page lands: "0 sessions" on a space that has
+ them is a wrong answer, and the card is about to have a right
+ one. */}
+ {total == null
+ ? "Space"
+ : `Space \u00b7 ${total} ${total === 1 ? "session" : "sessions"}`}
+ </ItemDescription>
+ </ItemContent>
+ {/* Top-aligned: the people belong to the space's name, not to the
+ block of text under it. */}
+ <ItemActions className="self-start">
+ <SpacePeople people={people} creatorUuid={channel.createdBy?.uuid} />
+ </ItemActions>
+ </Item>
+ <SpaceSignals
+ unreadSessions={unreadSessions}
+ blockedSessions={blockedSessions}
+ repositories={channel.repositories}
+ />
+ <ItemSeparator className="my-0" />
+ <div className="p-1">
+ <ChannelActionList actions={actions} onAction={onAction} />
+ </div>
+ </ItemGroup>
+ );
+}
+
+/**
+ * The contents of a space row's hover card: what the space is, who has been
+ * working in it, what it's wired to, and what you can do to it.
+ *
+ * Rendered by the one card the sidebar shares, from the payload of whichever
+ * trigger is active — so the query behind the people runs for the space being
+ * pointed at, once, rather than once per space in the list.
+ */
+export function SpacePreview({
+ payload,
+ onAction,
+}: {
+ payload: SpacePreviewPayload;
+ onAction: () => void;
+}) {
+ const overview = useSpaceOverview(
+ payload.channel.id,
+ payload.channel.createdBy,
+ MAX_PEOPLE,
+ );
+ return (
+ <SpacePreviewContent
+ payload={payload}
+ people={overview.people}
+ total={overview.total}
+ onAction={onAction}
+ />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
index f3e3e4310e41..7ab714070a47 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
@@ -1,4 +1,13 @@
-import { CaretRightIcon } from "@phosphor-icons/react";
+import {
+ ArchiveIcon,
+ CaretRightIcon,
+ FolderSimpleIcon,
+ PencilSimpleIcon,
+ PushPinIcon,
+ PushPinSlashIcon,
+ SquaresFourIcon,
+ TrashIcon,
+} from "@phosphor-icons/react";
import {
Button,
ContextMenu,
@@ -99,19 +108,35 @@ function TaskRowMenuItems({
return (
<>
- <Item onClick={menu.onTogglePin}>{menu.isPinned ? "Unpin" : "Pin"}</Item>
- {menu.onRename && <Item onClick={menu.onRename}>Rename</Item>}
+ <Item onClick={menu.onTogglePin}>
+ {menu.isPinned ? (
+ <PushPinSlashIcon size={14} />
+ ) : (
+ <PushPinIcon size={14} />
+ )}
+ {menu.isPinned ? "Unpin" : "Pin"}
+ </Item>
+ {menu.onRename && (
+ <Item onClick={menu.onRename}>
+ <PencilSimpleIcon size={14} />
+ Rename
+ </Item>
+ )}
{isTask && (
<Item
disabled={!menu.onAddToCommandCenter}
onClick={menu.onAddToCommandCenter}
>
+ <SquaresFourIcon size={14} />
Add to Command Center
</Item>
)}
{isTask && channelItems.length > 0 && (
<Sub>
- <SubTrigger>File to…</SubTrigger>
+ <SubTrigger>
+ <FolderSimpleIcon size={14} />
+ File to…
+ </SubTrigger>
<MenuSubFlyout className="w-64 p-0">
<SearchableMenuFlyout
items={channelItems}
@@ -124,11 +149,17 @@ function TaskRowMenuItems({
</MenuSubFlyout>
</Sub>
)}
- {menu.onArchive && <Item onClick={menu.onArchive}>Archive</Item>}
+ {menu.onArchive && (
+ <Item onClick={menu.onArchive}>
+ <ArchiveIcon size={14} />
+ Archive
+ </Item>
+ )}
{/* The ellipsis is the promise that a confirm follows — deleting a canvas
takes it away from everyone in the space. */}
{menu.onDelete && (
<Item variant="destructive" onClick={menu.onDelete}>
+ <TrashIcon size={14} />
Delete…
</Item>
)}
@@ -161,7 +192,6 @@ export function TaskRowMenuList({
Item: ({ children, disabled, variant, onClick }) => (
<Button
variant={variant === "destructive" ? "destructive" : "default"}
- size="sm"
left
disabled={disabled}
className="w-full"
@@ -187,8 +217,10 @@ export function TaskRowMenuList({
delay={150}
closeDelay={100}
render={
- <Button variant="default" size="sm" left className="w-full">
- <span className="flex-1 text-left">{children}</span>
+ <Button variant="default" left className="w-full">
+ <span className="flex flex-1 items-center gap-2 text-left">
+ {children}
+ </span>
<CaretRightIcon size={12} />
</Button>
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/channelActions.tsx b/products/desktop/packages/ui/src/features/canvas/components/channelActions.tsx
new file mode 100644
index 000000000000..cd473d447b17
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/channelActions.tsx
@@ -0,0 +1,58 @@
+import { Button } from "@posthog/quill";
+import type { ReactNode } from "react";
+
+/**
+ * One actionable entry in a space's menu, rendered the same whether it surfaces
+ * in the hover "..." dropdown, the right-click context menu, or the space's
+ * hover card.
+ */
+export type ChannelActionItem = {
+ key: string;
+ label: string;
+ icon: ReactNode;
+ onSelect: () => void;
+ variant?: "destructive";
+ disabled?: boolean;
+ /** Draw a divider above this item to separate it from the previous group. */
+ separatorBefore?: boolean;
+};
+
+/**
+ * The same actions as a plain list, for a surface that is already open — the
+ * space's hover card. Buttons rather than menu items for the reason the session
+ * card's list uses them: there is no menu root here to give a menu item its
+ * keyboard handling.
+ *
+ * `onAction` closes the card once something has been chosen. The separators the
+ * menus draw are dropped: the card's own rules already divide it, and a third
+ * rule inside a four-item list is more chrome than grouping.
+ */
+export function ChannelActionList({
+ actions,
+ onAction,
+}: {
+ actions: ChannelActionItem[];
+ onAction: () => void;
+}) {
+ return (
+ <div className="flex flex-col">
+ {actions.map((action) => (
+ <Button
+ key={action.key}
+ variant={action.variant === "destructive" ? "destructive" : "default"}
+ size="default"
+ left
+ disabled={action.disabled}
+ className="w-full"
+ onClick={() => {
+ action.onSelect();
+ onAction();
+ }}
+ >
+ {action.icon}
+ {action.label}
+ </Button>
+ ))}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
index ab652e06d336..408164d2e5c3 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
@@ -93,6 +93,8 @@ function channel(over: Partial<Channel> = {}): Channel {
name: "eng",
channelType: "public",
starred: false,
+ repositories: [],
+ createdBy: null,
...over,
};
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.test.tsx
index c2dfaf5fc6bb..ad2436a7bdf3 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.test.tsx
@@ -30,7 +30,14 @@ function taskChannel(id: string, name: string, starred = false): TaskChannel {
}
function channel(id: string, name: string, starred = false): Channel {
- return { id, name, channelType: "public", starred };
+ return {
+ id,
+ name,
+ channelType: "public",
+ starred,
+ repositories: [],
+ createdBy: null,
+ };
}
let queryClient: QueryClient;
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.ts
index 64fe8c0ac787..686d565b6b29 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelStars.ts
@@ -61,13 +61,21 @@ export function useChannelStarMutations() {
},
});
- return {
- star: (channelId: string) =>
- setStarredMutation.mutateAsync({ channelId, starred: true }),
- unstar: (channelId: string) =>
- setStarredMutation.mutateAsync({ channelId, starred: false }),
- isUpdating: setStarredMutation.isPending,
- };
+ // Stable identities: a space row's actions are memoized on `toggleStar`,
+ // which is built from these — fresh closures here would rebuild that list on
+ // every render and write the row's hover-card payload to the card's store
+ // with it.
+ const { mutateAsync } = setStarredMutation;
+ const star = useCallback(
+ (channelId: string) => mutateAsync({ channelId, starred: true }),
+ [mutateAsync],
+ );
+ const unstar = useCallback(
+ (channelId: string) => mutateAsync({ channelId, starred: false }),
+ [mutateAsync],
+ );
+
+ return { star, unstar, isUpdating: setStarredMutation.isPending };
}
/**
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
index cdabb5bb864a..cb89b95d6a51 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
@@ -30,7 +30,7 @@ export function useChannelTaskStatus(
const task = item.task ?? undefined;
const taskData = useChannelTaskData(task);
const workspace = useWorkspace(task?.id);
- const { prState, hasDiff } = useTaskPrStatus({
+ const { prState, hasDiff, prUrl } = useTaskPrStatus({
// An empty id is the hook's own "nothing to look up", so this asks for no
// query rather than one it throws away.
id: options?.withPrStatus === false ? "" : (task?.id ?? ""),
@@ -55,7 +55,8 @@ export function useChannelTaskStatus(
prState,
hasDiff,
// The url is the early signal: a cloud run writes it the moment it opens the
- // PR, long before (or without ever) resolving the PR's state.
- prUrl: taskData.cloudPrUrl,
+ // PR, long before (or without ever) resolving the PR's state. A local run
+ // has no cloud url, so the one the host cached against the task stands in.
+ prUrl: taskData.cloudPrUrl ?? prUrl,
};
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts
index f17f2314b06a..a957aca09418 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts
@@ -1,4 +1,4 @@
-import type { TaskChannel } from "@posthog/shared/domain-types";
+import type { TaskChannel, UserBasic } from "@posthog/shared/domain-types";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import {
TASK_CHANNELS_QUERY_KEY,
@@ -17,14 +17,22 @@ export interface Channel {
channelType: "public" | "personal";
/** Whether the current user starred this channel. */
starred: boolean;
+ /** The repos the space is wired to. Empty where none are. */
+ repositories: string[];
+ /** Who made the space, where the backend knows. */
+ createdBy: UserBasic | null;
}
+const NO_REPOSITORIES: string[] = [];
+
function toChannel(channel: TaskChannel): Channel {
return {
id: channel.id,
name: channel.name,
channelType: channel.channel_type,
starred: channel.starred,
+ repositories: channel.repositories ?? NO_REPOSITORIES,
+ createdBy: channel.created_by ?? null,
};
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useLatestTurnMessage.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useLatestTurnMessage.ts
new file mode 100644
index 000000000000..a814a8945d59
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useLatestTurnMessage.ts
@@ -0,0 +1,27 @@
+import {
+ latestAgentMessage,
+ persistedTurnMessage,
+} from "@posthog/core/sessions/latestTurnMessage";
+import type { Task } from "@posthog/shared/domain-types";
+import { useSessionSelector } from "@posthog/ui/features/sessions/useSession";
+
+/**
+ * The last thing the agent said on a task, for a surface showing it without
+ * opening it.
+ *
+ * The live session wins where there is one: it has the turn that is streaming
+ * right now, which the run's persisted text won't carry until the turn ends. A
+ * task this window has never opened has no session, and falls back to what the
+ * cloud run wrote when it finished.
+ *
+ * Costs nothing either way — both sources are already in the renderer, so a
+ * card can show this without a request per row.
+ */
+export function useLatestTurnMessage(
+ task: Task | null | undefined,
+): string | null {
+ const live = useSessionSelector(task?.id, (session) =>
+ latestAgentMessage(session?.events),
+ );
+ return live ?? persistedTurnMessage(task?.latest_run?.output);
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts
new file mode 100644
index 000000000000..be62a63a46b7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts
@@ -0,0 +1,53 @@
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { describe, expect, it } from "vitest";
+import { spacePeople } from "./useRecentSpaceTasks";
+
+function user(name: string): UserBasic {
+ return {
+ id: name.length,
+ uuid: `uuid-${name}`,
+ first_name: name,
+ last_name: "Tester",
+ email: `${name}@example.com`,
+ };
+}
+
+const ADA = user("ada");
+const GRACE = user("grace");
+const ALAN = user("alan");
+
+describe("spacePeople", () => {
+ it.each([
+ {
+ case: "puts the creator first even when they ran nothing",
+ createdBy: ADA,
+ ran: [GRACE, ALAN],
+ limit: 5,
+ expected: [ADA, GRACE, ALAN],
+ },
+ {
+ case: "counts the creator once when they also ran something",
+ createdBy: ADA,
+ ran: [GRACE, ADA, GRACE],
+ limit: 5,
+ expected: [ADA, GRACE],
+ },
+ {
+ case: "keeps the creator when the cap cuts the rest",
+ createdBy: ALAN,
+ ran: [ADA, GRACE],
+ limit: 2,
+ expected: [ALAN, ADA],
+ },
+ {
+ case: "leads with whoever ran when the space has no creator",
+ createdBy: null,
+ ran: [GRACE, ADA],
+ limit: 5,
+ expected: [GRACE, ADA],
+ },
+ ])("$case", ({ createdBy, ran, limit, expected }) => {
+ const tasks = ran.map((created_by) => ({ created_by }));
+ expect(spacePeople(tasks, createdBy, limit)).toEqual(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
index d6b83ca19693..7d38d935123c 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
@@ -2,7 +2,7 @@ import {
buildChannelItems,
type ChannelItemModel,
} from "@posthog/core/canvas/channelItems";
-import type { Task } from "@posthog/shared/domain-types";
+import type { Task, UserBasic } from "@posthog/shared/domain-types";
import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
@@ -13,7 +13,7 @@ import {
} from "@posthog/ui/features/canvas/hooks/useUnreadSessionCount";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";
-import { useQueries, useQueryClient } from "@tanstack/react-query";
+import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useMemo, useRef } from "react";
import {
SPACE_QUERY_GC_TIME_MS,
@@ -46,6 +46,30 @@ interface SpaceTaskPage {
const NO_PAGE: SpaceTaskPage = { tasks: [], count: 0 };
+/**
+ * One space's page, as every caller has to ask for it: the tree's `useQueries`,
+ * the hover prefetch, and the space card. Same key and same `staleTime`, so a
+ * warm cache is a no-op rather than a second request for the same rows.
+ */
+function spaceTaskPageQuery(
+ client: ReturnType<typeof useOptionalAuthenticatedClient>,
+ spaceId: string,
+) {
+ return {
+ queryKey: spaceTreeTasksQueryKey(spaceId),
+ queryFn: async (): Promise<SpaceTaskPage> => {
+ if (!client) throw new Error("Not authenticated");
+ return (await client.getTasksPage({
+ channel: spaceId,
+ limit: TREE_FETCH_LIMIT,
+ })) as SpaceTaskPage;
+ },
+ gcTime: SPACE_QUERY_GC_TIME_MS,
+ meta: AUTH_SCOPED_QUERY_META,
+ staleTime: SPACE_QUERY_STALE_TIME_MS,
+ };
+}
+
/** A space's rows: the newest few, and how many sessions it holds in all. */
export interface SpaceTasks {
items: ChannelItemModel[];
@@ -154,19 +178,9 @@ export function useRecentSpaceTasks(
const pagePerSpace = useQueries({
queries: spaceIds.map((spaceId) => ({
- queryKey: spaceTreeTasksQueryKey(spaceId),
- queryFn: async (): Promise<SpaceTaskPage> => {
- if (!client) throw new Error("Not authenticated");
- return (await client.getTasksPage({
- channel: spaceId,
- limit: TREE_FETCH_LIMIT,
- })) as SpaceTaskPage;
- },
+ ...spaceTaskPageQuery(client, spaceId),
enabled: !!client,
- gcTime: SPACE_QUERY_GC_TIME_MS,
- meta: AUTH_SCOPED_QUERY_META,
refetchInterval: SPACE_TREE_POLL_INTERVAL_MS,
- staleTime: SPACE_QUERY_STALE_TIME_MS,
})),
combine: combineTaskPages,
});
@@ -246,19 +260,86 @@ export function usePrefetchSpaceTasks(): (spaceId: string) => void {
return useCallback(
(spaceId: string) => {
if (!client) return;
- void queryClient.prefetchQuery({
- queryKey: spaceTreeTasksQueryKey(spaceId),
- queryFn: async (): Promise<SpaceTaskPage> =>
- (await client.getTasksPage({
- channel: spaceId,
- limit: TREE_FETCH_LIMIT,
- })) as SpaceTaskPage,
- gcTime: SPACE_QUERY_GC_TIME_MS,
- meta: AUTH_SCOPED_QUERY_META,
- // Same staleTime as the live query, so a warm cache is a no-op.
- staleTime: SPACE_QUERY_STALE_TIME_MS,
- });
+ void queryClient.prefetchQuery(spaceTaskPageQuery(client, spaceId));
},
[client, queryClient],
);
}
+
+/** What a space's card says about it beyond the counts its row already has. */
+export interface SpaceOverview {
+ /** Who has been working here, creator first. Capped by `peopleLimit`. */
+ people: UserBasic[];
+ /**
+ * Sessions in the space, by the same reckoning the tree's total uses, or
+ * `null` until the page arrives — a space's count is not zero just because
+ * nothing has been fetched yet.
+ */
+ total: number | null;
+}
+
+const NO_OVERVIEW: SpaceOverview = { people: [], total: null };
+
+/**
+ * A space's people and its session count, off the same page the tree draws its
+ * rows from — which the row's own hover has already warmed by the time a card
+ * opens over it, so this costs no request of its own.
+ *
+ * The people are who has been working here, not a membership list: the backend
+ * has no such list, and the page is the newest `TREE_FETCH_LIMIT` sessions
+ * rather than the space's whole history.
+ *
+ * The creator leads, whether or not they appear in that page. They are the one
+ * name the space itself carries, and a group that opened with whoever happened
+ * to run the last session read as if the space belonged to them.
+ */
+export function useSpaceOverview(
+ spaceId: string,
+ createdBy: UserBasic | null,
+ peopleLimit: number,
+): SpaceOverview {
+ const client = useOptionalAuthenticatedClient();
+ const archivedTaskIds = useArchivedTaskIds();
+ const { data } = useQuery({
+ ...spaceTaskPageQuery(client, spaceId),
+ enabled: !!client,
+ });
+
+ return useMemo(() => {
+ if (!data) return NO_OVERVIEW;
+ const live = data.tasks.filter((task) => !archivedTaskIds.has(task.id));
+ return {
+ people: spacePeople(live, createdBy, peopleLimit),
+ // A page that came back short is the whole space, so the count is exact
+ // once the archived ones are dropped. A full page falls back to the
+ // server's total, which still counts anything archived in it.
+ total: data.tasks.length < TREE_FETCH_LIMIT ? live.length : data.count,
+ };
+ }, [data, archivedTaskIds, createdBy, peopleLimit]);
+}
+
+/**
+ * The space's faces, in the order the group stacks them: the creator, then
+ * whoever ran the sessions, newest first, each person once and no more than
+ * `limit` of them.
+ *
+ * The creator leads whether or not they ran anything, and is not counted twice
+ * when they did — the leading avatar is the one that wears the crown, so its
+ * place is what makes the crown mean "created this".
+ */
+export function spacePeople(
+ tasks: Pick<Task, "created_by">[],
+ createdBy: UserBasic | null,
+ limit: number,
+): UserBasic[] {
+ const people: UserBasic[] = [];
+ const seen = new Set<string>();
+ const add = (user: UserBasic | null | undefined) => {
+ if (!user || seen.has(user.uuid) || people.length >= limit) return;
+ seen.add(user.uuid);
+ people.push(user);
+ };
+ add(createdBy);
+ for (const task of tasks) add(task.created_by);
+ return people;
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx
index 821708ada87e..93e33888e8ac 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarBulkActionBar.test.tsx
@@ -21,7 +21,14 @@ function makeActions(
pinDirection: "pin",
pinLabel: "Pin 3 sessions",
channels: [
- { id: "c1", name: "support", channelType: "public", starred: false },
+ {
+ id: "c1",
+ name: "support",
+ channelType: "public",
+ starred: false,
+ repositories: [],
+ createdBy: null,
+ },
],
archiveSelected: vi.fn(),
pinSelected: vi.fn(),
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx
index 3e9c5614f11a..c7e689441c96 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx
@@ -58,53 +58,75 @@ function RowTooltip({
}
/**
- * A task's state as a single dot: blue wants a decision, the brand yellow is
- * working or unread, grey is quiet. The trigger renders as a span because rows are
- * `<button>`s — a nested button would be invalid HTML.
+ * The dot itself, as a plain element. A function rather than a component so the
+ * result is a DOM element a tooltip trigger can clone — and so the mark can be
+ * drawn on its own where the state is already named in words beside it.
+ *
+ * `decorative` is for that second case: where the label is on screen already,
+ * naming the dot as well says it twice.
*/
-export function TaskStatusDot({ dot }: { dot: TaskDot }) {
+function dotMark(dot: TaskDot, decorative = false): ReactElement {
const color = DOT_TONE_VAR[dot.tone];
+ const naming = decorative
+ ? { "aria-hidden": true }
+ : { "aria-label": dot.label, role: "img" };
if (dot.spinner) {
return (
- <RowTooltip label={dot.label} side="right">
- <span
- aria-label={dot.label}
- role="img"
- className="flex shrink-0 items-center justify-center"
- // The spinner draws its dots in `currentColor`, so the tone is set
- // here rather than passed down.
- style={{ color: TONE_ICON_VAR[dot.tone], width: SPINNER_SIZE }}
- >
- <DotRingSpinner size={SPINNER_SIZE} />
- </span>
- </RowTooltip>
+ <span
+ {...naming}
+ className="flex shrink-0 items-center justify-center"
+ // The spinner draws its dots in `currentColor`, so the tone is set
+ // here rather than passed down.
+ style={{ color: TONE_ICON_VAR[dot.tone], width: SPINNER_SIZE }}
+ >
+ <DotRingSpinner size={SPINNER_SIZE} />
+ </span>
);
}
+ return (
+ <span
+ {...naming}
+ className={cn(
+ "block shrink-0 rounded-full",
+ // ph-pulse is the app's existing flash, but it has no reduced-motion
+ // rule of its own — hold a static dot rather than blinking at someone
+ // who asked us not to.
+ dot.pulse && "ph-pulse motion-reduce:animate-none",
+ )}
+ style={{
+ width: DOT_SIZE,
+ height: DOT_SIZE,
+ backgroundColor: dot.style === "solid" ? color : "transparent",
+ boxShadow:
+ dot.style === "hollow" ? `inset 0 0 0 1.5px ${color}` : undefined,
+ opacity: dot.faint ? FAINT_OPACITY : undefined,
+ }}
+ />
+ );
+}
+
+/**
+ * A task's state as a single dot: blue wants a decision, the brand yellow is
+ * working or unread, grey is quiet. The trigger renders as a span because rows are
+ * `<button>`s — a nested button would be invalid HTML.
+ */
+export function TaskStatusDot({ dot }: { dot: TaskDot }) {
return (
<RowTooltip label={dot.label} side="right">
- <span
- aria-label={dot.label}
- role="img"
- className={cn(
- "block shrink-0 rounded-full",
- // ph-pulse is the app's existing flash, but it has no reduced-motion
- // rule of its own — hold a static dot rather than blinking at someone
- // who asked us not to.
- dot.pulse && "ph-pulse motion-reduce:animate-none",
- )}
- style={{
- width: DOT_SIZE,
- height: DOT_SIZE,
- backgroundColor: dot.style === "solid" ? color : "transparent",
- boxShadow:
- dot.style === "hollow" ? `inset 0 0 0 1.5px ${color}` : undefined,
- opacity: dot.faint ? FAINT_OPACITY : undefined,
- }}
- />
+ {dotMark(dot)}
</RowTooltip>
);
}
+/**
+ * The same dot without the tooltip, for surfaces that already say what it means
+ * — the hover card names the state in words right beside it, and a tooltip over
+ * a label is a second answer to a question nobody asked twice.
+ */
+export function TaskDotMark({ dot }: { dot: TaskDot }) {
+ return dotMark(dot, true);
+}
+
/**
* The pin: this row was put here on purpose. Lives with the badges because it
* belongs in their stack — pinned rows sit in the one list with everything else,
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts b/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts
index 4ce1986c94ea..304d6c79ef0b 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts
@@ -213,6 +213,13 @@ export interface TaskBadge {
label: string;
/** Set only where colour earns its keep — currently PR state. */
tone?: DotTone;
+ /**
+ * Where the badge points, for the surfaces that can offer it. A row can't:
+ * it is a `<button>`, so its badges stay spans. The hover card is not, so it
+ * draws a badge with a url as something you can click through to — the PR, or
+ * the Slack thread the task was filed from.
+ */
+ url?: string;
}
/**
@@ -239,19 +246,25 @@ export interface TaskBadge {
export function taskBadges(props: TaskStatusInput): TaskBadge[] {
const badges: TaskBadge[] = [];
const origin = getOriginProductMeta(props.originProduct);
+ const isSlack = props.originProduct === "slack";
if (origin) {
badges.push({
key: "origin",
- Icon: props.originProduct === "slack" ? SlackMark : ArrowSquareIn,
+ Icon: isSlack ? SlackMark : ArrowSquareIn,
label: `Source: ${origin.label}`,
+ // Slack is the one origin that hands back a place to go: the thread the
+ // task was filed from. Other products name themselves and stop there.
+ url: isSlack ? (props.slackThreadUrl ?? undefined) : undefined,
});
}
+ const prUrl = props.prUrl ?? undefined;
if (props.prState === "merged") {
badges.push({
key: "pr",
Icon: GitMerge,
label: "Merged",
tone: "purple",
+ url: prUrl,
});
} else if (props.prState === "open") {
badges.push({
@@ -259,6 +272,7 @@ export function taskBadges(props: TaskStatusInput): TaskBadge[] {
Icon: GitPullRequest,
label: "PR ready for review",
tone: "green",
+ url: prUrl,
});
} else if (props.prState === "closed") {
badges.push({
@@ -266,6 +280,7 @@ export function taskBadges(props: TaskStatusInput): TaskBadge[] {
Icon: GitPullRequest,
label: "PR closed unmerged",
tone: "red",
+ url: prUrl,
});
} else if (props.prState === "draft") {
// Mid grey: a draft is a real PR, so it earns a solid glyph, but it isn't
@@ -275,6 +290,7 @@ export function taskBadges(props: TaskStatusInput): TaskBadge[] {
Icon: GitPullRequest,
label: "Draft PR",
tone: "gray",
+ url: prUrl,
});
} else if (props.prUrl) {
// A PR we know exists but haven't resolved the state of. Uncoloured on
@@ -282,7 +298,12 @@ export function taskBadges(props: TaskStatusInput): TaskBadge[] {
// saying "there's a PR, go look". Showing the badge is not optional — a
// task that opened a PR and shows no sign of it reads as having done
// nothing.
- badges.push({ key: "pr", Icon: GitPullRequest, label: "Pull request" });
+ badges.push({
+ key: "pr",
+ Icon: GitPullRequest,
+ label: "Pull request",
+ url: props.prUrl,
+ });
} else if (props.hasDiff) {
badges.push({
key: "branch",
diff --git a/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.test.ts b/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.test.ts
index 8d1f5480ddf4..d5e8ee66ba49 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.test.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.test.ts
@@ -52,19 +52,49 @@ describe("useTaskPrStatus", () => {
it("returns empty status when no data is available", () => {
const { result } = renderHook(() => useTaskPrStatus(makeTask()));
- expect(result.current).toEqual({ prState: null, hasDiff: false });
+ expect(result.current).toEqual({
+ prState: null,
+ hasDiff: false,
+ prUrl: null,
+ });
});
it("returns empty status when data has no prState and no diff", () => {
- queryData = { prState: null, hasDiff: false };
+ queryData = { prState: null, hasDiff: false, prUrl: null };
const { result } = renderHook(() => useTaskPrStatus(makeTask()));
- expect(result.current).toEqual({ prState: null, hasDiff: false });
+ expect(result.current).toEqual({
+ prState: null,
+ hasDiff: false,
+ prUrl: null,
+ });
});
- it("returns prState from query data", () => {
- queryData = { prState: "open", hasDiff: false };
+ it("keeps a cached url when the PR's state never resolved", () => {
+ queryData = {
+ prState: null,
+ hasDiff: false,
+ prUrl: "https://github.com/x/y/pull/1",
+ };
const { result } = renderHook(() => useTaskPrStatus(makeTask()));
- expect(result.current).toEqual({ prState: "open", hasDiff: false });
+ expect(result.current).toEqual({
+ prState: null,
+ hasDiff: false,
+ prUrl: "https://github.com/x/y/pull/1",
+ });
+ });
+
+ it("returns prState and the url it belongs to from query data", () => {
+ queryData = {
+ prState: "open",
+ hasDiff: false,
+ prUrl: "https://github.com/x/y/pull/1",
+ };
+ const { result } = renderHook(() => useTaskPrStatus(makeTask()));
+ expect(result.current).toEqual({
+ prState: "open",
+ hasDiff: false,
+ prUrl: "https://github.com/x/y/pull/1",
+ });
});
it("returns hasDiff from query data", () => {
@@ -116,6 +146,10 @@ describe("useTaskPrStatus", () => {
makeTask({ taskRunEnvironment: "cloud", cloudPrUrl: null }),
),
);
- expect(result.current).toEqual({ prState: null, hasDiff: false });
+ expect(result.current).toEqual({
+ prState: null,
+ hasDiff: false,
+ prUrl: null,
+ });
});
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.ts b/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.ts
index deb83767e62d..2907ab5bd188 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useTaskPrStatus.ts
@@ -6,10 +6,12 @@ export type SidebarPrState = "merged" | "open" | "draft" | "closed" | null;
export interface TaskPrStatus {
prState: SidebarPrState;
hasDiff: boolean;
+ /** The PR the state belongs to, where the host has one cached for the task. */
+ prUrl: string | null;
}
const SIDEBAR_STALE_TIME = 60_000;
-const EMPTY: TaskPrStatus = { prState: null, hasDiff: false };
+const EMPTY: TaskPrStatus = { prState: null, hasDiff: false, prUrl: null };
export function useTaskPrStatus(task: {
id: string;
@@ -37,6 +39,11 @@ export function useTaskPrStatus(task: {
// A disabled query can retain placeholder data from the previously selected
// task. Ignore it so a cloud task without a PR never shows stale PR status.
- if (skipQuery || !data || (!data.prState && !data.hasDiff)) return EMPTY;
+ if (skipQuery || !data) return EMPTY;
+ // Nothing to say about the branch, but the url still stands on its own: the
+ // host caches it as soon as a PR is opened, and its state stays null whenever
+ // the GitHub lookup behind it fails. Dropping it here is what would leave a
+ // task that opened a PR showing no sign of one.
+ if (!data.prState && !data.hasDiff) return { ...EMPTY, prUrl: data.prUrl };
return data;
}
diff --git a/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.test.ts b/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.test.ts
index ce3e6d020b11..23335b19b9a6 100644
--- a/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.test.ts
+++ b/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.test.ts
@@ -128,11 +128,19 @@ describe("WorkspaceEventsContribution", () => {
],
}),
).toBe(false);
- expect(updater({ prState: null, hasDiff: true })).toEqual({
+ // The url rides with the state: the badge the status draws is a link, so a
+ // cache holding the new state against the previous url points at the wrong
+ // PR until the next refetch.
+ expect(updater({ prState: null, hasDiff: true, prUrl: null })).toEqual({
prState: "open",
hasDiff: true,
+ prUrl: "https://github.com/o/r/pull/1",
+ });
+ expect(updater(undefined)).toEqual({
+ prState: "open",
+ hasDiff: false,
+ prUrl: "https://github.com/o/r/pull/1",
});
- expect(updater(undefined)).toEqual({ prState: "open", hasDiff: false });
expect(setQueryData).toHaveBeenCalledWith(
[
diff --git a/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.ts b/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.ts
index c273cba24a72..b78dd5000e9f 100644
--- a/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.ts
+++ b/products/desktop/packages/ui/src/features/workspace/workspace-events.contribution.ts
@@ -68,6 +68,7 @@ export class WorkspaceEventsContribution implements Contribution {
this.queryClient.setQueriesData<{
prState: typeof prState;
hasDiff: boolean;
+ prUrl: string | null;
}>(
{
...options.workspace.getTaskPrStatus.pathFilter(),
@@ -79,7 +80,13 @@ export class WorkspaceEventsContribution implements Contribution {
return params?.input?.taskId === taskId;
},
},
- (prev) => (prev ? { ...prev, prState } : { prState, hasDiff: false }),
+ // The url travels with the state, because the badge it draws is a
+ // link: writing one without the other leaves a row pointing at the
+ // PR before last until the next refetch.
+ (prev) =>
+ prev
+ ? { ...prev, prState, prUrl: prUrl ?? null }
+ : { prState, hasDiff: false, prUrl: prUrl ?? null },
);
this.queryClient.setQueryData(
options.workspace.getCachedPrUrl.queryKey({ taskId }),
diff --git a/products/desktop/packages/workspace-server/src/services/git/task-pr-status.test.ts b/products/desktop/packages/workspace-server/src/services/git/task-pr-status.test.ts
index ca8dd5e7ba4d..8af720d48ccb 100644
--- a/products/desktop/packages/workspace-server/src/services/git/task-pr-status.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/task-pr-status.test.ts
@@ -47,7 +47,7 @@ describe("TaskPrStatusService.getTaskPrStatus (missing worktree directory)", ()
const result = await service.getTaskPrStatus("task-1", null);
await new Promise((resolve) => setImmediate(resolve));
- expect(result).toEqual({ prState: null, hasDiff: false });
+ expect(result).toEqual({ prState: null, hasDiff: false, prUrl: null });
expect(gitService.getDiffStats).not.toHaveBeenCalled();
});
});
diff --git a/products/desktop/packages/workspace-server/src/services/git/task-pr-status.ts b/products/desktop/packages/workspace-server/src/services/git/task-pr-status.ts
index d499c58087ed..9bd85642ae4f 100644
--- a/products/desktop/packages/workspace-server/src/services/git/task-pr-status.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/task-pr-status.ts
@@ -34,10 +34,13 @@ export class TaskPrStatusService {
void this.revalidateTaskPrStatus(taskId, cloudPrUrl);
- if (cachedPrState) return { prState: cachedPrState, hasDiff: false };
+ const cachedPrUrl = cached?.prUrl ?? null;
+ if (cachedPrState) {
+ return { prState: cachedPrState, hasDiff: false, prUrl: cachedPrUrl };
+ }
const hasDiff = await this.computeWorktreeHasDiff(taskId);
- return { prState: null, hasDiff };
+ return { prState: null, hasDiff, prUrl: cachedPrUrl };
}
getCachedPrUrl(taskId: string): CachedPrUrlOutput {
diff --git a/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts b/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts
index 0de533573e76..f3fe32ce72bf 100644
--- a/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts
@@ -316,6 +316,8 @@ export const sidebarPrStateSchema = z
export const taskPrStatusOutput = z.object({
prState: sidebarPrStateSchema,
hasDiff: z.boolean(),
+ /** The PR the state belongs to, so a row can offer to open it. */
+ prUrl: z.string().nullable(),
});
export type TaskPrStatusInput = z.infer<typeof taskPrStatusInput>;