mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
feat(ui): filter the Tasks list by when tasks were updated (#22965)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Tasks page lists tasks and provides a Filters panel for status,
assignee, project, and other fields
> - The panel has no time filter, so users cannot limit the list to
tasks updated in a recent time window or date range
> - Users need a quick way to find recent work (such as the last 3 days)
or inspect a custom date range across both desktop and mobile views
> - This pull request supersedes #21822 on current `master` and adds an
"Updated" section to all Tasks filter panels (Any time, Last 24 hours,
Last 3 days, Last 7 days, Last 30 days, and Custom range), keeps the
filter in the URL, aligns "Last updated" display and sort with the
filter timestamp, and adds an optional `updatedBefore` server list bound
> - The benefit is that users can filter tasks by update time window and
share filtered links cleanly across all Tasks views
## Linked Issues or Issue Description
Refs #21822 (rebased onto current `master` with merge conflicts and
post-pruning test updates resolved).
**What existing behavior does this improve?**
The Tasks list filters (`CoordinatorTasks`, Classic `IssuesList`, and
`LegacyIssuesList`) and the company issue list API (`GET
/api/companies/:companyId/issues`). The Filters panel had status,
responsible, project, creator, and label filters, but no time filter.
**Subsystem affected**
UI (Tasks list filters, sorting, and URL sync) and Server (`GET
/api/companies/:companyId/issues`).
**Current behavior**
Users cannot limit the Tasks list to tasks updated within a recent time
window or custom date range. They must scan rows manually to find recent
activity.
**Proposed behavior**
Add an "Updated" section to the Tasks filter panels with options: Any
time (default), Last 24 hours, Last 3 days, Last 7 days, Last 30 days,
and Custom range (start and end local calendar day). Filter on the same
timestamp shown on each row (`lastActivityAt ?? lastExternalCommentAt ??
updatedAt`), count it as 1 active filter, reset it on Clear, persist it
in the page URL (`updated`, `updatedFrom`, `updatedTo`), and send an
optional `updatedBefore` upper bound to the server for custom ranges.
**Reason and benefit**
Users can narrow large task lists to recent work or a specific date
window in one click, including on phones, and share filtered URLs that
open with the same filter applied.
**Breaking changes**
None. The filter defaults to Any time, and `updatedBefore` is an
optional query parameter.
## What Changed
- `server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`docs/api/issues.md`: add the optional `updatedBefore` query parameter
(`issues.updatedAt < updatedBefore`) with `400` validation matching
`updatedSince`, apply both `updatedSince` and `updatedBefore` in
`blockedInboxIssueConditions` so `attention=blocked` enforces the same
bounds, and document both parameters.
- `ui/src/api/issues.ts`: add optional `updatedBefore` to
`IssueListFilters` and `issueListSearchParams`.
- `ui/src/lib/issue-filters.ts`,
`ui/src/hooks/useIssueUpdatedFilterNow.ts`: add `updatedWithin`,
`updatedFrom`, and `updatedTo` to `IssueFilterState`, plus
`issueUpdatedWithinOptions`, `issueUpdatedWithinPatch`,
`issueUpdatedTime`, `issueUpdatedTimeRange`,
`nextIssueUpdatedFilterExpiryMs`, `issueUpdatedServerBefore`,
`readIssueUpdatedParams`, and `writeIssueUpdatedParams`. Reject
impossible calendar dates (such as `2026-02-31`), swap reversed custom
ranges, count Updated as 1 active filter, filter in `applyIssueFilters`
on the row time, and schedule a single deadline timer when a relative
window (`24h`/`3d`/`7d`/`30d`) is active so tasks age out automatically
across task and inbox lists.
- `ui/src/components/IssueUpdatedRangeInputs.tsx`,
`ui/src/components/IssueFilterPanel.tsx`,
`ui/src/components/IssueFiltersPopover.tsx`: add the "Updated" section
and native date inputs (`text-base md:text-xs` to prevent mobile Safari
focus zoom) across refreshed, streamlined, and legacy filter panels.
- `ui/src/components/IssueColumns.tsx`,
`ui/src/components/TaskList.tsx`, `ui/src/lib/issue-sort.ts`,
`DESIGN.md`: align `TaskList` "Last updated" display and sort with
`issueUpdatedTime`, compute each task's sort key once before sorting
(`O(N)` context reads), and update `DESIGN.md` to document the shared
timestamp rule.
- `ui/src/components/IssuesList.tsx`,
`ui/src/components/LegacyIssuesList.tsx`, `ui/src/pages/Issues.tsx`,
`ui/src/pages/CoordinatorTasks.tsx`: sync `updated`, `updatedFrom`, and
`updatedTo` with the page URL, queue multiple URL filter writes in the
same event so Clear resets filters together, pass `updatedBefore` for
custom ranges while preserving `archiveQueryScope` as the final
`issuesQuery.queryKey` segment for `placeholderData`, and forward
`updatedBefore` to `CoordinatorTasks` and `Issues` `searchFilters`.
- `server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts`,
`ui/src/lib/issue-filters.test.ts`, `ui/src/lib/issue-sort.test.ts`,
`ui/src/lib/inbox.test.ts`,
`ui/src/components/IssueFiltersPopover.updated.test.tsx`: add
embedded-Postgres route tests for `updatedBefore` (strict bound,
combined range, `400` validation), unit tests for time windows/custom
ranges/local time zone/invalid dates/URL params/sort key caching, and
component tests across `legacy`, `streamlined`, and `refreshed` panels.
## Verification
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-list-updatedsince-filter-routes.test.ts`: **1 file,
6/6 tests pass** (embedded Postgres, including `attention=blocked` with
`updatedBefore` and `updatedSince`).
- `pnpm --filter @paperclipai/server typecheck`: **pass** (0 errors
across all server layers).
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/issue-filters.test.ts src/lib/issue-sort.test.ts
src/lib/inbox.test.ts
src/components/IssueFiltersPopover.updated.test.tsx
src/pages/Issues.test.tsx`: **5 files, 94/94 tests pass** (including
fake-timer relative window expiration and a 500-task bounded
timestamp-read render-cost test).
- `pnpm --filter @paperclipai/ui typecheck`: **pass** (0 errors,
Storybook catalog clean).
- `node scripts/check-token-gates.mjs`: **pass** (all 4 token gates
clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-sort.test.ts
ui/src/lib/inbox.test.ts
ui/src/components/IssueFiltersPopover.updated.test.tsx`: **pass** (110
nightly suites validated, 5 test files checked).
- `pnpm verify --base 2d06567795
--explain`: exited `2` because `DESIGN.md` is a global CI input; focused
server and UI verification ran locally and full PR CI supplies repo-wide
coverage.
## Risks
- Low risk. The Updated filter is off by default (`Any time`), and
`updatedBefore` is optional.
- `IssueFiltersPopover` is shared by Inbox and agent work panels; those
views use `applyIssueFilters`, so the Updated section works consistently
there as well.
- The refreshed `TaskList` "Last updated" column now displays and sorts
by latest activity (`lastActivityAt ?? lastExternalCommentAt ??
updatedAt`), matching the Classic row and the Updated filter.
- Relative windows filter loaded pages in the browser (like other Tasks
filters); because the server sorts by update time descending, recent
tasks load first.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment
with tool use, shell execution, and embedded Postgres testing), building
on original work from #21822 authored with Anthropic Claude Opus 5.5
(`claude-opus-5-5`).
## 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
- [x] All Paperclip CI gates are green
- [x] 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
27 files changed
+1035
-56
No files matched your search
@@ -524,7 +524,9 @@ width tokens and configurable column order. Review the complete composition in
|
||||
- Task combines the status icon and title under one header and one Columns-menu
|
||||
choice. Sorting Task uses the title. Status sorting is unavailable for now.
|
||||
- Parent Task refers to the structural parent; it can show its ID and title.
|
||||
- Last updated comes from `updatedAt`. Worktree shows the linked Git worktree's
|
||||
- Last updated shows the task's latest activity (`lastActivityAt`, then
|
||||
`lastExternalCommentAt`, then `updatedAt`), the same time the Updated filter
|
||||
and Last updated sort use. Worktree shows the linked Git worktree's
|
||||
branch name. Unassigned tasks say “Unassigned”; other missing values use “—”.
|
||||
- Default visibility is Task, Task ID, and Last updated. The All columns specimen
|
||||
starts with all nine visible for review. Widths are provisional: preserve
|
||||
|
||||
@@ -38,6 +38,8 @@ Query parameters:
|
||||
| `oneChildPerParent` | With `view=index` and `parentIds`, return at most one readable child per parent for collapsed-tree affordances |
|
||||
| `includeReadState` | Board-only `true` adds the current user's personal read state without removing read or untouched tasks |
|
||||
| `inboxArchive` | `include` adds the viewer's archive state to each result. `archived` returns only tasks actively archived by the viewer. |
|
||||
| `updatedSince` | ISO 8601 timestamp; return only issues whose stored `updatedAt` is strictly after it. An invalid value returns `400` |
|
||||
| `updatedBefore` | ISO 8601 timestamp; return only issues whose stored `updatedAt` is strictly before it. An invalid value returns `400` |
|
||||
|
||||
Results sorted by priority.
|
||||
|
||||
|
||||
@@ -173,4 +173,100 @@ describeEmbeddedPostgres("issue list routes updatedSince filter", () => {
|
||||
error: "updatedSince must be a valid ISO 8601 timestamp when provided",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns only issues updated before an updatedBefore timestamp", async () => {
|
||||
const companyId = randomUUID();
|
||||
const olderIssueId = randomUUID();
|
||||
const edgeIssueId = randomUUID();
|
||||
const newerIssueId = randomUUID();
|
||||
const before = new Date("2026-07-01T00:00:00.000Z");
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: uniqueIssuePrefix(),
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await seedCloudTenantMember(companyId);
|
||||
await db.insert(issues).values([
|
||||
{ id: olderIssueId, companyId, title: "Older issue", status: "todo", priority: "medium", updatedAt: new Date("2026-06-30T23:59:59.000Z") },
|
||||
{ id: edgeIssueId, companyId, title: "Edge issue", status: "todo", priority: "medium", updatedAt: before },
|
||||
{ id: newerIssueId, companyId, title: "Newer issue", status: "todo", priority: "medium", updatedAt: new Date("2026-07-02T00:00:00.000Z") },
|
||||
]);
|
||||
|
||||
const app = createApp(companyId);
|
||||
const res = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues`)
|
||||
.query({ updatedBefore: before.toISOString(), limit: "20" });
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(res.body.map((issue: { id: string }) => issue.id)).toEqual([olderIssueId]);
|
||||
|
||||
const between = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues`)
|
||||
.query({ updatedSince: "2026-06-01T00:00:00.000Z", updatedBefore: "2026-07-03T00:00:00.000Z", limit: "20" });
|
||||
expect(between.status, JSON.stringify(between.body)).toBe(200);
|
||||
expect(between.body.map((issue: { id: string }) => issue.id).sort()).toEqual([olderIssueId, edgeIssueId, newerIssueId].sort());
|
||||
});
|
||||
|
||||
it("returns 400 for a malformed updatedBefore timestamp", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: uniqueIssuePrefix(),
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await seedCloudTenantMember(companyId);
|
||||
|
||||
const app = createApp(companyId);
|
||||
const res = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues`)
|
||||
.query({ updatedBefore: "not-a-date", limit: "20" });
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toMatchObject({
|
||||
error: "updatedBefore must be a valid ISO 8601 timestamp when provided",
|
||||
});
|
||||
});
|
||||
|
||||
it("applies updatedBefore and updatedSince when attention=blocked", async () => {
|
||||
const companyId = randomUUID();
|
||||
const olderBlockedId = randomUUID();
|
||||
const edgeBlockedId = randomUUID();
|
||||
const newerBlockedId = randomUUID();
|
||||
const before = new Date("2026-07-01T00:00:00.000Z");
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: uniqueIssuePrefix(),
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await seedCloudTenantMember(companyId);
|
||||
await db.insert(issues).values([
|
||||
{ id: olderBlockedId, companyId, title: "Older blocked", status: "blocked", priority: "medium", updatedAt: new Date("2026-06-30T23:59:59.000Z") },
|
||||
{ id: edgeBlockedId, companyId, title: "Edge blocked", status: "blocked", priority: "medium", updatedAt: before },
|
||||
{ id: newerBlockedId, companyId, title: "Newer blocked", status: "blocked", priority: "medium", updatedAt: new Date("2026-07-02T00:00:00.000Z") },
|
||||
]);
|
||||
|
||||
const app = createApp(companyId);
|
||||
const res = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues`)
|
||||
.query({ attention: "blocked", updatedBefore: before.toISOString(), limit: "20" });
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(res.body.map((issue: { id: string }) => issue.id)).toEqual([olderBlockedId]);
|
||||
|
||||
const between = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues`)
|
||||
.query({
|
||||
attention: "blocked",
|
||||
updatedSince: "2026-06-30T23:59:59.000Z",
|
||||
updatedBefore: "2026-07-02T00:00:00.000Z",
|
||||
limit: "20",
|
||||
});
|
||||
expect(between.status, JSON.stringify(between.body)).toBe(200);
|
||||
expect(between.body.map((issue: { id: string }) => issue.id)).toEqual([edgeBlockedId]);
|
||||
});
|
||||
});
|
||||
@@ -8855,6 +8855,7 @@ export function issueRoutes(
|
||||
const assigneeAgentFilterRaw = req.query.assigneeAgentId;
|
||||
let assigneeAgentId: string | null | undefined;
|
||||
const rawUpdatedSince = req.query.updatedSince as string | undefined;
|
||||
const rawUpdatedBefore = req.query.updatedBefore as string | undefined;
|
||||
|
||||
if (
|
||||
assigneeUserFilterRaw === "me" &&
|
||||
@@ -8977,6 +8978,15 @@ export function issueRoutes(
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
rawUpdatedBefore !== undefined &&
|
||||
!Number.isFinite(new Date(rawUpdatedBefore).getTime())
|
||||
) {
|
||||
res.status(400).json({
|
||||
error: "updatedBefore must be a valid ISO 8601 timestamp when provided",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const uuidQuery = parseIssueListUuidQueryParams(req.query);
|
||||
if (!uuidQuery.ok) {
|
||||
res.status(422).json({ error: uuidQuery.error });
|
||||
@@ -9040,6 +9050,7 @@ export function issueRoutes(
|
||||
afterId: req.query.afterId as string | undefined,
|
||||
sortDir: sortDir === "asc" || sortDir === "desc" ? sortDir : undefined,
|
||||
updatedSince: rawUpdatedSince,
|
||||
updatedBefore: rawUpdatedBefore,
|
||||
};
|
||||
// readCondition is a Drizzle SQL object with cyclic internal references;
|
||||
// actor identity already scopes the coordinator key, so only serializable
|
||||
|
||||
@@ -1949,6 +1949,8 @@ export interface IssueFilters {
|
||||
sortDir?: "asc" | "desc";
|
||||
/** ISO 8601 timestamp — only return issues with updatedAt strictly after this value. */
|
||||
updatedSince?: string;
|
||||
/** ISO 8601 timestamp — only return issues with updatedAt strictly before this value. */
|
||||
updatedBefore?: string;
|
||||
}
|
||||
|
||||
type IssueRow = typeof issues.$inferSelect & { displayStatus?: IssueDisplayStatus; externalConversationState?: "active" | "waiting" | null };
|
||||
@@ -6832,6 +6834,18 @@ async function blockedInboxIssueConditions(
|
||||
),
|
||||
);
|
||||
}
|
||||
if (filters?.updatedSince) {
|
||||
const since = new Date(filters.updatedSince);
|
||||
if (Number.isFinite(since.getTime())) {
|
||||
conditions.push(gt(issues.updatedAt, since));
|
||||
}
|
||||
}
|
||||
if (filters?.updatedBefore) {
|
||||
const before = new Date(filters.updatedBefore);
|
||||
if (Number.isFinite(before.getTime())) {
|
||||
conditions.push(lt(issues.updatedAt, before));
|
||||
}
|
||||
}
|
||||
if (
|
||||
filters?.excludeRoutineExecutions &&
|
||||
!filters?.originKind &&
|
||||
@@ -8759,6 +8773,12 @@ export function issueService(db: Db) {
|
||||
conditions.push(gt(issues.updatedAt, since));
|
||||
}
|
||||
}
|
||||
if (filters?.updatedBefore) {
|
||||
const before = new Date(filters.updatedBefore);
|
||||
if (Number.isFinite(before.getTime())) {
|
||||
conditions.push(lt(issues.updatedAt, before));
|
||||
}
|
||||
}
|
||||
if (
|
||||
filters?.excludeRoutineExecutions &&
|
||||
!filters?.originKind &&
|
||||
|
||||
@@ -232,6 +232,8 @@ export type IssueListFilters = {
|
||||
sortField?: "updated" | "created" | "id";
|
||||
afterId?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
/** ISO 8601 timestamp — only issues whose stored updatedAt is strictly before it. */
|
||||
updatedBefore?: string;
|
||||
};
|
||||
|
||||
function issueListSearchParams(filters?: IssueListFilters) {
|
||||
@@ -286,6 +288,7 @@ function issueListSearchParams(filters?: IssueListFilters) {
|
||||
params.set("offset", String(filters.offset));
|
||||
if (filters?.sortField) params.set("sortField", filters.sortField);
|
||||
if (filters?.sortDir) params.set("sortDir", filters.sortDir);
|
||||
if (filters?.updatedBefore) params.set("updatedBefore", filters.updatedBefore);
|
||||
if (filters?.afterId) params.set("afterId", filters.afterId);
|
||||
return params;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { issuesApi } from "../api/issues";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { cn } from "../lib/utils";
|
||||
import { applyIssueFilters, type IssueFilterState, type IssueFilterWorkspaceContext } from "../lib/issue-filters";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import { resolveInboxIssueBlockerAttention } from "../lib/inbox-live-descendants";
|
||||
import {
|
||||
blockedRowMatchesSearch,
|
||||
@@ -29,6 +30,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { taskStatusIconProps } from "@/lib/task-status-presentation";
|
||||
|
||||
const EMPTY_BLOCKED_ISSUES: Issue[] = [];
|
||||
|
||||
interface BlockedInboxViewProps {
|
||||
companyId: string;
|
||||
searchQuery: string;
|
||||
@@ -87,16 +90,18 @@ export function BlockedInboxView({
|
||||
}),
|
||||
});
|
||||
const {
|
||||
data: issues = [] as Issue[],
|
||||
data: issues,
|
||||
isLoading,
|
||||
} = blockedQuery;
|
||||
const blockedIssues = issues ?? EMPTY_BLOCKED_ISSUES;
|
||||
const blockedView = useQueryView(blockedQuery);
|
||||
|
||||
const allRows = useMemo(() => buildBlockedInboxRows(issues), [issues]);
|
||||
const allRows = useMemo(() => buildBlockedInboxRows(blockedIssues), [blockedIssues]);
|
||||
const filteredRows = useMemo(
|
||||
() => allRows.filter((row) => blockedRowMatchesSearch(row, searchQuery)),
|
||||
[allRows, searchQuery],
|
||||
);
|
||||
const updatedFilterNow = useIssueUpdatedFilterNow(blockedIssues, issueFilters.updatedWithin);
|
||||
const issueFilteredRows = useMemo(() => {
|
||||
const visibleIssueIds = new Set(
|
||||
applyIssueFilters(
|
||||
@@ -106,10 +111,11 @@ export function BlockedInboxView({
|
||||
false,
|
||||
liveIssueIds,
|
||||
workspaceFilterContext,
|
||||
updatedFilterNow,
|
||||
).map((issue) => issue.id),
|
||||
);
|
||||
return filteredRows.filter((row) => visibleIssueIds.has(row.issue.id));
|
||||
}, [currentUserId, filteredRows, issueFilters, liveIssueIds, workspaceFilterContext]);
|
||||
}, [currentUserId, filteredRows, issueFilters, liveIssueIds, workspaceFilterContext, updatedFilterNow]);
|
||||
const sortedRows = useMemo(() => sortBlockedInboxRows(issueFilteredRows, sortBy), [issueFilteredRows, sortBy]);
|
||||
const groups = useMemo(
|
||||
() => groupBlockedInboxRows(issueFilteredRows, sortBy),
|
||||
|
||||
@@ -21,6 +21,7 @@ import { formatAssigneeUserLabel } from "../lib/assignees";
|
||||
import type { InboxIssueColumn } from "../lib/inbox";
|
||||
import { cn } from "../lib/utils";
|
||||
import { timeAgo } from "../lib/timeAgo";
|
||||
import { issueUpdatedTime } from "../lib/issue-filters";
|
||||
import { Identity } from "./Identity";
|
||||
import { StatusIcon } from "./StatusIcon";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -66,7 +67,7 @@ export function issueColumnDescription(
|
||||
}
|
||||
|
||||
export function issueActivityTimestamp(issue: Issue): string {
|
||||
return timeAgo(issue.lastActivityAt ?? issue.lastExternalCommentAt ?? issue.updatedAt);
|
||||
return timeAgo(issueUpdatedTime(issue));
|
||||
}
|
||||
|
||||
export function issueActivityText(issue: Issue): string {
|
||||
|
||||
@@ -5,7 +5,8 @@ import { Button } from "./ui/button";
|
||||
import { FlyoutHeader } from "./ui/flyout";
|
||||
import { StatusIcon } from "./StatusIcon";
|
||||
import { FilterGroup, FilterRow } from "./CollectionFilterOptions";
|
||||
import { issueFilterLabel, issueStatusOrder, searchIssueFilterOptions, toggleIssueFilterValue } from "@/lib/issue-filters";
|
||||
import { IssueUpdatedRangeInputs } from "./IssueUpdatedRangeInputs";
|
||||
import { issueFilterLabel, issueStatusOrder, issueUpdatedWithinOptions, issueUpdatedWithinPatch, searchIssueFilterOptions, toggleIssueFilterValue } from "@/lib/issue-filters";
|
||||
|
||||
type PanelProps = Pick<ComponentProps<typeof IssueFiltersPopover>, "state" | "onChange" | "activeFilterCount" | "agents" | "projects" | "labels" | "creators" | "currentUserId" | "enableRoutineTasksFilter" | "enableAgentCreatedVisibilityFilter" | "enableLiveRunsFilter"> & { onClear: () => void };
|
||||
|
||||
@@ -30,6 +31,13 @@ export function IssueFilterPanel({ state, onChange, activeFilterCount, agents =
|
||||
{enableAgentCreatedVisibilityFilter ? <FilterRow label="Show agent-created tasks" checked={state.showAgentCreatedTasks} onToggle={() => onChange({ showAgentCreatedTasks: !state.showAgentCreatedTasks })} /> : null}
|
||||
{enableRoutineTasksFilter ? <FilterRow label="Routine tasks" checked={state.routineTasksOnly === true} onToggle={() => onChange({ routineTasksOnly: !state.routineTasksOnly })} /> : null}
|
||||
</FilterGroup> : null}
|
||||
<FilterGroup title="Updated" optionsKey="updated">
|
||||
{issueUpdatedWithinOptions.map(option => {
|
||||
const selected = (state.updatedWithin ?? null) === option.value;
|
||||
return <FilterRow key={option.label} label={option.label} checked={selected} onToggle={() => onChange(issueUpdatedWithinPatch(selected ? null : option.value))} />;
|
||||
})}
|
||||
{state.updatedWithin === "custom" ? <IssueUpdatedRangeInputs state={state} onChange={onChange} className="grid-cols-1" /> : null}
|
||||
</FilterGroup>
|
||||
</div>
|
||||
<FilterGroup title="Project" optionsKey="projects" searchLabel="projects" query={queries.projects} onQueryChange={search("projects")}>
|
||||
{visibleProjects.map(project => <FilterRow key={project.id} label={project.name} checked={state.projects.includes(project.id)} onToggle={() => onChange({ projects: toggleIssueFilterValue(state.projects, project.id) })} />)}
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
issuePriorityOrder,
|
||||
issueQuickFilterPresets,
|
||||
issueStatusOrder,
|
||||
issueUpdatedWithinOptions,
|
||||
issueUpdatedWithinPatch,
|
||||
searchIssueFilterOptions,
|
||||
toggleIssueFilterValue,
|
||||
type IssueFilterState,
|
||||
@@ -27,6 +29,7 @@ import { formatAssigneeUserLabel } from "../lib/assignees";
|
||||
import type { InboxApprovalFilter, InboxCategoryFilter } from "../lib/inbox";
|
||||
import { cn } from "../lib/utils";
|
||||
import { IssueFilterPanel } from "./IssueFilterPanel";
|
||||
import { IssueUpdatedRangeInputs } from "./IssueUpdatedRangeInputs";
|
||||
import { FlyoutAppearanceProvider } from "./ui/flyout";
|
||||
|
||||
type AgentOption = {
|
||||
@@ -314,6 +317,31 @@ export function IssueFiltersPopover({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<span className="text-xs text-muted-foreground">Updated</span>
|
||||
<div className="flex flex-wrap gap-1.5" data-filter-options="updated">
|
||||
{issueUpdatedWithinOptions.map((option) => {
|
||||
const isActive = (state.updatedWithin ?? null) === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.label}
|
||||
type="button"
|
||||
aria-pressed={isActive}
|
||||
className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
|
||||
isActive
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: "border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground"
|
||||
}`}
|
||||
onClick={() => onChange(issueUpdatedWithinPatch(isActive ? null : option.value))}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{state.updatedWithin === "custom" ? <IssueUpdatedRangeInputs state={state} onChange={onChange} /> : null}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, useMemo, useState, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Issue } from "@paperclipai/shared";
|
||||
import { IssueFiltersPopover } from "./IssueFiltersPopover";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import {
|
||||
applyIssueFilters,
|
||||
countActiveIssueFilters,
|
||||
defaultIssueFilterState,
|
||||
issueUpdatedServerBefore,
|
||||
type IssueFilterState,
|
||||
} from "../lib/issue-filters";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
vi.mock("@/components/ui/popover", () => ({
|
||||
Popover: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
PopoverContent: ({ children, className }: { children: ReactNode; className?: string }) => (
|
||||
<div data-testid="popover-content" className={className}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/button", () => ({
|
||||
Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
|
||||
<button type="button" {...props}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/checkbox", () => ({
|
||||
Checkbox: ({ checked, onCheckedChange, ...props }: { checked?: boolean; onCheckedChange?: (checked: boolean) => void }) => (
|
||||
<input {...props} type="checkbox" checked={checked} onChange={event => onCheckedChange?.(event.target.checked)} />
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./StatusIcon", () => ({
|
||||
StatusIcon: ({ status }: { status: string }) => <span>{status}</span>,
|
||||
}));
|
||||
|
||||
vi.mock("./PriorityIcon", () => ({
|
||||
PriorityIcon: ({ priority }: { priority: string }) => <span>{priority}</span>,
|
||||
}));
|
||||
|
||||
function makeIssue(id: string, title: string, updatedAt: Date, lastActivityAt?: Date): Issue {
|
||||
return {
|
||||
id,
|
||||
companyId: "company-1",
|
||||
projectId: null,
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
title,
|
||||
description: null,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
reviewPolicy: null,
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
responsibleUserId: null,
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionAgentNameKey: null,
|
||||
executionLockedAt: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
issueNumber: 1,
|
||||
identifier: "PAP-1",
|
||||
requestDepth: 0,
|
||||
billingCode: null,
|
||||
assigneeAdapterOverrides: null,
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
cancelledAt: null,
|
||||
hiddenAt: null,
|
||||
labels: [],
|
||||
labelIds: [],
|
||||
createdAt: updatedAt,
|
||||
updatedAt,
|
||||
lastActivityAt: lastActivityAt ?? null,
|
||||
lastExternalCommentAt: null,
|
||||
workMode: "standard",
|
||||
};
|
||||
}
|
||||
|
||||
describe("IssueFiltersPopover Updated time filter", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each(["legacy", "streamlined", "refreshed"] as const)("filters tasks by Updated time window and custom range in %s", presentation => {
|
||||
const now = new Date("2026-11-15T12:00:00.000Z");
|
||||
const tasks = [
|
||||
makeIssue("fresh", "Fresh task", new Date("2026-11-14T12:00:00.000Z")),
|
||||
makeIssue("commented", "Recently active task", new Date("2026-10-01T12:00:00.000Z"), new Date("2026-11-13T12:00:00.000Z")),
|
||||
makeIssue("mid", "Mid-window task", new Date("2026-11-05T12:00:00.000Z")),
|
||||
makeIssue("old", "Old task", new Date("2026-10-10T12:00:00.000Z")),
|
||||
];
|
||||
|
||||
function Harness() {
|
||||
const [state, setState] = useState<IssueFilterState>(defaultIssueFilterState);
|
||||
const visible = applyIssueFilters(tasks, state, null, false, undefined, {}, now);
|
||||
return (
|
||||
<>
|
||||
<IssueFiltersPopover
|
||||
presentation={presentation}
|
||||
state={state}
|
||||
onChange={(patch) => setState((prev) => ({ ...prev, ...patch }))}
|
||||
activeFilterCount={countActiveIssueFilters(state)}
|
||||
/>
|
||||
<ul data-testid="visible-tasks">
|
||||
{visible.map((task) => <li key={task.id}>{task.id}</li>)}
|
||||
</ul>
|
||||
<output data-testid="updated-before">{issueUpdatedServerBefore(state) ?? ""}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(<Harness />));
|
||||
|
||||
const visibleIds = () => Array.from(container.querySelectorAll('[data-testid="visible-tasks"] li')).map(el => el.textContent);
|
||||
const updated = () => container.querySelector('[data-filter-options="updated"]')!;
|
||||
const option = (label: string) =>
|
||||
Array.from(updated().querySelectorAll("button, label")).find(el => el.textContent === label) as HTMLElement;
|
||||
|
||||
expect(updated().textContent).toBe("Any timeLast 24 hoursLast 3 daysLast 7 daysLast 30 daysCustom range");
|
||||
expect(container.querySelector('input[type="date"]')).toBeNull();
|
||||
expect(visibleIds()).toEqual(["fresh", "commented", "mid", "old"]);
|
||||
|
||||
// Pick Last 3 days — keeps fresh + recently active task, hides older ones.
|
||||
act(() => (option("Last 3 days").querySelector("input") ?? option("Last 3 days")).click());
|
||||
expect(visibleIds()).toEqual(["fresh", "commented"]);
|
||||
expect(container.querySelector('[data-testid="updated-before"]')?.textContent).toBe("");
|
||||
|
||||
// Switch to Custom range and set From / To dates.
|
||||
act(() => (option("Custom range").querySelector("input") ?? option("Custom range")).click());
|
||||
const from = container.querySelector<HTMLInputElement>('input[aria-label="Updated from"]');
|
||||
const to = container.querySelector<HTMLInputElement>('input[aria-label="Updated to"]');
|
||||
expect(from).not.toBeNull();
|
||||
expect(to).not.toBeNull();
|
||||
|
||||
const setInputValue = (input: HTMLInputElement, value: string) => {
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
|
||||
setter.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
};
|
||||
|
||||
act(() => setInputValue(from!, "2026-11-04"));
|
||||
act(() => setInputValue(to!, "2026-11-06"));
|
||||
expect(to!.min).toBe("2026-11-04");
|
||||
expect(visibleIds()).toEqual(["mid"]);
|
||||
expect(container.querySelector('[data-testid="updated-before"]')?.textContent).toBe(new Date(2026, 10, 7).toISOString());
|
||||
|
||||
// Clear resets Updated filter and shows all tasks again.
|
||||
const clearButton = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Clear");
|
||||
expect(clearButton).toBeDefined();
|
||||
act(() => clearButton!.click());
|
||||
expect(visibleIds()).toEqual(["fresh", "commented", "mid", "old"]);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("drops a task from Last 24 hours automatically when wall-clock time crosses the window", () => {
|
||||
vi.useFakeTimers({ now: new Date("2026-11-15T12:00:00.000Z") });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
const tasks = [
|
||||
makeIssue("aging", "Aging task", new Date("2026-11-14T13:00:00.000Z")), // 23h old
|
||||
makeIssue("fresh", "Fresh task", new Date("2026-11-15T11:00:00.000Z")), // 1h old
|
||||
];
|
||||
const filters: IssueFilterState = { ...defaultIssueFilterState, updatedWithin: "24h" };
|
||||
|
||||
function MemoizedListHarness() {
|
||||
const updatedNow = useIssueUpdatedFilterNow(tasks, filters.updatedWithin);
|
||||
const visible = useMemo(
|
||||
() => applyIssueFilters(tasks, filters, null, false, undefined, {}, updatedNow),
|
||||
[updatedNow],
|
||||
);
|
||||
return (
|
||||
<ul data-testid="aging-tasks">
|
||||
{visible.map((task) => <li key={task.id}>{task.id}</li>)}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
act(() => root.render(<MemoizedListHarness />));
|
||||
const ids = () => Array.from(container.querySelectorAll('[data-testid="aging-tasks"] li')).map(el => el.textContent);
|
||||
expect(ids()).toEqual(["aging", "fresh"]);
|
||||
|
||||
// Advance 2 hours with no task data changes: "aging" is now 25h old and drops out.
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2 * 60 * 60 * 1000);
|
||||
});
|
||||
expect(ids()).toEqual(["fresh"]);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("bounds timestamp reads on large collections across expiry and unchanged rerenders", () => {
|
||||
vi.useFakeTimers({ now: new Date("2026-11-15T12:00:00.000Z") });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
const count = 500;
|
||||
const maxReads = count * 5;
|
||||
let timestampReads = 0;
|
||||
|
||||
const tasks: Issue[] = Array.from({ length: count }, (_, index) => {
|
||||
// First task is 23h old (ages out in 1h); remaining 499 are 1h-10h old.
|
||||
const ageMs = index === 0
|
||||
? 23 * 60 * 60 * 1000
|
||||
: (1 + (index % 9)) * 60 * 60 * 1000;
|
||||
const storedUpdatedAt = new Date(Date.now() - ageMs);
|
||||
const task = makeIssue(`task-${index}`, `Task ${index}`, storedUpdatedAt);
|
||||
Object.defineProperty(task, "updatedAt", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
timestampReads += 1;
|
||||
if (timestampReads > maxReads) {
|
||||
throw new Error(`Exceeded bounded timestamp reads (${timestampReads} > ${maxReads})`);
|
||||
}
|
||||
return storedUpdatedAt;
|
||||
},
|
||||
});
|
||||
return task;
|
||||
});
|
||||
|
||||
const filters: IssueFilterState = { ...defaultIssueFilterState, updatedWithin: "24h" };
|
||||
|
||||
function LargeListHarness({ unrelatedProp }: { unrelatedProp: number }) {
|
||||
const updatedNow = useIssueUpdatedFilterNow(tasks, filters.updatedWithin);
|
||||
const visible = useMemo(
|
||||
() => applyIssueFilters(tasks, filters, null, false, undefined, {}, updatedNow),
|
||||
[updatedNow],
|
||||
);
|
||||
return <output data-testid="large-count" data-prop={unrelatedProp}>{visible.length}</output>;
|
||||
}
|
||||
|
||||
act(() => root.render(<LargeListHarness unrelatedProp={1} />));
|
||||
expect(container.querySelector('[data-testid="large-count"]')?.textContent).toBe("500");
|
||||
const readsAfterMount = timestampReads;
|
||||
expect(readsAfterMount).toBe(count * 2);
|
||||
|
||||
// Unchanged rerender hits memoization with zero extra scans.
|
||||
act(() => root.render(<LargeListHarness unrelatedProp={2} />));
|
||||
expect(timestampReads).toBe(readsAfterMount);
|
||||
|
||||
// Advance past the first task's 24h boundary: exactly one expiry refresh scan runs.
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2 * 60 * 60 * 1000);
|
||||
});
|
||||
expect(container.querySelector('[data-testid="large-count"]')?.textContent).toBe("499");
|
||||
const readsAfterExpiry = timestampReads;
|
||||
expect(readsAfterExpiry).toBe(count * 4);
|
||||
|
||||
// Subsequent unchanged rerender still performs zero extra scans.
|
||||
act(() => root.render(<LargeListHarness unrelatedProp={3} />));
|
||||
expect(timestampReads).toBe(readsAfterExpiry);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { IssueFilterState } from "../lib/issue-filters";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
function localDateString(date: Date): string {
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
}
|
||||
|
||||
/** Start and end days for the Updated filter's custom range, in the browser's time zone. */
|
||||
export function IssueUpdatedRangeInputs({
|
||||
state,
|
||||
onChange,
|
||||
className,
|
||||
inputClassName,
|
||||
}: {
|
||||
state: Pick<IssueFilterState, "updatedFrom" | "updatedTo">;
|
||||
onChange: (patch: Partial<IssueFilterState>) => void;
|
||||
className?: string;
|
||||
inputClassName?: string;
|
||||
}) {
|
||||
const today = localDateString(new Date());
|
||||
return (
|
||||
<div className={cn("grid grid-cols-2 gap-2", className)} data-filter-options="updated-range">
|
||||
<label className="min-w-0 space-y-1">
|
||||
<span className="text-xs text-muted-foreground">From</span>
|
||||
<Input
|
||||
type="date"
|
||||
aria-label="Updated from"
|
||||
value={state.updatedFrom ?? ""}
|
||||
max={state.updatedTo ?? today}
|
||||
onChange={(event) => onChange({ updatedFrom: event.target.value || null })}
|
||||
className={cn("h-8 min-w-0 text-base md:text-xs", inputClassName)}
|
||||
/>
|
||||
</label>
|
||||
<label className="min-w-0 space-y-1">
|
||||
<span className="text-xs text-muted-foreground">To</span>
|
||||
<Input
|
||||
type="date"
|
||||
aria-label="Updated to"
|
||||
value={state.updatedTo ?? ""}
|
||||
min={state.updatedFrom ?? undefined}
|
||||
max={today}
|
||||
onChange={(event) => onChange({ updatedTo: event.target.value || null })}
|
||||
className={cn("h-8 min-w-0 text-base md:text-xs", inputClassName)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { authApi } from "../api/auth";
|
||||
import { instanceSettingsApi } from "../api/instanceSettings";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import {
|
||||
shouldBlurPageSearchOnEnter,
|
||||
shouldBlurPageSearchOnEscape,
|
||||
@@ -49,7 +50,10 @@ import {
|
||||
resolveIssueFilterWorkspaceId,
|
||||
shouldIncludeIssueFilterWorkspaceOption,
|
||||
issueStatusOrder,
|
||||
issueUpdatedServerBefore,
|
||||
issueUpdatedTime,
|
||||
type IssueFilterState,
|
||||
type IssueUpdatedFilter,
|
||||
} from "../lib/issue-filters";
|
||||
import {
|
||||
DEFAULT_INBOX_ISSUE_COLUMNS,
|
||||
@@ -481,6 +485,11 @@ interface IssuesListProps {
|
||||
/** URL sorting overrides the saved collection preference when supplied. */
|
||||
sort?: IssueSort;
|
||||
onSortChange?: (sort: IssueSort) => void;
|
||||
/** Reports the server `updatedBefore` bound for the Updated filter's custom range end. */
|
||||
onUpdatedBeforeChange?: (updatedBefore: string | undefined) => void;
|
||||
/** URL Updated filter; when supplied it overrides the saved collection preference. */
|
||||
updatedFilter?: IssueUpdatedFilter;
|
||||
onUpdatedFilterChange?: (filter: IssueUpdatedFilter) => void;
|
||||
initialSearch?: string;
|
||||
searchFilters?: Omit<IssueListRequestFilters, "q" | "projectId" | "limit" | "includeRoutineExecutions" | "sortField" | "sortDir">;
|
||||
searchWithinLoadedIssues?: boolean;
|
||||
@@ -735,6 +744,9 @@ function StreamlinedIssuesList({
|
||||
onRoutineTasksOnlyChange,
|
||||
sort,
|
||||
onSortChange,
|
||||
onUpdatedBeforeChange,
|
||||
updatedFilter,
|
||||
onUpdatedFilterChange,
|
||||
initialSearch,
|
||||
searchFilters,
|
||||
searchWithinLoadedIssues = false,
|
||||
@@ -835,7 +847,12 @@ function StreamlinedIssuesList({
|
||||
...savedViewState,
|
||||
...sort,
|
||||
...(routineTasksOnly === undefined ? {} : { routineTasksOnly }),
|
||||
}), [savedViewState, sort, routineTasksOnly]);
|
||||
...updatedFilter,
|
||||
}), [savedViewState, sort, routineTasksOnly, updatedFilter]);
|
||||
const updatedBefore = issueUpdatedServerBefore(viewState);
|
||||
useEffect(() => {
|
||||
onUpdatedBeforeChange?.(updatedBefore);
|
||||
}, [onUpdatedBeforeChange, updatedBefore]);
|
||||
const showAgentCreatedTasks = useShowAgentCreatedTasks(selectedCompanyId, viewStateKey);
|
||||
useEffect(() => {
|
||||
if (!enableAgentCreatedVisibilityFilter) return;
|
||||
@@ -892,6 +909,13 @@ function StreamlinedIssuesList({
|
||||
|
||||
const updateView = useCallback((patch: Partial<IssueViewState>) => {
|
||||
if (patch.routineTasksOnly !== undefined) onRoutineTasksOnlyChange?.(patch.routineTasksOnly);
|
||||
if (patch.updatedWithin !== undefined || patch.updatedFrom !== undefined || patch.updatedTo !== undefined) {
|
||||
onUpdatedFilterChange?.({
|
||||
updatedWithin: patch.updatedWithin !== undefined ? patch.updatedWithin : viewState.updatedWithin,
|
||||
updatedFrom: patch.updatedFrom !== undefined ? patch.updatedFrom : viewState.updatedFrom,
|
||||
updatedTo: patch.updatedTo !== undefined ? patch.updatedTo : viewState.updatedTo,
|
||||
});
|
||||
}
|
||||
if (patch.sortField !== undefined || patch.sortDir !== undefined) {
|
||||
onSortChange?.({
|
||||
sortField: patch.sortField ?? viewState.sortField,
|
||||
@@ -914,9 +938,13 @@ function StreamlinedIssuesList({
|
||||
visibleIssueColumns,
|
||||
onRoutineTasksOnlyChange,
|
||||
onSortChange,
|
||||
onUpdatedFilterChange,
|
||||
sort,
|
||||
viewState.sortField,
|
||||
viewState.sortDir,
|
||||
viewState.updatedWithin,
|
||||
viewState.updatedFrom,
|
||||
viewState.updatedTo,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1239,6 +1267,7 @@ function StreamlinedIssuesList({
|
||||
&& !externalObjectSummariesReady;
|
||||
const externalObjectFilterError = hasExternalObjectStatusFilters ? externalObjectSummariesError : null;
|
||||
|
||||
const updatedFilterNow = useIssueUpdatedFilterNow(searchScopedIssues, viewState.updatedWithin);
|
||||
const filtered = useMemo(() => {
|
||||
const filteredByControls = applyIssueFilters(
|
||||
searchScopedIssues,
|
||||
@@ -1247,6 +1276,7 @@ function StreamlinedIssuesList({
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
updatedFilterNow,
|
||||
);
|
||||
const byId = new Map(searchScopedIssues.map(issue => [issue.id, issue]));
|
||||
return sortIssues(filteredByControls, viewState, issue => {
|
||||
@@ -1256,6 +1286,7 @@ function StreamlinedIssuesList({
|
||||
assignee: issue.assigneeAgentId ? agentName(issue.assigneeAgentId) ?? "Unknown agent" : companyUserLabelMap.get(issue.assigneeUserId ?? "") ?? null,
|
||||
project: projectById.get(issue.projectId ?? "")?.name,
|
||||
parentTask: parent ? `${parent.identifier} ${parent.title}` : null,
|
||||
updated: issueUpdatedTime(issue),
|
||||
};
|
||||
});
|
||||
}, [
|
||||
@@ -1265,6 +1296,7 @@ function StreamlinedIssuesList({
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
updatedFilterNow,
|
||||
agentName,
|
||||
companyUserLabelMap,
|
||||
projectById,
|
||||
@@ -2585,7 +2617,8 @@ function StreamlinedIssuesList({
|
||||
// dangle above an unrendered (or absent) row.
|
||||
if (node === null) return;
|
||||
if (separatorField && rowPresentation === "task") {
|
||||
const currentDateGroup = taskDateGroup(issue[separatorField], separatorNow);
|
||||
const separatorTimestamp = separatorField === "updatedAt" ? issueUpdatedTime(issue) : issue.createdAt;
|
||||
const currentDateGroup = taskDateGroup(separatorTimestamp, separatorNow);
|
||||
const separatorLabel = taskDateGroupSeparator(previousDateGroup, currentDateGroup);
|
||||
if (separatorLabel) {
|
||||
nodes.push(
|
||||
@@ -2597,7 +2630,8 @@ function StreamlinedIssuesList({
|
||||
}
|
||||
previousDateGroup = currentDateGroup;
|
||||
} else if (separatorField) {
|
||||
const currentAgeBucket = issueAgeBucket(issue[separatorField], separatorNow.getTime());
|
||||
const separatorTimestamp = separatorField === "updatedAt" ? issueUpdatedTime(issue) : issue.createdAt;
|
||||
const currentAgeBucket = issueAgeBucket(separatorTimestamp, separatorNow.getTime());
|
||||
for (const crossedBucket of previousAgeBucket === null
|
||||
? []
|
||||
: issueAgeBucketsCrossed(previousAgeBucket, currentAgeBucket)) {
|
||||
|
||||
@@ -22,6 +22,7 @@ import { authApi } from "../api/auth";
|
||||
import { instanceSettingsApi } from "../api/instanceSettings";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import {
|
||||
shouldBlurPageSearchOnEnter,
|
||||
shouldBlurPageSearchOnEscape,
|
||||
@@ -47,7 +48,10 @@ import {
|
||||
resolveIssueFilterWorkspaceId,
|
||||
shouldIncludeIssueFilterWorkspaceOption,
|
||||
issueStatusOrder,
|
||||
issueUpdatedServerBefore,
|
||||
issueUpdatedTime,
|
||||
type IssueFilterState,
|
||||
type IssueUpdatedFilter,
|
||||
} from "../lib/issue-filters";
|
||||
import {
|
||||
DEFAULT_INBOX_ISSUE_COLUMNS,
|
||||
@@ -459,6 +463,11 @@ interface IssuesListProps {
|
||||
/** URL sorting overrides the saved collection preference when supplied. */
|
||||
sort?: IssueSort;
|
||||
onSortChange?: (sort: IssueSort) => void;
|
||||
/** Reports the server `updatedBefore` bound for the Updated filter's custom range end. */
|
||||
onUpdatedBeforeChange?: (updatedBefore: string | undefined) => void;
|
||||
/** URL Updated filter; when supplied it overrides the saved collection preference. */
|
||||
updatedFilter?: IssueUpdatedFilter;
|
||||
onUpdatedFilterChange?: (filter: IssueUpdatedFilter) => void;
|
||||
initialSearch?: string;
|
||||
searchFilters?: Omit<IssueListRequestFilters, "q" | "projectId" | "limit" | "includeRoutineExecutions" | "sortField" | "sortDir">;
|
||||
searchWithinLoadedIssues?: boolean;
|
||||
@@ -683,6 +692,9 @@ export function IssuesList({
|
||||
onRoutineTasksOnlyChange,
|
||||
sort,
|
||||
onSortChange,
|
||||
onUpdatedBeforeChange,
|
||||
updatedFilter,
|
||||
onUpdatedFilterChange,
|
||||
initialSearch,
|
||||
searchFilters,
|
||||
searchWithinLoadedIssues = false,
|
||||
@@ -762,7 +774,12 @@ export function IssuesList({
|
||||
...savedViewState,
|
||||
...sort,
|
||||
...(routineTasksOnly === undefined ? {} : { routineTasksOnly }),
|
||||
}), [savedViewState, sort, routineTasksOnly]);
|
||||
...updatedFilter,
|
||||
}), [savedViewState, sort, routineTasksOnly, updatedFilter]);
|
||||
const updatedBefore = issueUpdatedServerBefore(viewState);
|
||||
useEffect(() => {
|
||||
onUpdatedBeforeChange?.(updatedBefore);
|
||||
}, [onUpdatedBeforeChange, updatedBefore]);
|
||||
const showAgentCreatedTasks = useShowAgentCreatedTasks(selectedCompanyId, viewStateKey);
|
||||
useEffect(() => {
|
||||
if (!enableAgentCreatedVisibilityFilter) return;
|
||||
@@ -804,6 +821,13 @@ export function IssuesList({
|
||||
|
||||
const updateView = useCallback((patch: Partial<IssueViewState>) => {
|
||||
if (patch.routineTasksOnly !== undefined) onRoutineTasksOnlyChange?.(patch.routineTasksOnly);
|
||||
if (patch.updatedWithin !== undefined || patch.updatedFrom !== undefined || patch.updatedTo !== undefined) {
|
||||
onUpdatedFilterChange?.({
|
||||
updatedWithin: patch.updatedWithin !== undefined ? patch.updatedWithin : viewState.updatedWithin,
|
||||
updatedFrom: patch.updatedFrom !== undefined ? patch.updatedFrom : viewState.updatedFrom,
|
||||
updatedTo: patch.updatedTo !== undefined ? patch.updatedTo : viewState.updatedTo,
|
||||
});
|
||||
}
|
||||
if (patch.sortField !== undefined || patch.sortDir !== undefined) {
|
||||
onSortChange?.({
|
||||
sortField: patch.sortField ?? viewState.sortField,
|
||||
@@ -818,7 +842,7 @@ export function IssuesList({
|
||||
}, { viewState: next, columns: visibleIssueColumns });
|
||||
return next;
|
||||
});
|
||||
}, [scopedKey, selectedCompanyId, viewStateKey, visibleIssueColumns, onRoutineTasksOnlyChange, onSortChange, sort, viewState.sortField, viewState.sortDir]);
|
||||
}, [scopedKey, selectedCompanyId, viewStateKey, visibleIssueColumns, onRoutineTasksOnlyChange, onSortChange, onUpdatedFilterChange, sort, viewState.sortField, viewState.sortDir, viewState.updatedWithin, viewState.updatedFrom, viewState.updatedTo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!experimentalSettingsLoaded || externalObjectsEnabled || viewState.externalObjectStatuses.length === 0) return;
|
||||
@@ -1131,6 +1155,7 @@ export function IssuesList({
|
||||
&& externalObjectSummariesLoading
|
||||
&& !externalObjectSummariesReady;
|
||||
|
||||
const updatedFilterNow = useIssueUpdatedFilterNow(searchScopedIssues, viewState.updatedWithin);
|
||||
const filtered = useMemo(() => {
|
||||
const filteredByControls = applyIssueFilters(
|
||||
searchScopedIssues,
|
||||
@@ -1139,6 +1164,7 @@ export function IssuesList({
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
updatedFilterNow,
|
||||
);
|
||||
const byId = new Map(searchScopedIssues.map(issue => [issue.id, issue]));
|
||||
return sortIssues(filteredByControls, viewState, issue => {
|
||||
@@ -1148,6 +1174,7 @@ export function IssuesList({
|
||||
assignee: issue.assigneeAgentId ? agentName(issue.assigneeAgentId) ?? "Unknown agent" : companyUserLabelMap.get(issue.assigneeUserId ?? "") ?? null,
|
||||
project: projectById.get(issue.projectId ?? "")?.name,
|
||||
parentTask: parent ? `${parent.identifier} ${parent.title}` : null,
|
||||
updated: issueUpdatedTime(issue),
|
||||
};
|
||||
});
|
||||
}, [
|
||||
@@ -1157,6 +1184,7 @@ export function IssuesList({
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
updatedFilterNow,
|
||||
agentName,
|
||||
companyUserLabelMap,
|
||||
projectById,
|
||||
@@ -2388,7 +2416,8 @@ export function IssuesList({
|
||||
// dangle above an unrendered (or absent) row.
|
||||
if (node === null) return;
|
||||
if (separatorField) {
|
||||
const bucket = issueAgeBucket(issue[separatorField], separatorNow);
|
||||
const separatorTimestamp = separatorField === "updatedAt" ? issueUpdatedTime(issue) : issue.createdAt;
|
||||
const bucket = issueAgeBucket(separatorTimestamp, separatorNow);
|
||||
for (const crossedBucket of prevBucket === null
|
||||
? []
|
||||
: issueAgeBucketsCrossed(prevBucket, bucket)) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Fragment, useId, useState, type ReactNode } from "react";
|
||||
import type { Issue } from "@paperclipai/shared";
|
||||
import { ChevronDown, ChevronRight, GitBranch } from "lucide-react";
|
||||
import { buildIssueTree } from "../lib/issue-tree";
|
||||
import { issueFilterLabel } from "../lib/issue-filters";
|
||||
import { issueFilterLabel, issueUpdatedTime } from "../lib/issue-filters";
|
||||
import { paperclipHumanAvatarUrl } from "../lib/issue-chat-human-author";
|
||||
import { defaultTaskListColumns, defaultTaskListSort, isTaskListColumnSort, taskListOrderToIssueSort, type TaskListColumnId, type TaskListSort, type TaskListOrder } from "../lib/task-list";
|
||||
import { sortIssues } from "../lib/issue-sort";
|
||||
@@ -104,7 +104,7 @@ export function TaskList({ items, allItems = items, initialColumns = defaultTask
|
||||
const ordered = sortIssues(items.map(item => item.issue), taskListOrderToIssueSort(sort ?? defaultTaskListSort), issue => {
|
||||
const item = byId.get(issue.id)!;
|
||||
const parent = issue.parentId ? byId.get(issue.parentId)?.issue : null;
|
||||
return { createdBy: item.createdBy, assignee: item.assignee, parentTask: parent ? `${parent.identifier} ${parent.title}` : null };
|
||||
return { createdBy: item.createdBy, assignee: item.assignee, parentTask: parent ? `${parent.identifier} ${parent.title}` : null, updated: issueUpdatedTime(issue) };
|
||||
});
|
||||
const { roots, childMap } = buildIssueTree(ordered);
|
||||
const rowIds: string[] = [];
|
||||
@@ -157,7 +157,7 @@ export function TaskList({ items, allItems = items, initialColumns = defaultTask
|
||||
parentTask: parent ? <span><span className="font-mono">{parent.identifier}</span> {parent.title}</span> : undefined,
|
||||
tags: issue.labels?.length ? <span className="inline-flex items-center gap-1">{issue.labels.map(label => <Badge key={label.id} variant="secondary" className="shrink-0 px-1.5 py-0">{label.name}</Badge>)}</span> : undefined,
|
||||
worktree: branch ? <span className="inline-flex items-center gap-1.5"><GitBranch className="size-3 shrink-0" aria-hidden />{branch}</span> : undefined,
|
||||
lastUpdated: timeAgo(issue.updatedAt),
|
||||
lastUpdated: timeAgo(issueUpdatedTime(issue)),
|
||||
}}
|
||||
/>
|
||||
{expanded ? children.map(child => renderBranch(child, depth + 1)) : null}
|
||||
|
||||
@@ -22,6 +22,9 @@ import { Link } from "@/lib/router";
|
||||
import { cn, formatDate, relativeTime } from "@/lib/utils";
|
||||
import { taskStatusIconProps } from "@/lib/task-status-presentation";
|
||||
import { companyProjectsQuery } from "@/lib/company-projects-query";
|
||||
import { useIssueUpdatedFilterNow } from "@/hooks/useIssueUpdatedFilterNow";
|
||||
|
||||
const EMPTY_AGENT_TASKS: Issue[] = [];
|
||||
|
||||
/**
|
||||
* The agent-scoped side panels shown beside an agent chat: every task the
|
||||
@@ -134,16 +137,18 @@ export function AgentTasksPanel({
|
||||
...companyProjectsQuery(companyId),
|
||||
});
|
||||
|
||||
const agentTasks = tasksQuery.data ?? EMPTY_AGENT_TASKS;
|
||||
const updatedFilterNow = useIssueUpdatedFilterNow(agentTasks, filters.updatedWithin);
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
const scoped = (tasksQuery.data ?? []).filter((task) => {
|
||||
const scoped = agentTasks.filter((task) => {
|
||||
if (task.id === excludeIssueId) return false;
|
||||
if (!needle) return true;
|
||||
return task.title.toLowerCase().includes(needle)
|
||||
|| (task.identifier ?? "").toLowerCase().includes(needle);
|
||||
});
|
||||
return sortAgentTasks(applyIssueFilters(scoped, filters), sortField, sortDir);
|
||||
}, [tasksQuery.data, excludeIssueId, query, filters, sortField, sortDir]);
|
||||
return sortAgentTasks(applyIssueFilters(scoped, filters, null, false, undefined, {}, updatedFilterNow), sortField, sortDir);
|
||||
}, [agentTasks, excludeIssueId, query, filters, sortField, sortDir, updatedFilterNow]);
|
||||
|
||||
const activeFilterCount = countActiveIssueFilters(filters);
|
||||
const total = (tasksQuery.data ?? []).filter((task) => task.id !== excludeIssueId).length;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type { Issue } from "@paperclipai/shared";
|
||||
import { nextIssueUpdatedFilterExpiryMs, type IssueUpdatedWithin } from "../lib/issue-filters";
|
||||
|
||||
const MAX_TIMEOUT_MS = 2_147_483_647;
|
||||
|
||||
/**
|
||||
* Provides a stable `Date` reference for relative Updated time filters (`24h`,
|
||||
* `3d`, `7d`, `30d`) and schedules a single deadline timer for the earliest
|
||||
* visible task that will age out of the active window. Returns `undefined` when
|
||||
* no relative window is active so callers pay zero timer or re-render cost.
|
||||
*/
|
||||
export function useIssueUpdatedFilterNow(
|
||||
issues: ReadonlyArray<Pick<Issue, "updatedAt" | "lastActivityAt" | "lastExternalCommentAt">>,
|
||||
updatedWithin: IssueUpdatedWithin | null | undefined,
|
||||
): Date | undefined {
|
||||
const isRelative = Boolean(updatedWithin && updatedWithin !== "custom");
|
||||
const [tick, setTick] = useState(0);
|
||||
|
||||
const nowMs = useMemo(
|
||||
() => (isRelative ? Date.now() : null),
|
||||
[isRelative, issues, updatedWithin, tick],
|
||||
);
|
||||
|
||||
const nextExpiryMs = useMemo(
|
||||
() => (nowMs === null ? null : nextIssueUpdatedFilterExpiryMs(issues, updatedWithin, nowMs)),
|
||||
[issues, updatedWithin, nowMs],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (nextExpiryMs === null) return;
|
||||
const delayMs = Math.max(0, Math.min(nextExpiryMs - Date.now(), MAX_TIMEOUT_MS));
|
||||
const timer = setTimeout(() => {
|
||||
setTick((current) => current + 1);
|
||||
}, delayMs);
|
||||
return () => clearTimeout(timer);
|
||||
}, [nextExpiryMs, nowMs]);
|
||||
|
||||
return useMemo(() => (nowMs === null ? undefined : new Date(nowMs)), [nowMs]);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { includeTaskListAncestors, type TaskListItem } from "@/components/TaskList";
|
||||
import { applyIssueFilters, countActiveIssueFilters, defaultIssueFilterState, type IssueFilterState } from "@/lib/issue-filters";
|
||||
import { loadTaskListView, matchesTaskListView, saveTaskListView, type TaskListView } from "@/lib/task-list-views";
|
||||
import { useIssueUpdatedFilterNow } from "./useIssueUpdatedFilterNow";
|
||||
|
||||
type CreatorOption = { id: string; label: string; kind: "agent" | "user" };
|
||||
const expanded: ReadonlySet<string> = new Set();
|
||||
@@ -36,7 +37,9 @@ export function useTaskListCollection({ items, companyId, userId, viewStorageKey
|
||||
const setCollapsedIds = (ids: ReadonlySet<string>) => setCollapse({ companyId, ids });
|
||||
const resetExpansion = () => setCollapsedIds(expanded);
|
||||
|
||||
const companyItems = items.filter(item => item.issue.companyId === companyId);
|
||||
const companyItems = useMemo(() => items.filter(item => item.issue.companyId === companyId), [items, companyId]);
|
||||
const companyIssues = useMemo(() => companyItems.map(item => item.issue), [companyItems]);
|
||||
const updatedFilterNow = useIssueUpdatedFilterNow(companyIssues, filters.updatedWithin);
|
||||
const creatorsById = new Map<string, CreatorOption>();
|
||||
for (const item of companyItems) {
|
||||
const { createdByAgentId, createdByUserId } = item.issue;
|
||||
@@ -46,7 +49,7 @@ export function useTaskListCollection({ items, companyId, userId, viewStorageKey
|
||||
const id = `${kind}:${rawId}`;
|
||||
creatorsById.set(id, { id, kind, label: item.createdBy || rawId });
|
||||
}
|
||||
const filteredIds = new Set(applyIssueFilters(companyItems.map(item => item.issue), filters, userId, false, liveIssueIds).map(issue => issue.id));
|
||||
const filteredIds = new Set(applyIssueFilters(companyIssues, filters, userId, false, liveIssueIds, undefined, updatedFilterNow).map(issue => issue.id));
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase();
|
||||
const matchingItems = companyItems.filter(item => filteredIds.has(item.issue.id)
|
||||
&& matchesTaskListView(view, item.issue, Boolean(item.unread), userId)
|
||||
|
||||
@@ -986,6 +986,7 @@ describe("inbox helpers", () => {
|
||||
externalObjectStatuses: [],
|
||||
showAgentCreatedTasks: true,
|
||||
routineTasksOnly: false,
|
||||
updatedWithin: "3d",
|
||||
},
|
||||
});
|
||||
saveInboxFilterPreferences("company-2", {
|
||||
@@ -1021,6 +1022,9 @@ describe("inbox helpers", () => {
|
||||
externalObjectStatuses: [],
|
||||
showAgentCreatedTasks: true,
|
||||
routineTasksOnly: false,
|
||||
updatedWithin: "3d",
|
||||
updatedFrom: null,
|
||||
updatedTo: null,
|
||||
},
|
||||
});
|
||||
expect(loadInboxFilterPreferences("company-2")).toEqual({
|
||||
@@ -1038,6 +1042,9 @@ describe("inbox helpers", () => {
|
||||
externalObjectStatuses: [],
|
||||
showAgentCreatedTasks: false,
|
||||
routineTasksOnly: false,
|
||||
updatedWithin: null,
|
||||
updatedFrom: null,
|
||||
updatedTo: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1074,6 +1081,9 @@ describe("inbox helpers", () => {
|
||||
externalObjectStatuses: [],
|
||||
showAgentCreatedTasks: false,
|
||||
routineTasksOnly: false,
|
||||
updatedWithin: null,
|
||||
updatedFrom: null,
|
||||
updatedTo: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,13 @@ import {
|
||||
applyIssueFilters,
|
||||
countActiveIssueFilters,
|
||||
defaultIssueFilterState,
|
||||
issueUpdatedServerBefore,
|
||||
issueUpdatedTimeRange,
|
||||
issueUpdatedWithinPatch,
|
||||
nextIssueUpdatedFilterExpiryMs,
|
||||
normalizeIssueFilterState,
|
||||
readIssueUpdatedParams,
|
||||
writeIssueUpdatedParams,
|
||||
resolveIssueFilterWorkspaceId,
|
||||
searchIssueFilterOptions,
|
||||
shouldIncludeIssueFilterWorkspaceOption,
|
||||
@@ -290,3 +296,122 @@ describe("issue filters", () => {
|
||||
expect(filtered).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Updated filter", () => {
|
||||
const now = new Date("2026-11-12T12:00:00.000Z");
|
||||
const hoursAgo = (hours: number) => new Date(now.getTime() - hours * 60 * 60 * 1000);
|
||||
const updatedIds = (issues: Issue[], patch: Parameters<typeof applyIssueFilters>[1]) =>
|
||||
applyIssueFilters(issues, patch, null, false, undefined, {}, now).map((issue) => issue.id);
|
||||
|
||||
it("keeps only tasks whose row time is inside the last 3 days", () => {
|
||||
const issues = [
|
||||
makeIssue({ id: "fresh", updatedAt: hoursAgo(1) }),
|
||||
makeIssue({ id: "edge", updatedAt: hoursAgo(72) }),
|
||||
makeIssue({ id: "old", updatedAt: hoursAgo(72.01) }),
|
||||
];
|
||||
expect(updatedIds(issues, { ...defaultIssueFilterState, updatedWithin: "3d" })).toEqual(["fresh", "edge"]);
|
||||
expect(updatedIds(issues, { ...defaultIssueFilterState, updatedWithin: "24h" })).toEqual(["fresh"]);
|
||||
expect(updatedIds(issues, { ...defaultIssueFilterState, updatedWithin: "7d" })).toEqual(["fresh", "edge", "old"]);
|
||||
expect(updatedIds(issues, defaultIssueFilterState)).toEqual(["fresh", "edge", "old"]);
|
||||
});
|
||||
|
||||
it("uses the same time the row shows, not only the stored update time", () => {
|
||||
const issues = [
|
||||
makeIssue({ id: "commented", updatedAt: hoursAgo(24 * 10), lastActivityAt: hoursAgo(2) }),
|
||||
makeIssue({ id: "external", updatedAt: hoursAgo(24 * 10), lastExternalCommentAt: hoursAgo(5) }),
|
||||
makeIssue({ id: "stale-activity", updatedAt: hoursAgo(1), lastActivityAt: hoursAgo(24 * 10) }),
|
||||
];
|
||||
expect(updatedIds(issues, { ...defaultIssueFilterState, updatedWithin: "3d" })).toEqual(["commented", "external"]);
|
||||
});
|
||||
|
||||
it("runs a custom range from the start of the first day to the end of the last day in local time", () => {
|
||||
const previousTz = process.env.TZ;
|
||||
process.env.TZ = "America/Los_Angeles";
|
||||
try {
|
||||
const issues = [
|
||||
makeIssue({ id: "before", updatedAt: new Date("2026-11-03T07:59:59.999Z") }),
|
||||
makeIssue({ id: "first-moment", updatedAt: new Date("2026-11-03T08:00:00.000Z") }),
|
||||
makeIssue({ id: "last-moment", updatedAt: new Date("2026-11-05T07:59:59.999Z") }),
|
||||
makeIssue({ id: "after", updatedAt: new Date("2026-11-05T08:00:00.000Z") }),
|
||||
];
|
||||
const range = { ...defaultIssueFilterState, updatedWithin: "custom" as const, updatedFrom: "2026-11-03", updatedTo: "2026-11-04" };
|
||||
expect(updatedIds(issues, range)).toEqual(["first-moment", "last-moment"]);
|
||||
expect(updatedIds(issues, { ...range, updatedFrom: "2026-11-04", updatedTo: "2026-11-03" })).toEqual(["first-moment", "last-moment"]);
|
||||
expect(updatedIds(issues, { ...range, updatedTo: null })).toEqual(["first-moment", "last-moment", "after"]);
|
||||
expect(updatedIds(issues, { ...range, updatedFrom: null })).toEqual(["before", "first-moment", "last-moment"]);
|
||||
expect(issueUpdatedTimeRange({ updatedWithin: "custom", updatedFrom: null, updatedTo: null }, now)).toBeNull();
|
||||
} finally {
|
||||
if (previousTz === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = previousTz;
|
||||
}
|
||||
});
|
||||
|
||||
it("restores saved choices and drops values it does not know", () => {
|
||||
expect(normalizeIssueFilterState({ updatedWithin: "3d" })).toMatchObject({ updatedWithin: "3d", updatedFrom: null, updatedTo: null });
|
||||
expect(normalizeIssueFilterState({ updatedWithin: "custom", updatedFrom: "2026-11-01", updatedTo: "2026-11-12" }))
|
||||
.toMatchObject({ updatedWithin: "custom", updatedFrom: "2026-11-01", updatedTo: "2026-11-12" });
|
||||
expect(normalizeIssueFilterState({ updatedWithin: "90d", updatedFrom: "Nov 1", updatedTo: 5 }))
|
||||
.toMatchObject({ updatedWithin: null, updatedFrom: null, updatedTo: null });
|
||||
expect(normalizeIssueFilterState({})).toMatchObject({ updatedWithin: null });
|
||||
expect(normalizeIssueFilterState({ updatedWithin: "custom", updatedFrom: "2026-02-31", updatedTo: "2026-13-01" }))
|
||||
.toMatchObject({ updatedWithin: "custom", updatedFrom: null, updatedTo: null });
|
||||
expect(issueUpdatedTimeRange({ updatedWithin: "custom", updatedFrom: "2026-02-31", updatedTo: "2026-02-30" })).toBeNull();
|
||||
});
|
||||
|
||||
it("counts as one active filter and clears with the default state", () => {
|
||||
expect(countActiveIssueFilters({ ...defaultIssueFilterState, updatedWithin: "3d" })).toBe(1);
|
||||
expect(countActiveIssueFilters({ ...defaultIssueFilterState, updatedWithin: "custom", updatedFrom: "2026-11-01", updatedTo: "2026-11-12" })).toBe(1);
|
||||
expect(countActiveIssueFilters(defaultIssueFilterState)).toBe(0);
|
||||
expect(defaultIssueFilterState).toMatchObject({ updatedWithin: null, updatedFrom: null, updatedTo: null });
|
||||
});
|
||||
|
||||
it("sends the server only the end of a custom range", () => {
|
||||
const previousTz = process.env.TZ;
|
||||
process.env.TZ = "America/Los_Angeles";
|
||||
try {
|
||||
expect(issueUpdatedServerBefore({ updatedWithin: "custom", updatedFrom: "2026-11-03", updatedTo: "2026-11-04" }))
|
||||
.toBe("2026-11-05T08:00:00.000Z");
|
||||
expect(issueUpdatedServerBefore({ updatedWithin: "custom", updatedFrom: "2026-11-03", updatedTo: null })).toBeUndefined();
|
||||
expect(issueUpdatedServerBefore({ updatedWithin: "3d", updatedFrom: null, updatedTo: null })).toBeUndefined();
|
||||
expect(issueUpdatedServerBefore({ updatedWithin: null, updatedFrom: null, updatedTo: "2026-11-04" })).toBeUndefined();
|
||||
} finally {
|
||||
if (previousTz === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = previousTz;
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps custom days only for a custom range", () => {
|
||||
expect(issueUpdatedWithinPatch("3d")).toEqual({ updatedWithin: "3d", updatedFrom: null, updatedTo: null });
|
||||
expect(issueUpdatedWithinPatch(null)).toEqual({ updatedWithin: null, updatedFrom: null, updatedTo: null });
|
||||
expect(issueUpdatedWithinPatch("custom")).toEqual({ updatedWithin: "custom" });
|
||||
});
|
||||
|
||||
it("reads and writes the page address values", () => {
|
||||
const params = new URLSearchParams("view=all&updated=custom&updatedFrom=2026-11-01&updatedTo=bad");
|
||||
expect(readIssueUpdatedParams(params)).toEqual({ updatedWithin: "custom", updatedFrom: "2026-11-01", updatedTo: null });
|
||||
expect(readIssueUpdatedParams(new URLSearchParams("updated=3d&updatedFrom=2026-11-01")))
|
||||
.toEqual({ updatedWithin: "3d", updatedFrom: null, updatedTo: null });
|
||||
expect(readIssueUpdatedParams(new URLSearchParams("updated=90d"))).toEqual({ updatedWithin: null, updatedFrom: null, updatedTo: null });
|
||||
|
||||
writeIssueUpdatedParams(params, { updatedWithin: "custom", updatedFrom: "2026-11-01", updatedTo: "2026-11-12" });
|
||||
expect(params.toString()).toBe("view=all&updated=custom&updatedFrom=2026-11-01&updatedTo=2026-11-12");
|
||||
writeIssueUpdatedParams(params, { updatedWithin: "7d", updatedFrom: "2026-11-01", updatedTo: null });
|
||||
expect(params.toString()).toBe("view=all&updated=7d");
|
||||
writeIssueUpdatedParams(params, { updatedWithin: null, updatedFrom: null, updatedTo: null });
|
||||
expect(params.toString()).toBe("view=all");
|
||||
});
|
||||
|
||||
it("computes the earliest expiry timestamp for relative windows only", () => {
|
||||
const issues = [
|
||||
makeIssue({ id: "already-old", updatedAt: hoursAgo(30) }),
|
||||
makeIssue({ id: "expiring-soon", updatedAt: hoursAgo(23) }),
|
||||
makeIssue({ id: "fresh", updatedAt: hoursAgo(1) }),
|
||||
];
|
||||
expect(nextIssueUpdatedFilterExpiryMs(issues, "24h", now.getTime())).toBe(
|
||||
hoursAgo(23).getTime() + 24 * 60 * 60 * 1000 + 1,
|
||||
);
|
||||
expect(nextIssueUpdatedFilterExpiryMs(issues, null, now.getTime())).toBeNull();
|
||||
expect(nextIssueUpdatedFilterExpiryMs(issues, "custom", now.getTime())).toBeNull();
|
||||
expect(nextIssueUpdatedFilterExpiryMs([makeIssue({ id: "old", updatedAt: hoursAgo(30) })], "24h", now.getTime())).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -38,8 +38,17 @@ export type IssueFilterState = {
|
||||
externalObjectStatuses: string[];
|
||||
showAgentCreatedTasks: boolean;
|
||||
routineTasksOnly?: boolean;
|
||||
/**
|
||||
* Keep tasks whose row time ("Updated X ago") is inside this window. `custom`
|
||||
* uses `updatedFrom` and `updatedTo`, local calendar days in `YYYY-MM-DD`.
|
||||
*/
|
||||
updatedWithin?: IssueUpdatedWithin | null;
|
||||
updatedFrom?: string | null;
|
||||
updatedTo?: string | null;
|
||||
};
|
||||
|
||||
export type IssueUpdatedWithin = "24h" | "3d" | "7d" | "30d" | "custom";
|
||||
|
||||
export const defaultIssueFilterState: IssueFilterState = {
|
||||
statuses: [],
|
||||
priorities: [],
|
||||
@@ -52,8 +61,145 @@ export const defaultIssueFilterState: IssueFilterState = {
|
||||
externalObjectStatuses: [],
|
||||
showAgentCreatedTasks: false,
|
||||
routineTasksOnly: false,
|
||||
updatedWithin: null,
|
||||
updatedFrom: null,
|
||||
updatedTo: null,
|
||||
};
|
||||
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
|
||||
const ISSUE_UPDATED_WINDOW_MS: Record<Exclude<IssueUpdatedWithin, "custom">, number> = {
|
||||
"24h": 24 * HOUR_MS,
|
||||
"3d": 3 * 24 * HOUR_MS,
|
||||
"7d": 7 * 24 * HOUR_MS,
|
||||
"30d": 30 * 24 * HOUR_MS,
|
||||
};
|
||||
|
||||
/** Same words as the Search page's "Updated within" filter, plus 3 days. */
|
||||
export const issueUpdatedWithinOptions: ReadonlyArray<{ value: IssueUpdatedWithin | null; label: string }> = [
|
||||
{ value: null, label: "Any time" },
|
||||
{ value: "24h", label: "Last 24 hours" },
|
||||
{ value: "3d", label: "Last 3 days" },
|
||||
{ value: "7d", label: "Last 7 days" },
|
||||
{ value: "30d", label: "Last 30 days" },
|
||||
{ value: "custom", label: "Custom range" },
|
||||
];
|
||||
|
||||
const ISSUE_UPDATED_WITHIN_VALUES = new Set<string>(["24h", "3d", "7d", "30d", "custom"]);
|
||||
const LOCAL_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
|
||||
function parseLocalDate(value: string | null | undefined, dayOffset = 0): number | null {
|
||||
const match = value ? LOCAL_DATE_PATTERN.exec(value) : null;
|
||||
if (!match) return null;
|
||||
const [year, month, day] = [Number(match[1]), Number(match[2]) - 1, Number(match[3])];
|
||||
// Reject impossible days such as 2026-02-31, which Date would roll into March.
|
||||
const date = new Date(year, month, day);
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) return null;
|
||||
const time = new Date(year, month, day + dayOffset).getTime();
|
||||
return Number.isFinite(time) ? time : null;
|
||||
}
|
||||
|
||||
function normalizeLocalDate(value: unknown): string | null {
|
||||
return typeof value === "string" && parseLocalDate(value) != null ? value : null;
|
||||
}
|
||||
|
||||
/** The filter change for one Updated option. Only a custom range keeps its days. */
|
||||
export function issueUpdatedWithinPatch(value: IssueUpdatedWithin | null): Partial<IssueFilterState> {
|
||||
return value === "custom" ? { updatedWithin: value } : { updatedWithin: value, updatedFrom: null, updatedTo: null };
|
||||
}
|
||||
|
||||
/** The time a task row shows as "Updated X ago". */
|
||||
export function issueUpdatedTime(
|
||||
issue: Pick<Issue, "updatedAt" | "lastActivityAt" | "lastExternalCommentAt">,
|
||||
): Date | string {
|
||||
return issue.lastActivityAt ?? issue.lastExternalCommentAt ?? issue.updatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* The half-open `[start, end)` time range for the Updated filter, or null when it
|
||||
* does not filter. A custom range runs from the start of its first local day to
|
||||
* the end of its last local day; either end may be left open.
|
||||
*/
|
||||
export function issueUpdatedTimeRange(
|
||||
state: Pick<IssueFilterState, "updatedWithin" | "updatedFrom" | "updatedTo">,
|
||||
now: Date = new Date(),
|
||||
): { start: number | null; end: number | null } | null {
|
||||
const within = state.updatedWithin;
|
||||
if (!within) return null;
|
||||
if (within !== "custom") return { start: now.getTime() - ISSUE_UPDATED_WINDOW_MS[within], end: null };
|
||||
let start = parseLocalDate(state.updatedFrom);
|
||||
let end = parseLocalDate(state.updatedTo, 1);
|
||||
if (start == null && end == null) return null;
|
||||
if (start != null && end != null && start >= end) {
|
||||
// A reversed pick still means "between these two days".
|
||||
start = parseLocalDate(state.updatedTo);
|
||||
end = parseLocalDate(state.updatedFrom, 1);
|
||||
}
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
/**
|
||||
* The earliest wall-clock timestamp (ms) at which one of `issues` will age out
|
||||
* of a relative Updated window (`24h`, `3d`, `7d`, `30d`), or null when no
|
||||
* relative window is active or no remaining issue can cross the boundary.
|
||||
*/
|
||||
export function nextIssueUpdatedFilterExpiryMs(
|
||||
issues: ReadonlyArray<Pick<Issue, "updatedAt" | "lastActivityAt" | "lastExternalCommentAt">>,
|
||||
updatedWithin: IssueUpdatedWithin | null | undefined,
|
||||
nowMs: number = Date.now(),
|
||||
): number | null {
|
||||
if (!updatedWithin || updatedWithin === "custom") return null;
|
||||
const windowMs = ISSUE_UPDATED_WINDOW_MS[updatedWithin];
|
||||
const cutoff = nowMs - windowMs;
|
||||
let earliestExpiry: number | null = null;
|
||||
for (const issue of issues) {
|
||||
const time = new Date(issueUpdatedTime(issue)).getTime();
|
||||
if (!Number.isFinite(time) || time < cutoff) continue;
|
||||
const expiry = time + windowMs + 1;
|
||||
if (earliestExpiry === null || expiry < earliestExpiry) {
|
||||
earliestExpiry = expiry;
|
||||
}
|
||||
}
|
||||
return earliestExpiry;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server `updatedBefore` bound for a custom range's end, or undefined. The row
|
||||
* time is never older than the stored `updatedAt`, so this bound never drops a task
|
||||
* the range keeps. A start bound on `updatedAt` could, so the start stays in the browser.
|
||||
*/
|
||||
export function issueUpdatedServerBefore(
|
||||
state: Pick<IssueFilterState, "updatedWithin" | "updatedFrom" | "updatedTo">,
|
||||
): string | undefined {
|
||||
if (state.updatedWithin !== "custom") return undefined;
|
||||
const end = issueUpdatedTimeRange(state)?.end;
|
||||
return end == null ? undefined : new Date(end).toISOString();
|
||||
}
|
||||
|
||||
export type IssueUpdatedFilter = Pick<IssueFilterState, "updatedWithin" | "updatedFrom" | "updatedTo">;
|
||||
|
||||
/** Read the Updated filter from `updated`, `updatedFrom` and `updatedTo` page address values. */
|
||||
export function readIssueUpdatedParams(params: URLSearchParams): IssueUpdatedFilter {
|
||||
const { updatedWithin, updatedFrom, updatedTo } = normalizeIssueFilterState({
|
||||
updatedWithin: params.get("updated"),
|
||||
updatedFrom: params.get("updatedFrom"),
|
||||
updatedTo: params.get("updatedTo"),
|
||||
});
|
||||
return updatedWithin === "custom"
|
||||
? { updatedWithin, updatedFrom, updatedTo }
|
||||
: { updatedWithin, updatedFrom: null, updatedTo: null };
|
||||
}
|
||||
|
||||
/** Write the Updated filter into page address values; the default removes them. */
|
||||
export function writeIssueUpdatedParams(params: URLSearchParams, state: IssueUpdatedFilter): void {
|
||||
for (const key of ["updated", "updatedFrom", "updatedTo"]) params.delete(key);
|
||||
if (!state.updatedWithin) return;
|
||||
params.set("updated", state.updatedWithin);
|
||||
if (state.updatedWithin !== "custom") return;
|
||||
if (state.updatedFrom) params.set("updatedFrom", state.updatedFrom);
|
||||
if (state.updatedTo) params.set("updatedTo", state.updatedTo);
|
||||
}
|
||||
|
||||
export const externalObjectFilterOrder = [
|
||||
"failed",
|
||||
"waiting",
|
||||
@@ -121,6 +267,11 @@ export function normalizeIssueFilterState(value: unknown): IssueFilterState {
|
||||
externalObjectStatuses: normalizeIssueFilterValueArray(candidate.externalObjectStatuses),
|
||||
showAgentCreatedTasks: candidate.showAgentCreatedTasks === true,
|
||||
routineTasksOnly: candidate.routineTasksOnly === true,
|
||||
updatedWithin: typeof candidate.updatedWithin === "string" && ISSUE_UPDATED_WITHIN_VALUES.has(candidate.updatedWithin)
|
||||
? candidate.updatedWithin as IssueUpdatedWithin
|
||||
: null,
|
||||
updatedFrom: normalizeLocalDate(candidate.updatedFrom),
|
||||
updatedTo: normalizeLocalDate(candidate.updatedTo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -233,8 +384,18 @@ export function applyIssueFilters(
|
||||
enableAgentCreatedVisibilityFilter = false,
|
||||
liveIssueIds?: ReadonlySet<string>,
|
||||
workspaceContext: IssueFilterWorkspaceContext = {},
|
||||
now: Date = new Date(),
|
||||
): Issue[] {
|
||||
let result = issues;
|
||||
const updatedRange = issueUpdatedTimeRange(state, now);
|
||||
if (updatedRange) {
|
||||
result = result.filter((issue) => {
|
||||
const time = new Date(issueUpdatedTime(issue)).getTime();
|
||||
if (!Number.isFinite(time)) return false;
|
||||
return (updatedRange.start == null || time >= updatedRange.start)
|
||||
&& (updatedRange.end == null || time < updatedRange.end);
|
||||
});
|
||||
}
|
||||
if (state.liveOnly) {
|
||||
result = result.filter((issue) => liveIssueIds?.has(issue.id) === true);
|
||||
}
|
||||
@@ -305,6 +466,7 @@ export function countActiveIssueFilters(
|
||||
if (state.liveOnly) count += 1;
|
||||
if (state.routineTasksOnly) count += 1;
|
||||
if (state.externalObjectStatuses.length > 0) count += 1;
|
||||
if (state.updatedWithin) count += 1;
|
||||
if (enableAgentCreatedVisibilityFilter && state.showAgentCreatedTasks) count += 1;
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Issue } from "@paperclipai/shared";
|
||||
import { sortIssues } from "./issue-sort";
|
||||
|
||||
const issue = (id: string, updatedAt: string) => ({ id, updatedAt: new Date(updatedAt) }) as Issue;
|
||||
|
||||
describe("sortIssues", () => {
|
||||
it("sorts by an updated time from the context and reads it once per task", () => {
|
||||
const issues = [issue("a", "2026-11-01"), issue("b", "2026-11-02"), issue("c", "2026-11-03"), issue("d", "2026-11-04")];
|
||||
const shown: Record<string, string> = { a: "2026-11-10", b: "2026-11-02", c: "2026-11-03", d: "2026-11-04" };
|
||||
const context = vi.fn((task: Issue) => ({ updated: shown[task.id] }));
|
||||
expect(sortIssues(issues, { sortField: "updated", sortDir: "desc" }, context).map(task => task.id)).toEqual(["a", "d", "c", "b"]);
|
||||
expect(context).toHaveBeenCalledTimes(issues.length);
|
||||
});
|
||||
|
||||
it("falls back to the stored updatedAt without a context time", () => {
|
||||
const issues = [issue("old", "2026-11-01"), issue("new", "2026-11-05")];
|
||||
expect(sortIssues(issues, { sortField: "updated", sortDir: "desc" }).map(task => task.id)).toEqual(["new", "old"]);
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,8 @@ export type IssueSortContext = {
|
||||
assignee?: string | null;
|
||||
project?: string | null;
|
||||
parentTask?: string | null;
|
||||
/** The time a list shows as "Last updated"; defaults to the stored `updatedAt`. */
|
||||
updated?: Date | string | null;
|
||||
};
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
@@ -35,7 +37,7 @@ export function sortIssues(issues: readonly Issue[], sort: IssueSort, context: (
|
||||
case "priority": return issuePriorityOrder.indexOf(issue.priority);
|
||||
case "title": return issue.title;
|
||||
case "created": return new Date(issue.createdAt).getTime();
|
||||
case "updated": return new Date(issue.updatedAt).getTime();
|
||||
case "updated": return new Date(context(issue).updated ?? issue.updatedAt).getTime();
|
||||
case "taskId": return issue.identifier;
|
||||
case "createdBy": return context(issue).createdBy;
|
||||
case "assignee": return context(issue).assignee;
|
||||
@@ -45,12 +47,14 @@ export function sortIssues(issues: readonly Issue[], sort: IssueSort, context: (
|
||||
case "worktree": return issue.currentExecutionWorkspace?.branchName;
|
||||
}
|
||||
};
|
||||
return [...issues].sort((a, b) => {
|
||||
const left = value(a), right = value(b);
|
||||
// Read each task's value once; context lookups can scan agent lists.
|
||||
const keyed = issues.map(issue => ({ issue, key: value(issue) }));
|
||||
return keyed.sort((a, b) => {
|
||||
const left = a.key, right = b.key;
|
||||
const missing = (value: string | number | null | undefined) => value == null || value === "" || (typeof value === "number" && !Number.isFinite(value));
|
||||
const leftMissing = missing(left), rightMissing = missing(right);
|
||||
if (leftMissing || rightMissing) return Number(leftMissing) - Number(rightMissing);
|
||||
const result = typeof left === "number" && typeof right === "number" ? left - right : collator.compare(String(left), String(right));
|
||||
return sort.sortDir === "asc" ? result : -result;
|
||||
});
|
||||
}).map(entry => entry.issue);
|
||||
}
|
||||
@@ -31,7 +31,7 @@ import { formatUserLabel } from "@/lib/assignees";
|
||||
import { buildCompanyUserProfileMap } from "@/lib/company-members";
|
||||
import { coordinatorAttentionTasksQueryKey } from "@/lib/coordinator-attention";
|
||||
import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb";
|
||||
import { defaultIssueFilterState, type IssueFilterState } from "@/lib/issue-filters";
|
||||
import { defaultIssueFilterState, issueUpdatedServerBefore, readIssueUpdatedParams, writeIssueUpdatedParams, type IssueFilterState } from "@/lib/issue-filters";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useLocation, useNavigate, useSearchParams } from "@/lib/router";
|
||||
import { loadTaskListView, saveTaskListView, taskListViews, taskListViewStorageKey, type TaskListView } from "@/lib/task-list-views";
|
||||
@@ -57,6 +57,9 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
|
||||
const urlStatuses = JSON.stringify(params.getAll("status"));
|
||||
const urlLabels = JSON.stringify(params.getAll("label").filter(Boolean));
|
||||
const urlView = params.get("view");
|
||||
const urlUpdatedFilter = readIssueUpdatedParams(params);
|
||||
const urlUpdated = JSON.stringify(urlUpdatedFilter);
|
||||
const updatedBefore = issueUpdatedServerBefore(urlUpdatedFilter);
|
||||
const viewStorageKey = taskListViewStorageKey("coordinator", userId ?? "local-board");
|
||||
const [preference, setPreference] = useState(() => ({ key: viewStorageKey, view: loadTaskListView(viewStorageKey) }));
|
||||
const savedView = preference.key === viewStorageKey ? preference.view : loadTaskListView(viewStorageKey);
|
||||
@@ -95,7 +98,7 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
|
||||
const normalizedView = normalizeTaskViewKey(urlView);
|
||||
const presetStatuses = normalizedView && taskView(normalizedView).surface === "issues" ? taskView(normalizedView).statuses ?? [] : [];
|
||||
const initialStatuses: string[] = params.has("status") ? params.getAll("status") : presetStatuses;
|
||||
const previousUrlFilters = useRef({ assignee: urlAssignee, statuses: urlStatuses, labels: urlLabels, view: urlView, routineTasksOnly });
|
||||
const previousUrlFilters = useRef({ assignee: urlAssignee, statuses: urlStatuses, labels: urlLabels, view: urlView, routineTasksOnly, updated: urlUpdated });
|
||||
const needsAttention = view === "blocked";
|
||||
const archivedView = urlView === "archived";
|
||||
const hideArchived = view === "inbox" || view === "unread";
|
||||
@@ -122,12 +125,12 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
|
||||
useEffect(() => { setBreadcrumbs([{ label: "Tasks" }]); }, [setBreadcrumbs]);
|
||||
|
||||
const tasks = useInfiniteQuery({
|
||||
queryKey: [...queryKeys.issues.list(companyId!), "coordinator-table", "index", userId, deferredQuery, participantAgentId, workspaceIds, originKind, serverSortField, serverSortDir, includeBlockedBy, view === "unread", hideArchived, PERSONAL_ARCHIVE_QUERY_KEY, inboxArchive],
|
||||
queryKey: [...queryKeys.issues.list(companyId!), "coordinator-table", "index", userId, deferredQuery, participantAgentId, workspaceIds, originKind, serverSortField, serverSortDir, includeBlockedBy, updatedBefore ?? "__any__", view === "unread", hideArchived, PERSONAL_ARCHIVE_QUERY_KEY, inboxArchive],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const pages = await Promise.all((workspaceIds.length ? workspaceIds : [undefined]).map(workspaceId => issuesApi.listCompact(companyId!, {
|
||||
projection: "index", limit: pageSize, offset: pageParam, includeAgentCreatedTasks: true, includeRoutineExecutions: true,
|
||||
sortField: serverSortField, sortDir: serverSortDir,
|
||||
includeBlockedBy: includeBlockedBy || undefined, q: deferredQuery || undefined, participantAgentId, workspaceId, originKind,
|
||||
includeBlockedBy: includeBlockedBy || undefined, updatedBefore, q: deferredQuery || undefined, participantAgentId, workspaceId, originKind,
|
||||
unreadForUserId: view === "unread" ? "me" : undefined,
|
||||
inboxArchivedByUserId: hideArchived && userId ? "me" : undefined,
|
||||
inboxArchive,
|
||||
@@ -210,23 +213,26 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
|
||||
searchMode: "server",
|
||||
liveIssueIds: collectLiveIssueIds(liveRuns.data, records),
|
||||
viewStorageKey,
|
||||
initialFilters: { labels: params.getAll("label").filter(Boolean), assignees: params.getAll("assignee"), statuses: initialStatuses, routineTasksOnly },
|
||||
initialFilters: { labels: params.getAll("label").filter(Boolean), assignees: params.getAll("assignee"), statuses: initialStatuses, routineTasksOnly, ...urlUpdatedFilter },
|
||||
});
|
||||
useEffect(() => {
|
||||
const previous = previousUrlFilters.current;
|
||||
if (previous.assignee === urlAssignee && previous.view === urlView && previous.statuses === urlStatuses && previous.labels === urlLabels && previous.routineTasksOnly === routineTasksOnly) return;
|
||||
previousUrlFilters.current = { assignee: urlAssignee, statuses: urlStatuses, labels: urlLabels, view: urlView, routineTasksOnly };
|
||||
if (previous.assignee === urlAssignee && previous.view === urlView && previous.statuses === urlStatuses && previous.labels === urlLabels && previous.routineTasksOnly === routineTasksOnly && previous.updated === urlUpdated) return;
|
||||
previousUrlFilters.current = { assignee: urlAssignee, statuses: urlStatuses, labels: urlLabels, view: urlView, routineTasksOnly, updated: urlUpdated };
|
||||
collection.updateFilters({
|
||||
...(previous.labels !== urlLabels ? { labels: params.getAll("label").filter(Boolean) } : {}),
|
||||
...(previous.routineTasksOnly !== routineTasksOnly ? { routineTasksOnly } : {}),
|
||||
...(previous.updated !== urlUpdated ? JSON.parse(urlUpdated) as Partial<IssueFilterState> : {}),
|
||||
...(previous.assignee !== urlAssignee ? { assignees: params.getAll("assignee") } : {}),
|
||||
...(previous.view !== urlView || previous.statuses !== urlStatuses ? { statuses: initialStatuses } : {}),
|
||||
});
|
||||
}, [urlAssignee, urlView, urlStatuses, urlLabels, initialStatuses, routineTasksOnly, collection.updateFilters]);
|
||||
}, [urlAssignee, urlView, urlStatuses, urlLabels, urlUpdated, initialStatuses, routineTasksOnly, collection.updateFilters]);
|
||||
const updateFilters = (patch: Partial<IssueFilterState>) => {
|
||||
collection.updateFilters(patch);
|
||||
if (patch.assignees === undefined && patch.statuses === undefined && patch.labels === undefined && patch.routineTasksOnly === undefined) return;
|
||||
const updatedChanged = patch.updatedWithin !== undefined || patch.updatedFrom !== undefined || patch.updatedTo !== undefined;
|
||||
if (patch.assignees === undefined && patch.statuses === undefined && patch.labels === undefined && patch.routineTasksOnly === undefined && !updatedChanged) return;
|
||||
const next = new URLSearchParams(params);
|
||||
if (updatedChanged) writeIssueUpdatedParams(next, { ...collection.filters, ...patch });
|
||||
if (patch.routineTasksOnly !== undefined) {
|
||||
if (patch.routineTasksOnly) next.set("originKind", "routine_execution");
|
||||
else next.delete("originKind");
|
||||
@@ -250,7 +256,7 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
|
||||
const clearFilters = () => {
|
||||
collection.updateFilters(defaultIssueFilterState);
|
||||
const next = new URLSearchParams(params);
|
||||
for (const key of ["q", "assignee", "status", "label", "originKind"]) next.delete(key);
|
||||
for (const key of ["q", "assignee", "status", "label", "originKind", "updated", "updatedFrom", "updatedTo"]) next.delete(key);
|
||||
if (!needsAttention && !archivedView) next.set("view", "all");
|
||||
navigate({ search: next.toString(), hash: location.hash }, { replace: true });
|
||||
};
|
||||
|
||||
@@ -40,6 +40,7 @@ import { queryKeys } from "../lib/queryKeys";
|
||||
import { buildMineRevealSources, mineRevealSourcesQueryKey, readMineRevealSources, type MineRevealSources } from "../lib/inbox-mine-reveal-sources";
|
||||
import { useDialogActions } from "../context/DialogContext";
|
||||
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import {
|
||||
applyIssueFilters,
|
||||
countActiveIssueFilters,
|
||||
@@ -1362,13 +1363,15 @@ function StreamlinedInbox({
|
||||
externalObjectSummaryByIssueId,
|
||||
externalObjectSummariesReady: externalObjectSummariesReady && !externalObjectSummariesLoading,
|
||||
}), [externalObjectSummariesLoading, externalObjectSummariesReady, externalObjectSummaryByIssueId]);
|
||||
const mineUpdatedNow = useIssueUpdatedFilterNow(mineIssues, issueFilters.updatedWithin);
|
||||
const touchedUpdatedNow = useIssueUpdatedFilterNow(touchedIssues, issueFilters.updatedWithin);
|
||||
const visibleMineIssues = useMemo(
|
||||
() => applyIssueFilters(mineIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||||
[mineIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||||
() => applyIssueFilters(mineIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext, mineUpdatedNow),
|
||||
[mineIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext, mineUpdatedNow],
|
||||
);
|
||||
const visibleTouchedIssues = useMemo(
|
||||
() => applyIssueFilters(touchedIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||||
[touchedIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||||
() => applyIssueFilters(touchedIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext, touchedUpdatedNow),
|
||||
[touchedIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext, touchedUpdatedNow],
|
||||
);
|
||||
const unreadTouchedIssues = useMemo(
|
||||
() => visibleTouchedIssues.filter((issue) => issue.isUnreadForMe),
|
||||
|
||||
+38
-13
@@ -22,6 +22,7 @@ import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
|
||||
import { EmptyState } from "../components/EmptyState";
|
||||
import { IssuesList } from "../components/IssuesList";
|
||||
import { readIssueSortParams, type IssueSort } from "../lib/issue-sort";
|
||||
import { readIssueUpdatedParams, writeIssueUpdatedParams, type IssueUpdatedFilter } from "../lib/issue-filters";
|
||||
import { TaskViewsMenu } from "../components/TaskViewsMenu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CircleDot, Plus } from "lucide-react";
|
||||
@@ -201,29 +202,48 @@ function OrganizationIssues({
|
||||
const includeBlockedBy = sort?.sortField === "workflow";
|
||||
const serverSortField = sort?.sortField === "created" ? "created" : "updated";
|
||||
const serverSortDir = sort?.sortField === "created" || sort?.sortField === "updated" ? sort.sortDir : "desc";
|
||||
const handleSortChange = useCallback((nextSort: IssueSort) => {
|
||||
// React Router does not queue functional search updates, so writes made in the
|
||||
// same event (Clear resets several URL filters) build on each other here.
|
||||
const pendingSearchParamsRef = useRef<URLSearchParams | null>(null);
|
||||
const writeTaskParams = useCallback((mutate: (next: URLSearchParams) => void) => {
|
||||
setSearchParams(current => {
|
||||
const next = new URLSearchParams(current);
|
||||
const next = new URLSearchParams(pendingSearchParamsRef.current ?? current);
|
||||
if (syncedSearch) next.set("q", syncedSearch);
|
||||
else next.delete("q");
|
||||
next.set("sortField", nextSort.sortField);
|
||||
next.set("sortDir", nextSort.sortDir);
|
||||
mutate(next);
|
||||
if (!pendingSearchParamsRef.current) queueMicrotask(() => { pendingSearchParamsRef.current = null; });
|
||||
pendingSearchParamsRef.current = next;
|
||||
return next;
|
||||
}, { replace: true });
|
||||
}, [setSearchParams, syncedSearch]);
|
||||
const handleSortChange = useCallback((nextSort: IssueSort) => {
|
||||
writeTaskParams(next => {
|
||||
next.set("sortField", nextSort.sortField);
|
||||
next.set("sortDir", nextSort.sortDir);
|
||||
});
|
||||
}, [writeTaskParams]);
|
||||
const [updatedBefore, setUpdatedBefore] = useState<string | undefined>(undefined);
|
||||
// The Tasks URL owns the Updated filter, so a filtered link opens filtered.
|
||||
const urlUpdated = searchParams.get("updated");
|
||||
const urlUpdatedFrom = searchParams.get("updatedFrom");
|
||||
const urlUpdatedTo = searchParams.get("updatedTo");
|
||||
const updatedFilter = useMemo(() => readIssueUpdatedParams(new URLSearchParams({
|
||||
...(urlUpdated ? { updated: urlUpdated } : {}),
|
||||
...(urlUpdatedFrom ? { updatedFrom: urlUpdatedFrom } : {}),
|
||||
...(urlUpdatedTo ? { updatedTo: urlUpdatedTo } : {}),
|
||||
})), [urlUpdated, urlUpdatedFrom, urlUpdatedTo]);
|
||||
const handleUpdatedFilterChange = useCallback((filter: IssueUpdatedFilter) => {
|
||||
writeTaskParams(next => writeIssueUpdatedParams(next, filter));
|
||||
}, [writeTaskParams]);
|
||||
const routineTasksOnly = searchParams.get("originKind") === "routine_execution";
|
||||
const includeAgentCreatedTasks = showAgentCreatedTasks || routineTasksOnly;
|
||||
const originKind = routineTasksOnly ? "routine_execution" : undefined;
|
||||
const handleRoutineTasksOnlyChange = useCallback((checked: boolean) => {
|
||||
setSearchParams(current => {
|
||||
const next = new URLSearchParams(current);
|
||||
if (syncedSearch) next.set("q", syncedSearch);
|
||||
else next.delete("q");
|
||||
writeTaskParams(next => {
|
||||
if (checked) next.set("originKind", "routine_execution");
|
||||
else next.delete("originKind");
|
||||
return next;
|
||||
}, { replace: true });
|
||||
}, [setSearchParams, syncedSearch]);
|
||||
});
|
||||
}, [writeTaskParams]);
|
||||
const participantAgentId = searchParams.get("participantAgentId") ?? undefined;
|
||||
const initialWorkspaces = searchParams.getAll("workspace").filter((workspaceId) => workspaceId.length > 0);
|
||||
const workspaceIdFilter = initialWorkspaces.length === 1 ? initialWorkspaces[0] : undefined;
|
||||
@@ -298,6 +318,7 @@ function OrganizationIssues({
|
||||
serverSortField,
|
||||
serverSortDir,
|
||||
includeBlockedBy,
|
||||
updatedBefore ?? "__any__",
|
||||
PERSONAL_ARCHIVE_QUERY_KEY,
|
||||
archiveQueryScope,
|
||||
],
|
||||
@@ -314,6 +335,7 @@ function OrganizationIssues({
|
||||
sortField: serverSortField,
|
||||
sortDir: serverSortDir,
|
||||
includeBlockedBy: includeBlockedBy || undefined,
|
||||
updatedBefore,
|
||||
}, { signal }),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (lastPage, _allPages, lastPageParam) =>
|
||||
@@ -385,11 +407,14 @@ function OrganizationIssues({
|
||||
onRoutineTasksOnlyChange={handleRoutineTasksOnlyChange}
|
||||
sort={sort}
|
||||
onSortChange={handleSortChange}
|
||||
onUpdatedBeforeChange={setUpdatedBefore}
|
||||
updatedFilter={updatedFilter}
|
||||
onUpdatedFilterChange={handleUpdatedFilterChange}
|
||||
hasMoreIssues={hasMoreServerIssues}
|
||||
onLoadMoreIssues={loadMoreServerIssues}
|
||||
onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
|
||||
searchFilters={participantAgentId || workspaceIdFilter || originKind || includeBlockedBy || inboxArchive ? {
|
||||
participantAgentId, workspaceId: workspaceIdFilter, originKind, inboxArchive,
|
||||
searchFilters={participantAgentId || workspaceIdFilter || originKind || includeBlockedBy || inboxArchive || updatedBefore ? {
|
||||
participantAgentId, workspaceId: workspaceIdFilter, originKind, inboxArchive, updatedBefore,
|
||||
...(includeBlockedBy ? { includeBlockedBy: true } : {}),
|
||||
} : undefined}
|
||||
/>
|
||||
|
||||
@@ -30,6 +30,7 @@ import { useSidebar } from "../context/SidebarContext";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useDialogActions } from "../context/DialogContext";
|
||||
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
|
||||
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
|
||||
import {
|
||||
applyIssueFilters,
|
||||
countActiveIssueFilters,
|
||||
@@ -1030,13 +1031,15 @@ export function Inbox() {
|
||||
externalObjectSummaryByIssueId,
|
||||
externalObjectSummariesReady: externalObjectSummariesReady && !externalObjectSummariesLoading,
|
||||
}), [externalObjectSummariesLoading, externalObjectSummariesReady, externalObjectSummaryByIssueId]);
|
||||
const mineUpdatedNow = useIssueUpdatedFilterNow(mineIssues, issueFilters.updatedWithin);
|
||||
const touchedUpdatedNow = useIssueUpdatedFilterNow(touchedIssues, issueFilters.updatedWithin);
|
||||
const visibleMineIssues = useMemo(
|
||||
() => applyIssueFilters(mineIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||||
[mineIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||||
() => applyIssueFilters(mineIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext, mineUpdatedNow),
|
||||
[mineIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext, mineUpdatedNow],
|
||||
);
|
||||
const visibleTouchedIssues = useMemo(
|
||||
() => applyIssueFilters(touchedIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||||
[touchedIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||||
() => applyIssueFilters(touchedIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext, touchedUpdatedNow),
|
||||
[touchedIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext, touchedUpdatedNow],
|
||||
);
|
||||
const unreadTouchedIssues = useMemo(
|
||||
() => visibleTouchedIssues.filter((issue) => issue.isUnreadForMe),
|
||||
|
||||
Reference in new issue
Block a user