Files
PaperClipAI/ui/src/lib/recent-tasks.ts
T
4434714824 Fix sidebar Recents task order and archive visibility (#22251)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The sidebar gives people quick access to tasks, chats, and projects
they recently opened.
> - Expanding a parent or project in Recents can show tasks the person
never opened.
> - Archiving a task from the inbox leaves it in Recents.
> - This change gives each recent task its own row and removes tasks
archived for the current viewer.
> - People can reopen an individual task and keep saved shortcuts above
More.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Recents in the Standard and Classic sidebars.

**Subsystem affected**

Board navigation and task summaries.

**Current behavior**

Opening a parent or project can show other tasks beneath it. A recent
subtask moves its parent group when reopened. Archiving a task leaves
its recent link visible.

**Proposed behavior**

Show each visited task in its own row, in recent activity order. Keep
canceled and completed tasks eligible. Remove tasks archived for the
current viewer from Recents. Preserve saved pins.

**Reason and benefit**

People can find the task they opened by its own position in the list.
Archiving removes its recent link without removing a saved shortcut.

**Breaking changes**

The Recents rows no longer expand into task lists. Project links still
open the project. The navigation summary adds an optional personal
archive flag.

Related work: #22219, #22024, #21904, and #20450.

## What Changed

- Render task, agent chat, and project rows directly in Standard
Recents. Keep the existing controls to pin each kind of row.
- Render standalone task rows with the existing Classic action menus.
Remove sidebar child loading and refresh code.
- Derive the viewer’s archive state using the existing inbox rule.
Filter archived tasks out of Recents while retaining authorized pinned
shortcuts.
- Cover independent parent and child order, canceled and archived tasks,
pin retention, and the Classic Archive action.

## Verification

- Reproduced the empty Recents row after cancellation before the fix.
- On the rebased branch, 424 focused UI and live-update tests and the UI
typecheck passed on macOS.
- Ran 77 issue-summary and OpenAPI integration tests with embedded
PostgreSQL on macOS. The Runner source SDK registry check passed on the
pushed revision.
- The updated sidebar test renders 402 recent rows. A deliberate
repeated task lookup made the input-read guard fail. The restored
implementation passed.
- The paused-assignee browser test checks the task detail heading in
each interface. Both variants reproduced the CI locator failure locally
and passed with the scoped locator.
- All 17 focused Storybook browser checks passed in Chromium on macOS.
- Run `pnpm verify` for local selection. The product documentation
change requests broader GitHub CI coverage.
- Open a parent task and a child task in either sidebar. Reopen the
child and check that its row moves ahead of the parent. Cancel the child
and check that it stays visible. Archive it and check that its recent
row disappears.

- On commit `8051038099`, [GitHub
CI](https://github.com/paperclipai/paperclip/actions/runs/44421716811)
passed, including the required verification and end-to-end checks.
-
[Greptile](https://github.com/paperclipai/paperclip/pull/22251#issuecomment-6994494812)
rated the same commit 5/5. Its review thread is resolved.

## Risks

- Recents uses the same viewer-specific archive rule as the inbox.
Archiving prunes the local recent entry. A restored task can enter
Recents again when opened.
- Task summaries still return authorized tasks for saved pins. Child and
unread counts remain in the existing API response for older clients.
- The change requires no database migration.

## Model Used

- OpenAI GPT-6 via Codex with shell, GitHub CLI, Vitest, and Chromium.

## 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: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-18 16:04:42 -08:00

222 lines
8.9 KiB
TypeScript

import type { Issue, IssueStatus, IssueSummary } from "@paperclipai/shared";
export const RECENT_TASKS_UPDATED_EVENT = "paperclip:recent-tasks-updated";
const STORAGE_PREFIX = "paperclip.recentTasks.v3:";
const LEGACY_STORAGE_PREFIXES = ["paperclip.recentTasks.v2:", "paperclip.recentTasks:"];
export interface RecentTaskEntry {
id: string;
companyId: string;
title: string;
identifier: string | null;
status: IssueStatus;
displayStatus?: Issue["displayStatus"];
externalConversationState?: Issue["externalConversationState"];
/** Blocked tasks covered by active work render the "in queue" glyph everywhere. */
blockerAttention?: Issue["blockerAttention"];
isUnreadForMe?: boolean;
recordedAt: number;
// Server version of the title/status snapshot, independent of comment activity.
// Legacy entries have no version until a detail query refreshes them.
snapshotUpdatedAt?: number;
}
interface RecentTasksUpdatedDetail {
storageKey: string;
entries: RecentTaskEntry[];
}
export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) {
// Old tabs still promote machine activity. Keep their writes out of v3.
return `${STORAGE_PREFIX}${companyId}:${userId ?? "__local_board__"}`;
}
function isRecentTaskEntry(value: unknown, companyId: string): value is RecentTaskEntry {
if (!value || typeof value !== "object") return false;
const entry = value as Partial<RecentTaskEntry>;
return entry.companyId === companyId
&& typeof entry.id === "string"
&& entry.id.length > 0
&& typeof entry.title === "string"
&& (entry.identifier === null || typeof entry.identifier === "string")
&& typeof entry.status === "string"
&& typeof entry.recordedAt === "number"
&& Number.isFinite(entry.recordedAt)
&& (entry.snapshotUpdatedAt === undefined || (
typeof entry.snapshotUpdatedAt === "number" && Number.isFinite(entry.snapshotUpdatedAt)
));
}
export function readRecentTasks(storageKey: string, companyId: string): RecentTaskEntry[] {
if (typeof window === "undefined") return [];
try {
const keys = storageKey.startsWith(STORAGE_PREFIX)
? [storageKey, ...LEGACY_STORAGE_PREFIXES.map(prefix => prefix + storageKey.slice(STORAGE_PREFIX.length))]
: [storageKey];
const raw = keys.map(key => window.localStorage.getItem(key)).find(value => value !== null);
const parsed = JSON.parse(raw ?? "[]") as unknown;
if (!Array.isArray(parsed)) return [];
return normalizeRecentTasks(
parsed.filter((entry): entry is RecentTaskEntry => isRecentTaskEntry(entry, companyId)),
);
} catch {
return [];
}
}
export function migrateRecentTasks(storageKey: string, companyId: string) {
if (typeof window === "undefined") return;
try {
if (window.localStorage.getItem(storageKey) !== null) return;
} catch {
return;
}
// Persist even an empty list so an old tab cannot seed it again later.
writeRecentTasks(storageKey, readRecentTasks(storageKey, companyId));
}
function normalizeRecentTasks(entries: RecentTaskEntry[]) {
const seen = new Set<string>();
return [...entries]
.sort((left, right) => right.recordedAt - left.recordedAt)
.filter((entry) => {
if (seen.has(entry.id)) return false;
seen.add(entry.id);
return true;
});
}
function publishRecentTasks(storageKey: string, entries: RecentTaskEntry[]) {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent<RecentTasksUpdatedDetail>(RECENT_TASKS_UPDATED_EVENT, {
detail: { storageKey, entries },
}));
}
export function writeRecentTasks(storageKey: string, entries: RecentTaskEntry[]) {
if (typeof window === "undefined") return;
const normalized = normalizeRecentTasks(entries);
try {
const serialized = JSON.stringify(normalized);
if (window.localStorage.getItem(storageKey) === serialized) return;
window.localStorage.setItem(storageKey, serialized);
} catch {
// The in-tab event still keeps mounted navigation current for this session.
}
publishRecentTasks(storageKey, normalized);
}
type TaskSnapshot = Omit<IssueSummary, "externalConversationState"> & Pick<Issue, "externalConversationState">;
function sameBlockerAttention(a: RecentTaskEntry["blockerAttention"], b: RecentTaskEntry["blockerAttention"]) {
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
}
export function mergeRecentTaskSnapshot(entry: RecentTaskEntry, issue: TaskSnapshot): RecentTaskEntry {
if (entry.id !== issue.id || entry.companyId !== issue.companyId) return entry;
const snapshotUpdatedAt = new Date(issue.updatedAt).getTime();
if (!Number.isFinite(snapshotUpdatedAt)) return entry;
if (entry.snapshotUpdatedAt !== undefined && snapshotUpdatedAt < entry.snapshotUpdatedAt) return entry;
// Conversation readiness also depends on deliveries and decisions, which
// can change without changing the task's title/status version.
if (snapshotUpdatedAt === entry.snapshotUpdatedAt) {
return (issue.externalConversationState !== undefined
&& issue.externalConversationState !== entry.externalConversationState) || issue.displayStatus !== entry.displayStatus
|| !sameBlockerAttention(issue.blockerAttention, entry.blockerAttention)
? { ...entry, status: issue.status, displayStatus: issue.displayStatus, externalConversationState: issue.externalConversationState, blockerAttention: issue.blockerAttention }
: entry;
}
return {
...entry,
title: issue.title,
identifier: issue.identifier,
status: issue.status,
displayStatus: issue.displayStatus,
externalConversationState: issue.externalConversationState,
blockerAttention: issue.blockerAttention,
snapshotUpdatedAt,
};
}
export function recordRecentTask(
issue: Pick<Issue, "id" | "companyId" | "title" | "identifier" | "status" | "displayStatus" | "externalConversationState" | "blockerAttention" | "updatedAt" | "conversationAgentId" | "archivedAt">,
userId: string | null | undefined,
recordedAt?: number,
) {
if (issue.conversationAgentId || issue.archivedAt) return;
const storageKey = getRecentTasksStorageKey(issue.companyId, userId);
const current = readRecentTasks(storageKey, issue.companyId);
const existing = current.find((candidate) => candidate.id === issue.id);
const snapshotUpdatedAt = new Date(issue.updatedAt).getTime();
// Passive reads can seed a candidate, but only explicit local human actions
// advance its recency. New passive candidates go below existing history;
// their server update times are not personal activity.
const activityAt = recordedAt !== undefined && Number.isFinite(recordedAt)
? recordedAt
: existing?.recordedAt ?? Math.min(0, (current.at(-1)?.recordedAt ?? 1) - 1);
const snapshot: RecentTaskEntry = existing ? mergeRecentTaskSnapshot(existing, issue) : {
id: issue.id,
companyId: issue.companyId,
title: issue.title,
identifier: issue.identifier,
status: issue.status,
displayStatus: issue.displayStatus,
externalConversationState: issue.externalConversationState,
blockerAttention: issue.blockerAttention,
recordedAt: activityAt,
...(Number.isFinite(snapshotUpdatedAt) ? { snapshotUpdatedAt } : {}),
};
const entry: RecentTaskEntry = {
...snapshot,
// A comment can promote activity even when its task details are stale.
recordedAt: Math.max(activityAt, snapshot.recordedAt),
};
if (
existing
&& existing.title === entry.title
&& existing.identifier === entry.identifier
&& existing.status === entry.status
&& existing.displayStatus === entry.displayStatus
&& existing.externalConversationState === entry.externalConversationState
&& sameBlockerAttention(existing.blockerAttention, entry.blockerAttention)
&& existing.recordedAt === entry.recordedAt
&& existing.snapshotUpdatedAt === entry.snapshotUpdatedAt
) return;
writeRecentTasks(
storageKey,
existing
? current.map((candidate) => candidate.id === issue.id ? entry : candidate)
: [entry, ...current],
);
}
export function pruneRecentTasks(
storageKey: string,
companyId: string,
removeIds: ReadonlySet<string>,
) {
if (removeIds.size === 0) return;
const current = readRecentTasks(storageKey, companyId);
const next = current.filter((entry) => !removeIds.has(entry.id));
if (next.length !== current.length) writeRecentTasks(storageKey, next);
}
export function updateRecentTaskSnapshots(
storageKey: string,
companyId: string,
issues: ReadonlyArray<TaskSnapshot>,
) {
const issueById = new Map(issues.map((issue) => [issue.id, issue]));
const current = readRecentTasks(storageKey, companyId);
let changed = false;
const next = current.map((entry) => {
const issue = issueById.get(entry.id);
if (!issue || issue.companyId !== companyId) return entry;
const nextEntry = mergeRecentTaskSnapshot(entry, issue);
if (nextEntry !== entry) changed = true;
return nextEntry;
});
if (changed) writeRecentTasks(storageKey, next);
}