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): redesign task feed cards (#81098)

Shy Alter058d3e4f6928
diff --git a/products/desktop/packages/shared/src/links.ts b/products/desktop/packages/shared/src/links.ts
index 1563b7caf6f6..27e965bfca35 100644
--- a/products/desktop/packages/shared/src/links.ts
+++ b/products/desktop/packages/shared/src/links.ts
@@ -1,5 +1,6 @@
export const EXTERNAL_LINKS = {
discord: "https://discord.gg/m4uHvPa4SN",
+ docs: "https://posthog.com/docs/posthog-desktop",
ghInstall: "https://cli.github.com/",
gitInstall: "https://git-scm.com/downloads",
privacy: "https://posthog.com/privacy",
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx
index 53ef7c7eb08f..e1a742a82e73 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.test.tsx
@@ -53,7 +53,7 @@ vi.mock("@posthog/ui/features/canvas/components/TaskCommentsList", () => ({
TaskCommentsList: () => <div>comments body</div>,
}));
vi.mock("@posthog/ui/features/canvas/components/ChannelFeedView", () => ({
- TaskCard: () => <div>task card</div>,
+ TaskSummaryRow: () => <div>task summary</div>,
}));
vi.mock("@posthog/ui/features/canvas/components/ThreadPanel", () => ({
AgentStatusLine: () => <div>agent status</div>,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
index 56ff6d26d5b6..5861f436674e 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanel.tsx
@@ -10,14 +10,15 @@ import {
ActivityPanelBody,
type ActivityTab,
} from "@posthog/ui/features/canvas/components/ActivityPanelBody";
-import { TaskCard } from "@posthog/ui/features/canvas/components/ChannelFeedView";
+import { TaskSummaryRow } from "@posthog/ui/features/canvas/components/ChannelFeedView";
import { ThreadLoadingState } from "@posthog/ui/features/canvas/components/ThreadPanel";
import { useTaskThread } from "@posthog/ui/features/canvas/hooks/useTaskThread";
+import { useThreadPanelStore } from "@posthog/ui/features/canvas/stores/threadPanelStore";
import { useCommentFocusRequest } from "@posthog/ui/features/sessions/useCommentFocusRequest";
import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
import { track } from "@posthog/ui/shell/analytics";
import { useQuery } from "@tanstack/react-query";
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
const ACTIVITY_TABS: readonly { key: ActivityTab; label: string }[] = [
{ key: "timeline", label: "Timeline" },
@@ -139,6 +140,22 @@ function ActivityConversation({
// Not handleTabChange: a programmatic switch isn't a user tab change.
useCommentFocusRequest(taskId, () => setTab("comments"));
+ // A caller can open the panel pointed at a tab (the feed's comment chip
+ // lands on Comments, its "+N files" rows on Artifacts). Applied once, then
+ // consumed in the store — a local ref would reset when the panel remounts
+ // (collapse/expand) and replay the stale request over the user's tab pick.
+ const tabRequest = useThreadPanelStore(
+ (state) => state.tabRequestByTask[taskId],
+ );
+ const consumeTabRequest = useThreadPanelStore(
+ (state) => state.consumeTabRequest,
+ );
+ useEffect(() => {
+ if (!tabRequest) return;
+ setTab(tabRequest.tab);
+ consumeTabRequest(taskId, tabRequest.nonce);
+ }, [tabRequest, consumeTabRequest, taskId]);
+
return (
<div className="flex h-full min-w-0 flex-col bg-gray-1">
<ActivityHeader
@@ -149,11 +166,7 @@ function ActivityConversation({
onClose={onClose}
/>
- {showTaskSummary && (
- <div className="z-10 px-2">
- <TaskCard task={task} channelId={channelId} inThread />
- </div>
- )}
+ {showTaskSummary && <TaskSummaryRow task={task} channelId={channelId} />}
{/* Keyed by session: the body latches "the timeline has drawn" so it
never blinks back to a loader, and the dock reuses one body across
tasks, which would carry that latch onto a session still loading. */}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
index aa5aa64065b3..99105eb6c711 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.stories.tsx
@@ -1,111 +1,200 @@
-import type { Task, UserBasic } from "@posthog/shared/domain-types";
+import type { Task, TaskRun, UserBasic } from "@posthog/shared/domain-types";
import type { Meta, StoryObj } from "@storybook/react-vite";
-import { TaskFeedRow } from "./ChannelFeedView";
+import { ChannelFeedView } from "./ChannelFeedView";
-function MockTaskCard({ title }: { title: string }) {
- return (
- <div className="mt-1.5 rounded-sm border border-border-primary px-3 py-2.5">
- <div className="flex items-center justify-between gap-2">
- <span className="font-medium text-sm">{title}</span>
- <span className="rounded-full bg-fill-secondary px-2 py-0.5 text-muted-foreground text-xs">
- Ready
- </span>
- </div>
- </div>
- );
-}
-
-const user = (overrides: Partial<UserBasic> = {}): UserBasic => ({
+const adam: UserBasic = {
id: 1,
- uuid: "user-1",
- email: "[email protected]",
+ uuid: "user-adam",
+ email: "[email protected]",
first_name: "Adam",
last_name: "Bowker",
- ...overrides,
-});
+};
+const marta: UserBasic = {
+ id: 2,
+ uuid: "user-marta",
+ email: "[email protected]",
+ first_name: "Marta",
+ last_name: "Nowak",
+};
-const task = (overrides: Partial<Task> = {}): Task => ({
- id: "task-1",
- task_number: 1,
- slug: "task-1",
- title: "Add feedback modal to spaces view",
- description:
- "Add a feedback modal to the spaces view so people can share thoughts without leaving the feed",
- created_at: "2026-07-17T12:00:00.000Z",
- updated_at: "2026-07-17T12:00:00.000Z",
- origin_product: "user_created",
- created_by: user(),
- ...overrides,
-});
+function run(overrides: Partial<TaskRun>): TaskRun {
+ return {
+ id: "run-1",
+ task: "task-1",
+ team: 1,
+ branch: null,
+ status: "completed",
+ environment: "cloud",
+ log_url: "",
+ error_message: null,
+ output: null,
+ state: {},
+ created_at: "2026-07-01T09:00:00Z",
+ updated_at: "2026-07-01T09:05:00Z",
+ completed_at: null,
+ ...overrides,
+ };
+}
+
+function task(overrides: Partial<Task>): Task {
+ return {
+ id: "task-1",
+ task_number: 1,
+ slug: "task-1",
+ title: "Add feedback modal to spaces view",
+ description:
+ "Add a feedback modal to the spaces view so people can share thoughts without leaving the feed",
+ created_at: "2026-07-01T09:00:00Z",
+ updated_at: "2026-07-01T09:05:00Z",
+ origin_product: "user_created",
+ created_by: adam,
+ repository: "example-org/webapp",
+ ...overrides,
+ };
+}
-const meta: Meta<typeof TaskFeedRow> = {
- title: "Spaces/TaskFeedRow",
- component: TaskFeedRow,
+// Dates sit around the frozen test-runner clock (2026-07-01T10:30Z) so the
+// day separators read Today / Yesterday and the relative times stay stable.
+const tasks: Task[] = [
+ task({
+ id: "task-pr",
+ title: "Fix flaky onboarding e2e test",
+ description:
+ "The onboarding e2e test fails one run in five — find why and fix it",
+ created_at: "2026-07-01T10:00:00Z",
+ updated_at: "2026-07-01T10:20:00Z",
+ latest_run: run({
+ id: "run-pr",
+ task: "task-pr",
+ status: "completed",
+ output: { pr_url: "https://github.com/example-org/webapp/pull/421" },
+ }),
+ }),
+ task({
+ id: "task-running",
+ title: "Investigate signup drop-off",
+ description:
+ "Investigate the signup drop-off we saw over the weekend. Check the funnel between the pricing page and the signup form, and look at whether the new consent banner overlaps the submit button on small screens.",
+ created_at: "2026-07-01T09:15:00Z",
+ updated_at: "2026-07-01T09:40:00Z",
+ created_by: marta,
+ latest_run: run({
+ id: "run-running",
+ task: "task-running",
+ status: "in_progress",
+ }),
+ }),
+ task({
+ id: "task-multi-pr",
+ title: "Split the settings page into sections",
+ description: "Split the settings page into sections with one PR each",
+ created_at: "2026-06-30T16:00:00Z",
+ updated_at: "2026-06-30T18:00:00Z",
+ latest_run: run({
+ id: "run-multi",
+ task: "task-multi-pr",
+ status: "completed",
+ output: {
+ pr_urls: [
+ "https://github.com/example-org/webapp/pull/415",
+ "https://github.com/example-org/webapp/pull/416",
+ "https://github.com/example-org/webapp/pull/417",
+ ],
+ },
+ }),
+ }),
+ task({
+ id: "task-other-repo",
+ title: "Bump the SDK to the latest release",
+ description: "Bump the SDK to the latest release and fix the type breaks",
+ created_at: "2026-06-30T11:00:00Z",
+ updated_at: "2026-06-30T11:30:00Z",
+ repository: "example-org/sdk",
+ created_by: marta,
+ latest_run: run({
+ id: "run-failed",
+ task: "task-other-repo",
+ status: "failed",
+ }),
+ }),
+ task({
+ id: "task-old",
+ title: "Summarize last week's shipped changes",
+ description: "Summarize last week's shipped changes for the changelog",
+ created_at: "2026-06-24T12:00:00Z",
+ updated_at: "2026-06-24T12:10:00Z",
+ created_by: null,
+ origin_product: "slack",
+ }),
+];
+
+const systemMessages = [
+ {
+ id: "system-context",
+ createdAt: "2026-06-30T10:59:59Z",
+ text: "Building CONTEXT.md for this channel",
+ },
+];
+
+function MockComposer() {
+ return (
+ <div className="rounded-xl border border-(--gray-6) bg-(--gray-2) px-4 py-3 text-(--gray-9) text-sm">
+ Start a new task…
+ </div>
+ );
+}
+
+const meta: Meta<typeof ChannelFeedView> = {
+ title: "Spaces/ChannelFeedView",
+ component: ChannelFeedView,
+ parameters: { layout: "fullscreen" },
decorators: [
(Story) => (
- <div className="max-w-xl">
+ <div className="flex h-[720px] flex-col">
<Story />
</div>
),
],
-};
-
-export default meta;
-type Story = StoryObj<typeof TaskFeedRow>;
-
-export const HumanStarted: Story = {
- args: {
- task: task(),
- children: <MockTaskCard title="Add feedback modal to spaces view" />,
- },
-};
-
-export const HumanEmailOnly: Story = {
args: {
- task: task({
- created_by: user({ first_name: undefined, last_name: undefined }),
- title: "Make background color configurable",
- description: "Make the space background color configurable in settings",
- }),
- children: <MockTaskCard title="Make background color configurable" />,
+ channelId: "channel-1",
+ isLoading: false,
+ onOpenTask: () => undefined,
+ onOpenThread: () => undefined,
},
};
-export const AgentOrigin: Story = {
- args: {
- task: task({
- origin_product: "slack",
- title: "Investigate signup drop-off",
- description: "Investigate the signup drop-off we saw over the weekend",
- }),
- children: <MockTaskCard title="Investigate signup drop-off" />,
- },
-};
+export default meta;
+type Story = StoryObj<typeof ChannelFeedView>;
-export const LongPrompt: Story = {
+export const Feed: Story = {
args: {
- task: task({
- description:
- "Rework the space feed so each row reads as the person who started the task rather than the agent, show a preview of their prompt under the header, keep the task card below, and make sure long prompts truncate cleanly instead of pushing the card down the feed",
- }),
- children: <MockTaskCard title="Rework the space feed attribution" />,
+ tasks,
+ systemMessages,
+ composer: <MockComposer />,
},
};
-export const NoPrompt: Story = {
+export const PendingKickoff: Story = {
args: {
- task: task({ description: "", title: "Untitled task" }),
- children: <MockTaskCard title="Untitled task" />,
+ tasks: tasks.slice(1),
+ composer: <MockComposer />,
+ pending: [
+ {
+ id: "pending-1",
+ prompt: "Add a dark-mode toggle to the settings page",
+ },
+ ],
},
};
-export const NoStarter: Story = {
+export const EmptyChannel: Story = {
args: {
- task: task({
- created_by: null,
- title: "Untitled task",
- description: "Summarize this week's shipped changes",
- }),
- children: <MockTaskCard title="Summarize this week's shipped changes" />,
+ tasks: [],
+ composer: <MockComposer />,
+ emptyState: (
+ <div className="mx-auto w-full max-w-[660px] py-10 text-center text-(--gray-9) text-sm">
+ No tasks yet. Start one above.
+ </div>
+ ),
},
};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
index 8ea61a4c3e39..0484632ff588 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
@@ -1,4 +1,4 @@
-import type { Task, TaskThreadMessage } from "@posthog/shared/domain-types";
+import type { Task } from "@posthog/shared/domain-types";
import { Theme } from "@radix-ui/themes";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -26,13 +26,6 @@ vi.mock("@tanstack/react-router", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskData", () => ({
useChannelTaskData: () => undefined,
}));
-const threadMocks = vi.hoisted(() => ({
- messages: [] as TaskThreadMessage[],
-}));
-
-vi.mock("@posthog/ui/features/canvas/hooks/useTaskThread", () => ({
- useTaskThread: () => ({ messages: threadMocks.messages }),
-}));
vi.mock("@posthog/ui/features/sidebar/useTaskPrStatus", () => ({
useTaskPrStatus: () => ({ prState: null }),
}));
@@ -40,7 +33,12 @@ vi.mock("@posthog/ui/features/browser-tabs/TaskTabIcon", () => ({
TaskTabIcon: () => <span />,
}));
-import { ReplyFooter, TaskCard, TaskFeedRow } from "./ChannelFeedView";
+import {
+ ExpandablePrompt,
+ mergeFeedEntries,
+ stripContextBlocks,
+ TaskCard,
+} from "./ChannelFeedView";
const task = {
id: "task-1",
@@ -62,7 +60,6 @@ const task = {
afterEach(() => {
vi.restoreAllMocks();
- threadMocks.messages = [];
});
// ExpandablePrompt measures how the prompt wraps to decide where to cut and
@@ -87,7 +84,7 @@ function mockLayout(charsPerLine: number) {
);
}
-describe("TaskFeedRow", () => {
+describe("ChannelFeedView", () => {
it("reports when its task is opened", async () => {
const user = userEvent.setup();
const onOpen = vi.fn();
@@ -107,12 +104,12 @@ describe("TaskFeedRow", () => {
const user = userEvent.setup();
const { container } = render(
<Theme>
- <TaskFeedRow task={task} />
+ <ExpandablePrompt lines={2}>{task.description}</ExpandablePrompt>
</Theme>,
);
const prompt = container.querySelector(
- "[data-slot=thread-item-body]",
+ "[data-slot=expandable-prompt]",
) as HTMLElement;
// The visible text is the non-measure child (the measure copy is aria-hidden).
const visible = Array.from(prompt.children).find(
@@ -135,34 +132,43 @@ describe("TaskFeedRow", () => {
mockLayout(1000);
render(
<Theme>
- <TaskFeedRow task={task} />
+ <ExpandablePrompt lines={2}>{task.description}</ExpandablePrompt>
</Theme>,
);
expect(screen.queryByRole("button")).not.toBeInTheDocument();
});
- it("wears the agent's face on an agent reply", () => {
- // An agent reply carries no user, so the person avatar fell back to an initial and every
- // agent in the thread collapsed onto one slot.
- threadMocks.messages = [
- {
- id: "agent-reply",
- task: task.id,
- author_kind: "agent",
- content: "Finished the task",
- created_at: "2026-07-17T12:05:00.000Z",
- author: null,
- } as unknown as TaskThreadMessage,
- ];
- const { container } = render(
- <ReplyFooter taskId={task.id} inView onOpenThread={() => undefined} />,
- );
+ // Guards against injected context wrappers (Slack thread history, channel
+ // CONTEXT.md) leaking verbatim into the card's prompt snippet.
+ it("strips injected context blocks from prompts", () => {
+ const description =
+ '<slack_thread_context>\nThread started by someone.\n</slack_thread_context>\n\nfix the flaky test in <channel_context channel="web">context body</channel_context> ci';
+
+ expect(stripContextBlocks(description)).toBe("fix the flaky test in ci");
+ });
- expect(screen.getByText("1 reply")).toBeInTheDocument();
- expect(screen.queryByText("U")).toBeNull();
- expect(
- container.querySelector('[data-slot="avatar-fallback"] svg'),
- ).not.toBeNull();
+ // Guards the feed's direction (newest first, not chat-style oldest first)
+ // and the tie-break that keeps a same-timestamp announcement directly under
+ // the task card it describes.
+ it("merges entries newest-first with announcements under their card", () => {
+ const older = {
+ ...task,
+ id: "task-old",
+ created_at: "2026-07-16T12:00:00.000Z",
+ };
+ const announcement = {
+ id: "system-1",
+ createdAt: task.created_at,
+ text: "Building CONTEXT.md",
+ };
+
+ const entries = mergeFeedEntries([older, task], [announcement]);
+
+ expect(entries.map((entry) => entry.id)).toEqual([
+ "task-1",
+ "system-1",
+ "task-old",
+ ]);
});
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
index 2090760aca8f..f8b3633b5988 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
@@ -1,8 +1,10 @@
import {
+ AppWindowIcon,
ArrowSquareOutIcon,
ChatCircleIcon,
GitBranchIcon,
- LinkIcon,
+ GitPullRequestIcon,
+ PlusIcon,
RobotIcon,
} from "@phosphor-icons/react";
import { taskFeedRunStatus } from "@posthog/core/canvas/channelFeed";
@@ -10,37 +12,26 @@ import {
RUN_STATUS_LABELS,
runStatusVariant,
} from "@posthog/core/canvas/runStatus";
+import { buildThreadTimeline } from "@posthog/core/canvas/threadTimeline";
+import type { PrCheck } from "@posthog/core/git/router-schemas";
+import { parsePrNumber } from "@posthog/core/git-interaction/prStatus";
import { xmlToPlainText } from "@posthog/core/message-editor/content";
import {
- Avatar,
- AvatarFallback,
AvatarGroup,
Badge,
Card,
CardContent,
- ChatMessageScroller,
- ChatMessageScrollerButton,
- ChatMessageScrollerContent,
- ChatMessageScrollerItem,
- ChatMessageScrollerProvider,
- ChatMessageScrollerViewport,
cn,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
Spinner,
- ThreadItem,
- ThreadItemAction,
- ThreadItemActions,
- ThreadItemAuthor,
- ThreadItemBody,
- ThreadItemContent,
- ThreadItemGutter,
- ThreadItemHeader,
- ThreadItemReplies,
- ThreadItemRepliesLabel,
- ThreadItemRepliesMeta,
- ThreadItemTimestamp,
- useChatMessageScroller,
} from "@posthog/quill";
-import { formatRelativeTimeShort } from "@posthog/shared";
+import {
+ formatRelativeTimeShort,
+ mergePrUrls,
+ readPrUrls,
+} from "@posthog/shared";
import type {
Task,
TaskRunStatus,
@@ -48,18 +39,28 @@ import type {
} from "@posthog/shared/domain-types";
import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
import { TaskTabIcon } from "@posthog/ui/features/browser-tabs/TaskTabIcon";
+import { buildRows } from "@posthog/ui/features/canvas/components/taskArtifactRows";
import type { ChannelFeedSystemMessage } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
import { useChannelTaskData } from "@posthog/ui/features/canvas/hooks/useChannelTaskData";
import { useMarkTaskActivityRead } from "@posthog/ui/features/canvas/hooks/useMarkTaskActivityRead";
import { useTaskThread } from "@posthog/ui/features/canvas/hooks/useTaskThread";
+import type { ThreadPanelTab } from "@posthog/ui/features/canvas/stores/threadPanelStore";
import { taskCardNavigation } from "@posthog/ui/features/canvas/taskCardNavigation";
-import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";
+import { canvasArtifactOpenHandler } from "@posthog/ui/features/canvas/utils/canvasArtifactNavigation";
import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { usePrArtifact } from "@posthog/ui/features/git-interaction/usePrArtifact";
+import { usePrTitles } from "@posthog/ui/features/git-interaction/usePrDetails";
+import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
+import { usePrChecks } from "@posthog/ui/features/pr-review/usePrChecks";
import {
type SidebarPrState,
useTaskPrStatus,
} from "@posthog/ui/features/sidebar/useTaskPrStatus";
+import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { useInView } from "@posthog/ui/primitives/hooks/useInView";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
import { Text } from "@radix-ui/themes";
import { Link } from "@tanstack/react-router";
import {
@@ -78,6 +79,20 @@ import {
// shared query key means an open panel naturally speeds the row up too.
const FEED_REPLIES_POLL_INTERVAL_MS = 15_000;
+// Injected context wrappers a prompt may carry (Slack thread history, a
+// channel's CONTEXT.md, canvas instructions, saved personalization). The feed
+// shows what the user actually asked, so these are stripped — the timeline
+// renders them as their own collapsible surfaces.
+const CONTEXT_BLOCK_REGEX =
+ /<(slack_thread_context|channel_context|canvas_generation_instructions|user_custom_instructions)\b[^>]*>[\s\S]*?<\/\1>/g;
+
+export function stripContextBlocks(text: string): string {
+ return text
+ .replace(CONTEXT_BLOCK_REGEX, "")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
// Once a PR exists its GitHub state is the truest top-line status — more
// accurate than the run status, which routinely lingers on "in_progress"
// (or a stale cloud status) after the agent opens the PR. Mirrors the PR
@@ -106,7 +121,6 @@ interface TaskStatusDisplay {
base: ReactNode;
// The PR's GitHub state, shown alongside the run badge when a PR exists.
prState: Exclude<SidebarPrState, null> | null;
- // Whether the PR has merged — the card lifts this to a purple border + tint.
isMerged: boolean;
}
@@ -209,6 +223,31 @@ function TaskStatusBadge({ display }: { display: TaskStatusDisplay }) {
);
}
+// The one-line task summary pinned under the activity panel's tabs: icon,
+// truncated title, live status. Links to the task's full view.
+export function TaskSummaryRow({
+ task,
+ channelId,
+}: {
+ task: Task;
+ channelId: string;
+}) {
+ const statusDisplay = useTaskStatusDisplay(task);
+ return (
+ <Link
+ {...taskCardNavigation(channelId, task.id)}
+ preload="intent"
+ className="flex min-w-0 items-center gap-2 border-b px-3 py-2 text-inherit no-underline outline-none transition-colors hover:bg-fill-hover focus-visible:ring-(--accent-8) focus-visible:ring-2"
+ >
+ <TaskTabIcon task={task} size={14} />
+ <span className="min-w-0 flex-1 truncate font-medium text-[13px]">
+ {task.title || "Untitled task"}
+ </span>
+ <TaskStatusBadge display={statusDisplay} />
+ </Link>
+ );
+}
+
// A kickoff a user just submitted, before its task exists on the backend. The
// feed shows it optimistically so a submit reacts instantly instead of waiting
// on the create round trip; it's swapped for the real card once created.
@@ -297,100 +336,23 @@ export function TaskCard({
);
}
-// The reply row under the card, always present at a constant height: the
-// Slack-style teaser (author facepile, count, last-reply time) once the thread
-// has messages, and a quiet "Reply" affordance otherwise. Keeping the row
-// mounted at a fixed height means the teaser swaps in after the thread fetch
-// lands without shifting the feed — and it surfaces an always-visible way into
-// the thread instead of hiding it in the hover toolbar.
-//
-// The fetch/poll only runs for near-viewport rows (`inView`); off-screen rows
-// render the static affordance and idle, so a long feed isn't polling per row.
-export function ReplyFooter({
- taskId,
- inView,
- onOpenThread,
-}: {
- taskId: string;
- inView: boolean;
- onOpenThread: () => void;
-}) {
- const { messages } = useTaskThread(taskId, {
- pollIntervalMs: FEED_REPLIES_POLL_INTERVAL_MS,
- enabled: inView,
- markActivityRead: false,
- });
- // Keyed by who authored the reply, not by author uuid: an agent reply carries no user, so
- // every agent in the thread collapsed onto one "unknown" slot and wore a person's fallback
- // initial. The whole message is kept, because drawing the agent needs its kind.
- const authors = useMemo(() => {
- const seen = new Map<string, (typeof messages)[number]>();
- for (const message of messages) {
- const authorKind = message.author_kind ?? "human";
- const key =
- authorKind === "human"
- ? `human:${message.author?.uuid ?? "unknown"}`
- : authorKind;
- if (!seen.has(key)) seen.set(key, message);
- }
- return [...seen.entries()].slice(0, 4);
- }, [messages]);
-
- if (messages.length === 0) {
- // A single avatar-sized slot keeps this row the exact height of the
- // populated teaser, so swapping to it after the fetch never shifts the feed.
- return (
- <ThreadItemReplies onClick={onOpenThread} className="mt-1">
- <AvatarGroup size="xs">
- <Avatar size="xs">
- <AvatarFallback>
- <ChatCircleIcon size={12} />
- </AvatarFallback>
- </Avatar>
- </AvatarGroup>
- <ThreadItemRepliesLabel>Reply</ThreadItemRepliesLabel>
- </ThreadItemReplies>
- );
- }
-
- const last = messages[messages.length - 1];
- return (
- <ThreadItemReplies onClick={onOpenThread} className="mt-1">
- <AvatarGroup size="xs">
- {authors.map(([key, message]) =>
- message.author_kind === "agent" ? (
- <Avatar key={key} size="xs">
- <AvatarFallback>
- <RobotIcon size={12} />
- </AvatarFallback>
- </Avatar>
- ) : (
- <UserAvatar key={key} user={message.author} size="xs" />
- ),
- )}
- </AvatarGroup>
- <ThreadItemRepliesLabel>
- {messages.length} {messages.length === 1 ? "reply" : "replies"}
- </ThreadItemRepliesLabel>
- <ThreadItemRepliesMeta>
- Last reply {formatRelativeTimeShort(last.created_at)}
- </ThreadItemRepliesMeta>
- </ThreadItemReplies>
- );
-}
-
function channelTaskStarter(task: Task): UserBasic | null {
return task.origin_product === "user_created"
? (task.created_by ?? null)
: null;
}
-function ExpandablePrompt({
+export function ExpandablePrompt({
children,
lines,
+ expandedContent,
}: {
children: string;
lines: 2 | 4;
+ /** Rendered in place of the raw text when expanded — lets the collapsed
+ * clamp stay plain text (the cut is measured on text) while the expanded
+ * view renders rich markdown. */
+ expandedContent?: ReactNode;
}) {
// The prompt is truncated by hand — not with -webkit-line-clamp — so the
// "more" toggle can sit inline right after the ellipsis on the last visible
@@ -398,69 +360,97 @@ function ExpandablePrompt({
// find how much fits, leaving room for the toggle; the visible body renders
// the cut. Measuring the full text (not the visible, already-cut text) keeps
// the ResizeObserver stable instead of oscillating as content swaps.
- const observerRef = useRef<ResizeObserver | null>(null);
+ const [measure, setMeasure] = useState<HTMLDivElement | null>(null);
const [expanded, setExpanded] = useState(false);
const [cut, setCut] = useState<string | null>(null);
- const measureRef = useCallback(
- (measure: HTMLDivElement | null) => {
- observerRef.current?.disconnect();
- observerRef.current = null;
- if (!measure || expanded) return;
-
- const compute = () => {
- const lineHeight = parseFloat(getComputedStyle(measure).lineHeight);
- const maxHeight = lineHeight * lines;
- if (measure.scrollHeight <= maxHeight + 0.5) {
- setCut(null);
- return;
- }
- // Find the longest prefix that still fits in `lines` once "…more" is
- // appended — so the toggle can sit inline right after the ellipsis on the
- // last line. We probe by swapping the measure's text node to "prefix…more"
- // and reading scrollHeight (no per-line geometry), then restore it so the
- // next resize re-measures against the uncut prompt. `children` is the
- // source of truth (and a dep below) so a polled prompt update re-measures
- // even when its rendered size is unchanged.
- const text = measure.firstChild as Text;
- const fits = (end: number) => {
- text.nodeValue = `${children.slice(0, end).trimEnd()}…more`;
- return measure.scrollHeight <= maxHeight + 0.5;
- };
- let lo = 0;
- let hi = children.length;
- let best = 0;
- while (lo <= hi) {
- const mid = (lo + hi) >> 1;
- if (fits(mid)) {
- best = mid;
- lo = mid + 1;
- } else {
- hi = mid - 1;
- }
- }
- text.nodeValue = children;
- // Even when no full character fits alongside "…more" (best === 0, only at
- // extreme narrow widths), still cut so the toggle shows and the prompt
- // stays expandable instead of silently clipped.
- setCut(`${children.slice(0, best).trimEnd()}…`);
+ const measureRef = useCallback((node: HTMLDivElement | null) => {
+ setMeasure(node);
+ }, []);
+
+ useEffect(() => {
+ if (!measure || expanded) return;
+
+ const compute = () => {
+ const lineHeight = parseFloat(getComputedStyle(measure).lineHeight);
+ const maxHeight = lineHeight * lines;
+ if (measure.scrollHeight <= maxHeight + 0.5) {
+ setCut(null);
+ return;
+ }
+ // Find the longest prefix that still fits in `lines` once "…more" is
+ // appended — so the toggle can sit inline right after the ellipsis on the
+ // last line. We probe by swapping the measure's text node to "prefix…more"
+ // and reading scrollHeight (no per-line geometry), then restore it so the
+ // next resize re-measures against the uncut prompt. `children` is the
+ // source of truth (and a dep below) so a polled prompt update re-measures
+ // even when its rendered size is unchanged.
+ const text = measure.lastChild;
+ if (text?.nodeType !== Node.TEXT_NODE) {
+ setCut(null);
+ return;
+ }
+ const fits = (end: number) => {
+ text.nodeValue = `${children.slice(0, end).trimEnd()}…more`;
+ return measure.scrollHeight <= maxHeight + 0.5;
};
+ let lo = 0;
+ let hi = children.length;
+ let best = 0;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ if (fits(mid)) {
+ best = mid;
+ lo = mid + 1;
+ } else {
+ hi = mid - 1;
+ }
+ }
+ text.nodeValue = children;
+ // Even when no full character fits alongside "…more" (best === 0, only at
+ // extreme narrow widths), still cut so the toggle shows and the prompt
+ // stays expandable instead of silently clipped.
+ setCut(`${children.slice(0, best).trimEnd()}…`);
+ };
- compute();
- const observer = new ResizeObserver(compute);
- observer.observe(measure);
- observerRef.current = observer;
- },
- [children, expanded, lines],
- );
+ compute();
+ const observer = new ResizeObserver(compute);
+ observer.observe(measure);
+ return () => observer.disconnect();
+ }, [children, expanded, lines, measure]);
const truncated = cut !== null;
const displayText = expanded || !truncated ? children : cut;
const clampClass = lines === 2 ? "max-h-[2lh]" : "max-h-[4lh]";
+ if (expanded && expandedContent !== undefined) {
+ return (
+ <div data-slot="expandable-prompt" className="min-w-0">
+ {expandedContent}
+ <button
+ type="button"
+ aria-expanded
+ className="text-muted-foreground text-xs underline underline-offset-2 hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ setExpanded(false);
+ }}
+ >
+ less
+ </button>
+ </div>
+ );
+ }
+
return (
- <ThreadItemBody className="wrap-break-word relative overflow-hidden whitespace-pre-line">
+ // A plain div, deliberately not ThreadItemBody: quill's thread body pins
+ // font-size to text-sm and color to --foreground, which would flatten the
+ // card's title/prompt hierarchy. Typography comes from the caller.
+ <div
+ data-slot="expandable-prompt"
+ className="wrap-break-word relative min-w-0 overflow-hidden whitespace-pre-line"
+ >
<div
aria-hidden
className="pointer-events-none invisible absolute top-0 right-0 left-0"
@@ -478,85 +468,305 @@ function ExpandablePrompt({
type="button"
aria-expanded={expanded}
className="pl-1 text-muted-foreground text-xs underline underline-offset-2 hover:text-foreground"
- onClick={() => setExpanded((value) => !value)}
+ onClick={(event) => {
+ event.stopPropagation();
+ setExpanded((value) => !value);
+ }}
>
{expanded ? "less" : "more"}
</button>
)}
</div>
- </ThreadItemBody>
+ </div>
);
}
-export function TaskFeedRow({
- task,
- actions,
- children,
+const CHIP_CLASS =
+ "inline-flex h-6 items-center gap-1.5 rounded-md border border-(--gray-6) bg-(--gray-4) px-2 font-medium text-(--gray-11) text-xs transition-colors hover:border-(--gray-7) hover:bg-(--gray-5)";
+
+// A popover that opens on hover (with a short close delay so the pointer can
+// travel into it) and on click for keyboard and touch. Quill has no HoverCard,
+// so this composes one from Popover; content mounts only while open, which
+// keeps per-item data fetches (PR checks, titles) off the feed's steady-state
+// render. Deliberately no focus handlers: closing returns focus to the
+// trigger, so opening on focus re-opens the popover in an endless blink loop
+// (and hands it to whichever trigger focus lands on next).
+function HoverPopover({
+ trigger,
+ content,
+ contentClassName,
}: {
- task: Task;
- actions?: ReactNode;
- children?: ReactNode;
+ trigger: ReactElement;
+ content: ReactNode;
+ contentClassName?: string;
}) {
- const starter = channelTaskStarter(task);
- const prompt = useMemo(
- () => xmlToPlainText(task.description ?? "").trim(),
- [task.description],
+ const [open, setOpen] = useState(false);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
+ undefined,
+ );
+ useEffect(() => () => clearTimeout(closeTimer.current), []);
+ const show = useCallback(() => {
+ clearTimeout(closeTimer.current);
+ setOpen(true);
+ }, []);
+ const hide = useCallback(() => {
+ clearTimeout(closeTimer.current);
+ closeTimer.current = setTimeout(() => setOpen(false), 150);
+ }, []);
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={trigger}
+ onMouseEnter={show}
+ onMouseLeave={hide}
+ />
+ <PopoverContent
+ // Quill's popover is a fixed 18rem; these cards size to their content.
+ className={cn("w-auto gap-0 p-2", contentClassName)}
+ onMouseEnter={show}
+ onMouseLeave={hide}
+ onClick={(event) => event.stopPropagation()}
+ >
+ {content}
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// One line summarizing a PR's CI: failing beats running beats passing.
+function summarizePrChecks(
+ checks: PrCheck[] | null | undefined,
+): { label: string; color: string } | null {
+ if (!checks || checks.length === 0) return null;
+ let failed = 0;
+ let pending = 0;
+ let passed = 0;
+ for (const check of checks) {
+ if (check.bucket === "fail" || check.bucket === "cancel") failed++;
+ else if (check.bucket === "pending") pending++;
+ else if (check.bucket === "pass") passed++;
+ }
+ if (failed) {
+ return {
+ label: `CI failing · ${failed} ${failed === 1 ? "check" : "checks"}`,
+ color: "var(--red-11)",
+ };
+ }
+ if (pending) return { label: "CI running", color: "var(--amber-11)" };
+ if (passed) return { label: "CI passing", color: "var(--green-11)" };
+ return null;
+}
+
+function PrCiLine({ url }: { url: string }) {
+ const checks = usePrChecks(url);
+ const ci = summarizePrChecks(checks.data);
+ if (!ci) {
+ if (!checks.isPending) return null;
+ return (
+ <div className="flex items-center gap-1.5 text-(--gray-9) text-xs">
+ <Spinner className="size-3" />
+ Checking CI…
+ </div>
+ );
+ }
+ return (
+ <div className="flex items-center gap-1.5 text-(--gray-11) text-xs">
+ <span
+ className="size-1.5 rounded-full"
+ style={{ backgroundColor: ci.color }}
+ />
+ {ci.label}
+ </div>
);
+}
+// The hover card for one PR chip: number + state, truncated title, CI line.
+// Mounted only while the popover is open, so its title/checks fetches never
+// run for chips just sitting in the feed.
+function PrPopoverContent({ url }: { url: string }) {
+ const { prNumber, stateLabel, Icon, iconColor } = usePrArtifact(url);
+ const prUrls = useMemo(() => [url], [url]);
+ const titles = usePrTitles(prUrls);
return (
- <ThreadItem className="rounded-none py-1 pr-8 hover:bg-fill-hover/50">
- <ThreadItemGutter>
- {starter ? (
- <UserAvatar user={starter} />
- ) : (
- <Avatar>
- <AvatarFallback>
- <RobotIcon size={16} />
- </AvatarFallback>
- </Avatar>
- )}
- </ThreadItemGutter>
-
- <ThreadItemContent className="min-w-0">
- <ThreadItemHeader>
- <ThreadItemAuthor>
- {starter ? userDisplayName(starter) : "PostHog"}
- </ThreadItemAuthor>
- {!starter && <Badge variant="info">Agent</Badge>}
- <ThreadItemTimestamp
- dateTime={new Date(task.created_at).toISOString()}
- >
- {formatRelativeTimeShort(task.created_at)}
- </ThreadItemTimestamp>
- </ThreadItemHeader>
+ <div className="flex max-w-72 flex-col gap-1.5">
+ <div className="flex items-center gap-1.5 text-xs">
+ <Icon size={13} style={{ color: iconColor }} />
+ <span className="font-semibold">
+ {prNumber ? `#${prNumber}` : "PR"}
+ </span>
+ {stateLabel && <span className="text-(--gray-9)">{stateLabel}</span>}
+ </div>
+ {titles[url] ? (
+ <div className="truncate font-medium text-sm">{titles[url]}</div>
+ ) : (
+ // The title resolves via gh after open; hold its line so the card
+ // doesn't jump when it lands.
+ <div className="flex h-5 items-center">
+ <Spinner className="size-3" />
+ </div>
+ )}
+ <PrCiLine url={url} />
+ </div>
+ );
+}
- <ExpandablePrompt lines={2}>
- {prompt ||
- (starter ? "started a new task" : "A new task was started")}
- </ExpandablePrompt>
+// One PR inside the "+N PRs" popover: state icon, number, truncated title,
+// CI dot. Same mounted-only-while-open economics as PrPopoverContent.
+function PrPopoverRow({ url }: { url: string }) {
+ const { safeUrl, prNumber, Icon, iconColor } = usePrArtifact(url);
+ const prUrls = useMemo(() => [url], [url]);
+ const titles = usePrTitles(prUrls);
+ const checks = usePrChecks(safeUrl);
+ const ci = summarizePrChecks(checks.data);
+ if (!safeUrl) return null;
+ return (
+ <button
+ type="button"
+ className="flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-(--gray-4)"
+ onClick={(event) => {
+ event.stopPropagation();
+ openExternalUrl(safeUrl);
+ }}
+ >
+ <Icon size={13} className="shrink-0" style={{ color: iconColor }} />
+ <span className="shrink-0 font-medium">
+ {prNumber ? `#${prNumber}` : "PR"}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-(--gray-11)">
+ {titles[url] ?? ""}
+ </span>
+ {ci ? (
+ <span
+ title={ci.label}
+ className="size-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: ci.color }}
+ />
+ ) : (
+ checks.isPending && <Spinner className="size-3 shrink-0" />
+ )}
+ </button>
+ );
+}
- {children}
- </ThreadItemContent>
+// The closed chip renders from the URL alone — no data fetch. usePrArtifact
+// starts a per-PR GitHub details query (a `gh` subprocess per distinct PR),
+// and the feed mounts every card, so the state/title/CI lookups stay inside
+// the hover card, which mounts only when opened.
+function PrChip({ url }: { url: string }) {
+ const parsed = parseHttpsUrl(url);
+ const safeUrl = parsed?.origin === "https://github.com" ? parsed.href : null;
+ if (!safeUrl) return null;
+ const prNumber = parsePrNumber(safeUrl);
+ return (
+ <HoverPopover
+ trigger={
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ title="Pull request"
+ onClick={(event) => {
+ event.stopPropagation();
+ openExternalUrl(safeUrl);
+ }}
+ >
+ <GitPullRequestIcon size={12} />
+ {prNumber ? `#${prNumber}` : "PR"}
+ </button>
+ }
+ content={<PrPopoverContent url={safeUrl} />}
+ />
+ );
+}
- {actions}
- </ThreadItem>
+function OverflowChip({
+ label,
+ children,
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <HoverPopover
+ trigger={
+ <button
+ type="button"
+ className={cn(CHIP_CLASS, "border-dashed text-(--gray-9)")}
+ onClick={(event) => event.stopPropagation()}
+ >
+ {label}
+ </button>
+ }
+ content={<div className="flex min-w-60 flex-col gap-0.5">{children}</div>}
+ />
);
}
const FeedItem = memo(function FeedItem({
task,
- channelId,
inView,
+ showRepo,
onOpenTask,
onOpenThread,
}: {
task: Task;
- channelId: string;
inView: boolean;
+ showRepo: boolean;
onOpenTask: (task: Task) => void;
- onOpenThread: (task: Task) => void;
+ onOpenThread: (task: Task, tab?: ThreadPanelTab) => void;
}) {
const { mutate: markTasksRead } = useMarkTaskActivityRead();
+ const statusDisplay = useTaskStatusDisplay(task);
+ const taskData = useChannelTaskData(task);
+ const starter = channelTaskStarter(task);
+ const prompt = useMemo(
+ () => stripContextBlocks(xmlToPlainText(task.description ?? "")),
+ [task.description],
+ );
+ const prUrls = useMemo(
+ () =>
+ mergePrUrls(
+ readPrUrls(task.latest_run?.output),
+ taskData?.cloudPrUrl ? [taskData.cloudPrUrl] : [],
+ ),
+ [task.latest_run?.output, taskData?.cloudPrUrl],
+ );
+ const { messages } = useTaskThread(task.id, {
+ pollIntervalMs: FEED_REPLIES_POLL_INTERVAL_MS,
+ enabled: inView,
+ markActivityRead: false,
+ });
+ // Canvas artifacts only exist as thread timeline announcements, so the rows
+ // are built from the thread; file rows come from the run outputs either way.
+ const artifacts = useMemo(
+ () =>
+ buildRows(task, buildThreadTimeline(messages), []).filter(
+ (row) => row.kind === "canvas" || row.kind === "file",
+ ),
+ [task, messages],
+ );
+ // Only conversational human rows count as comments — agent/system rows
+ // (turn_complete) would inflate the count and render authorless "U" bubbles
+ // in the facepile, and human-authored event rows (comment announcements like
+ // comment_state_changed) are activity, not something a person typed. Same
+ // rule as buildThreadTimeline's human-message classification.
+ const humanMessages = useMemo(
+ () =>
+ messages.filter(
+ (m) => !m.event && (m.author_kind ?? "human") === "human",
+ ),
+ [messages],
+ );
+ // The starter leads the facepile — it's how the card attributes the task
+ // (the prompt itself carries no name) — followed by comment participants.
+ const authors = useMemo(() => {
+ const seen = new Map<string, UserBasic>();
+ if (starter) seen.set(starter.uuid, starter);
+ for (const message of humanMessages) {
+ const author = message.author;
+ if (author && !seen.has(author.uuid)) seen.set(author.uuid, author);
+ }
+ return [...seen.values()].slice(0, 4);
+ }, [humanMessages, starter]);
const markRead = useCallback(() => {
markTasksRead([
{ task_id: task.id, seen_before: new Date().toISOString() },
@@ -566,122 +776,289 @@ const FeedItem = memo(function FeedItem({
markRead();
onOpenTask(task);
}, [markRead, onOpenTask, task]);
+ // A chip opens its artifact directly: canvases navigate to the canvas, files
+ // open as a tab in the task view (the tab is staged in the layout store, then
+ // the task view is opened to show it). Anything unopenable falls back to the
+ // side pane's Artifacts tab.
+ const openArtifact = useCallback(
+ (artifact: (typeof artifacts)[number]) => {
+ if (artifact.kind === "canvas") {
+ const open = canvasArtifactOpenHandler(artifact.url);
+ if (open) {
+ open();
+ return;
+ }
+ } else if (artifact.artifactId && artifact.runId) {
+ // A task never opened in this session has no panel layout yet, and
+ // openArtifactTab no-ops without one — seed it first so the staged tab
+ // survives into the task view's mount (PanelLayout only initializes
+ // when the layout is missing).
+ const layoutStore = usePanelLayoutStore.getState();
+ if (!layoutStore.getLayout(task.id))
+ layoutStore.initializeTask(task.id);
+ layoutStore.openArtifactTab(task.id, {
+ runId: artifact.runId,
+ artifactId: artifact.artifactId,
+ name: artifact.name,
+ });
+ openTask();
+ return;
+ }
+ onOpenThread(task, "artifacts");
+ },
+ [onOpenThread, openTask, task],
+ );
+ const visiblePrCount = prUrls.length >= 5 ? 1 : 2;
return (
- <TaskFeedRow
- task={task}
- actions={
- // Replying now lives in the always-visible ReplyFooter, so the hover
- // toolbar only carries per-row actions (copy link, open task). Actions
- // anchor to the row's top-right corner; a top tooltip there overhangs
- // the panel edge and gets clipped by the scroll container, so open
- // tooltips toward the content instead.
- <ThreadItemActions aria-label="Message actions" className="inset-bs-2">
- <ThreadItemAction
- label="Copy link to task"
- onClick={() =>
- void copyChannelLink(channelId, "thread_panel", task.id)
+ <Card
+ size="sm"
+ role="button"
+ tabIndex={0}
+ className="mx-auto my-1.5 w-full max-w-[660px] cursor-pointer rounded-xl bg-(--gray-2) py-0 transition-colors hover:border-(--gray-7) hover:bg-(--gray-3)"
+ onClick={() => {
+ markRead();
+ onOpenThread(task);
+ }}
+ onKeyDown={(event) => {
+ // Only when the card itself has focus: descendant buttons (title, PR
+ // and comment chips, the prompt toggle) bubble their key events here,
+ // and preventDefault would swallow their own Enter/Space activation.
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ markRead();
+ onOpenThread(task);
+ }
+ }}
+ >
+ <CardContent className="flex flex-col px-4 pt-3.5 pb-3">
+ <div className="flex items-center gap-3">
+ <div className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <button
+ type="button"
+ className="min-w-0 truncate text-left font-semibold text-sm leading-snug"
+ onClick={(event) => {
+ event.stopPropagation();
+ openTask();
+ }}
+ >
+ {task.title || "Untitled task"}
+ </button>
+ <span className="shrink-0 text-(--gray-9) text-xs">
+ · {formatRelativeTimeShort(task.updated_at)}
+ </span>
+ </div>
+ <TaskStatusBadge display={statusDisplay} />
+ </div>
+ <div className="mt-1.5 text-(--gray-9) text-xs leading-normal">
+ <ExpandablePrompt
+ lines={2}
+ expandedContent={
+ <div className="whitespace-normal text-(--gray-11) [&_pre]:my-1.5">
+ <MarkdownRenderer content={prompt} />
+ </div>
}
>
- <LinkIcon size={15} />
- </ThreadItemAction>
- <ThreadItemAction label="Open task" onClick={openTask}>
- <ArrowSquareOutIcon size={15} />
- </ThreadItemAction>
- </ThreadItemActions>
- }
- >
- <TaskCard task={task} channelId={channelId} onOpen={markRead} />
- <ReplyFooter
- taskId={task.id}
- inView={inView}
- onOpenThread={() => onOpenThread(task)}
- />
- </TaskFeedRow>
+ {prompt || "A new task was started"}
+ </ExpandablePrompt>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-1.5">
+ {showRepo && task.repository && (
+ <span
+ className={cn(CHIP_CLASS, "border-transparent bg-transparent")}
+ >
+ <GitBranchIcon size={12} />
+ {task.repository}
+ </span>
+ )}
+ {prUrls.slice(0, visiblePrCount).map((url) => (
+ <PrChip key={url} url={url} />
+ ))}
+ {prUrls.length > visiblePrCount && (
+ <OverflowChip
+ label={`+${prUrls.length - visiblePrCount} ${
+ prUrls.length - visiblePrCount === 1 ? "PR" : "PRs"
+ }`}
+ >
+ {prUrls.slice(visiblePrCount).map((url) => (
+ <PrPopoverRow key={url} url={url} />
+ ))}
+ </OverflowChip>
+ )}
+ {artifacts.slice(0, 2).map((artifact) => (
+ <button
+ key={artifact.key}
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ openArtifact(artifact);
+ }}
+ >
+ {artifact.kind === "canvas" ? (
+ <AppWindowIcon size={12} />
+ ) : (
+ <FileIcon filename={artifact.name} size={12} />
+ )}
+ <span className="max-w-40 truncate">{artifact.name}</span>
+ </button>
+ ))}
+ {artifacts.length > 2 && (
+ <OverflowChip
+ label={`+${artifacts.length - 2} ${
+ artifacts.length - 2 === 1 ? "file" : "files"
+ }`}
+ >
+ {artifacts.slice(2).map((artifact) => (
+ <button
+ key={artifact.key}
+ type="button"
+ className={cn(CHIP_CLASS, "w-full")}
+ onClick={(event) => {
+ event.stopPropagation();
+ openArtifact(artifact);
+ }}
+ >
+ {artifact.kind === "canvas" ? (
+ <AppWindowIcon size={12} />
+ ) : (
+ <FileIcon filename={artifact.name} size={12} />
+ )}
+ <span className="truncate">{artifact.name}</span>
+ </button>
+ ))}
+ </OverflowChip>
+ )}
+ {humanMessages.length > 0 ? (
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenThread(task, "comments");
+ }}
+ >
+ <ChatCircleIcon size={12} />
+ <span className="font-semibold text-(--gray-9)">
+ {humanMessages.length}
+ </span>
+ </button>
+ ) : (
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenThread(task, "comments");
+ }}
+ >
+ <PlusIcon size={12} />
+ Comment
+ </button>
+ )}
+ <span className="flex-1" />
+ {authors.length > 0 && (
+ <HoverPopover
+ trigger={
+ // A real button: the popover trigger expects native button
+ // semantics, and it gives keyboard users a way to open the
+ // participant list.
+ <button
+ type="button"
+ aria-label="Participants"
+ className="inline-flex cursor-default"
+ onClick={(event) => event.stopPropagation()}
+ >
+ {/* reverse: the stack sits at the card's right edge, so the
+ hover expansion must spread left, into the card — the
+ default spreads right, off the edge and clipped. */}
+ <AvatarGroup size="xs" stacked reverse>
+ {authors.map((author) => (
+ <UserAvatar key={author.uuid} user={author} size="xs" />
+ ))}
+ </AvatarGroup>
+ </button>
+ }
+ content={
+ <div className="flex flex-col gap-1.5">
+ {authors.map((author) => (
+ <div
+ key={author.uuid}
+ className="flex items-center gap-2 text-xs"
+ >
+ <UserAvatar user={author} size="xs" />
+ {userDisplayName(author)}
+ </div>
+ ))}
+ </div>
+ }
+ />
+ )}
+ </div>
+ </CardContent>
+ </Card>
);
});
-// One feed row: owns the scroller item (the `content-visibility` boundary, so
-// its box is always laid out and safe to observe) and reports whether it is
-// near the viewport, letting `FeedItem` shed off-screen polling.
+// One feed row: owns the `content-visibility` boundary (so its box is always
+// laid out and safe to observe) and reports whether it is near the viewport,
+// letting `FeedItem` shed off-screen polling. The intrinsic-size estimate
+// keeps the scrollbar stable while off-screen rows are skipped; `auto` still
+// remembers each row's real height after first paint.
function FeedRow({
task,
- channelId,
+ showRepo,
onOpenTask,
onOpenThread,
}: {
task: Task;
- channelId: string;
+ showRepo: boolean;
onOpenTask: (task: Task) => void;
- onOpenThread: (task: Task) => void;
+ onOpenThread: (task: Task, tab?: ThreadPanelTab) => void;
}) {
const [ref, inView] = useInView<HTMLDivElement>({ rootMargin: "1200px 0px" });
return (
- <ChatMessageScrollerItem
+ <div
ref={ref}
- messageId={task.id}
- // Rows already get `content-visibility:auto` from quill, but its default
- // `contain-intrinsic-size` (10rem) under-reserves a feed row (message +
- // task card + replies ≈ 13rem), so off-screen rows collapse too small and
- // the scrollbar jumps as they paint in. A closer estimate keeps scrolling
- // stable; `auto` still remembers each row's real height after first paint.
- className="[contain-intrinsic-size:auto_13rem]"
+ className="[contain-intrinsic-size:auto_9rem] [content-visibility:auto]"
>
<FeedItem
task={task}
- channelId={channelId}
inView={inView}
+ showRepo={showRepo}
onOpenTask={onOpenTask}
onOpenThread={onOpenThread}
/>
- </ChatMessageScrollerItem>
+ </div>
);
}
-// The optimistic kickoff row: the user's message plus a "Starting…" card,
-// shown the moment they submit. Deliberately dumb — no per-task data hooks or
-// polls (there's no task id to query yet); it's replaced by a real FeedRow as
-// soon as the task is created.
-function PendingFeedRow({
- pending,
- createdAt,
-}: {
- pending: PendingKickoff;
- createdAt: string;
-}) {
+// The optimistic kickoff row: the user's prompt as a "Starting…" card, shown
+// at the top of the feed the moment they submit. Deliberately dumb — no
+// per-task data hooks or polls (there's no task id to query yet); it's
+// replaced by a real FeedRow as soon as the task is created.
+function PendingFeedRow({ pending }: { pending: PendingKickoff }) {
return (
- <ChatMessageScrollerItem
- messageId={pending.id}
- className="[contain-intrinsic-size:auto_13rem]"
+ <Card
+ size="sm"
+ className="mx-auto my-1.5 w-full max-w-[660px] rounded-xl bg-(--gray-2) py-0"
>
- <ThreadItem className="rounded-none py-4 pr-8">
- <ThreadItemGutter>
- <Avatar>
- <AvatarFallback>
- <Spinner className="size-4" />
- </AvatarFallback>
- </Avatar>
- </ThreadItemGutter>
- <ThreadItemContent className="min-w-0">
- <ThreadItemHeader>
- <ThreadItemAuthor>You</ThreadItemAuthor>
- <ThreadItemTimestamp dateTime={createdAt}>now</ThreadItemTimestamp>
- </ThreadItemHeader>
- <ExpandablePrompt lines={4}>{pending.prompt}</ExpandablePrompt>
- <Card
- size="sm"
- className="mt-1.5 w-full max-w-[820px] rounded-sm py-0"
- >
- <CardContent className="py-2.5">
- <Badge variant="info">
- <Spinner className="size-2.5" />
- Starting…
- </Badge>
- </CardContent>
- </Card>
- </ThreadItemContent>
- </ThreadItem>
- </ChatMessageScrollerItem>
+ <CardContent className="flex flex-col px-4 pt-3.5 pb-3">
+ <div className="flex items-start gap-3">
+ <span className="min-w-0 flex-1 font-semibold text-sm leading-snug">
+ New task
+ </span>
+ <Badge variant="info">
+ <Spinner className="size-2.5" />
+ Starting…
+ </Badge>
+ </div>
+ <div className="mt-1.5 text-(--gray-9) text-xs leading-normal">
+ <ExpandablePrompt lines={2}>{pending.prompt}</ExpandablePrompt>
+ </div>
+ </CardContent>
+ </Card>
);
}
@@ -691,57 +1068,34 @@ function PendingFeedRow({
// as a task row, minus the task card and reply footer.
function SystemFeedRow({ message }: { message: ChannelFeedSystemMessage }) {
return (
- <ChatMessageScrollerItem messageId={message.id}>
- <ThreadItem className="rounded-none py-1 pr-8">
- <ThreadItemGutter>
- {message.author ? (
- <UserAvatar user={message.author} />
- ) : (
- <Avatar>
- <AvatarFallback>
- <RobotIcon size={16} />
- </AvatarFallback>
- </Avatar>
- )}
- </ThreadItemGutter>
- <ThreadItemContent className="min-w-0">
- <ThreadItemHeader>
- <ThreadItemAuthor>
- {message.author ? userDisplayName(message.author) : "PostHog"}
- </ThreadItemAuthor>
- {!message.author && <Badge variant="info">Agent</Badge>}
- <ThreadItemTimestamp dateTime={message.createdAt}>
- {formatRelativeTimeShort(message.createdAt)}
- </ThreadItemTimestamp>
- </ThreadItemHeader>
- <ThreadItemBody className="wrap-break-word text-muted-foreground">
+ <div className="mx-auto flex w-full min-w-0 max-w-[660px] items-center gap-2 px-1 py-1.5 text-(--gray-9) text-xs">
+ {message.author ? (
+ <UserAvatar user={message.author} size="xs" />
+ ) : (
+ <RobotIcon size={14} className="shrink-0" />
+ )}
+ <span className="min-w-0 truncate">
+ {message.author ? (
+ <>
+ <span className="font-medium text-(--gray-11)">
+ {userDisplayName(message.author)}
+ </span>{" "}
{message.text}
- </ThreadItemBody>
- </ThreadItemContent>
- </ThreadItem>
- </ChatMessageScrollerItem>
+ </>
+ ) : (
+ message.text
+ )}
+ </span>
+ <span className="shrink-0">
+ · {formatRelativeTimeShort(message.createdAt)}
+ </span>
+ </div>
);
}
-// Follow the feed to the bottom when *this* user posts, but not when a
-// teammate's card arrives via polling — a new `pending` kickoff is only ever
-// added by the local composer, so it's the right signal. Must live inside the
-// scroller provider to reach `scrollToEnd`. Renders nothing.
-function FollowOwnPost({ latestPendingId }: { latestPendingId?: string }) {
- const { scrollToEnd } = useChatMessageScroller();
- const prevRef = useRef(latestPendingId);
- useEffect(() => {
- if (latestPendingId && latestPendingId !== prevRef.current) {
- scrollToEnd();
- }
- prevRef.current = latestPendingId;
- }, [latestPendingId, scrollToEnd]);
- return null;
-}
-
// A single feed entry, either a real task card or a synthetic system row, tagged
// with the timestamp used to interleave the two.
-type FeedEntry =
+export type FeedEntry =
| { kind: "task"; id: string; createdAt: string; task: Task }
| {
kind: "system";
@@ -750,10 +1104,70 @@ type FeedEntry =
message: ChannelFeedSystemMessage;
};
-// The Slack-style channel feed: every task kicked off in the channel, oldest
-// first, rendered as a kickoff message + task card. Multiplayer — the list is
-// team-visible and polls for teammates' cards and status flips. Synthetic
-// "PostHog agent" system rows (context lifecycle) are interleaved by timestamp.
+// Merge tasks + system rows into one newest-first list. ISO timestamps sort
+// lexically, so a plain string compare is chronological. Announcements are
+// posted 1ms before the task they describe; if the backend truncates that
+// sub-second offset the timestamps tie, so break ties task-first to keep the
+// announcement directly under its card.
+export function mergeFeedEntries(
+ tasks: Task[],
+ systemMessages: ChannelFeedSystemMessage[],
+): FeedEntry[] {
+ const merged: FeedEntry[] = [
+ ...tasks.map((task) => ({
+ kind: "task" as const,
+ id: task.id,
+ createdAt: task.created_at,
+ task,
+ })),
+ ...systemMessages.map((message) => ({
+ kind: "system" as const,
+ id: message.id,
+ createdAt: message.createdAt,
+ message,
+ })),
+ ];
+ merged.sort(
+ (a, b) =>
+ b.createdAt.localeCompare(a.createdAt) ||
+ (a.kind === b.kind ? 0 : a.kind === "task" ? -1 : 1),
+ );
+ return merged;
+}
+
+const DAY_MS = 86_400_000;
+
+// "Today" / "Yesterday" / "Aug 8" (with the year once it differs) for the
+// feed's day separators.
+function feedDayLabel(iso: string, now: Date): string {
+ const date = new Date(iso);
+ const startOfDay = (d: Date) =>
+ new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
+ const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);
+ if (days <= 0) return "Today";
+ if (days === 1) return "Yesterday";
+ return date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ ...(date.getFullYear() !== now.getFullYear() ? { year: "numeric" } : {}),
+ });
+}
+
+function DaySeparator({ label }: { label: string }) {
+ return (
+ <div className="mx-auto flex w-full max-w-[660px] items-center gap-3 pt-5 pb-2 font-semibold text-(--gray-9) text-[11px] uppercase tracking-wider">
+ <span className="h-px flex-1 bg-(--gray-5)" />
+ {label}
+ <span className="h-px flex-1 bg-(--gray-5)" />
+ </div>
+ );
+}
+
+// The channel feed: every task kicked off in the channel, newest first in a
+// plain top-down scroll (Twitter-style, not a bottom-anchored chat).
+// Multiplayer — the list is team-visible and polls for teammates' cards and
+// status flips. Synthetic "PostHog agent" system rows (context lifecycle) are
+// interleaved by timestamp, and day separators group the cards.
export function ChannelFeedView({
channelId,
tasks,
@@ -762,6 +1176,7 @@ export function ChannelFeedView({
isLoading,
emptyState,
intro,
+ composer,
onOpenTask,
onOpenThread,
}: {
@@ -775,98 +1190,127 @@ export function ChannelFeedView({
* (name, creation line, onboarding card). When set, the feed renders even
* with no entries instead of falling back to `emptyState`. */
intro?: ReactElement;
+ /** The new-session composer, rendered at the top of the feed column
+ * (Twitter-style) so it scrolls away with the content and shares the cards'
+ * width. Rendered in every state, including loading and empty. */
+ composer?: ReactNode;
onOpenTask: (task: Task) => void;
- onOpenThread: (task: Task) => void;
+ onOpenThread: (task: Task, tab?: ThreadPanelTab) => void;
}) {
- // Merge tasks + system rows into one chronological list. ISO timestamps sort
- // lexically, so a plain string compare is chronological. Announcements are
- // posted 1ms before the task they describe; if the backend truncates that
- // sub-second offset the timestamps tie, so break ties system-row-first to
- // keep the announcement above its card.
- const entries = useMemo<FeedEntry[]>(() => {
- const merged: FeedEntry[] = [
- ...tasks.map((task) => ({
- kind: "task" as const,
- id: task.id,
- createdAt: task.created_at,
- task,
- })),
- ...(systemMessages ?? []).map((message) => ({
- kind: "system" as const,
- id: message.id,
- createdAt: message.createdAt,
- message,
- })),
- ];
- merged.sort(
- (a, b) =>
- a.createdAt.localeCompare(b.createdAt) ||
- (a.kind === b.kind ? 0 : a.kind === "system" ? -1 : 1),
- );
- return merged;
- }, [tasks, systemMessages]);
+ const entries = useMemo<FeedEntry[]>(
+ () => mergeFeedEntries(tasks, systemMessages ?? []),
+ [tasks, systemMessages],
+ );
+
+ // The channel's dominant repo: on a single-repo channel every card would
+ // repeat the same chip, so the repo chip only renders on tasks that target a
+ // different repo than most of the channel.
+ const dominantRepo = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const task of tasks) {
+ if (!task.repository) continue;
+ counts.set(task.repository, (counts.get(task.repository) ?? 0) + 1);
+ }
+ let best: string | null = null;
+ let bestCount = 0;
+ for (const [repo, count] of counts) {
+ if (count > bestCount) {
+ best = repo;
+ bestCount = count;
+ }
+ }
+ return best;
+ }, [tasks]);
const viewportRef = useRef<HTMLDivElement>(null);
- // biome-ignore lint/correctness/useExhaustiveDependencies: channelId is a trigger — switching channels or finishing the initial load swaps/completes the rows without a remount, so re-land at the latest message
+ // biome-ignore lint/correctness/useExhaustiveDependencies: channelId is a trigger — switching channels or finishing the initial load swaps/completes the rows without a remount, so re-land at the latest cards
useLayoutEffect(() => {
if (isLoading) return;
- const viewport = viewportRef.current;
- if (viewport) viewport.scrollTop = viewport.scrollHeight;
+ viewportRef.current?.scrollTo({ top: 0 });
}, [channelId, isLoading]);
- // Wait for the complete feed: the scroller's initial end-scroll fires once,
- // so mounting around partial rows would land it short of the latest message.
+ // Follow the feed to the top when *this* user posts (their card lands at the
+ // top), but not when a teammate's card arrives via polling — a new `pending`
+ // kickoff is only ever added by the local composer, so it's the right signal.
+ const latestPendingId = pending[pending.length - 1]?.id;
+ const prevPendingRef = useRef(latestPendingId);
+ useEffect(() => {
+ if (latestPendingId && latestPendingId !== prevPendingRef.current) {
+ viewportRef.current?.scrollTo({ top: 0, behavior: "smooth" });
+ }
+ prevPendingRef.current = latestPendingId;
+ }, [latestPendingId]);
+
+ const composerBlock = composer && (
+ <div className="mx-auto mb-2 w-full max-w-[660px]">{composer}</div>
+ );
+
if (isLoading && pending.length === 0) {
return (
- <div className="flex flex-1 items-center justify-center">
- <Spinner />
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto flex w-full flex-col px-4 pt-4">
+ {composerBlock}
+ <div className="flex justify-center py-16">
+ <Spinner />
+ </div>
+ </div>
</div>
);
}
if (entries.length === 0 && pending.length === 0 && !intro) {
- return <div className="flex-1 overflow-y-auto">{emptyState}</div>;
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto w-full px-4 pt-4 pb-10">
+ {composerBlock}
+ {emptyState}
+ </div>
+ </div>
+ );
}
const now = new Date();
- const latestPendingId = pending[pending.length - 1]?.id;
+ const rows: ReactNode[] = [];
+ // Pending kickoffs land at the top, newest first, under a "Today" separator.
+ let lastDayLabel: string | null = null;
+ if (pending.length > 0) {
+ lastDayLabel = "Today";
+ rows.push(<DaySeparator key="separator-pending" label="Today" />);
+ for (let i = pending.length - 1; i >= 0; i--) {
+ const p = pending[i];
+ rows.push(<PendingFeedRow key={p.id} pending={p} />);
+ }
+ }
+ for (const entry of entries) {
+ const label = feedDayLabel(entry.createdAt, now);
+ if (label !== lastDayLabel) {
+ lastDayLabel = label;
+ rows.push(<DaySeparator key={`separator-${label}`} label={label} />);
+ }
+ rows.push(
+ entry.kind === "task" ? (
+ <FeedRow
+ key={entry.id}
+ task={entry.task}
+ showRepo={
+ !!entry.task.repository && entry.task.repository !== dominantRepo
+ }
+ onOpenTask={onOpenTask}
+ onOpenThread={onOpenThread}
+ />
+ ) : (
+ <SystemFeedRow key={entry.id} message={entry.message} />
+ ),
+ );
+ }
return (
- <ChatMessageScrollerProvider defaultScrollPosition="end">
- <FollowOwnPost latestPendingId={latestPendingId} />
- <ChatMessageScroller className="min-h-0 flex-1">
- <ChatMessageScrollerViewport ref={viewportRef}>
- {/* Horizontal padding is load-bearing: ThreadItem's actions float at
- the row's top-right corner (absolute, past the row edge). Without a
- gutter they hug the scroll container and get clipped. The deeper
- bottom padding clears the composer's floating workspace-mode
- selector, which hangs over the end of the feed. */}
- <ChatMessageScrollerContent className="mx-auto w-full gap-0 pt-4 pb-10">
- {intro as never}
- {entries.map((entry) =>
- entry.kind === "task" ? (
- <FeedRow
- key={entry.id}
- task={entry.task}
- channelId={channelId}
- onOpenTask={onOpenTask}
- onOpenThread={onOpenThread}
- />
- ) : (
- <SystemFeedRow key={entry.id} message={entry.message} />
- ),
- )}
- {pending.map((p) => (
- <PendingFeedRow
- key={p.id}
- pending={p}
- createdAt={now.toISOString()}
- />
- ))}
- </ChatMessageScrollerContent>
- </ChatMessageScrollerViewport>
- <ChatMessageScrollerButton />
- </ChatMessageScroller>
- </ChatMessageScrollerProvider>
+ <div ref={viewportRef} className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto w-full px-4 pt-4 pb-10">
+ {intro && <div className="mx-auto w-full max-w-[660px]">{intro}</div>}
+ {composerBlock}
+ {rows}
+ </div>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index f0cc0c559652..46cdeb2d8a60 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -398,7 +398,10 @@ export const ChannelHomeComposer = forwardRef<
return (
<div className="relative flex w-full flex-col">
- <div className="absolute bottom-full left-0 mb-2 flex items-center gap-2 rounded-sm bg-card">
+ {/* The row sits in normal flow above the input, mirroring the new-task
+ page's composer (the composer scrolls with the feed, so nothing may
+ float over the cards below). */}
+ <div className="mb-1 flex min-w-0 items-center gap-1">
<WorkspaceModeSelect
value={workspaceMode}
onChange={setWorkspaceMode}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelIntro.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelIntro.tsx
index 934342b7a57c..512e57692dcd 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelIntro.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelIntro.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Item,
ItemContent,
ItemDescription,
@@ -6,13 +7,14 @@ import {
ItemTitle,
Spinner,
} from "@posthog/quill";
-import { getLocalDayDiff } from "@posthog/shared";
+import { EXTERNAL_LINKS, getLocalDayDiff } from "@posthog/shared";
import type { TaskChannel } from "@posthog/shared/domain-types";
import { mentionChipClass } from "@posthog/ui/features/canvas/components/MentionText";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { Heading, Text } from "@radix-ui/themes";
-import { FileCheckCorner, FilePlusCorner, Info } from "lucide-react";
+import { FileCheckCorner, FilePlusCorner, Info, X } from "lucide-react";
// "today" / "yesterday" / "on July 10" for the intro's creation line.
function creationDatePhrase(iso: string): string {
@@ -37,19 +39,35 @@ export function ChannelIntro({
channelName,
contextMdState,
onCreateContextMd,
+ onDismiss,
}: {
/** The backend channel row (creator + creation time). */
channel: TaskChannel | undefined;
channelName: string;
contextMdState: ContextMdState;
onCreateContextMd: () => void;
+ /** Renders a close button that hides the intro for this channel. */
+ onDismiss?: () => void;
}) {
const creator = channel?.created_by;
const spacesLayout = useChannelsLayout();
const noun = spacesLayout ? "space" : "channel";
return (
- <div className="flex w-full max-w-[70ch] flex-col gap-3 px-4 pt-8 pb-10">
+ // Width and horizontal padding come from the feed column that renders
+ // this, so the intro lines up with the composer and the cards below.
+ <div className="group/intro relative flex w-full flex-col gap-3 pt-2 pb-4">
+ {onDismiss && (
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="Dismiss intro"
+ className="absolute top-2 right-0 opacity-0 transition-opacity focus-visible:opacity-100 group-hover/intro:opacity-100"
+ onClick={onDismiss}
+ >
+ <X size={14} />
+ </Button>
+ )}
<div className="flex flex-col gap-0">
<Heading className="font-bold text-2xl">{channelName}</Heading>
{channel && (
@@ -58,9 +76,7 @@ export function ChannelIntro({
<span className={mentionChipClass}>
@{userDisplayName(creator ?? null)}
</span>{" "}
- created this {noun} {creationDatePhrase(channel.created_at)}. This
- is the very beginning of the{" "}
- <Text weight="bold">{channelName}</Text> {noun}.
+ created this {noun} {creationDatePhrase(channel.created_at)}.
</Text>
)}
</div>
@@ -122,7 +138,12 @@ export function ChannelIntro({
<Item
className="w-full border-primary/50 hover:bg-fill-hover"
variant="pressable"
- render={<button type="button" onClick={() => {}} />}
+ render={
+ <button
+ type="button"
+ onClick={() => openExternalUrl(EXTERNAL_LINKS.docs)}
+ />
+ }
>
<ItemMedia variant="icon">
<Info size={18} />
diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
index e31edb2f58a9..d7eadc54d9b6 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx
@@ -23,15 +23,17 @@ import {
channelFeedQueryKey,
useChannelFeed,
} from "@posthog/ui/features/canvas/hooks/useChannelFeed";
-import {
- channelCreationMessage,
- useChannelFeedMessages,
-} from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
+import { useChannelFeedMessages } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { useChannelTaskMutations } from "@posthog/ui/features/canvas/hooks/useChannelTasks";
import { useFolderInstructions } from "@posthog/ui/features/canvas/hooks/useFolderInstructions";
import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
-import { useThreadPanelStore } from "@posthog/ui/features/canvas/stores/threadPanelStore";
+import { useChannelIntroStore } from "@posthog/ui/features/canvas/stores/channelIntroStore";
+import {
+ type ThreadPanelTab,
+ useThreadPanelStore,
+} from "@posthog/ui/features/canvas/stores/threadPanelStore";
+import { openRightPanelSide } from "@posthog/ui/features/navigation/rightPanelSide";
import { SuggestedPromptCard } from "@posthog/ui/features/task-detail/components/SuggestedPromptCard";
import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
@@ -42,10 +44,11 @@ import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-// A channel: a Slack-style multiplayer feed. Each member message kicks off a
-// task rendered as a card everyone in the channel sees; the composer stays
-// pinned at the bottom and threads open in a right-hand panel. The channel's
-// artifacts/history/context views stay in the tabs above (ChannelHeader).
+// A channel: a multiplayer feed. Each member message kicks off a task rendered
+// as a card everyone in the channel sees; the composer stays pinned at the top
+// (Twitter-style — new session first, newest cards under it) and threads open
+// in a right-hand panel. The channel's artifacts/history/context views stay in
+// the tabs above (ChannelHeader).
export function WebsiteChannelHome({ channelId }: { channelId: string }) {
const spacesLayout = useChannelsLayout();
const navigate = useNavigate();
@@ -67,16 +70,13 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {
// Marking this channel read lives in ChannelHeader (rendered by every channel
// surface), so opening Artifacts or CONTEXT.md counts as reading it too.
- // Durable "PostHog agent" rows (CONTEXT.md being built, …).
- const { messages: feedMessages, isLoading: isLoadingMessages } =
+ // Durable "PostHog agent" rows (CONTEXT.md being built, …). The old chat
+ // feed also injected a synthetic "joined" opener here; the newest-first feed
+ // drops it — the intro header already attributes the channel's creation, and
+ // the opener would dangle at the bottom as the oldest entry.
+ const { messages: systemMessages, isLoading: isLoadingMessages } =
useChannelFeedMessages(channelId);
const isLoading = isLoadingChannels || isLoadingFeed || isLoadingMessages;
- // The Slack-style "joined" opener, derived from the channel row so it renders
- // (and sorts first) even where the feed endpoint isn't deployed.
- const systemMessages = useMemo(() => {
- const creation = channelCreationMessage(channel);
- return creation ? [creation, ...feedMessages] : feedMessages;
- }, [channel, feedMessages]);
useSetHeaderContent(
useMemo(
@@ -203,10 +203,17 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {
);
// Under the spaces chrome there is no thread dock to peek into, so the feed
- // opens the session itself and the right panel carries what the dock used to.
+ // opens the session itself and the right panel carries what the dock used to
+ // — including a chip's tab, which lands on the matching panel side there.
const handleOpenThread = useCallback(
- (task: Task) =>
- spacesLayout ? handleOpenFull(task.id) : openThread(channelId, task.id),
+ (task: Task, tab?: ThreadPanelTab) => {
+ if (spacesLayout) {
+ if (tab) openRightPanelSide(tab, task.id);
+ handleOpenFull(task.id);
+ return;
+ }
+ openThread(channelId, task.id, tab ? { tab } : undefined);
+ },
[channelId, openThread, spacesLayout, handleOpenFull],
);
@@ -236,13 +243,18 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {
: isBuildingContextMd
? "building"
: "none";
+ const introDismissed = useChannelIntroStore(
+ (s) => !!s.dismissedByChannel[channelId],
+ );
+ const dismissIntro = useChannelIntroStore((s) => s.dismissIntro);
const intro =
- !isPersonal && channelName && channel ? (
+ !isPersonal && !introDismissed && channelName && channel ? (
<ChannelIntro
channel={channel}
channelName={channelName}
contextMdState={contextMdState}
onCreateContextMd={() => setContextMdDialogOpen(true)}
+ onDismiss={() => dismissIntro(channelId)}
/>
) : undefined;
@@ -291,22 +303,22 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {
isLoading={isLoading}
emptyState={emptyState}
intro={intro}
+ composer={
+ <ChannelHomeComposer
+ ref={composerRef}
+ channelId={channelId}
+ channelName={channelName}
+ channelContext={channelContext}
+ channelRepositories={channel?.repositories}
+ channelGithubIntegration={channel?.github_integration}
+ onTaskCreated={onTaskCreated}
+ onPendingStart={addPending}
+ onPendingEnd={removePending}
+ />
+ }
onOpenTask={handleOpenTask}
onOpenThread={handleOpenThread}
/>
- <div className="mx-auto w-full px-4 pt-2 pb-2">
- <ChannelHomeComposer
- ref={composerRef}
- channelId={channelId}
- channelName={channelName}
- channelContext={channelContext}
- channelRepositories={channel?.repositories}
- channelGithubIntegration={channel?.github_integration}
- onTaskCreated={onTaskCreated}
- onPendingStart={addPending}
- onPendingEnd={removePending}
- />
- </div>
</div>
{!spacesLayout &&
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
index 0a3f2d0e0f70..f0477c28389a 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
@@ -27,26 +27,21 @@ export function channelFeedMessagesQueryKey(channelId: string | undefined) {
return ["channel-feed-messages", channelId ?? "none"] as const;
}
-// The "created this context" row is synthesized from the channel row itself
-// (below) — the canonical creation record, available even where the feed
-// endpoint isn't. Server-emitted channel_created (and its legacy client-posted
-// context_created twin) would duplicate it, so both are dropped from the feed.
-const CREATION_EVENTS = new Set(["channel_created", "context_created"]);
+// Announcements the card feed already represents, dropped to avoid saying the
+// same thing twice: creation is the intro header's line (channel_created and
+// its legacy client-posted context_created twin), and a CONTEXT.md build is
+// its own plan-task card in the feed plus the intro card's "Creating…" state.
+const REDUNDANT_EVENTS = new Set([
+ "channel_created",
+ "context_created",
+ "context_md_building",
+]);
-// Render the announcement from its event + structured payload (rename-safe),
-// falling back to the freeform content.
+// Render the announcement from its freeform content, with a generic fallback
+// so an unknown future event still shows something.
function messageText(message: ChannelFeedMessage): string {
const actor = userDisplayName(message.author ?? null);
- const contextName =
- typeof message.payload?.context_name === "string"
- ? message.payload.context_name
- : "";
- switch (message.event) {
- case "context_md_building":
- return `${actor} is building CONTEXT.md${contextName ? ` for ${contextName}` : ""}`;
- default:
- return message.content || `${actor} posted an update`;
- }
+ return message.content || `${actor} posted an update`;
}
/**
@@ -91,7 +86,7 @@ export function useChannelFeedMessages(channelId: string | undefined): {
const messages = useMemo(
() =>
(query.data ?? [])
- .filter((m) => !CREATION_EVENTS.has(m.event))
+ .filter((m) => !REDUNDANT_EVENTS.has(m.event))
.map((m) => ({
id: m.id,
createdAt: m.created_at,
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/channelIntroStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/channelIntroStore.ts
new file mode 100644
index 000000000000..25a7f25f1ef9
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/stores/channelIntroStore.ts
@@ -0,0 +1,29 @@
+import { electronStorage } from "@posthog/ui/shell/rendererStorage";
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+interface ChannelIntroState {
+ dismissedByChannel: Record<string, true>;
+ dismissIntro: (channelId: string) => void;
+}
+
+// Which channels' feed intro (welcome + onboarding card) the user has closed.
+// Per-device on purpose: the intro is orientation, not shared channel state.
+export const useChannelIntroStore = create<ChannelIntroState>()(
+ persist(
+ (set) => ({
+ dismissedByChannel: {},
+ dismissIntro: (channelId) =>
+ set((state) => ({
+ dismissedByChannel: {
+ ...state.dismissedByChannel,
+ [channelId]: true,
+ },
+ })),
+ }),
+ {
+ name: "channel-intro-storage",
+ storage: electronStorage,
+ },
+ ),
+);
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.test.ts b/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.test.ts
index 722bd29263da..70af18392405 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.test.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.test.ts
@@ -5,6 +5,7 @@ describe("threadPanelStore", () => {
beforeEach(() => {
useThreadPanelStore.setState({
openByChannel: {},
+ tabRequestByTask: {},
collapsed: false,
width: 360,
});
@@ -22,6 +23,34 @@ describe("threadPanelStore", () => {
});
});
+ it("drops a tab request once consumed, so a remounting panel can't replay it", () => {
+ const { openThread, consumeTabRequest } = useThreadPanelStore.getState();
+
+ openThread("channel-a", "task-a", { tab: "comments" });
+ const request = useThreadPanelStore.getState().tabRequestByTask["task-a"];
+ expect(request?.tab).toBe("comments");
+
+ consumeTabRequest("task-a", request?.nonce ?? -1);
+
+ expect(
+ useThreadPanelStore.getState().tabRequestByTask["task-a"],
+ ).toBeUndefined();
+ });
+
+ it("keeps a newer tab request when a stale ack arrives", () => {
+ const { openThread, consumeTabRequest } = useThreadPanelStore.getState();
+
+ openThread("channel-a", "task-a", { tab: "comments" });
+ const first = useThreadPanelStore.getState().tabRequestByTask["task-a"];
+ openThread("channel-a", "task-a", { tab: "artifacts" });
+
+ consumeTabRequest("task-a", first?.nonce ?? -1);
+
+ expect(useThreadPanelStore.getState().tabRequestByTask["task-a"]?.tab).toBe(
+ "artifacts",
+ );
+ });
+
it("closes only the active channel's thread", () => {
useThreadPanelStore.setState({
openByChannel: { "channel-a": "task-a", "channel-b": "task-b" },
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.ts
index ee2c66427ee3..836da77d9393 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/threadPanelStore.ts
@@ -4,15 +4,32 @@ import { persist } from "zustand/middleware";
const DEFAULT_PANEL_WIDTH = 360;
+export type ThreadPanelTab = "timeline" | "artifacts" | "comments";
+
+// Bumped per request so re-asking for the same tab re-applies even after the
+// user has navigated away from it.
+let tabRequestNonce = 0;
+
interface ThreadPanelState {
openByChannel: Record<string, string | null>;
+ /** Which tab the panel should land on for a task — set when a caller opens
+ * the thread pointed at a specific tab (e.g. the feed's comment chip),
+ * cleared by any tab-less open so a stale request can't hijack a later
+ * plain open. Consumed by ActivityPanel. */
+ tabRequestByTask: Record<
+ string,
+ { tab: ThreadPanelTab; nonce: number } | undefined
+ >;
collapsed: boolean;
width: number;
openThread: (
channelId: string,
taskId: string,
- opts?: { expand?: boolean },
+ opts?: { expand?: boolean; tab?: ThreadPanelTab },
) => void;
+ /** Acknowledge an applied tab request. Nonce-matched so a stale ack (from a
+ * panel that unmounted mid-flight) can't drop a newer request. */
+ consumeTabRequest: (taskId: string, nonce: number) => void;
closeThread: (channelId: string) => void;
setCollapsed: (collapsed: boolean) => void;
setWidth: (width: number) => void;
@@ -22,13 +39,31 @@ export const useThreadPanelStore = create<ThreadPanelState>()(
persist(
(set) => ({
openByChannel: {},
+ tabRequestByTask: {},
collapsed: false,
width: DEFAULT_PANEL_WIDTH,
openThread: (channelId, taskId, opts) =>
set((state) => ({
openByChannel: { ...state.openByChannel, [channelId]: taskId },
+ tabRequestByTask: {
+ ...state.tabRequestByTask,
+ [taskId]: opts?.tab
+ ? { tab: opts.tab, nonce: ++tabRequestNonce }
+ : undefined,
+ },
...(opts?.expand === false ? {} : { collapsed: false }),
})),
+ consumeTabRequest: (taskId, nonce) =>
+ set((state) =>
+ state.tabRequestByTask[taskId]?.nonce === nonce
+ ? {
+ tabRequestByTask: {
+ ...state.tabRequestByTask,
+ [taskId]: undefined,
+ },
+ }
+ : state,
+ ),
closeThread: (channelId) =>
set((state) => ({
openByChannel: { ...state.openByChannel, [channelId]: null },