feat(recents): add tasks from manual routine runs to Recents (#23675)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The sidebar Recents list shows the tasks from a person's own recent
activity
> - A person can run a routine manually with "Run now", and the run
creates a task
> - That task does not show in Recents, and opening it does not keep it
there, because Recents only admits tasks under the Mine participation
rule. This also affects every routine, channel, and agent-created task
that a person opens
> - The Mine rule keeps these tasks out of Mine on purpose, so we must
not change that rule
> - This pull request adds a separate Recents eligibility flag. It also
admits tasks that the viewer opened and tasks from manual routine runs
that the viewer started. The UI records the new task in Recents when the
run starts
> - The benefit is that people can find the task they just started from
the sidebar at once, and Mine stays unchanged

## Linked Issues or Issue Description

**Is your feature request related to a problem? Please describe.**
When I run a routine manually and it creates a task, the task is not in
my Recents list. I must go to the routine or the task list to find it.

**Describe the solution you'd like**
When I run a routine manually and a task is created, add that task to my
Recents list automatically, even if I did not open it.

Also, a task that a routine creates does not show in Recents even after
I open it.

**Additional context**
Mine must continue to keep routine tasks out by default, including
routines that a person starts manually (see `doc/PRODUCT.md`).

## What Changed

- `server/src/services/issue-summaries.ts`: navigation summaries return
a new `isRecentEligibleForMe` flag. It is true when one of these
conditions is true:
  - The viewer participates under the Mine rule.
- The viewer opened the task. The check is the viewer's
`issue_read_states` row, which is unique on company, issue, and user.
- The viewer started the manual routine run that created the task. The
check is a `routine_runs` row found through the indexed
`linked_issue_id`, with `source = 'manual'` and the same ID as the
issue's `originRunId`. The issue `createdByUserId` must be the viewer,
with no creating agent.
  `isParticipantForMe`, Mine, and unread state do not change.
- `packages/shared`: add `isRecentEligibleForMe` to `IssueSummary`.
- `ui/src/hooks/useRecentTasks.ts`: Recents uses `isRecentEligibleForMe`
(with a fallback to `isParticipantForMe` for older cached summaries) to
show, keep, and prune entries.
- `ui/src/lib/recent-tasks.ts`: add `recordStartedRoutineRunTask`. It
puts the run's task at the top of Recents. The summary fetch then
supplies the title and status and confirms eligibility.
- New `useRecordRoutineRunInRecents` hook. All five "Run now" paths call
it on success: Routines (both list variants), Routine detail, Execution
workspace detail, and the Responsibility screen.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for
`packages/shared/src/types/issue.ts`.
- `doc/PRODUCT.md`: document the Recents behavior.

## Verification

- `cd ui && npx vitest run src/hooks/useRecentTasks.test.tsx`: 29
passed. The new test "shows a task from the viewer's manual routine run
at the top before it is opened" fails on the old hook (red) and passes
with the change (green). Other new tests cover a run that the server
does not confirm (for example, a coalesced run) and a repeat run for a
task that is already in Recents.
- `cd server && npx vitest run
src/__tests__/issue-summaries-routes.test.ts` (embedded Postgres): 24
passed. One new test checks that a manual run by the viewer is
Recents-eligible but not a Mine participant, and that runs by another
person and scheduled runs are not eligible. Another new test checks that
a routine task the viewer opened is Recents-eligible, and that a task
opened only by another person is not. That test fails on the previous
service code (red) and passes with the change (green).
- `ui` typecheck: no errors in changed files. (Errors exist only in
ungenerated Storybook feature-map indexes, which this change does not
touch.)
- The full `server` typecheck was killed by the local memory limit. CI
covers it.
- Manual check: run a routine with "Run now", then look at sidebar
Recents. The new task shows at the top before you open it. Mine does not
show it.

## Risks

- Low risk. No schema change and no migration.
- The summaries query adds two `EXISTS` subqueries per requested task.
Both use indexes (the read-state unique index and
`routine_runs_linked_issue_idx`). The request is bounded by
`ISSUE_SUMMARIES_MAX_IDS`.
- Behavior change: Recents now keeps tasks that the person opened, also
when the task is automatic work. Old local Recents entries for automatic
tasks that the person read can come back.
- If a manual run coalesces into an existing task that the viewer did
not start, the entry is pruned after the summary read. That task does
not show in Recents.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use
(shell, file edit, test runs).

## 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
- [ ] 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)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-03 20:54:26 -08:00
1 parent b93527b632
commit bca282e587
16 files changed
+292 -20

