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): mark a task as unread from its row menu (#126000)

Dylan Martin7cc95fe5cdd2
diff --git a/products/desktop/apps/web/src/web-host-router.ts b/products/desktop/apps/web/src/web-host-router.ts
index f173ae039a28..977953e18b73 100644
--- a/products/desktop/apps/web/src/web-host-router.ts
+++ b/products/desktop/apps/web/src/web-host-router.ts
@@ -353,6 +353,11 @@ const workspaceStubRouter = router({
.mutation(({ input }) => {
webTaskMetadataStore.markViewed(input.taskId);
}),
+ markUnread: publicProcedure
+ .input(z.object({ taskId: z.string(), activityAt: z.number() }))
+ .mutation(({ input }) => {
+ webTaskMetadataStore.markUnread(input.taskId, input.activityAt);
+ }),
markActivity: publicProcedure
.input(z.object({ taskId: z.string() }))
.mutation(({ input }) => {
diff --git a/products/desktop/apps/web/src/web-task-metadata-store.ts b/products/desktop/apps/web/src/web-task-metadata-store.ts
index fe0bd79e364b..c4e15e876da8 100644
--- a/products/desktop/apps/web/src/web-task-metadata-store.ts
+++ b/products/desktop/apps/web/src/web-task-metadata-store.ts
@@ -59,6 +59,10 @@ export const webTaskMetadataStore = {
update(taskId, { lastViewedAt: new Date().toISOString() });
},
+ markUnread(taskId: string, activityAt: number): void {
+ update(taskId, { lastViewedAt: new Date(activityAt - 1).toISOString() });
+ },
+
markActivity(taskId: string): void {
update(taskId, { lastActivityAt: new Date().toISOString() });
},
diff --git a/products/desktop/packages/core/src/context-menu/context-menu.test.ts b/products/desktop/packages/core/src/context-menu/context-menu.test.ts
index 732dc7d3cd32..7f922f743b98 100644
--- a/products/desktop/packages/core/src/context-menu/context-menu.test.ts
+++ b/products/desktop/packages/core/src/context-menu/context-menu.test.ts
@@ -129,6 +129,28 @@ describe("ContextMenuService.showTaskContextMenu", () => {
expect(labels(idle.lastItems)).not.toContain("Stop task");
});
+ it("labels the read toggle by read state and hides it when omitted", async () => {
+ const read = new FakeContextMenu();
+ const toggled = makeService(read).showTaskContextMenu({
+ ...baseTask,
+ isUnread: false,
+ });
+ await read.shown;
+ findItem(read.lastItems, "Mark as unread").click();
+ expect(await toggled).toEqual({ action: { type: "toggle-unread" } });
+
+ const unread = new FakeContextMenu();
+ makeService(unread).showTaskContextMenu({ ...baseTask, isUnread: true });
+ await unread.shown;
+ expect(labels(unread.lastItems)).toContain("Mark as read");
+
+ const omitted = new FakeContextMenu();
+ makeService(omitted).showTaskContextMenu(baseTask);
+ await omitted.shown;
+ expect(labels(omitted.lastItems)).not.toContain("Mark as unread");
+ expect(labels(omitted.lastItems)).not.toContain("Mark as read");
+ });
+
it("hides Add to Command Center when already in it", async () => {
const inCc = new FakeContextMenu();
makeService(inCc).showTaskContextMenu({
diff --git a/products/desktop/packages/core/src/context-menu/context-menu.ts b/products/desktop/packages/core/src/context-menu/context-menu.ts
index 6867a01af9b1..64a68f7fa8f4 100644
--- a/products/desktop/packages/core/src/context-menu/context-menu.ts
+++ b/products/desktop/packages/core/src/context-menu/context-menu.ts
@@ -118,6 +118,7 @@ export class ContextMenuService {
worktreePath,
folderPath,
isPinned,
+ isUnread,
isSuspended,
canStop,
isInCommandCenter,
@@ -147,6 +148,14 @@ export class ContextMenuService {
: [];
return this.showMenu<TaskAction>([
+ ...(isUnread !== undefined
+ ? [
+ this.item<TaskAction>(
+ isUnread ? "Mark as read" : "Mark as unread",
+ { type: "toggle-unread" as const },
+ ),
+ ]
+ : []),
this.item(isPinned ? "Unpin" : "Pin", { type: "pin" }),
this.item("Rename", { type: "rename" }),
...(canStop
diff --git a/products/desktop/packages/core/src/context-menu/schemas.ts b/products/desktop/packages/core/src/context-menu/schemas.ts
index 5f29b83ecc5c..f65904ff368f 100644
--- a/products/desktop/packages/core/src/context-menu/schemas.ts
+++ b/products/desktop/packages/core/src/context-menu/schemas.ts
@@ -13,6 +13,8 @@ export const taskContextMenuInput = z.object({
worktreePath: z.string().optional(),
folderPath: z.string().optional(),
isPinned: z.boolean().optional(),
+ // Omit to hide the read/unread item.
+ isUnread: z.boolean().optional(),
isSuspended: z.boolean().optional(),
canStop: z.boolean().optional(),
isInCommandCenter: z.boolean().optional(),
@@ -62,6 +64,8 @@ const externalAppAction = z.discriminatedUnion("type", [
]);
const taskAction = z.discriminatedUnion("type", [
+ // Carries no direction: the label and the resolver derive it from `isUnread`.
+ z.object({ type: z.literal("toggle-unread") }),
z.object({ type: z.literal("rename") }),
z.object({ type: z.literal("pin") }),
z.object({ type: z.literal("suspend") }),
diff --git a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
index 8a83aa90e9cb..cf6af5e11ac6 100644
--- a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
+++ b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
@@ -182,7 +182,7 @@ export interface DeriveTaskDataContext {
* When a task last moved: the activity time the caller passes (the backend's, via
* `taskActivityAt`), or local renderer activity where that has run ahead of the next poll.
*/
-function taskLastActivityAt(
+export function taskLastActivityAt(
activityAt: string,
timestamp: TaskTimestamp | undefined,
): number {
diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts
index 6282e01f7754..3ca4945d4fcc 100644
--- a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts
+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts
@@ -12,6 +12,21 @@ describe("resolveTaskContextMenuIntent", () => {
).toEqual({ type: "restore" });
});
+ it("maps toggle-unread by the current read state", () => {
+ expect(
+ resolveTaskContextMenuIntent(
+ { type: "toggle-unread" },
+ { isUnread: true },
+ ),
+ ).toEqual({ type: "mark-read" });
+ expect(
+ resolveTaskContextMenuIntent(
+ { type: "toggle-unread" },
+ { isUnread: false },
+ ),
+ ).toEqual({ type: "mark-unread" });
+ });
+
it("maps suspend to suspend when not suspended", () => {
expect(
resolveTaskContextMenuIntent({ type: "suspend" }, { isSuspended: false }),
diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.ts
index c4b28ab3b87e..05055a23edee 100644
--- a/products/desktop/packages/core/src/tasks/contextMenuActions.ts
+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.ts
@@ -5,6 +5,8 @@ import type {
} from "@posthog/core/context-menu/schemas";
export type TaskContextMenuIntent =
+ | { type: "mark-read" }
+ | { type: "mark-unread" }
| { type: "rename" }
| { type: "pin" }
| { type: "suspend" }
@@ -20,9 +22,11 @@ export type TaskContextMenuIntent =
export function resolveTaskContextMenuIntent(
action: TaskAction,
- flags: { isSuspended?: boolean },
+ flags: { isSuspended?: boolean; isUnread?: boolean },
): TaskContextMenuIntent {
switch (action.type) {
+ case "toggle-unread":
+ return flags.isUnread ? { type: "mark-read" } : { type: "mark-unread" };
case "rename":
return { type: "rename" };
case "pin":
diff --git a/products/desktop/packages/host-router/src/routers/workspace.router.ts b/products/desktop/packages/host-router/src/routers/workspace.router.ts
index 94e8094ea50a..5554718bc17b 100644
--- a/products/desktop/packages/host-router/src/routers/workspace.router.ts
+++ b/products/desktop/packages/host-router/src/routers/workspace.router.ts
@@ -35,6 +35,7 @@ import {
listRepoCheckoutsInput,
listRepoCheckoutsOutput,
markActivityInput,
+ markUnreadInput,
markViewedInput,
reconcileCloudWorkspacesInput,
reconcileCloudWorkspacesOutput,
@@ -205,6 +206,12 @@ export const workspaceRouter = router({
getMetadata(ctx.container).markViewed(input.taskId),
),
+ markUnread: publicProcedure
+ .input(markUnreadInput)
+ .mutation(({ ctx, input }) =>
+ getMetadata(ctx.container).markUnread(input.taskId, input.activityAt),
+ ),
+
markActivity: publicProcedure
.input(markActivityInput)
.mutation(({ ctx, input }) =>
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 0752fedabd09..ef1fd0f25caf 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1273,6 +1273,8 @@ type ChannelActionType =
| "expand_channel"
| "activity_unreads_toggle"
| "activity_mark_all_read"
+ | "mark_task_read"
+ | "mark_task_unread"
| "activity_load_more";
type TaskFeedActionType = "create" | "update" | "delete" | "open";
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 2015191ec493..b90a7299498f 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
@@ -103,6 +103,9 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
useFileTaskToChannel: () => vi.fn(),
}));
+vi.mock("@posthog/ui/features/sidebar/useToggleTaskRead", () => ({
+ useTaskReadItem: () => ({ isUnread: false, toggle: vi.fn() }),
+}));
vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({
useOpenBrowserTab: () => vi.fn(),
}));
@@ -388,6 +391,7 @@ describe("ChannelFeedView", () => {
await waitFor(() => expect(screen.getByText("Pin")).toBeInTheDocument());
for (const label of [
+ "Mark as unread",
"Pin",
"Rename",
"Add to Command Center…",
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 b83f5e464aac..fd8d4836c42b 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
@@ -59,6 +59,9 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
useFileTaskToChannel: () => vi.fn(),
}));
+vi.mock("@posthog/ui/features/sidebar/useToggleTaskRead", () => ({
+ useTaskReadItem: () => ({ isUnread: false, toggle: vi.fn() }),
+}));
vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({
useOpenBrowserTab: () => mocks.openBrowserTab,
}));
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 9a5d47db366c..1c379d985197 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
@@ -85,6 +85,9 @@ vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
useFileTaskToChannel: () => ({ fileTask: vi.fn() }),
}));
+vi.mock("@posthog/ui/features/sidebar/useToggleTaskRead", () => ({
+ useTaskReadItem: () => ({ isUnread: false, toggle: vi.fn() }),
+}));
vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({
useOpenBrowserTab: () => vi.fn(),
}));
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 794b162ad3be..857540c29274 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
@@ -3,6 +3,8 @@ import {
ArrowSquareOutIcon,
CaretRightIcon,
DotsThreeIcon,
+ EnvelopeSimpleIcon,
+ EnvelopeSimpleOpenIcon,
FolderSimpleIcon,
LinkIcon,
MagnifyingGlassIcon,
@@ -46,6 +48,7 @@ import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLi
import { useSidebarPeekStore } from "@posthog/ui/features/sidebar/sidebarPeekStore";
import { useHoldSidebarPeek } from "@posthog/ui/features/sidebar/useHoldSidebarPeek";
import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";
+import { useTaskReadItem } from "@posthog/ui/features/sidebar/useToggleTaskRead";
import { useTaskAnalysis } from "@posthog/ui/features/task-detail/components/TaskAnalysisButton";
import {
type MenuFlyoutItem,
@@ -134,6 +137,27 @@ function TaskAnalysisMenuItem({
);
}
+function TaskReadMenuItem({
+ Item,
+ task,
+}: {
+ Item: MenuParts["Item"];
+ task: Task;
+}): ReactElement {
+ const { isUnread, toggle } = useTaskReadItem(task);
+
+ return (
+ <Item onClick={toggle}>
+ {isUnread ? (
+ <EnvelopeSimpleOpenIcon size={14} />
+ ) : (
+ <EnvelopeSimpleIcon size={14} />
+ )}
+ {isUnread ? "Mark as read" : "Mark as unread"}
+ </Item>
+ );
+}
+
/**
* The row's actions, in the order the native menu used: the edits, then the
* places a task can be sent, then the destructive one last.
@@ -194,6 +218,7 @@ function TaskRowMenuItems({
<LinkIcon size={14} />
Copy link
</Item>
+ {isTask && menu.task && <TaskReadMenuItem Item={Item} task={menu.task} />}
<Item onClick={menu.onTogglePin}>
{menu.isPinned ? (
<PushPinSlashIcon size={14} />
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
index b69b6fda89ce..1051924e0b13 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
@@ -317,6 +317,8 @@ function SidebarMenuComponent() {
worktreePath: workspace?.worktreePath ?? undefined,
folderPath: workspace?.folderPath ?? undefined,
isPinned,
+ isUnread: taskData.isUnread,
+ lastActivityAt: taskData.lastActivityAt,
isSuspended: taskData?.isSuspended,
canStop:
taskData?.taskRunEnvironment === "cloud" &&
diff --git a/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.test.tsx b/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.test.tsx
index cc472a94bd01..2e32ebed4111 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.test.tsx
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
loadTimestamps: vi.fn(),
markActivity: vi.fn(),
markViewed: vi.fn(),
+ markUnread: vi.fn(),
}));
vi.mock("@posthog/host-router/react", () => ({
@@ -32,12 +33,26 @@ vi.mock("@posthog/host-router/react", () => ({
workspace: {
markActivity: { mutate: mocks.markActivity },
markViewed: { mutate: mocks.markViewed },
+ markUnread: { mutate: mocks.markUnread },
},
}),
}));
import { useTaskViewed } from "./useTaskViewed";
+function setup() {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: PropsWithChildren) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ return { queryClient, wrapper };
+}
+
describe("useTaskViewed", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -45,15 +60,7 @@ describe("useTaskViewed", () => {
});
it("clears unread immediately when a task is viewed", async () => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- const wrapper = ({ children }: PropsWithChildren) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- );
+ const { queryClient, wrapper } = setup();
const activityAt = new Date(Date.now() - 60_000).toISOString();
queryClient.setQueryData<Record<string, RawTaskTimestamp>>(
TIMESTAMPS_QUERY_KEY,
@@ -78,4 +85,51 @@ describe("useTaskViewed", () => {
taskId: "task-1",
});
});
+
+ it("rolls back a failed unread without losing a view that landed meanwhile", async () => {
+ const { queryClient, wrapper } = setup();
+ const viewedAt = "2026-01-01T00:00:00.000Z";
+ queryClient.setQueryData<Record<string, RawTaskTimestamp>>(
+ TIMESTAMPS_QUERY_KEY,
+ {
+ "task-1": {
+ pinnedAt: null,
+ lastViewedAt: viewedAt,
+ lastActivityAt: null,
+ },
+ "task-2": { pinnedAt: null, lastViewedAt: null, lastActivityAt: null },
+ },
+ );
+ let failUnread: (error: Error) => void = () => undefined;
+ mocks.markUnread.mockReturnValue(
+ new Promise((_, reject) => {
+ failUnread = reject;
+ }),
+ );
+ const { result } = renderHook(() => useTaskViewed(), { wrapper });
+
+ act(() =>
+ result.current.markAsUnread(
+ "task-1",
+ new Date(viewedAt).getTime() + 60_000,
+ ),
+ );
+ await waitFor(() =>
+ expect(result.current.timestamps["task-1"]?.lastViewedAt).not.toBe(
+ new Date(viewedAt).getTime(),
+ ),
+ );
+ act(() => result.current.markAsViewed("task-2"));
+ await waitFor(() =>
+ expect(result.current.timestamps["task-2"]?.lastViewedAt).not.toBeNull(),
+ );
+ await act(async () => failUnread(new Error("host unavailable")));
+
+ await waitFor(() =>
+ expect(result.current.timestamps["task-1"]?.lastViewedAt).toBe(
+ new Date(viewedAt).getTime(),
+ ),
+ );
+ expect(result.current.timestamps["task-2"]?.lastViewedAt).not.toBeNull();
+ });
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.ts b/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.ts
index 5e1e081b2ca4..ae03f428e021 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useTaskViewed.ts
@@ -63,6 +63,54 @@ export function useTaskViewed() {
},
});
+ const markUnreadMutation = useMutation({
+ mutationFn: ({
+ taskId,
+ activityAt,
+ }: {
+ taskId: string;
+ activityAt: number;
+ }) => hostClient.workspace.markUnread.mutate({ taskId, activityAt }),
+ onMutate: async ({ taskId, activityAt }) => {
+ await queryClient.cancelQueries({ queryKey: timestampsQueryKey });
+ const previousLastViewedAt =
+ queryClient.getQueryData<Record<string, RawTaskTimestamp>>(
+ timestampsQueryKey,
+ )?.[taskId]?.lastViewedAt ?? null;
+ const lastViewedAt = new Date(activityAt - 1).toISOString();
+ queryClient.setQueryData<Record<string, RawTaskTimestamp>>(
+ timestampsQueryKey,
+ (old) => ({
+ ...old,
+ [taskId]: {
+ pinnedAt: old?.[taskId]?.pinnedAt ?? null,
+ lastActivityAt: old?.[taskId]?.lastActivityAt ?? null,
+ lastViewedAt,
+ },
+ }),
+ );
+ return { previousLastViewedAt, lastViewedAt };
+ },
+ // Roll back only this task's field. Other tasks' updates and a newer view of
+ // this task can land while the request is in flight, and must survive.
+ onError: (_, { taskId }, context) => {
+ if (!context) return;
+ queryClient.setQueryData<Record<string, RawTaskTimestamp>>(
+ timestampsQueryKey,
+ (current) => {
+ const entry = current?.[taskId];
+ if (!current || entry?.lastViewedAt !== context.lastViewedAt) {
+ return current;
+ }
+ return {
+ ...current,
+ [taskId]: { ...entry, lastViewedAt: context.previousLastViewedAt },
+ };
+ },
+ );
+ },
+ });
+
const markActivityMutation = useMutation({
mutationFn: ({ taskId }: { taskId: string }) =>
hostClient.workspace.markActivity.mutate({ taskId }),
@@ -108,6 +156,9 @@ export function useTaskViewed() {
const markViewedMutationRef = useRef(markViewedMutation);
markViewedMutationRef.current = markViewedMutation;
+ const markUnreadMutationRef = useRef(markUnreadMutation);
+ markUnreadMutationRef.current = markUnreadMutation;
+
const markActivityMutationRef = useRef(markActivityMutation);
markActivityMutationRef.current = markActivityMutation;
@@ -115,6 +166,10 @@ export function useTaskViewed() {
markViewedMutationRef.current.mutate({ taskId });
}, []);
+ const markAsUnread = useCallback((taskId: string, activityAt: number) => {
+ markUnreadMutationRef.current.mutate({ taskId, activityAt });
+ }, []);
+
const markActivity = useCallback((taskId: string) => {
markActivityMutationRef.current.mutate({ taskId });
}, []);
@@ -134,6 +189,7 @@ export function useTaskViewed() {
timestampsReady,
isLoading,
markAsViewed,
+ markAsUnread,
markActivity,
getLastViewedAt,
getLastActivityAt,
diff --git a/products/desktop/packages/ui/src/features/sidebar/useToggleTaskRead.ts b/products/desktop/packages/ui/src/features/sidebar/useToggleTaskRead.ts
new file mode 100644
index 000000000000..b5a0caaea8b5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/useToggleTaskRead.ts
@@ -0,0 +1,61 @@
+import {
+ isTaskUnread,
+ taskLastActivityAt,
+} from "@posthog/core/sidebar/buildSidebarData";
+import { taskActivityAt } from "@posthog/core/tasks/taskActivity";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import type { Task } from "@posthog/shared/domain-types";
+import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";
+import { track } from "@posthog/ui/shell/analytics";
+import { useCallback } from "react";
+
+interface TaskReadState {
+ isUnread: boolean;
+ /** The activity time behind the unread dot, from `taskLastActivityAt`. */
+ lastActivityAt: number;
+}
+
+/** Flips a task between read and unread, for the row menus. */
+export function useToggleTaskRead(): (
+ taskId: string,
+ state: TaskReadState,
+) => void {
+ const { markAsViewed, markAsUnread } = useTaskViewed();
+
+ return useCallback(
+ (taskId, { isUnread, lastActivityAt }) => {
+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
+ action_type: isUnread ? "mark_task_read" : "mark_task_unread",
+ surface: "sidebar",
+ task_id: taskId,
+ });
+ if (isUnread) {
+ markAsViewed(taskId);
+ } else {
+ markAsUnread(taskId, lastActivityAt);
+ }
+ },
+ [markAsViewed, markAsUnread],
+ );
+}
+
+/** A task's read state from the same rule as its unread dot, with the flip. */
+export function useTaskReadItem(task: Task): {
+ isUnread: boolean;
+ toggle: () => void;
+} {
+ const { timestamps } = useTaskViewed();
+ const toggleRead = useToggleTaskRead();
+ const timestamp = timestamps[task.id];
+ const activityAt = taskActivityAt(task);
+ const isUnread = isTaskUnread(activityAt, timestamp);
+
+ return {
+ isUnread,
+ toggle: () =>
+ toggleRead(task.id, {
+ isUnread,
+ lastActivityAt: taskLastActivityAt(activityAt, timestamp),
+ }),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
index 1909e3782510..cfc948efb596 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
@@ -8,6 +8,7 @@ import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useFileTaskToChannel } from "@posthog/ui/features/canvas/hooks/useFileTaskToChannel";
import { useExternalAppAction } from "@posthog/ui/features/external-apps/useExternalAppAction";
+import { useToggleTaskRead } from "@posthog/ui/features/sidebar/useToggleTaskRead";
import { useRestoreTask } from "@posthog/ui/features/suspension/useRestoreTask";
import { useSuspendTask } from "@posthog/ui/features/suspension/useSuspendTask";
import { useDeleteTask } from "@posthog/ui/features/tasks/useTaskCrudMutations";
@@ -26,6 +27,7 @@ export function useTaskContextMenu() {
const { restoreTask } = useRestoreTask();
const { channels } = useChannels();
const fileTaskToChannel = useFileTaskToChannel();
+ const toggleRead = useToggleTaskRead();
const showContextMenu = useCallback(
async (
@@ -35,6 +37,9 @@ export function useTaskContextMenu() {
worktreePath?: string;
folderPath?: string;
isPinned?: boolean;
+ isUnread?: boolean;
+ /** Marking unread needs it, so the item is hidden without it. */
+ lastActivityAt?: number;
isSuspended?: boolean;
canStop?: boolean;
runId?: string;
@@ -57,6 +62,8 @@ export function useTaskContextMenu() {
worktreePath,
folderPath,
isPinned,
+ isUnread,
+ lastActivityAt,
isSuspended,
canStop,
runId,
@@ -78,6 +85,7 @@ export function useTaskContextMenu() {
worktreePath,
folderPath,
isPinned,
+ isUnread: lastActivityAt === undefined ? undefined : isUnread,
isSuspended,
canStop,
isInCommandCenter,
@@ -96,9 +104,19 @@ export function useTaskContextMenu() {
const intent = resolveTaskContextMenuIntent(result.action, {
isSuspended,
+ isUnread,
});
switch (intent.type) {
+ case "mark-read":
+ case "mark-unread":
+ if (lastActivityAt !== undefined) {
+ toggleRead(task.id, {
+ isUnread: intent.type === "mark-read",
+ lastActivityAt,
+ });
+ }
+ break;
case "rename":
setEditingTaskId(task.id);
break;
@@ -171,6 +189,7 @@ export function useTaskContextMenu() {
suspendTask,
hostClient,
openExternalApp,
+ toggleRead,
],
);
diff --git a/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.test.ts b/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.test.ts
index ecdebc84a783..5f77a487ef98 100644
--- a/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.test.ts
@@ -102,6 +102,30 @@ describe("WorkspaceMetadataService.markViewed", () => {
});
});
+describe("WorkspaceMetadataService.markUnread", () => {
+ const activityAt = new Date("2025-12-31T12:00:00.000Z").getTime();
+ const justBefore = new Date(activityAt - 1).toISOString();
+
+ it("puts the last view just before the activity on the workspace row", () => {
+ const { service, repo } = createService();
+ repo.findByTaskId.mockReturnValue({ taskId: "t1" });
+
+ service.markUnread("t1", activityAt);
+
+ expect(repo.updateLastViewedAt).toHaveBeenCalledWith("t1", justBefore);
+ });
+
+ it("records the unread state in task_metadata for a rowless task", () => {
+ const { service, repo, metadataRepo } = createService();
+ repo.findByTaskId.mockReturnValue(undefined);
+
+ service.markUnread("t1", activityAt);
+
+ expect(repo.updateLastViewedAt).not.toHaveBeenCalled();
+ expect(metadataRepo.findByTaskId("t1")?.lastViewedAt).toBe(justBefore);
+ });
+});
+
describe("WorkspaceMetadataService.markActivity", () => {
it("uses the current time when the last viewed time is in the past", () => {
const { service, repo } = createService();
diff --git a/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.ts b/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.ts
index e7eb2b3f9d51..994b6a07caf4 100644
--- a/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.ts
+++ b/products/desktop/packages/workspace-server/src/services/workspace-metadata/workspace-metadata.ts
@@ -55,6 +55,19 @@ export class WorkspaceMetadataService {
this.taskMetadataRepo.upsert(taskId, { lastViewedAt });
}
+ /**
+ * Puts the last view just before the last activity, so the task reads as
+ * unread without moving it in an activity-sorted list.
+ */
+ markUnread(taskId: string, activityAt: number): void {
+ const lastViewedAt = new Date(activityAt - 1).toISOString();
+ if (this.workspaceRepo.findByTaskId(taskId)) {
+ this.workspaceRepo.updateLastViewedAt(taskId, lastViewedAt);
+ return;
+ }
+ this.taskMetadataRepo.upsert(taskId, { lastViewedAt });
+ }
+
markActivity(taskId: string): void {
const workspace = this.workspaceRepo.findByTaskId(taskId);
const metadata = workspace ?? this.taskMetadataRepo.findByTaskId(taskId);
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 d4112323eca8..15cb8ae59d86 100644
--- a/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/workspace/schemas.ts
@@ -225,6 +225,12 @@ export const markActivityInput = z.object({
taskId: z.string(),
});
+export const markUnreadInput = z.object({
+ taskId: z.string(),
+ // The task's last activity time in ms. The host can't see the backend's.
+ activityAt: z.number(),
+});
+
export const getPinnedTaskIdsOutput = z.array(z.string());
export const getTaskTimestampsInput = z.object({