Files
PaperClipAI/ui/src/lib/recent-tasks.test.ts
T
DottaandPaperclip 7f9867895c fix(ui): keep automated work out of personal recents (#22024)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The sidebar helps each person return to their own work.
> - A task visit previously added any readable task to personal recents.
> - Automated updates also moved old tasks above newer personal work.
> - The Mine inbox already defines personal participation.
> - This pull request applies that rule to recent task candidates and
preserves their order during background updates.
> - Users can see current task status without a stream of unrelated
automated work.

## Linked Issues or Issue Description

**What happened?**

Routine tasks and imported GitHub review tasks appeared in personal
recents after a read. Later agent updates moved these tasks up the list.
A connected account or stored creator ID could make these tasks look
like personal work.

**Expected behavior**

A task must pass the viewer's existing Mine participation rule before it
appears in personal recents. Routine ownership, connected-account
provenance and reads alone do not qualify. A viewer can qualify through
manual creation, assignment, a direct comment, an allowed user action or
a live request addressed to them. Inbox archive state does not remove
personal history. Passive reads and machine updates must not advance its
order.

**Steps to reproduce**

1. Open an automated routine task or imported review task without
participating in it.
2. Check the sidebar recents.
3. Let an agent update an older task while newer personal work is in the
list.
4. Before this fix, the automated task appears and background updates
can move older tasks up.

## What Changed

- Add a viewer participation field to bounded navigation summaries.
Reuse the canonical Mine query and existing access checks. The field is
a read projection; no database migration is needed.
- Show only confirmed personal tasks. Remove old nonparticipants after a
successful read. Do not trust participation from local storage or full
task caches.
- Keep status and title snapshots current without changing personal
order. Explicit local edits and comments can advance recency.
- Migrate browser history once to a new storage version. Older tabs
cannot restore machine-driven ordering.
- Keep confirmed rows visible if a new batch request fails. Keep these
facts within the current account and company. Hidden candidates do not
bypass the one-second reorder delay.
- Record sidebar renames as local activity. Place a first passive visit
below existing history.
- Use the saved comment time for comments sent with reassignment or
custom run settings. Pending sends do not advance recency.
- Keep readable subtasks as context beneath qualifying parents. Keep
inbox archive independent of recents.
- Update the design rules, UI behavior notes, regression tests and
Runner source contract pin.

## Verification

- Current head: `92ece0e61859a6c54b714b3611f062ff9b5633bb`. The PR
merges cleanly with current master.
- Latest red/green: both configured-comment cases failed before the fix
and now pass. Reassignment and custom run settings advance recency only
after the comment saves, using its saved time.
- Latest local checks: 339 tests passed across IssueDetail and recent
storage, hooks and sidebar. UI typecheck and diff checks passed.
- Earlier local coverage: 592 targeted API/UI tests passed. After the
master conflict resolution, all 29 overlapping Gmail tests and the
548-input source registry check passed.
- Both Greptile and Paperclip Review report 5/5 on the current head. All
four review threads are resolved.
- Current-head [CI attempt
2](https://github.com/paperclipai/paperclip/actions/runs/44132164473)
passed, including the final verify gate, build, typecheck, browser
shards, serialized tests, Runner checks and all general-test shards. The
workspace-a (1/2) retry passed after the first attempt hit an
asynchronous jsdom/Radix event error in NewAgentDialog.
- `pnpm verify` requires broader CI because DESIGN.md changed. No full
local suite or deployed-browser acceptance was claimed. This change is
not deployed.

## Risks

- Unknown eligibility stays hidden until the summary succeeds. Failed
requests preserve saved candidates and previously confirmed state within
the current account and company, including after batch changes.
- This intentionally removes automated tasks from old personal history
when the viewer has no qualifying participation.
- Readable subtasks under a personal parent remain context. They do not
become independent recent entries from machine activity.
- No task ownership, routine definition, inbox membership or permission
rule changes.

## Model Used

OpenAI GPT-6, running as Codex, with reasoning, repository tools and
focused test execution. No additional model workers were used.

## 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: Paperclip <noreply@paperclip.ing>
2026-11-17 11:25:58 -06:00

316 lines
16 KiB
TypeScript

import { clearIssueExecutionRun } from "./optimistic-issue-runs";
import type { Issue } from "@paperclipai/shared";
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
RECENT_TASKS_UPDATED_EVENT,
getRecentTasksStorageKey,
migrateRecentTasks,
pruneRecentTasks,
readRecentTasks,
recordRecentTask,
updateRecentTaskSnapshots,
writeRecentTasks,
} from "./recent-tasks";
const issue = (id: string, companyId = "company-1") => ({
id,
companyId,
title: `Task ${id}`,
identifier: `PAP-${id}`,
status: "todo" as const,
updatedAt: new Date(0),
});
// Support both jsdom Storage (Node 24) and the setup's storage shim (newer Node).
const storageMethods = window.localStorage instanceof window.Storage ? window.Storage.prototype : window.localStorage;
describe("recent task persistence", () => {
beforeEach(() => window.localStorage.clear());
it("is account and company scoped", () => {
expect(getRecentTasksStorageKey("company-1", "user-1")).not.toBe(
getRecentTasksStorageKey("company-1", "user-2"),
);
expect(getRecentTasksStorageKey("company-1", "user-1")).not.toBe(
getRecentTasksStorageKey("company-2", "user-1"),
);
});
it("retains the full history, deduplicates, and only promotes newer activity", () => {
for (let index = 0; index < 20; index += 1) {
recordRecentTask(issue(String(index)), "user-1", index);
}
recordRecentTask(issue("4"), "user-1", 4);
let entries = readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");
expect(entries[0]?.id).toBe("19");
recordRecentTask(issue("4"), "user-1", 99);
entries = readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");
expect(entries).toHaveLength(20);
expect(entries[0]?.id).toBe("4");
expect(entries.filter((entry) => entry.id === "4")).toHaveLength(1);
});
it("refreshes machine updates without moving a task above more recent personal work", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask(issue("older"), "user-1", 10);
recordRecentTask(issue("newer"), "user-1", 20);
updateRecentTaskSnapshots(storageKey, "company-1", [{
...issue("older"), title: "Agent finished", status: "done", updatedAt: new Date(100),
}]);
recordRecentTask({ ...issue("older"), title: "Agent finished", status: "done", updatedAt: new Date(100) }, "user-1");
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(["newer", "older"]);
expect(readRecentTasks(storageKey, "company-1")[1]).toMatchObject({
title: "Agent finished", status: "done", recordedAt: 10, snapshotUpdatedAt: 100,
});
});
it("migrates v2 history once without accepting old-tab machine promotions", () => {
const key = getRecentTasksStorageKey("company-1", "user-1");
const oldKey = "paperclip.recentTasks.v2:company-1:user-1";
localStorage.setItem(oldKey, JSON.stringify([{ ...issue("1"), recordedAt: 10 }]));
migrateRecentTasks(key, "company-1");
localStorage.setItem(oldKey, JSON.stringify([{ ...issue("2"), recordedAt: 100 }]));
migrateRecentTasks(key, "company-1");
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["1"]);
});
it("seeds passive visits below existing history independently of machine update times", () => {
const key = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask(issue("personal"), "user-1", 10);
recordRecentTask({ ...issue("first-visit"), updatedAt: new Date(100) }, "user-1");
recordRecentTask({ ...issue("second-visit"), updatedAt: new Date(1_000) }, "user-1");
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["personal", "first-visit", "second-visit"]);
recordRecentTask(issue("second-visit"), "user-1", 20);
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["second-visit", "personal", "first-visit"]);
});
it("refreshes conversation readiness when review or delivery changes without a task edit", () => {
const task = { ...issue("1"), status: "in_review" as const, externalConversationState: "waiting" as const };
recordRecentTask(task, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...task, externalConversationState: "active" }]);
expect(readRecentTasks(storageKey, "company-1")[0]?.externalConversationState).toBe("active");
});
it("keeps the covered-blocker state so the sidebar shows the same queued glyph as the task pane (BUG-07)", () => {
const covered = {
state: "covered" as const, reason: "active_child" as const, unresolvedBlockerCount: 1, coveredBlockerCount: 1,
attentionBlockerCount: 0, stalledBlockerCount: 0, sampleBlockerIdentifier: "ONB-3", sampleStalledBlockerIdentifier: null,
};
const blocked = { ...issue("1"), status: "blocked" as const, updatedAt: new Date(10) };
recordRecentTask({ ...blocked, blockerAttention: covered }, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
expect(readRecentTasks(storageKey, "company-1")[0]?.blockerAttention).toEqual(covered);
// A same-version summary refresh can change only the derived blocker state.
const attention = { ...covered, state: "needs_attention" as const, reason: "attention_required" as const, coveredBlockerCount: 0, attentionBlockerCount: 1 };
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...blocked, externalConversationState: null, blockerAttention: attention }]);
expect(readRecentTasks(storageKey, "company-1")[0]?.blockerAttention).toEqual(attention);
});
it("accepts server settlement after an optimistic run-lock clear", () => {
const running = { ...issue("1"), status: "in_progress" as const, externalConversationState: "active" as const, executionRunId: "run-1", updatedAt: new Date(10) } as Issue;
recordRecentTask(running, "user-1");
recordRecentTask(clearIssueExecutionRun(running, "run-1")!, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...running, status: "in_review", externalConversationState: "waiting", updatedAt: new Date(20) }]);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ status: "in_review", externalConversationState: "waiting", snapshotUpdatedAt: 20 });
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...running, updatedAt: new Date(30) }]);
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...running, status: "in_review", externalConversationState: "waiting", updatedAt: new Date(20) }]);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ status: "in_progress", externalConversationState: "active", snapshotUpdatedAt: 30 });
});
it("keeps readiness and task status together when a turn settles at the same timestamp", () => {
const task = { ...issue("1"), status: "in_progress" as const, externalConversationState: "active" as const };
recordRecentTask(task, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...task, status: "in_review", externalConversationState: "waiting" }]);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ status: "in_review", externalConversationState: "waiting" });
});
it("refreshes Monitoring when a run starts without a new task version", () => {
const task = { ...issue("1"), status: "in_progress" as const, displayStatus: "monitoring" as const, externalConversationState: null };
recordRecentTask(task, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...task, displayStatus: "in_progress" }]);
expect(readRecentTasks(storageKey, "company-1")[0]?.displayStatus).toBe("in_progress");
});
it("publishes same-tab updates", () => {
const listener = vi.fn();
window.addEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
recordRecentTask(issue("1"), "user-1");
expect(listener).toHaveBeenCalledOnce();
listener.mockClear();
recordRecentTask(issue("1"), "user-1");
expect(listener).not.toHaveBeenCalled();
window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
});
it("records a new display status without a task edit or newer activity", () => {
const task = { ...issue("1"), status: "in_progress" as const, displayStatus: "monitoring" as const };
recordRecentTask(task, "user-1");
recordRecentTask({ ...task, displayStatus: "in_progress" }, "user-1");
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
expect(readRecentTasks(storageKey, "company-1")[0]?.displayStatus).toBe("in_progress");
});
it("prunes unavailable tasks and refreshes stored snapshots", () => {
recordRecentTask(issue("1"), "user-1", 1);
recordRecentTask(issue("2"), "user-1", 2);
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [{
...issue("2"),
title: "Updated task",
status: "in_progress",
updatedAt: new Date(3),
}]);
pruneRecentTasks(storageKey, "company-1", new Set(["1"]));
expect(readRecentTasks(storageKey, "company-1")).toEqual([
expect.objectContaining({
id: "2",
title: "Updated task",
status: "in_progress",
recordedAt: 2,
}),
]);
});
it("does not demote recent comment activity when older task details arrive", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask({ ...issue("1"), updatedAt: new Date(50) }, "user-1", 100);
recordRecentTask({ ...issue("2"), updatedAt: new Date(80) }, "user-1", 90);
const listener = vi.fn();
window.addEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
for (let index = 0; index < 10; index += 1) {
recordRecentTask({ ...issue("1"), updatedAt: new Date(50) }, "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [
{ ...issue("1"), updatedAt: new Date(50) },
{ ...issue("2"), updatedAt: new Date(80) },
]);
}
expect(readRecentTasks(storageKey, "company-1").map(({ id, recordedAt }) => ({ id, recordedAt }))).toEqual([
{ id: "1", recordedAt: 100 },
{ id: "2", recordedAt: 90 },
]);
expect(listener).not.toHaveBeenCalled();
window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
updateRecentTaskSnapshots(storageKey, "company-1", [{
...issue("1"), title: "Renamed task", status: "done", updatedAt: new Date(60),
}]);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({
id: "1", title: "Renamed task", status: "done", recordedAt: 100,
});
});
it("ignores malformed and cross-company entries", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
window.localStorage.setItem(storageKey, JSON.stringify([
issue("other", "company-2"),
{ nonsense: true },
{ ...issue("invalid-version"), recordedAt: 1, snapshotUpdatedAt: "invalid" },
]));
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
});
it("settles conflicting tab snapshots without further writes or notifications", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
const older = { ...issue("1"), title: "Old title", updatedAt: new Date(10) };
const newer = { ...issue("1"), title: "New title", status: "done" as const, updatedAt: new Date(20) };
recordRecentTask(older, "user-1", 10);
updateRecentTaskSnapshots(storageKey, "company-1", [newer]);
const setItem = vi.spyOn(storageMethods, "setItem");
const listener = vi.fn();
window.addEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
try {
for (let index = 0; index < 20; index += 1) {
updateRecentTaskSnapshots(storageKey, "company-1", [older]);
recordRecentTask(older, "user-1");
updateRecentTaskSnapshots(storageKey, "company-1", [newer]);
}
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({
title: "New title", status: "done", snapshotUpdatedAt: 20, recordedAt: 10,
});
expect(setItem).not.toHaveBeenCalled();
expect(listener).not.toHaveBeenCalled();
} finally {
setItem.mockRestore();
window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
}
});
it("promotes a new comment without overwriting newer task details", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask({ ...issue("1"), title: "Done", status: "done", updatedAt: new Date(20) }, "user-1");
recordRecentTask({ ...issue("1"), updatedAt: new Date(10) }, "user-1", 30);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({
title: "Done", status: "done", snapshotUpdatedAt: 20, recordedAt: 30,
});
});
it("retains the current snapshot for equal or invalid versions", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask(issue("1"), "user-1");
for (const updatedAt of [new Date(0), new Date("invalid")]) {
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...issue("1"), title: "Conflict", updatedAt }]);
}
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ title: "Task 1", snapshotUpdatedAt: 0 });
});
it("does not write or publish an unchanged normalized list", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
recordRecentTask(issue("1"), "user-1", 1);
recordRecentTask(issue("2"), "user-1", 2);
const entries = readRecentTasks(storageKey, "company-1");
const setItem = vi.spyOn(storageMethods, "setItem");
const listener = vi.fn();
window.addEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
try {
writeRecentTasks(storageKey, [...entries].reverse());
expect(setItem).not.toHaveBeenCalled();
expect(listener).not.toHaveBeenCalled();
} finally {
setItem.mockRestore();
window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, listener);
}
});
it("migrates legacy tasks once and isolates subsequent old-tab writes", () => {
const legacyKey = "paperclip.recentTasks:company-1:user-1";
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
const legacy = [{ ...issue("1"), recordedAt: 100 }];
window.localStorage.setItem(legacyKey, JSON.stringify(legacy));
expect(readRecentTasks(storageKey, "company-1")[0]?.id).toBe("1");
expect(window.localStorage.getItem(storageKey)).toBeNull();
migrateRecentTasks(storageKey, "company-1");
expect(window.localStorage.getItem(legacyKey)).toBe(JSON.stringify(legacy));
// The first versioned refresh can update legacy metadata, even after a comment.
updateRecentTaskSnapshots(storageKey, "company-1", [{ ...issue("1"), title: "Fresh", updatedAt: new Date(20) }]);
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({
title: "Fresh", snapshotUpdatedAt: 20, recordedAt: 100,
});
window.localStorage.setItem(legacyKey, JSON.stringify([{ ...issue("old-tab"), recordedAt: 200 }]));
migrateRecentTasks(storageKey, "company-1");
expect(readRecentTasks(storageKey, "company-1")[0]?.title).toBe("Fresh");
pruneRecentTasks(storageKey, "company-1", new Set(["1"]));
migrateRecentTasks(storageKey, "company-1");
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
});
it("does not import legacy tasks that appear after an empty migration", () => {
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
migrateRecentTasks(storageKey, "company-1");
window.localStorage.setItem("paperclip.recentTasks:company-1:user-1", JSON.stringify([{ ...issue("1"), recordedAt: 1 }]));
migrateRecentTasks(storageKey, "company-1");
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
});
});