mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(ui): stop re-sorting Recents sidebar items to the top on click (#23404)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The sidebar includes a Recents list that mixes recent tasks, agent chats, and projects. > - Opening an existing task or project from Recents currently writes `Date.now()` as its timestamp and jumps that item to the top. > - That breaks spatial stability when a person clicks through items in Recents, because every click re-sorts the list. > - This pull request stops passive opens and clicks from changing an existing item's recency timestamp, seeds unseen items from their latest activity timestamp, and records explicit user activity when a person takes action on a task. > - The benefit is a predictable Recents list that orders items by recent activity without shifting on click. ## Linked Issues or Issue Description **What happened?** When a person clicked an existing task or project in the sidebar Recents list, opening that item stamped it with `Date.now()` and moved it to the top of Recents. Clicking through several recent items constantly re-sorted the sidebar. **Expected behavior** Recents sorts items with the most recent activity at the top, and clicking or passively opening an existing item keeps the list order unchanged. Only real activity (such as creating, editing, commenting, approving/rejecting, or responding to an interaction on a task, or server-side updates on chats and projects) moves an item to the top. **Steps to reproduce** 1. Open the Coordinator workspace with at least two tasks or projects in the sidebar Recents list. 2. Click an older item lower in Recents. 3. Observe that the clicked item jumps to the top of Recents even though no activity occurred. **Paperclip version or commit** Reproduced on `master` (`b63445c8f1`). **Deployment mode** Local dev (source checkout). Related PRs: #22219, #22024. ## What Changed - Updated `recordRecentTask` in `ui/src/lib/recent-tasks.ts` so passive opens never change an existing entry's `recordedAt`, and unseen passive opens seed chronologically from `lastActivityAt` or `updatedAt` (falling back below existing history when no valid timestamp exists). - Removed visit-time `Date.now()` bumping in `ui/src/pages/IssueDetail.tsx` and centralized explicit local activity updates (`recordLocalTaskActivity`) across task edits, comments, approvals (captured at mutation start), interaction responses, and isolated re-issues for both Streamlined and Coordinator modes. - Enabled immediate recent-task recording on task creation in `ui/src/components/NewIssueDialog.tsx` when Coordinator mode is enabled (previously gated only on Streamlined mode). - Extracted `recordProjectRecentVisit` and `buildCoordinatorRecents` in `ui/src/components/CoordinatorSidebar.tsx` so revisiting a project keeps its existing entry unchanged, unseen projects seed from `project.updatedAt`, real project updates advance its sort time via `Math.max`, and memo inputs remain referentially stable. - Updated `DESIGN.md` and `doc/PRODUCT.md` to document activity-based Recents ordering without click-driven re-sorting. - Added and updated unit and component tests in `ui/src/lib/recent-tasks.test.ts`, `ui/src/components/CoordinatorSidebar.recents.test.ts` (including a linear-scan read-budget check across 450 items), and `ui/src/pages/IssueDetail.mobile.test.tsx`. ## Verification Tested on rebased commit `79f028344b56ec41092ad458b956c3fd02be0fe0`: - `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors). - `pnpm --filter @paperclipai/ui exec vitest run src/lib/recent-tasks.test.ts src/hooks/useRecentTasks.test.tsx src/hooks/useRecentTaskOpenWarmup.test.tsx src/components/CoordinatorSidebar.recents.test.ts src/pages/IssueDetail.mobile.test.tsx` — passed (5 files, 68 tests). - `pnpm check:token-gates` — passed (all 4 token gates clean). - Broad typecheck, build, and full test coverage will be verified by GitHub CI on this PR. ## Risks - Low risk. Changes are scoped to client-side Recents ordering, state recording, and documentation. No database migrations, API schema changes, or permission changes. - Users who relied on clicking an old task solely to pin it at the top of Recents can use the existing sidebar pin control or take action on the task. ## Model Used - Antigravity (Google DeepMind agentic assistant) with code inspection, file editing, shell execution, Vitest, TypeScript, and GitHub CLI tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
c5a705ce92
commit
70d780107d
10 files changed
+723
-73
No files matched your search
@@ -776,9 +776,11 @@ Recents appears only when it contains entries, without an empty state.
|
||||
Task entries require the viewer's own participation under the Mine inbox rule,
|
||||
regardless of inbox archive state. Automated provenance, account ownership and
|
||||
read-only visits do not establish participation. A qualifying task's title and
|
||||
status stay current, but passive visits and background updates do not promote it
|
||||
above newer user activity. A first passive visit places a qualifying candidate
|
||||
below existing history. Readable subtasks remain contextual navigation under a
|
||||
status stay current, but clicking or passively visiting an existing entry and
|
||||
background updates do not promote it above newer user activity. A first passive
|
||||
visit seeds an unseen qualifying entry from its latest activity timestamp (or
|
||||
below existing history when unavailable) so newer items sort near the top
|
||||
without re-sorting on click. Readable subtasks remain contextual navigation under a
|
||||
qualifying parent.
|
||||
|
||||
### Reuse collection behavior as well as appearance
|
||||
|
||||
+8
-7
@@ -120,13 +120,14 @@ The Tasks tab keeps the full relationship list and shows each task once. Project
|
||||
groups omit tasks already shown in the other sections and disappear when empty.
|
||||
|
||||
Sidebar Recents and Classic Recent Tasks show tasks from the viewer’s own
|
||||
recent activity as a flat list. A subtask has its own row and its own unread
|
||||
marker. Tasks archived from the viewer’s inbox leave Recents. Canceled and
|
||||
completed tasks remain eligible. Opening a recent task moves its row to the top
|
||||
of Recents. Any task a person opens is eligible for their Recents, including
|
||||
routine, channel, and agent-created tasks. When a person runs a routine manually,
|
||||
the task that run creates goes to the top of their Recents at once, before they
|
||||
open it. Neither of these adds the task to Mine.
|
||||
recent activity as a flat list ordered by most recent activity. A subtask has
|
||||
its own row and its own unread marker. Tasks archived from the viewer’s inbox
|
||||
leave Recents. Canceled and completed tasks remain eligible. Clicking or opening
|
||||
an existing item in Recents does not move it to the top; items re-sort only
|
||||
when new activity occurs. Any task a person opens is eligible for their Recents,
|
||||
including routine, channel, and agent-created tasks. When a person runs a
|
||||
routine manually, the task that run creates goes to the top of their Recents at
|
||||
once, before they open it. Neither of these adds the task to Mine.
|
||||
|
||||
Standard Recents also shows recent chats and projects.
|
||||
The Coordinator sidebar pins **Plugins** above **More** by default. Users can
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Inbox, Boxes, CircleCheck, Compass, Folder, History, LayoutDashboard, MessageCircle, MoreHorizontal, Network, Plus, Repeat, Search, Settings, SquarePen, Unplug, type LucideIcon } from "lucide-react";
|
||||
import type { Agent, IssueSummary, Project } from "@paperclipai/shared";
|
||||
import type { Agent, Issue, IssueSummary, Project } from "@paperclipai/shared";
|
||||
import { useCoordinatorAttentionCount } from "@/hooks/useCoordinatorAttentionCount";
|
||||
import { instanceSettingsApi } from "@/api/instanceSettings";
|
||||
import { useAgentChatNavigation } from "@/hooks/useAgentChatNavigation";
|
||||
@@ -12,6 +12,11 @@ import { projectPinKey, usePinnedNavigation } from "@/hooks/usePinnedNavigation"
|
||||
import { useDialogActions } from "@/context/DialogContext";
|
||||
import { useSidebar } from "@/context/SidebarContext";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import {
|
||||
buildCoordinatorRecents,
|
||||
recordProjectRecentVisit,
|
||||
type CoordinatorProjectVisits,
|
||||
} from "@/lib/coordinator-recents";
|
||||
import type { RecentTaskEntry } from "@/lib/recent-tasks";
|
||||
import { Link, useLocation } from "@/lib/router";
|
||||
import { agentRouteRef, projectRouteRef } from "@/lib/utils";
|
||||
@@ -33,6 +38,9 @@ import { companyProjectsQuery } from "@/lib/company-projects-query";
|
||||
import { NavigationPinButton, type PinControls } from "./NavigationPinButton";
|
||||
import { SidebarProjectTasks } from "./SidebarProjectTasks";
|
||||
|
||||
const NO_AGENTS: readonly Agent[] = [];
|
||||
const NO_CHATS: readonly Issue[] = [];
|
||||
const NO_PROJECTS: readonly Project[] = [];
|
||||
const NO_RECENT_TASKS: never[] = [];
|
||||
const TASK_PIN_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
||||
const taskPinKey = (companyId: string, id: string) => `task:${companyId}:${id}`;
|
||||
@@ -156,29 +164,29 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
|
||||
const { openNewIssue } = useDialogActions();
|
||||
const attentionCount = useCoordinatorAttentionCount(companyId);
|
||||
const { data: projects } = useQuery({ ...companyProjectsQuery(companyId!), enabled: !!companyId });
|
||||
const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agents.data ?? [], destinations,
|
||||
pinnedTasks, session.isSuccess ? projects : undefined), [pinnedNavigation.pins, agents.data, destinations, pinnedTasks, projects, session.isSuccess]);
|
||||
// Only project IDs and visit times are kept in memory. Labels and task lists
|
||||
const agentList = agents.data ?? NO_AGENTS;
|
||||
const chatList = chats.data ?? NO_CHATS;
|
||||
const projectList = projects ?? NO_PROJECTS;
|
||||
const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agentList, destinations,
|
||||
pinnedTasks, session.isSuccess ? projectList : undefined), [pinnedNavigation.pins, agentList, destinations, pinnedTasks, projectList, session.isSuccess]);
|
||||
// Only project IDs and activity timestamps are kept in memory. Labels and task lists
|
||||
// always come from the authorized API, scoped to the current person/company.
|
||||
const scope = `${companyId}:${userId}`;
|
||||
const [projectVisits, setProjectVisits] = useState<{ scope: string; entries: Record<string, number> }>({ scope, entries: {} });
|
||||
const [projectVisits, setProjectVisits] = useState<CoordinatorProjectVisits>({ scope, entries: {} });
|
||||
useEffect(() => {
|
||||
const ref = location.pathname.match(/\/projects\/([^/]+)/)?.[1];
|
||||
const project = projects?.find(item => item.id === ref || projectRouteRef(item) === ref);
|
||||
const project = projectList.find(item => item.id === ref || projectRouteRef(item) === ref);
|
||||
if (!project) return;
|
||||
setProjectVisits(previous => ({ scope, entries: { ...(previous.scope === scope ? previous.entries : {}), [project.id]: Date.now() } }));
|
||||
}, [location.pathname, projects, scope]);
|
||||
const recents = useMemo(() => {
|
||||
const roster = new Map((agents.data ?? []).map(agent => [agent.id, agent]));
|
||||
const taskRows = recentTasks.map(task => ({ kind: "task" as const, id: task.id, time: task.recordedAt, task }));
|
||||
const chatRows = (chats.data ?? []).flatMap(chat => {
|
||||
const agent = chat.conversationAgentId ? roster.get(chat.conversationAgentId) : null;
|
||||
return agent ? [{ kind: "chat" as const, id: chat.id, time: new Date(chat.updatedAt).getTime(), agent }] : [];
|
||||
});
|
||||
const projectRows = (projects ?? []).flatMap(project => projectVisits.scope === scope && projectVisits.entries[project.id]
|
||||
? [{ kind: "project" as const, id: project.id, time: projectVisits.entries[project.id]!, project }] : []);
|
||||
return [...taskRows, ...chatRows, ...projectRows].sort((a, b) => b.time - a.time);
|
||||
}, [agents.data, chats.data, recentTasks, projects, projectVisits, scope]);
|
||||
setProjectVisits(previous => recordProjectRecentVisit(previous, scope, project));
|
||||
}, [location.pathname, projectList, scope]);
|
||||
const recents = useMemo(() => buildCoordinatorRecents({
|
||||
agents: agentList,
|
||||
chats: chatList,
|
||||
recentTasks,
|
||||
projects: projectList,
|
||||
projectVisits,
|
||||
scope,
|
||||
}), [agentList, chatList, recentTasks, projectList, projectVisits, scope]);
|
||||
const newTaskButton = <Button type="button" variant="ghost" className="design-sidebar-new-task rounded-lg" aria-label="New task" onClick={() => openNewIssue()}>
|
||||
<SquarePen aria-hidden />
|
||||
<span className="truncate">New task</span>
|
||||
|
||||
@@ -649,7 +649,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
|
||||
trackRecentProject(issue.projectId ?? "", companyId);
|
||||
if (issue.assigneeAgentId) trackRecentAssignee(issue.assigneeAgentId, companyId);
|
||||
if (issue.assigneeUserId) trackRecentAssigneeUser(issue.assigneeUserId, companyId);
|
||||
if (streamlinedUiEnabled) recordRecentTask(issue, currentUserId, Date.now());
|
||||
if (streamlinedUiEnabled || coordinatorEnabled) recordRecentTask(issue, currentUserId, Date.now());
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(companyId) });
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent, Project } from "@paperclipai/shared";
|
||||
import type { RecentTaskEntry } from "./recent-tasks";
|
||||
import {
|
||||
buildCoordinatorRecents,
|
||||
recordProjectRecentVisit,
|
||||
type CoordinatorProjectVisits,
|
||||
} from "./coordinator-recents";
|
||||
|
||||
const makeAgent = (id: string, name = `Agent ${id}`): Agent => ({
|
||||
id,
|
||||
companyId: "company-1",
|
||||
name,
|
||||
urlKey: id,
|
||||
role: "engineer",
|
||||
title: name,
|
||||
icon: null,
|
||||
status: "idle",
|
||||
reportsTo: null,
|
||||
capabilities: null,
|
||||
adapterType: "claude_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
budgetMonthlyCents: 0,
|
||||
spentMonthlyCents: 0,
|
||||
pauseReason: null,
|
||||
pausedAt: null,
|
||||
permissions: { canCreateAgents: false },
|
||||
lastHeartbeatAt: null,
|
||||
metadata: null,
|
||||
createdAt: new Date(1_000),
|
||||
updatedAt: new Date(1_000),
|
||||
});
|
||||
|
||||
const makeProject = (id: string, updatedAt: number): Project => ({
|
||||
id,
|
||||
companyId: "company-1",
|
||||
urlKey: id,
|
||||
goalId: null,
|
||||
goalIds: [],
|
||||
goals: [],
|
||||
name: `Project ${id}`,
|
||||
description: null,
|
||||
status: "in_progress",
|
||||
leadAgentId: null,
|
||||
targetDate: null,
|
||||
color: null,
|
||||
icon: null,
|
||||
env: null,
|
||||
pauseReason: null,
|
||||
pausedAt: null,
|
||||
executionWorkspacePolicy: null,
|
||||
codebase: {
|
||||
workspaceId: null,
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
defaultRef: null,
|
||||
repoName: null,
|
||||
localFolder: null,
|
||||
managedFolder: "",
|
||||
effectiveLocalFolder: "",
|
||||
origin: "managed_checkout",
|
||||
},
|
||||
workspaces: [],
|
||||
primaryWorkspace: null,
|
||||
archivedAt: null,
|
||||
createdAt: new Date(1_000),
|
||||
updatedAt: new Date(updatedAt),
|
||||
});
|
||||
|
||||
const makeTask = (id: string, recordedAt: number): RecentTaskEntry => ({
|
||||
id,
|
||||
companyId: "company-1",
|
||||
title: `Task ${id}`,
|
||||
identifier: `PAP-${id}`,
|
||||
status: "todo",
|
||||
recordedAt,
|
||||
});
|
||||
|
||||
describe("CoordinatorSidebar Recents ordering", () => {
|
||||
it("seeds an unseen project by updatedAt and keeps the entry stable on revisit", () => {
|
||||
const scope = "company-1:user-1";
|
||||
const initial: CoordinatorProjectVisits = { scope, entries: {} };
|
||||
const project = makeProject("proj-1", 5_000);
|
||||
|
||||
const first = recordProjectRecentVisit(initial, scope, project, 10_000);
|
||||
expect(first).toEqual({ scope, entries: { "proj-1": 5_000 } });
|
||||
|
||||
// Revisiting/clicking the same project must not bump its timestamp or replace state.
|
||||
const revisit = recordProjectRecentVisit(first, scope, project, 20_000);
|
||||
expect(revisit).toBe(first);
|
||||
expect(revisit.entries["proj-1"]).toBe(5_000);
|
||||
|
||||
// Falls back to `now` when updatedAt is epoch 0 / invalid.
|
||||
const noTimestamp = makeProject("proj-no-ts", 0);
|
||||
const second = recordProjectRecentVisit(first, scope, noTimestamp, 15_000);
|
||||
expect(second.entries["proj-no-ts"]).toBe(15_000);
|
||||
expect(recordProjectRecentVisit(second, scope, noTimestamp, 25_000)).toBe(second);
|
||||
|
||||
// Switching scopes clears prior scope entries.
|
||||
const otherScope = recordProjectRecentVisit(second, "company-2:user-1", project, 30_000);
|
||||
expect(otherScope).toEqual({ scope: "company-2:user-1", entries: { "proj-1": 5_000 } });
|
||||
});
|
||||
|
||||
it("interleaves tasks, chats, and projects by activity without re-sorting on click", () => {
|
||||
const scope = "company-1:user-1";
|
||||
const agent = makeAgent("agent-1", "Chief of Staff");
|
||||
const projectA = makeProject("proj-a", 1_500);
|
||||
const projectB = makeProject("proj-b", 3_500);
|
||||
let projectVisits: CoordinatorProjectVisits = { scope, entries: {} };
|
||||
projectVisits = recordProjectRecentVisit(projectVisits, scope, projectA, 9_000);
|
||||
projectVisits = recordProjectRecentVisit(projectVisits, scope, projectB, 9_100);
|
||||
|
||||
const tasks = [makeTask("task-new", 4_000), makeTask("task-old", 1_000)];
|
||||
const chats = [{ id: "chat-1", conversationAgentId: agent.id, updatedAt: new Date(2_500) }];
|
||||
|
||||
const beforeClick = buildCoordinatorRecents({
|
||||
agents: [agent],
|
||||
chats,
|
||||
recentTasks: tasks,
|
||||
projects: [projectA, projectB],
|
||||
projectVisits,
|
||||
scope,
|
||||
});
|
||||
expect(beforeClick.map((item) => `${item.kind}:${item.id}`)).toEqual([
|
||||
"task:task-new",
|
||||
"project:proj-b",
|
||||
"chat:chat-1",
|
||||
"project:proj-a",
|
||||
"task:task-old",
|
||||
]);
|
||||
|
||||
// Clicking an older project does not move it to the top.
|
||||
projectVisits = recordProjectRecentVisit(projectVisits, scope, projectA, 99_000);
|
||||
const afterClick = buildCoordinatorRecents({
|
||||
agents: [agent],
|
||||
chats,
|
||||
recentTasks: tasks,
|
||||
projects: [projectA, projectB],
|
||||
projectVisits,
|
||||
scope,
|
||||
});
|
||||
expect(afterClick.map((item) => `${item.kind}:${item.id}`)).toEqual(
|
||||
beforeClick.map((item) => `${item.kind}:${item.id}`),
|
||||
);
|
||||
|
||||
// Real activity on a chat, task, or project moves that item to the top.
|
||||
const afterActivity = buildCoordinatorRecents({
|
||||
agents: [agent],
|
||||
chats: [{ id: "chat-1", conversationAgentId: agent.id, updatedAt: new Date(5_000) }],
|
||||
recentTasks: [makeTask("task-new", 4_000), makeTask("task-old", 6_000)],
|
||||
projects: [makeProject("proj-a", 7_000), projectB],
|
||||
projectVisits,
|
||||
scope,
|
||||
});
|
||||
expect(afterActivity.map((item) => `${item.kind}:${item.id}`)).toEqual([
|
||||
"project:proj-a",
|
||||
"task:task-old",
|
||||
"chat:chat-1",
|
||||
"task:task-new",
|
||||
"project:proj-b",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores other scopes, tolerates invalid chat timestamps, and scans large collections linearly", () => {
|
||||
const scope = "company-1:user-1";
|
||||
const agents = Array.from({ length: 150 }, (_, index) => makeAgent(`agent-${index}`));
|
||||
const chats = agents.map((agent, index) => ({
|
||||
id: `chat-${index}`,
|
||||
conversationAgentId: agent.id,
|
||||
updatedAt: index === 0 ? new Date("invalid") : new Date(10_000 + index * 3),
|
||||
}));
|
||||
const recentTasks = Array.from({ length: 150 }, (_, index) =>
|
||||
makeTask(`task-${index}`, 10_000 + index * 3 + 1),
|
||||
);
|
||||
const projects = Array.from({ length: 150 }, (_, index) =>
|
||||
makeProject(`proj-${index}`, 10_000 + index * 3 + 2),
|
||||
);
|
||||
const projectVisits: CoordinatorProjectVisits = {
|
||||
scope,
|
||||
entries: Object.fromEntries(projects.map((project, index) => [project.id, 10_000 + index * 3 + 2])),
|
||||
};
|
||||
|
||||
let reads = 0;
|
||||
const maxReads = (agents.length + chats.length + recentTasks.length + projects.length) * 3;
|
||||
const bounded = <T,>(items: T[]): T[] =>
|
||||
new Proxy(items, {
|
||||
get(target, property, receiver) {
|
||||
if (typeof property === "string" && /^\d+$/.test(property)) {
|
||||
reads += 1;
|
||||
if (reads > maxReads) {
|
||||
throw new Error(`Recents builder exceeded linear read budget (${reads} > ${maxReads})`);
|
||||
}
|
||||
}
|
||||
return Reflect.get(target, property, receiver);
|
||||
},
|
||||
});
|
||||
|
||||
const sorted = buildCoordinatorRecents({
|
||||
agents: bounded(agents),
|
||||
chats: bounded(chats),
|
||||
recentTasks: bounded(recentTasks),
|
||||
projects: bounded(projects),
|
||||
projectVisits,
|
||||
scope,
|
||||
});
|
||||
expect(sorted).toHaveLength(450);
|
||||
expect(reads).toBeLessThanOrEqual(maxReads);
|
||||
expect(sorted[0]).toMatchObject({ kind: "project", id: "proj-149" });
|
||||
expect(sorted.at(-1)).toMatchObject({ kind: "chat", id: "chat-0", time: 0 });
|
||||
for (let index = 1; index < sorted.length; index += 1) {
|
||||
expect(sorted[index - 1]!.time).toBeGreaterThanOrEqual(sorted[index]!.time);
|
||||
}
|
||||
|
||||
const wrongScope = buildCoordinatorRecents({
|
||||
agents,
|
||||
chats: [],
|
||||
recentTasks: [],
|
||||
projects,
|
||||
projectVisits,
|
||||
scope: "company-2:user-1",
|
||||
});
|
||||
expect(wrongScope).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { Agent, Issue, Project } from "@paperclipai/shared";
|
||||
import { parseRecentActivityTimestamp, type RecentTaskEntry } from "./recent-tasks";
|
||||
|
||||
export interface CoordinatorProjectVisits {
|
||||
scope: string;
|
||||
entries: Record<string, number>;
|
||||
}
|
||||
|
||||
export type CoordinatorRecentItem =
|
||||
| { kind: "task"; id: string; time: number; task: RecentTaskEntry }
|
||||
| { kind: "chat"; id: string; time: number; agent: Agent }
|
||||
| { kind: "project"; id: string; time: number; project: Project };
|
||||
|
||||
export function recordProjectRecentVisit(
|
||||
previous: CoordinatorProjectVisits,
|
||||
scope: string,
|
||||
project: Pick<Project, "id" | "updatedAt">,
|
||||
now = Date.now(),
|
||||
): CoordinatorProjectVisits {
|
||||
const scopedEntries = previous.scope === scope ? previous.entries : {};
|
||||
if (previous.scope === scope && Object.prototype.hasOwnProperty.call(scopedEntries, project.id)) {
|
||||
return previous;
|
||||
}
|
||||
const seededAt = parseRecentActivityTimestamp(project.updatedAt) ?? now;
|
||||
return {
|
||||
scope,
|
||||
entries: { ...scopedEntries, [project.id]: seededAt },
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCoordinatorRecents({
|
||||
agents,
|
||||
chats,
|
||||
recentTasks,
|
||||
projects,
|
||||
projectVisits,
|
||||
scope,
|
||||
}: {
|
||||
agents: readonly Agent[];
|
||||
chats: readonly Pick<Issue, "id" | "conversationAgentId" | "updatedAt">[];
|
||||
recentTasks: readonly RecentTaskEntry[];
|
||||
projects: readonly Project[];
|
||||
projectVisits: CoordinatorProjectVisits;
|
||||
scope: string;
|
||||
}): CoordinatorRecentItem[] {
|
||||
const roster = new Map(agents.map(agent => [agent.id, agent]));
|
||||
const taskRows: CoordinatorRecentItem[] = recentTasks.map(task => ({
|
||||
kind: "task",
|
||||
id: task.id,
|
||||
time: task.recordedAt,
|
||||
task,
|
||||
}));
|
||||
const chatRows: CoordinatorRecentItem[] = [];
|
||||
for (const chat of chats) {
|
||||
const agent = chat.conversationAgentId ? roster.get(chat.conversationAgentId) : null;
|
||||
if (!agent) continue;
|
||||
chatRows.push({
|
||||
kind: "chat",
|
||||
id: chat.id,
|
||||
time: parseRecentActivityTimestamp(chat.updatedAt) ?? 0,
|
||||
agent,
|
||||
});
|
||||
}
|
||||
const projectRows: CoordinatorRecentItem[] = [];
|
||||
if (projectVisits.scope === scope) {
|
||||
for (const project of projects) {
|
||||
if (!Object.prototype.hasOwnProperty.call(projectVisits.entries, project.id)) continue;
|
||||
const recordedTime = projectVisits.entries[project.id]!;
|
||||
const updatedTime = parseRecentActivityTimestamp(project.updatedAt);
|
||||
projectRows.push({
|
||||
kind: "project",
|
||||
id: project.id,
|
||||
time: updatedTime !== null ? Math.max(recordedTime, updatedTime) : recordedTime,
|
||||
project,
|
||||
});
|
||||
}
|
||||
}
|
||||
return [...taskRows, ...chatRows, ...projectRows].sort((a, b) => b.time - a.time);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
pruneRecentTasks,
|
||||
readRecentTasks,
|
||||
recordRecentTask,
|
||||
settleRecentTaskVisit,
|
||||
updateRecentTaskSnapshots,
|
||||
writeRecentTasks,
|
||||
} from "./recent-tasks";
|
||||
@@ -79,14 +80,41 @@ describe("recent task persistence", () => {
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["1"]);
|
||||
});
|
||||
|
||||
it("seeds passive visits below existing history independently of machine update times", () => {
|
||||
it("seeds unseen passive visits by latest activity timestamp without re-sorting on revisit", () => {
|
||||
const key = getRecentTasksStorageKey("company-1", "user-1");
|
||||
recordRecentTask(issue("personal"), "user-1", 10);
|
||||
recordRecentTask({ ...issue("first-visit"), updatedAt: new Date(100) }, "user-1");
|
||||
recordRecentTask({ ...issue("second-visit"), updatedAt: new Date(1_000) }, "user-1");
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["personal", "first-visit", "second-visit"]);
|
||||
recordRecentTask(issue("second-visit"), "user-1", 20);
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["second-visit", "personal", "first-visit"]);
|
||||
recordRecentTask(issue("personal"), "user-1", 500);
|
||||
recordRecentTask({ ...issue("older-visit"), updatedAt: new Date(100) }, "user-1");
|
||||
recordRecentTask({ ...issue("newer-visit"), updatedAt: new Date(1_000) }, "user-1");
|
||||
recordRecentTask({ ...issue("canonical-activity"), updatedAt: new Date(50), lastActivityAt: new Date(750) }, "user-1");
|
||||
recordRecentTask(issue("no-timestamp"), "user-1");
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
||||
"newer-visit",
|
||||
"canonical-activity",
|
||||
"personal",
|
||||
"older-visit",
|
||||
"no-timestamp",
|
||||
]);
|
||||
|
||||
// Revisiting/clicking existing entries passively must not move them to the top.
|
||||
recordRecentTask({ ...issue("older-visit"), updatedAt: new Date(100) }, "user-1");
|
||||
recordRecentTask(issue("personal"), "user-1");
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
||||
"newer-visit",
|
||||
"canonical-activity",
|
||||
"personal",
|
||||
"older-visit",
|
||||
"no-timestamp",
|
||||
]);
|
||||
|
||||
// Explicit local activity (comment, edit, create, interaction) advances recency.
|
||||
recordRecentTask(issue("older-visit"), "user-1", 2_000);
|
||||
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
||||
"older-visit",
|
||||
"newer-visit",
|
||||
"canonical-activity",
|
||||
"personal",
|
||||
"no-timestamp",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refreshes conversation readiness when review or delivery changes without a task edit", () => {
|
||||
@@ -178,6 +206,42 @@ describe("recent task persistence", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps passive awaitingRead visits in chronological order without bumping existing entries", () => {
|
||||
const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);
|
||||
try {
|
||||
recordRecentTask(issue("older"), "user-1", 100);
|
||||
recordRecentTask(issue("newer"), "user-1", 200);
|
||||
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
||||
|
||||
// Revisiting an existing task with awaitingRead must not bump it above newer items.
|
||||
recordRecentTask(issue("older"), "user-1", undefined, { awaitingRead: true });
|
||||
// Opening an unseen task with awaitingRead seeds chronologically and resists pruning until settled.
|
||||
recordRecentTask({ ...issue("unseen"), updatedAt: new Date(150) }, "user-1", undefined, { awaitingRead: true });
|
||||
|
||||
expect(readRecentTasks(storageKey, "company-1").map(entry => [entry.id, entry.recordedAt])).toEqual([
|
||||
["newer", 200],
|
||||
["unseen", 150],
|
||||
["older", 100],
|
||||
]);
|
||||
|
||||
pruneRecentTasks(storageKey, "company-1", new Set(["older", "unseen"]));
|
||||
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([
|
||||
"newer",
|
||||
"unseen",
|
||||
"older",
|
||||
]);
|
||||
|
||||
settleRecentTaskVisit("company-1", "unseen", "user-1");
|
||||
pruneRecentTasks(storageKey, "company-1", new Set(["unseen"]));
|
||||
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([
|
||||
"newer",
|
||||
"older",
|
||||
]);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("prunes unavailable tasks and refreshes stored snapshots", () => {
|
||||
recordRecentTask(issue("1"), "user-1", 1);
|
||||
recordRecentTask(issue("2"), "user-1", 2);
|
||||
@@ -325,6 +389,16 @@ describe("recent task persistence", () => {
|
||||
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores conversation, archived, and hidden tasks consistently", () => {
|
||||
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
||||
recordRecentTask({ ...issue("chat"), conversationAgentId: "agent-1" }, "user-1", 100);
|
||||
recordRecentTask({ ...issue("archived"), archivedAt: new Date(50) }, "user-1", 100);
|
||||
recordRecentTask({ ...issue("hidden"), hiddenAt: new Date(50) }, "user-1", 100);
|
||||
recordRecentTask({ ...issue("visible"), hiddenAt: null }, "user-1", 100);
|
||||
|
||||
expect(readRecentTasks(storageKey, "company-1").map((entry) => entry.id)).toEqual(["visible"]);
|
||||
});
|
||||
|
||||
it("does not import legacy tasks that appear after an empty migration", () => {
|
||||
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
||||
migrateRecentTasks(storageKey, "company-1");
|
||||
|
||||
@@ -38,11 +38,40 @@ function isAwaitingRead(entry: RecentTaskEntry, now: number) {
|
||||
&& now - entry.awaitingRead < AWAITING_READ_TTL_MS;
|
||||
}
|
||||
|
||||
export type RecentTaskSource = Pick<
|
||||
Issue,
|
||||
| "id"
|
||||
| "companyId"
|
||||
| "title"
|
||||
| "identifier"
|
||||
| "status"
|
||||
| "displayStatus"
|
||||
| "externalConversationState"
|
||||
| "blockerAttention"
|
||||
| "updatedAt"
|
||||
| "conversationAgentId"
|
||||
| "archivedAt"
|
||||
> & Partial<Pick<Issue, "lastActivityAt" | "hiddenAt">>;
|
||||
|
||||
interface RecentTasksUpdatedDetail {
|
||||
storageKey: string;
|
||||
entries: RecentTaskEntry[];
|
||||
}
|
||||
|
||||
export function isEligibleRecentTask(
|
||||
issue: Pick<RecentTaskSource, "conversationAgentId" | "archivedAt" | "hiddenAt">,
|
||||
): boolean {
|
||||
return !issue.conversationAgentId && !issue.archivedAt && !issue.hiddenAt;
|
||||
}
|
||||
|
||||
export function parseRecentActivityTimestamp(
|
||||
value: Date | string | null | undefined,
|
||||
): number | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const timestamp = value instanceof Date ? value.getTime() : new Date(value).getTime();
|
||||
return Number.isFinite(timestamp) && timestamp > 0 ? timestamp : null;
|
||||
}
|
||||
|
||||
export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) {
|
||||
// Old tabs still promote machine activity. Keep their writes out of v3.
|
||||
return `${STORAGE_PREFIX}${companyId}:${userId ?? "__local_board__"}`;
|
||||
@@ -156,22 +185,26 @@ export function mergeRecentTaskSnapshot(entry: RecentTaskEntry, issue: TaskSnaps
|
||||
}
|
||||
|
||||
export function recordRecentTask(
|
||||
issue: Pick<Issue, "id" | "companyId" | "title" | "identifier" | "status" | "displayStatus" | "externalConversationState" | "blockerAttention" | "updatedAt" | "conversationAgentId" | "archivedAt">,
|
||||
issue: RecentTaskSource,
|
||||
userId: string | null | undefined,
|
||||
recordedAt?: number,
|
||||
options?: { awaitingRead?: boolean },
|
||||
) {
|
||||
if (issue.conversationAgentId || issue.archivedAt) return;
|
||||
if (!isEligibleRecentTask(issue)) return;
|
||||
const storageKey = getRecentTasksStorageKey(issue.companyId, userId);
|
||||
const current = readRecentTasks(storageKey, issue.companyId);
|
||||
const existing = current.find((candidate) => candidate.id === issue.id);
|
||||
const snapshotUpdatedAt = new Date(issue.updatedAt).getTime();
|
||||
// Passive reads can seed a candidate, but only explicit local human actions
|
||||
// advance its recency. New passive candidates go below existing history;
|
||||
// their server update times are not personal activity.
|
||||
// Passive opens never re-sort an existing entry. When seeding an unseen task
|
||||
// passively, place it chronologically by its latest activity timestamp (or
|
||||
// below existing history when no valid timestamp is available). Only explicit
|
||||
// local user actions advance recency via `recordedAt`.
|
||||
const activityAt = recordedAt !== undefined && Number.isFinite(recordedAt)
|
||||
? recordedAt
|
||||
: existing?.recordedAt ?? Math.min(0, (current.at(-1)?.recordedAt ?? 1) - 1);
|
||||
: existing?.recordedAt
|
||||
?? parseRecentActivityTimestamp(issue.lastActivityAt)
|
||||
?? parseRecentActivityTimestamp(issue.updatedAt)
|
||||
?? Math.min(0, (current.at(-1)?.recordedAt ?? 1) - 1);
|
||||
const snapshot: RecentTaskEntry = existing ? mergeRecentTaskSnapshot(existing, issue) : {
|
||||
id: issue.id,
|
||||
companyId: issue.companyId,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, type ReactNode } from "react";
|
||||
import { act, forwardRef, useImperativeHandle, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { MemoryRouter, Route, Routes, useNavigate } from "react-router-dom";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Agent, Issue } from "@paperclipai/shared";
|
||||
import { BreadcrumbBar } from "../components/BreadcrumbBar";
|
||||
@@ -11,6 +11,7 @@ import { PanelProvider } from "../context/PanelContext";
|
||||
import { ThemeProvider } from "../context/ThemeContext";
|
||||
import { ToastProvider, useToastState } from "../context/ToastContext";
|
||||
import { DialogProvider } from "../context/DialogContext";
|
||||
import { getRecentTasksStorageKey, readRecentTasks, recordRecentTask } from "../lib/recent-tasks";
|
||||
import { IssueDetail, TaskDetailSurface } from "./IssueDetail";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
@@ -103,8 +104,42 @@ const CHAT_ISSUE: Issue = {
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
issue: null as Issue | null,
|
||||
issuesByRef: {} as Record<string, Issue>,
|
||||
onPostComment: null as ((pathname: string, init?: RequestInit) => Promise<Response> | Response) | null,
|
||||
}));
|
||||
|
||||
vi.mock("../components/MarkdownEditor", () => {
|
||||
const MarkdownEditor = forwardRef(function MockMarkdownEditor(
|
||||
{
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
disabled,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
},
|
||||
ref: React.ForwardedRef<{ focus: () => void; insertMarkdown?: (value: string) => void }>,
|
||||
) {
|
||||
useImperativeHandle(ref, () => ({
|
||||
focus: () => {},
|
||||
insertMarkdown: () => {},
|
||||
}));
|
||||
return (
|
||||
<textarea
|
||||
data-testid="mock-markdown-editor"
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
return { MarkdownEditor };
|
||||
});
|
||||
|
||||
vi.mock("../context/SidebarContext", () => ({
|
||||
useSidebar: () => ({
|
||||
isMobile: true,
|
||||
@@ -190,9 +225,10 @@ vi.mock("@/lib/router", async () => {
|
||||
|
||||
function installMockFetch() {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
|
||||
globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const pathname = new URL(rawUrl, "http://localhost").pathname;
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const json = (data: unknown) =>
|
||||
new Response(JSON.stringify(data), {
|
||||
status: 200,
|
||||
@@ -200,7 +236,7 @@ function installMockFetch() {
|
||||
});
|
||||
|
||||
if (pathname === "/api/auth/get-session") {
|
||||
return json({ session: { userId: "user-1" }, user: { id: "user-1", name: "Riley Board" } });
|
||||
return json({ session: { id: "session-1", userId: "user-1" }, user: { id: "user-1", email: "riley@example.com", name: "Riley Board", image: null }, sentryDsn: null });
|
||||
}
|
||||
if (pathname === "/api/instance/settings/experimental") {
|
||||
return json({ enableStreamlinedUi: true, enableAgentChat: true });
|
||||
@@ -217,8 +253,27 @@ function installMockFetch() {
|
||||
if (pathname === `/api/companies/${COMPANY_ID}/access/user-directory`) {
|
||||
return json({ users: [{ principalId: "user-1", status: "active", user: { name: "Riley Board" } }] });
|
||||
}
|
||||
if (method === "POST" && /^\/api\/issues\/[^/]+\/comments$/.test(pathname)) {
|
||||
if (testState.onPostComment) {
|
||||
return testState.onPostComment(pathname, init);
|
||||
}
|
||||
const ref = decodeURIComponent(pathname.split("/")[3] ?? "");
|
||||
const target = testState.issuesByRef[ref] ?? testState.issue ?? BASE_ISSUE;
|
||||
const bodyPayload = typeof init?.body === "string" ? JSON.parse(init.body) as { body?: string } : {};
|
||||
return json({
|
||||
id: "44444444-4444-4444-8444-444444444441",
|
||||
companyId: COMPANY_ID,
|
||||
issueId: target.id,
|
||||
authorAgentId: null,
|
||||
authorUserId: "user-1",
|
||||
body: bodyPayload.body ?? "",
|
||||
createdAt: "2026-08-03T12:00:00.000Z",
|
||||
updatedAt: "2026-08-03T12:00:00.000Z",
|
||||
});
|
||||
}
|
||||
if (/^\/api\/issues\/[^/]+$/.test(pathname)) {
|
||||
return json(testState.issue ?? BASE_ISSUE);
|
||||
const ref = decodeURIComponent(pathname.slice("/api/issues/".length));
|
||||
return json(testState.issuesByRef[ref] ?? testState.issue ?? BASE_ISSUE);
|
||||
}
|
||||
if (pathname === `/api/issues/${BASE_ISSUE.id}/inbox-archive`) {
|
||||
return json({ id: BASE_ISSUE.id, archivedAt: "2026-08-01T11:00:00Z" });
|
||||
@@ -259,7 +314,10 @@ describe("IssueDetail & AgentChat mobile parity", () => {
|
||||
let restoreFetch: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
testState.issue = BASE_ISSUE;
|
||||
testState.issuesByRef = {};
|
||||
testState.onPostComment = null;
|
||||
restoreFetch = installMockFetch();
|
||||
if (!globalThis.ResizeObserver) {
|
||||
globalThis.ResizeObserver = class ResizeObserver {
|
||||
@@ -433,4 +491,130 @@ describe("IssueDetail & AgentChat mobile parity", () => {
|
||||
expect(document.querySelector('[data-testid="task-side-panel-sentinel"]')?.textContent).toContain("PAP-9001");
|
||||
expect(container.querySelector<HTMLButtonElement>('button[aria-label="Hide properties"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("does not move an existing Recents task to the top when opened passively", async () => {
|
||||
const storageKey = getRecentTasksStorageKey(COMPANY_ID, "user-1");
|
||||
const newerIssue: Issue = {
|
||||
...BASE_ISSUE,
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
identifier: "PAP-6795",
|
||||
title: "Newer active task",
|
||||
updatedAt: new Date("2026-08-02T12:00:00Z"),
|
||||
};
|
||||
recordRecentTask(BASE_ISSUE, "user-1", 1_000);
|
||||
recordRecentTask(newerIssue, "user-1", 2_000);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness initialEntry="/PAP/issues/PAP-6794">
|
||||
<Routes>
|
||||
<Route path="/:companyPrefix/issues/:issueId" element={<IssueDetail />} />
|
||||
</Routes>
|
||||
</Harness>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
|
||||
const entries = readRecentTasks(storageKey, COMPANY_ID);
|
||||
expect(entries.map((entry) => entry.id)).toEqual([newerIssue.id, BASE_ISSUE.id]);
|
||||
expect(entries[1]?.recordedAt).toBe(1_000);
|
||||
});
|
||||
|
||||
it("promotes a Recents task when the user posts a comment and preserves promotion across navigation", async () => {
|
||||
const storageKey = getRecentTasksStorageKey(COMPANY_ID, "user-1");
|
||||
const newerIssue: Issue = {
|
||||
...BASE_ISSUE,
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
identifier: "PAP-6795",
|
||||
title: "Newer active task",
|
||||
updatedAt: new Date("2026-08-02T12:00:00Z"),
|
||||
};
|
||||
testState.issuesByRef = {
|
||||
"PAP-6794": BASE_ISSUE,
|
||||
[BASE_ISSUE.id]: BASE_ISSUE,
|
||||
"PAP-6795": newerIssue,
|
||||
[newerIssue.id]: newerIssue,
|
||||
};
|
||||
recordRecentTask(BASE_ISSUE, "user-1", 1_000);
|
||||
recordRecentTask(newerIssue, "user-1", 2_000);
|
||||
|
||||
const commentCreatedAt = "2026-08-03T12:00:00.000Z";
|
||||
let resolveCommentPost: ((response: Response) => void) | null = null;
|
||||
testState.onPostComment = () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveCommentPost = resolve;
|
||||
});
|
||||
|
||||
let navigateTo: ((to: string) => void) | null = null;
|
||||
function NavigationCapture() {
|
||||
navigateTo = useNavigate();
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness initialEntry="/PAP/issues/PAP-6794">
|
||||
<NavigationCapture />
|
||||
<Routes>
|
||||
<Route path="/:companyPrefix/issues/:issueId" element={<IssueDetail />} />
|
||||
</Routes>
|
||||
</Harness>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
|
||||
// Passive open kept the existing order intact.
|
||||
expect(readRecentTasks(storageKey, COMPANY_ID).map((entry) => entry.id)).toEqual([
|
||||
newerIssue.id,
|
||||
BASE_ISSUE.id,
|
||||
]);
|
||||
|
||||
const editor = container.querySelector<HTMLTextAreaElement>('[data-testid="mock-markdown-editor"]');
|
||||
expect(editor).not.toBeNull();
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
|
||||
await act(async () => {
|
||||
setValue?.call(editor, "Explicit follow-up comment");
|
||||
editor!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const sendButton = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]');
|
||||
expect(sendButton).not.toBeNull();
|
||||
expect(sendButton!.disabled).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
sendButton!.click();
|
||||
});
|
||||
await flush();
|
||||
expect(resolveCommentPost).not.toBeNull();
|
||||
|
||||
// Navigate to another task before the comment POST resolves.
|
||||
await act(async () => {
|
||||
navigateTo!("/PAP/issues/PAP-6795");
|
||||
});
|
||||
await flush();
|
||||
|
||||
await act(async () => {
|
||||
resolveCommentPost!(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
companyId: COMPANY_ID,
|
||||
issueId: BASE_ISSUE.id,
|
||||
authorAgentId: null,
|
||||
authorUserId: "user-1",
|
||||
body: "Explicit follow-up comment",
|
||||
createdAt: commentCreatedAt,
|
||||
updatedAt: commentCreatedAt,
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
),
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
|
||||
const entries = readRecentTasks(storageKey, COMPANY_ID);
|
||||
expect(entries.map((entry) => entry.id)).toEqual([BASE_ISSUE.id, newerIssue.id]);
|
||||
expect(entries[0]?.recordedAt).toBe(new Date(commentCreatedAt).getTime());
|
||||
});
|
||||
});
|
||||
@@ -220,7 +220,11 @@ import {
|
||||
upsertInterruptedRun,
|
||||
} from "../lib/optimistic-issue-runs";
|
||||
import { useProjectOrder } from "../hooks/useProjectOrder";
|
||||
import { recordRecentTask, settleRecentTaskVisit } from "../lib/recent-tasks";
|
||||
import {
|
||||
isEligibleRecentTask,
|
||||
recordRecentTask,
|
||||
settleRecentTaskVisit,
|
||||
} from "../lib/recent-tasks";
|
||||
import { modelStillUnavailableToast } from "../lib/model-retry-refusal";
|
||||
import {
|
||||
relativeTime,
|
||||
@@ -3898,17 +3902,40 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
});
|
||||
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
||||
const recentTaskVisit = useRef<string | null>(null);
|
||||
const canTrackRecents =
|
||||
(streamlinedUiEnabled || coordinatorWorkspaceEnabled)
|
||||
&& sessionResolved
|
||||
&& !conversation;
|
||||
const recordLocalTaskActivity = useCallback(
|
||||
(target: Issue | null | undefined, activityAt = Date.now()) => {
|
||||
if (!canTrackRecents || !target) return;
|
||||
recordRecentTask(target, currentUserId, activityAt);
|
||||
},
|
||||
[canTrackRecents, currentUserId],
|
||||
);
|
||||
const resolveMutationActivityTarget = (
|
||||
expectedIssueId: string,
|
||||
capturedIssue: Issue | null | undefined,
|
||||
): Issue | null =>
|
||||
capturedIssue?.id === expectedIssueId
|
||||
? capturedIssue
|
||||
: issue?.id === expectedIssueId
|
||||
? issue
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!(streamlinedUiEnabled || coordinatorWorkspaceEnabled) || !loadedIssue || !sessionResolved
|
||||
|| conversation || loadedIssue.conversationAgentId || loadedIssue.hiddenAt) return;
|
||||
if (!canTrackRecents || !loadedIssue || !isEligibleRecentTask(loadedIssue)) return;
|
||||
const visit = `${loadedIssue.companyId}:${currentUserId}:${loadedIssue.id}`;
|
||||
const freshVisit = recentTaskVisit.current !== visit;
|
||||
// A fresh visit waits for its read unless that read is already confirmed.
|
||||
const readConfirmed = readReceiptRef.current?.issueId === loadedIssue.id && readReceiptRef.current.confirmed;
|
||||
recordRecentTask(loadedIssue, currentUserId, freshVisit ? Date.now() : undefined,
|
||||
freshVisit && !readConfirmed ? { awaitingRead: true } : undefined);
|
||||
recordRecentTask(
|
||||
loadedIssue,
|
||||
currentUserId,
|
||||
undefined,
|
||||
freshVisit && !readConfirmed ? { awaitingRead: true } : undefined,
|
||||
);
|
||||
recentTaskVisit.current = visit;
|
||||
}, [loadedIssue, currentUserId, sessionResolved, streamlinedUiEnabled, coordinatorWorkspaceEnabled, conversation]);
|
||||
}, [canTrackRecents, loadedIssue, currentUserId]);
|
||||
const { data: boardAccess } = useQuery({
|
||||
queryKey: queryKeys.access.currentBoardAccess,
|
||||
queryFn: () => accessApi.getCurrentBoardAccess(),
|
||||
@@ -4697,9 +4724,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
const issueRefs = new Set<string>([issueId!, nextIssue.id]);
|
||||
if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);
|
||||
mergeIssueResponseIntoCaches(issueRefs, nextIssue);
|
||||
if (streamlinedUiEnabled && sessionResolved) {
|
||||
recordRecentTask(nextIssue, currentUserId, Date.now());
|
||||
}
|
||||
recordLocalTaskActivity(nextIssue);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.issues.activity(issueId!),
|
||||
});
|
||||
@@ -5131,8 +5156,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
},
|
||||
onMutate: ({ approvalId, action }) => {
|
||||
setPendingApprovalAction({ approvalId, action });
|
||||
return { targetIssue: loadedIssue };
|
||||
},
|
||||
onSuccess: (_approval, variables) => {
|
||||
onSuccess: (_approval, variables, context) => {
|
||||
recordLocalTaskActivity(context?.targetIssue);
|
||||
invalidateIssueDetail();
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.issues.approvals(issueId!),
|
||||
@@ -5241,6 +5268,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
optimisticCommentId: optimisticComment?.clientId ?? null,
|
||||
queuedCommentTargetRunId: queuedComment?.id ?? null,
|
||||
previousIssue,
|
||||
targetIssue: loadedIssue ?? previousIssue ?? null,
|
||||
};
|
||||
},
|
||||
onSuccess: async (comment, _variables, context) => {
|
||||
@@ -5321,13 +5349,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
),
|
||||
);
|
||||
}
|
||||
if (streamlinedUiEnabled && issue && sessionResolved) {
|
||||
recordRecentTask(
|
||||
issue,
|
||||
currentUserId,
|
||||
new Date(comment.createdAt).getTime(),
|
||||
);
|
||||
}
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(comment.issueId, context?.targetIssue),
|
||||
new Date(comment.createdAt).getTime(),
|
||||
);
|
||||
},
|
||||
onError: (err, _variables, context) => {
|
||||
if (context?.optimisticCommentId) {
|
||||
@@ -5395,8 +5420,12 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
selectedOptionIds,
|
||||
rememberAction,
|
||||
}),
|
||||
onSuccess: (interaction) => {
|
||||
onMutate: () => ({ targetIssue: loadedIssue ?? issue ?? null }),
|
||||
onSuccess: (interaction, _variables, context) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(interaction.issueId, context?.targetIssue),
|
||||
);
|
||||
if (
|
||||
interaction.kind === "suggest_tasks" &&
|
||||
resolvedCompanyId &&
|
||||
@@ -5446,8 +5475,12 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
interaction: ActionableIssueThreadInteraction;
|
||||
reason?: string;
|
||||
}) => issuesApi.rejectInteraction(issueId!, interaction.id, reason),
|
||||
onSuccess: (interaction) => {
|
||||
onMutate: () => ({ targetIssue: loadedIssue ?? issue ?? null }),
|
||||
onSuccess: (interaction, _variables, context) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(interaction.issueId, context?.targetIssue),
|
||||
);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
@@ -5476,7 +5509,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
interaction: IssueThreadInteraction;
|
||||
answers: AskUserQuestionsAnswer[];
|
||||
}) => issuesApi.respondToInteraction(issueId!, interaction.id, { answers }),
|
||||
onSuccess: (interaction) => {
|
||||
onMutate: () => ({ targetIssue: loadedIssue ?? issue ?? null }),
|
||||
onSuccess: (interaction, _variables, context) => {
|
||||
if (issue?.originKind === "onboarding_chat" && issue.id === interaction.issueId
|
||||
&& currentUserId && issue.conversationUserId === currentUserId && interaction.resolvedByUserId === currentUserId
|
||||
&& interaction.status === "answered" && isOnboardingWelcomeChoice(interaction)) {
|
||||
@@ -5485,6 +5519,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
});
|
||||
}
|
||||
upsertInteractionInCache(interaction);
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(interaction.issueId, context?.targetIssue),
|
||||
);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
@@ -5514,8 +5551,12 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
}[];
|
||||
}) =>
|
||||
issuesApi.submitInteractionVerdicts(issueId!, interaction.id, verdicts),
|
||||
onSuccess: (interaction, variables) => {
|
||||
onMutate: () => ({ targetIssue: loadedIssue ?? issue ?? null }),
|
||||
onSuccess: (interaction, variables, context) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(interaction.issueId, context?.targetIssue),
|
||||
);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
const applied = variables.verdicts.length;
|
||||
@@ -5546,8 +5587,12 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
}: {
|
||||
interaction: AskUserQuestionsInteraction;
|
||||
}) => issuesApi.cancelInteraction(issueId!, interaction.id),
|
||||
onSuccess: (interaction) => {
|
||||
onMutate: () => ({ targetIssue: loadedIssue ?? issue ?? null }),
|
||||
onSuccess: (interaction, _variables, context) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
recordLocalTaskActivity(
|
||||
resolveMutationActivityTarget(interaction.issueId, context?.targetIssue),
|
||||
);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
@@ -5755,9 +5800,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
if (!historyExpanded) {
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.issues.comments(issueId!), exact: true, refetchType: "none" });
|
||||
}
|
||||
if (streamlinedUiEnabled && sessionResolved) {
|
||||
recordRecentTask(nextIssue, currentUserId, new Date(comment.createdAt).getTime());
|
||||
}
|
||||
recordLocalTaskActivity(nextIssue, new Date(comment.createdAt).getTime());
|
||||
}
|
||||
if (context?.optimisticCommentId) {
|
||||
setOptimisticComments((current) =>
|
||||
@@ -7379,6 +7422,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
});
|
||||
},
|
||||
onSuccess: (created) => {
|
||||
recordLocalTaskActivity(created);
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
title: "Isolated re-issue created",
|
||||
|
||||
Reference in new issue
Block a user