diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index e862bcf0ea4..4b95c53eeb3 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -123,7 +123,10 @@ Sidebar Recents and Classic Recent Tasks show tasks from the viewer’s own recent activity as a flat list. A subtask has its own row and its own unread marker. Tasks archived from the viewer’s inbox leave Recents. Canceled and completed tasks remain eligible. Opening a recent task moves its row to the top -of Recents. +of Recents. Any task a person opens is eligible for their Recents, including +routine, channel, and agent-created tasks. When a person runs a routine manually, +the task that run creates goes to the top of their Recents at once, before they +open it. Neither of these adds the task to Mine. Standard Recents also shows recent chats and projects. The Coordinator sidebar pins **Plugins** above **More** by default. Users can diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 1a01870cfda..c926a6a5687 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -915,6 +915,11 @@ export type IssueSummary = Pick< parentId?: string | null; /** Viewer participates under the Mine rule, regardless of inbox archive state. Navigation only. */ isParticipantForMe?: boolean; + /** + * Viewer participates, opened the task, or started the manual routine run + * that created it. Gates Recents without adding the task to Mine. Navigation only. + */ + isRecentEligibleForMe?: boolean; isArchivedForMe?: boolean; isUnreadForMe?: boolean; subtaskCount?: number; diff --git a/server/src/__tests__/issue-summaries-routes.test.ts b/server/src/__tests__/issue-summaries-routes.test.ts index 8ad69ea7348..be1469e2d23 100644 --- a/server/src/__tests__/issue-summaries-routes.test.ts +++ b/server/src/__tests__/issue-summaries-routes.test.ts @@ -6,7 +6,7 @@ import { drizzle } from "drizzle-orm/postgres-js"; import * as schema from "@paperclipai/db/schema/index"; import { afterAll, beforeAll, expect, it, vi } from "vitest"; import { - activityLog, agents, chatConversations, chatEndpoints, companyMemberships, heartbeatRuns, issueComments, issueInboxArchives, issueReadStates, issueRelations, issues, issueThreadInteractions, toolApplications, toolConnections, + activityLog, agents, chatConversations, chatEndpoints, companyMemberships, heartbeatRuns, issueComments, issueInboxArchives, issueReadStates, issueRelations, issues, issueThreadInteractions, routineRuns, routines, toolApplications, toolConnections, } from "@paperclipai/db"; import { ISSUE_SUMMARIES_MAX_IDS } from "@paperclipai/shared"; import { issueRoutes } from "../routes/issues.js"; @@ -86,6 +86,52 @@ describeEmbeddedPostgres("bounded issue summaries", () => { expect(res.body.every((row: { isParticipantForMe: unknown }) => typeof row.isParticipantForMe === "boolean")).toBe(true); }); + it("admits a task from the viewer's own manual routine run to Recents without Mine participation", async () => { + const f = await fixture(); + const user = f.actor.userId!; + const [routine] = await ctx.db.insert(routines).values({ companyId: f.companyId, title: "Daily scan" }).returning(); + const runs = await ctx.db.insert(routineRuns).values(["manual", "manual", "schedule"].map(source => ({ + companyId: f.companyId, routineId: routine!.id, source, + }))).returning(); + const names = ["mine", "someone-else", "scheduled", "manual-task"]; + const rows = await ctx.db.insert(issues).values(names.map((title, index) => ({ + companyId: f.companyId, title, + originKind: title === "manual-task" ? "manual" : "routine_execution", + originRunId: title === "manual-task" ? null : runs[Math.min(index, 2)]!.id, + createdByUserId: title === "someone-else" ? "other-user" : title === "scheduled" ? null : user, + responsibleUserId: user, + }))).returning(); + // A run links the task it created, as the routine service records it. + for (const row of rows.filter(row => row.originRunId)) { + await ctx.db.update(routineRuns).set({ linkedIssueId: row.id }).where(eq(routineRuns.id, row.originRunId!)); + } + const res = await request(app(f.actor)).get(url(f.companyId)).query({ ids: rows.map(row => row.id).join(","), navigation: "true" }).expect(200); + const byTitle = new Map(res.body.map((row: { title: string }) => [row.title, row])); + // Mine keeps routine work out, including runs the person starts manually. + expect(byTitle.get("mine")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: true }); + expect(byTitle.get("someone-else")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: false }); + expect(byTitle.get("scheduled")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: false }); + expect(byTitle.get("manual-task")).toMatchObject({ isParticipantForMe: true, isRecentEligibleForMe: true }); + }); + + it("admits a routine task the viewer opened to Recents without Mine participation", async () => { + const f = await fixture(); + const user = f.actor.userId!; + const rows = await ctx.db.insert(issues).values(["opened", "opened-by-other", "never-opened"].map(title => ({ + companyId: f.companyId, title, originKind: "routine_execution", responsibleUserId: user, + }))).returning(); + const id = (name: string) => rows.find(row => row.title === name)!.id; + await ctx.db.insert(issueReadStates).values([ + { companyId: f.companyId, issueId: id("opened"), userId: user }, + { companyId: f.companyId, issueId: id("opened-by-other"), userId: "other-user" }, + ]); + const res = await request(app(f.actor)).get(url(f.companyId)).query({ ids: rows.map(row => row.id).join(","), navigation: "true" }).expect(200); + const byTitle = new Map(res.body.map((row: { title: string }) => [row.title, row])); + expect(byTitle.get("opened")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: true }); + expect(byTitle.get("opened-by-other")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: false }); + expect(byTitle.get("never-opened")).toMatchObject({ isParticipantForMe: false, isRecentEligibleForMe: false }); + }); + it("matches the inbox unread predicate across participation, request, withdrawal and read histories", async () => { const f = await fixture(); const user = f.actor.userId!; diff --git a/server/src/services/issue-summaries.ts b/server/src/services/issue-summaries.ts index be1b9150d82..dc4a33caee0 100644 --- a/server/src/services/issue-summaries.ts +++ b/server/src/services/issue-summaries.ts @@ -1,6 +1,6 @@ import { issueDisplayStatusSql } from "./issue-display-status.js"; import { and, eq, inArray, isNull, sql, type SQL } from "drizzle-orm"; -import { activityLog, issueComments, issueReadStates, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; +import { activityLog, issueComments, issueReadStates, issueThreadInteractions, issues, routineRuns, type Db } from "@paperclipai/db"; import { ISSUE_SUMMARIES_MAX_IDS } from "@paperclipai/shared"; import { directHumanCommentCondition } from "./issue-participation.js"; import { inboxVisibleForUserCondition, mineParticipationIssueIds, unreadForUserCondition } from "./issues.js"; @@ -62,7 +62,7 @@ export async function listIssueNavigationState( // MATERIALIZED prevents PostgreSQL from repeating privacy and viewer facts // across the task-state and child-count branches of the final union. const rows = await db.execute<{ - kind: string; id: string; unread: boolean; participant: boolean; archived: boolean; total: number; unread_count: number; + kind: string; id: string; unread: boolean; participant: boolean; recent_activity: boolean; archived: boolean; total: number; unread_count: number; }>(sql` with navigation_candidates as materialized ( select ${issues.id}, ${issues.parentId}, ${issues.conversationAgentId}, @@ -123,11 +123,29 @@ export async function listIssueNavigationState( select issues.id, issues.parent_id, issues.conversation_agent_id, coalesce(${unread}, false) as unread from navigation_facts as issues ) - select 'task' as kind, c.id, coalesce(s.unread, false) as unread, p.id is not null as participant, c.archived, 0 as total, 0 as unread_count + select 'task' as kind, c.id, coalesce(s.unread, false) as unread, p.id is not null as participant, + -- Recent personal activity that is not Mine participation: the viewer + -- opened the task (it has their read state), or started the manual + -- routine run that created it. + (exists ( + select 1 from ${issueReadStates} + where ${issueReadStates.companyId} = ${companyId} and ${issueReadStates.issueId} = c.id + and ${issueReadStates.userId} = ${userId} + ) or exists ( + -- The linked-issue index bounds this lookup; the origin-run check keeps + -- only the run that created the task, not later runs coalesced into it. + select 1 from ${issues} join ${routineRuns} + on ${routineRuns.linkedIssueId} = ${issues.id} and ${routineRuns.companyId} = ${companyId} + and ${routineRuns.id}::text = ${issues.originRunId} + where ${issues.id} = c.id and ${issues.companyId} = ${companyId} + and ${issues.createdByUserId} = ${userId} and ${issues.createdByAgentId} is null + and ${routineRuns.source} = 'manual' + )) as recent_activity, + c.archived, 0 as total, 0 as unread_count from navigation_candidates c left join navigation_state s on s.id = c.id left join navigation_participants p on p.id = c.id where c.id in (${requested}) union all - select 'children', c.parent_id, false, false, false, count(*)::int, count(*) filter (where s.unread)::int + select 'children', c.parent_id, false, false, false, false, count(*)::int, count(*) filter (where s.unread)::int from navigation_candidates c left join navigation_state s on s.id = c.id where c.parent_id in (${requested}) and c.conversation_agent_id is null group by c.parent_id `); @@ -135,6 +153,7 @@ export async function listIssueNavigationState( const children = new Map(rows.filter(row => row.kind === "children").map(row => [row.id, row])); return new Map(ids.map(id => [id, { isParticipantForMe: tasks.get(id)?.participant ?? false, + isRecentEligibleForMe: Boolean(tasks.get(id)?.participant || tasks.get(id)?.recent_activity), isUnreadForMe: tasks.get(id)?.unread ?? false, isArchivedForMe: tasks.get(id)?.archived ?? false, subtaskCount: children.get(id)?.total ?? 0, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 07480d3b562..44f5b1bfde6 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -463,7 +463,7 @@ "packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428", "packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "1a01870cfda97510486c20425fabe7ac553460ac", + "packages/shared/src/types/issue.ts": "c926a6a56874b18b3a61e22defaf9aca54172ca7", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "9fa76312dc773a6fd461c7895323e7c7c3f99fef", diff --git a/ui/src/components/responsibilities/ResponsibilityOneScreenV2.tsx b/ui/src/components/responsibilities/ResponsibilityOneScreenV2.tsx index d81a3ff847a..9d110ef4381 100644 --- a/ui/src/components/responsibilities/ResponsibilityOneScreenV2.tsx +++ b/ui/src/components/responsibilities/ResponsibilityOneScreenV2.tsx @@ -54,6 +54,7 @@ import { WhoAvatar, } from "./SectionTable"; import type { ResponsibilityViewProps } from "./view-props"; +import { useRecordRoutineRunInRecents } from "@/hooks/useRecordRoutineRunInRecents"; /** The sections under the bar, in order. Each is one table whose header bar is just the word. */ export const ONE_SCREEN_V2_SECTIONS = ["routines", "skills", "projects", "tasks", "runs", "artifacts"] as const; @@ -326,9 +327,11 @@ export function ResponsibilityOneScreenV2({ }, [responsibility, agentsById]); const firstAgentId = working[0]?.id ?? null; + const recordRoutineRunInRecents = useRecordRoutineRunInRecents(); const runNow = useMutation({ mutationFn: (routine: ResponsibilityRoutineSummary) => routinesApi.run(routine.id, {}), - onSuccess: async () => { + onSuccess: async (run) => { + recordRoutineRunInRecents(run); await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.runs(responsibility.id) }), queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.detail(responsibility.id) }), diff --git a/ui/src/hooks/useRecentTasks.test.tsx b/ui/src/hooks/useRecentTasks.test.tsx index 7f65bdf3354..74439fc5517 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -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()); + 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()); + 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()); + 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()); + 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")); diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index 860de8fd422..947f6008c9b 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -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; diff --git a/ui/src/hooks/useRecordRoutineRunInRecents.ts b/ui/src/hooks/useRecordRoutineRunInRecents.ts new file mode 100644 index 00000000000..286e55963b3 --- /dev/null +++ b/ui/src/hooks/useRecordRoutineRunInRecents.ts @@ -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 | 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]); +} diff --git a/ui/src/lib/recent-tasks.test.ts b/ui/src/lib/recent-tasks.test.ts index 5918827bc86..de3ca1e9426 100644 --- a/ui/src/lib/recent-tasks.test.ts +++ b/ui/src/lib/recent-tasks.test.ts @@ -4,6 +4,7 @@ import type { Issue } from "@paperclipai/shared"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { + AWAITING_READ_TTL_MS, RECENT_TASKS_UPDATED_EVENT, getRecentTasksStorageKey, migrateRecentTasks, @@ -158,6 +159,25 @@ describe("recent task persistence", () => { expect(readRecentTasks(storageKey, "company-1")[0]?.displayStatus).toBe("in_progress"); }); + it("keeps a visit waiting for its read, but prunes it once the wait is abandoned", () => { + const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000); + try { + recordRecentTask(issue("1"), "user-1", 100, { awaitingRead: true }); + const storageKey = getRecentTasksStorageKey("company-1", "user-1"); + + now.mockReturnValue(1_000_000 + AWAITING_READ_TTL_MS - 1); + pruneRecentTasks(storageKey, "company-1", new Set(["1"])); + expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(["1"]); + + // The tab closed before the read settled, so nothing clears the wait. + now.mockReturnValue(1_000_000 + AWAITING_READ_TTL_MS); + pruneRecentTasks(storageKey, "company-1", new Set(["1"])); + expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + } finally { + now.mockRestore(); + } + }); + it("prunes unavailable tasks and refreshes stored snapshots", () => { recordRecentTask(issue("1"), "user-1", 1); recordRecentTask(issue("2"), "user-1", 2); diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.ts index 61c3c40c4ca..4222fcd4ff3 100644 --- a/ui/src/lib/recent-tasks.ts +++ b/ui/src/lib/recent-tasks.ts @@ -19,6 +19,23 @@ export interface RecentTaskEntry { // Server version of the title/status snapshot, independent of comment activity. // Legacy entries have no version until a detail query refreshes them. snapshotUpdatedAt?: number; + /** + * A fresh visit whose read is not saved yet. The read state is what makes an + * opened automatic task eligible, so the entry is kept (but not shown) until + * the read finishes. Holds when the wait started, stored so every tab honors + * it. A wait older than AWAITING_READ_TTL_MS is abandoned (e.g. the tab + * closed before the read settled) and no longer protects the entry. + */ + awaitingRead?: number; +} + +/** Longest time a fresh visit may wait for its read before pruning can remove it. */ +export const AWAITING_READ_TTL_MS = 2 * 60 * 1000; + +function isAwaitingRead(entry: RecentTaskEntry, now: number) { + return typeof entry.awaitingRead === "number" + && Number.isFinite(entry.awaitingRead) + && now - entry.awaitingRead < AWAITING_READ_TTL_MS; } interface RecentTasksUpdatedDetail { @@ -142,6 +159,7 @@ export function recordRecentTask( issue: Pick, userId: string | null | undefined, recordedAt?: number, + options?: { awaitingRead?: boolean }, ) { if (issue.conversationAgentId || issue.archivedAt) return; const storageKey = getRecentTasksStorageKey(issue.companyId, userId); @@ -170,6 +188,7 @@ export function recordRecentTask( ...snapshot, // A comment can promote activity even when its task details are stale. recordedAt: Math.max(activityAt, snapshot.recordedAt), + ...(options?.awaitingRead ? { awaitingRead: Date.now() } : {}), }; if ( existing @@ -181,6 +200,7 @@ export function recordRecentTask( && sameBlockerAttention(existing.blockerAttention, entry.blockerAttention) && existing.recordedAt === entry.recordedAt && existing.snapshotUpdatedAt === entry.snapshotUpdatedAt + && existing.awaitingRead === entry.awaitingRead ) return; writeRecentTasks( @@ -191,6 +211,28 @@ export function recordRecentTask( ); } +/** + * Puts a task the viewer just started from a manual routine run at the top of + * Recents before they open it. The run response has only the task ID, so the + * entry has no snapshot; the navigation summary supplies title and status and + * confirms that this viewer started the run before the row is shown. + */ +export function recordStartedRoutineRunTask( + companyId: string, + issueId: string, + userId: string | null | undefined, + recordedAt = Date.now(), +) { + const storageKey = getRecentTasksStorageKey(companyId, userId); + const current = readRecentTasks(storageKey, companyId); + const existing = current.find((candidate) => candidate.id === issueId); + if (existing && existing.recordedAt >= recordedAt) return; + const entry: RecentTaskEntry = existing + ? { ...existing, recordedAt } + : { id: issueId, companyId, title: "", identifier: null, status: "todo", recordedAt }; + writeRecentTasks(storageKey, [entry, ...current.filter((candidate) => candidate.id !== issueId)]); +} + export function pruneRecentTasks( storageKey: string, companyId: string, @@ -198,10 +240,28 @@ export function pruneRecentTasks( ) { if (removeIds.size === 0) return; const current = readRecentTasks(storageKey, companyId); - const next = current.filter((entry) => !removeIds.has(entry.id)); + // A visit waiting for its read cannot be judged yet; the read decides it. + // An abandoned wait expires so a deleted or inaccessible task is not kept. + const now = Date.now(); + const next = current.filter((entry) => isAwaitingRead(entry, now) || !removeIds.has(entry.id)); if (next.length !== current.length) writeRecentTasks(storageKey, next); } +/** + * Ends the wait that a fresh visit started. Call it when the visit's read + * settles; the next navigation summary then shows or prunes the entry. + */ +export function settleRecentTaskVisit(companyId: string, issueId: string, userId: string | null | undefined) { + const storageKey = getRecentTasksStorageKey(companyId, userId); + const current = readRecentTasks(storageKey, companyId); + if (!current.some((entry) => entry.id === issueId && entry.awaitingRead !== undefined)) return; + writeRecentTasks(storageKey, current.map((entry) => { + if (entry.id !== issueId) return entry; + const { awaitingRead: _awaitingRead, ...settled } = entry; + return settled; + })); +} + export function updateRecentTaskSnapshots( storageKey: string, companyId: string, diff --git a/ui/src/pages/ExecutionWorkspaceDetail.tsx b/ui/src/pages/ExecutionWorkspaceDetail.tsx index 9d8822c525d..ce2f4479620 100644 --- a/ui/src/pages/ExecutionWorkspaceDetail.tsx +++ b/ui/src/pages/ExecutionWorkspaceDetail.tsx @@ -53,6 +53,7 @@ import { import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { safeExternalHttpUrl } from "@/lib/safe-url"; +import { useRecordRoutineRunInRecents } from "@/hooks/useRecordRoutineRunInRecents"; type WorkspaceFormState = { name: string; @@ -666,6 +667,7 @@ function ExecutionWorkspaceRoutinesList({ [routinesQuery.data], ); + const recordRoutineRunInRecents = useRecordRoutineRunInRecents(); const runRoutine = useMutation({ mutationFn: ({ id, data }: { id: string; data?: RoutineRunDialogSubmitData }) => routinesApi.run(id, { ...(data?.variables && Object.keys(data.variables).length > 0 ? { variables: data.variables } : {}), @@ -682,7 +684,8 @@ function ExecutionWorkspaceRoutinesList({ onMutate: ({ id }) => { setRunningRoutineId(id); }, - onSuccess: async (_, { id }) => { + onSuccess: async (run, { id }) => { + recordRoutineRunInRecents(run); setRunDialogRoutine(null); await Promise.all([ queryClient.invalidateQueries({ queryKey: ["routines", workspace.companyId] }), diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 32397df64b3..ad89f6bc28f 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -219,7 +219,7 @@ import { upsertInterruptedRun, } from "../lib/optimistic-issue-runs"; import { useProjectOrder } from "../hooks/useProjectOrder"; -import { recordRecentTask } from "../lib/recent-tasks"; +import { recordRecentTask, settleRecentTaskVisit } from "../lib/recent-tasks"; import { modelStillUnavailableToast } from "../lib/model-retry-refusal"; import { relativeTime, @@ -3901,7 +3901,11 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS if (!(streamlinedUiEnabled || coordinatorWorkspaceEnabled) || !loadedIssue || !sessionResolved || conversation || loadedIssue.conversationAgentId || loadedIssue.hiddenAt) return; const visit = `${loadedIssue.companyId}:${currentUserId}:${loadedIssue.id}`; - recordRecentTask(loadedIssue, currentUserId, recentTaskVisit.current === visit ? undefined : Date.now()); + const freshVisit = recentTaskVisit.current !== visit; + // A fresh visit waits for its read unless that read is already confirmed. + const readConfirmed = readReceiptRef.current?.issueId === loadedIssue.id && readReceiptRef.current.confirmed; + recordRecentTask(loadedIssue, currentUserId, freshVisit ? Date.now() : undefined, + freshVisit && !readConfirmed ? { awaitingRead: true } : undefined); recentTaskVisit.current = visit; }, [loadedIssue, currentUserId, sessionResolved, streamlinedUiEnabled, coordinatorWorkspaceEnabled, conversation]); const { data: boardAccess } = useQuery({ @@ -4648,6 +4652,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS }, onSuccess: (_data, receipt) => { receipt.confirmed = true; + // Settle before the refresh below so the new summary judges this visit. + settleRecentTaskVisit(receipt.companyId, receipt.issueId, currentUserId); // A late receipt belongs to its original company, even after navigation. queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(receipt.companyId) }); if (selectedCompanyId) { @@ -4667,6 +4673,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS }, onFinished: (receipt) => { pendingReadReceiptsRef.current.delete(receipt.issueId); + // The saved read makes an opened automatic task eligible for Recents. + // Until now Recents kept the visit without judging it; after a failed + // read, the next summary prunes it unless the person qualifies otherwise. + settleRecentTaskVisit(receipt.companyId, receipt.issueId, currentUserId); // An older read can settle after navigation has changed the mutation observer. if (readReceiptRef.current === receipt) setReadReceiptRevision(revision => revision + 1); }, diff --git a/ui/src/pages/RoutineDetail.tsx b/ui/src/pages/RoutineDetail.tsx index 1b964f1287e..f982387dd3a 100644 --- a/ui/src/pages/RoutineDetail.tsx +++ b/ui/src/pages/RoutineDetail.tsx @@ -49,6 +49,7 @@ import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb"; import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { queryKeys } from "@/lib/queryKeys"; import { Navigate, useLocation, useNavigate, useParams, useSearchParams } from "@/lib/router"; +import { useRecordRoutineRunInRecents } from "@/hooks/useRecordRoutineRunInRecents"; /** Tasks shown per History page; "Load more" fetches the next page. */ export const ROUTINE_HISTORY_PAGE_SIZE = 20; @@ -205,6 +206,7 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string; onError: (error) => toastError("Couldn’t change the routine", error, "change the routine"), }); + const recordRoutineRunInRecents = useRecordRoutineRunInRecents(); const runRoutine = useMutation({ mutationFn: (data?: RoutineRunDialogSubmitData) => routinesApi.run(routineId, { @@ -215,7 +217,8 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string; ...(data?.executionWorkspacePreference !== undefined ? { executionWorkspacePreference: data.executionWorkspacePreference } : {}), ...(data?.executionWorkspaceSettings !== undefined ? { executionWorkspaceSettings: data.executionWorkspaceSettings } : {}), }), - onSuccess: async () => { + onSuccess: async (run) => { + recordRoutineRunInRecents(run); pushToast({ title: "Routine run started", tone: "success" }); setRunOpen(false); await Promise.all([ diff --git a/ui/src/pages/Routines.production.tsx b/ui/src/pages/Routines.production.tsx index 38c24c08dff..fa2356b35a6 100644 --- a/ui/src/pages/Routines.production.tsx +++ b/ui/src/pages/Routines.production.tsx @@ -58,6 +58,7 @@ import { selectedFolderFromList, type FolderSelection, } from "../components/folders/FolderControls"; +import { useRecordRoutineRunInRecents } from "@/hooks/useRecordRoutineRunInRecents"; type RoutinesTab = "routines" | "runs"; @@ -411,6 +412,7 @@ export function Routines() { }, }); + const recordRoutineRunInRecents = useRecordRoutineRunInRecents(); const runRoutine = useMutation({ mutationFn: ({ id, data }: { id: string; data?: RoutineRunDialogSubmitData }) => routinesApi.run(id, { ...(data?.variables && Object.keys(data.variables).length > 0 ? { variables: data.variables } : {}), @@ -427,7 +429,8 @@ export function Routines() { onMutate: ({ id }) => { setRunningRoutineId(id); }, - onSuccess: async (_, { id }) => { + onSuccess: async (run, { id }) => { + recordRoutineRunInRecents(run); setRunDialogRoutine(null); await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }), diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx index 4aad20ca963..8b45876677b 100644 --- a/ui/src/pages/Routines.tsx +++ b/ui/src/pages/Routines.tsx @@ -59,6 +59,7 @@ import { type FolderSelection, } from "../components/folders/FolderControls"; import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation"; +import { useRecordRoutineRunInRecents } from "@/hooks/useRecordRoutineRunInRecents"; type RoutinesTab = "routines" | "runs"; @@ -399,6 +400,7 @@ export function Routines() { }, }); + const recordRoutineRunInRecents = useRecordRoutineRunInRecents(); const runRoutine = useMutation({ mutationFn: ({ id, data }: { id: string; data?: RoutineRunDialogSubmitData }) => routinesApi.run(id, { ...(data?.variables && Object.keys(data.variables).length > 0 ? { variables: data.variables } : {}), @@ -415,7 +417,8 @@ export function Routines() { onMutate: ({ id }) => { setRunningRoutineId(id); }, - onSuccess: async (_, { id }) => { + onSuccess: async (run, { id }) => { + recordRoutineRunInRecents(run); setRunDialogRoutine(null); await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),