No files matched your search

+70
View File
@@ -11,6 +11,8 @@ import {
getRecentTasksStorageKey,
readRecentTasks,
recordRecentTask,
recordStartedRoutineRunTask,
settleRecentTaskVisit,
RECENT_TASKS_UPDATED_EVENT,
} from "@/lib/recent-tasks";
import { RECENT_TASK_SUMMARY_CONCURRENCY, useRecentTasks } from "./useRecentTasks";
@@ -352,6 +354,74 @@ describe("recent task synchronization", () => {
expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(100);
});
it("shows a task from the viewer's manual routine run at the top before it is opened", async () => {
const personal = { ...task(10, "My work"), id: "personal" };
recordRecentTask(personal, "user-1", 50);
recordStartedRoutineRunTask("company-1", "routine-task", "user-1", 100);
const started = {
...task(20, "Daily scan"), id: "routine-task", identifier: "TASK-2",
isParticipantForMe: false, isRecentEligibleForMe: true,
};
summaries.mockResolvedValue([personal, started]);
await act(async () => root.render(<QueryClientProvider client={client()}><RecentTasks name="started" /></QueryClientProvider>));
await flush();
expect(container.textContent).toBe("Daily scan:todo,My work:todo");
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ id: "routine-task", title: "Daily scan", identifier: "TASK-2", recordedAt: 100 });
});
it("drops a routine run task when the server does not confirm the viewer started it", async () => {
recordStartedRoutineRunTask("company-1", "routine-task", "user-1", 100);
summaries.mockResolvedValue([{ ...task(20, "Coalesced run"), id: "routine-task", isParticipantForMe: false, isRecentEligibleForMe: false }]);
await act(async () => root.render(<QueryClientProvider client={client()}><RecentTasks name="coalesced" /></QueryClientProvider>));
await flush();
expect(container.textContent).toBe("");
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
});
it("moves an existing entry up when the viewer runs its routine again without losing its snapshot", () => {
recordRecentTask({ ...task(10, "Older"), id: "older" }, "user-1", 50);
recordRecentTask({ ...task(10, "Existing"), id: "existing" }, "user-1", 60);
recordStartedRoutineRunTask("company-1", "older", "user-1", 200);
expect(readRecentTasks(storageKey, "company-1").map(entry => [entry.id, entry.title, entry.recordedAt]))
.toEqual([["older", "Older", 200], ["existing", "Existing", 60]]);
});
it("keeps an opened automatic task until its read is saved, then shows it", async () => {
const opened = { ...task(10, "Routine result"), id: "opened", isParticipantForMe: false };
recordRecentTask(opened, "user-1", 100, { awaitingRead: true });
// The summary read races ahead of the read state that makes it eligible.
summaries.mockResolvedValue([{ ...opened, isRecentEligibleForMe: false }]);
const cache = client();
await act(async () => root.render(<QueryClientProvider client={cache}><RecentTasks name="race" /></QueryClientProvider>));
await flush();
expect(container.textContent).toBe("");
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(["opened"]);
summaries.mockResolvedValue([{ ...opened, isRecentEligibleForMe: true }]);
await act(async () => {
settleRecentTaskVisit("company-1", "opened", "user-1");
await cache.invalidateQueries({ queryKey: queryKeys.issues.summaries("company-1") });
});
await flush();
expect(container.textContent).toBe("Routine result:todo");
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ recordedAt: 100 });
expect(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("awaitingRead");
});
it("prunes an opened task after its read settles without making it eligible", async () => {
const opened = { ...task(10, "Failed read"), id: "opened", isParticipantForMe: false };
recordRecentTask(opened, "user-1", 100, { awaitingRead: true });
summaries.mockResolvedValue([{ ...opened, isRecentEligibleForMe: false }]);
const cache = client();
await act(async () => root.render(<QueryClientProvider client={cache}><RecentTasks name="failed" /></QueryClientProvider>));
await flush();
await act(async () => {
settleRecentTaskVisit("company-1", "opened", "user-1");
await cache.invalidateQueries({ queryKey: queryKeys.issues.summaries("company-1") });
});
await flush();
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
});
it("fetches a 25-task history in one request", async () => {
const tasks = Array.from({ length: 25 }, (_, i) => ({ ...task(i + 1, `Task ${i}`), id: `issue-${String(i).padStart(2, "0")}` }));
tasks.forEach(issue => recordRecentTask(issue, "user-1"));
+12 -5
View File
@@ -26,6 +26,11 @@ const NO_PINNED_TASKS: readonly IssueSummary[] = [];
/** Summary chunks in flight at once for a history longer than one request. */
export const RECENT_TASK_SUMMARY_CONCURRENCY = 3;
/** Recents admits participation, tasks the viewer opened, and manual routine runs they started. */
function recentEligibility(issue: IssueSummary) {
return issue.isRecentEligibleForMe ?? issue.isParticipantForMe;
}
export function useRecentTasks({
companyId,
userId,
@@ -136,11 +141,13 @@ export function useRecentTasks({
const issue = confirmed.get(id);
return issue ? [issue] : [];
}), [confirmed, denied, pinnedTaskIds]);
// A visit is only a candidate. Neither imported provenance nor a persisted
// browser snapshot proves personal participation for the current account.
// A local entry is only a candidate. Neither imported provenance nor a
// persisted browser snapshot proves activity for the current account; the
// server confirms it (participation, a read state from opening it, or a
// manual routine run the viewer started).
const refreshedEntries = useMemo(() => entries.flatMap((entry) => {
const issue = confirmed.get(entry.id);
if (issue?.isParticipantForMe !== true || issue.isArchivedForMe) return [];
if (!issue || recentEligibility(issue) !== true || issue.isArchivedForMe) return [];
return [{ ...mergeRecentTaskSnapshot(entry, issue), isUnreadForMe: issue.isUnreadForMe }];
}), [entries, confirmed]);
const processed = useRef<{ visit: typeof batchVisit; revision: number } | null>(null);
@@ -151,7 +158,7 @@ export function useRecentTasks({
processed.current = { visit: batchVisit, revision: updateCount };
// Older cached summaries without the new projection cannot prove either
// eligibility or ineligibility. Keep those candidates until a current read.
const returnedIds = new Set(summaries.filter((issue) => issue.companyId === companyId && issue.isParticipantForMe !== false && !issue.isArchivedForMe).map((issue) => issue.id));
const returnedIds = new Set(summaries.filter((issue) => issue.companyId === companyId && recentEligibility(issue) !== false && !issue.isArchivedForMe).map((issue) => issue.id));
updateRecentTaskSnapshots(storageKey, companyId, summaries);
const omittedIds = new Set(recentIds.filter((id) => !returnedIds.has(id)));
if (omittedIds.size && updateCount <= batchVisit.initialUpdateCount) {
@@ -167,7 +174,7 @@ export function useRecentTasks({
useEffect(() => {
if (!storageKey || !companyId || !summaries) return;
const summaryById = new Map(summaries.filter((issue) => issue.companyId === companyId).map((issue) => [issue.id, issue]));
const authorizedIds = new Set([...summaryById.values()].filter(issue => issue.isParticipantForMe === true).map(issue => issue.id));
const authorizedIds = new Set([...summaryById.values()].filter(issue => recentEligibility(issue) === true).map(issue => issue.id));
const mergeCached = (value: unknown) => {
if (!value || typeof value !== "object") return;
const issue = value as Issue;
@@ -0,0 +1,17 @@
import { useCallback } from "react";
import type { RoutineRun } from "@paperclipai/shared";
import { useAccountIdentity } from "@/api/companies-query";
import { recordStartedRoutineRunTask } from "@/lib/recent-tasks";
/**
* Returns a callback for manual "Run now" successes. It adds the task that the
* run created to the viewer's Recents, even though they have not opened it.
*/
export function useRecordRoutineRunInRecents() {
const { userId, current } = useAccountIdentity();
return useCallback((run: Pick<RoutineRun, "companyId" | "linkedIssueId"> | null | undefined) => {
// Never write one account's history while the session still holds another.
if (!current || !run?.linkedIssueId) return;
recordStartedRoutineRunTask(run.companyId, run.linkedIssueId, userId);
}, [current, userId]);
}