mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## 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 > - Each browser kept Recents in `localStorage`. A laptop, a phone, and a second browser each showed a different list > - People expect one list for their account, the same on every client > - This pull request moves Recents to the server. The server keeps one list for each person in each company. The UI shows that list and gets live updates when another client changes it > - The benefit is that every client shows the same Recents in the same order, and a change on one client shows on the others at once ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** Recents is kept in the browser. When I open a task on my laptop, the task does not show in Recents on my phone or in another browser. **Describe the solution you'd like** Keep Recents on the server, so that every client that I sign in to shows the same list. **Additional context** Eligibility (which rows show) does not change. The navigation summaries still decide it (see #23675). ## What Changed - `packages/db`: new `user_recent_tasks` table (company, user, issue, `recorded_at`), unique on company + user + issue. Migration `0515` creates only a new table, so it is `online_compatible`. - `packages/shared`: `RecentTaskRecord`, `RecentTaskList`, `RECENT_TASKS_MAX_ENTRIES` (200), and the `recordRecentTaskSchema` and `importRecentTasksSchema` validators. - `server`: new `recentTaskService` and routes: - `GET /api/companies/:companyId/recent-tasks/me`: the list, newest first. - `POST /api/companies/:companyId/recent-tasks/me` `{ issueId, touch }`: `touch: true` moves the task to the top (server time). `touch: false` adds a missing task below the history and does not move an existing task. - `POST /api/companies/:companyId/recent-tasks/me/import`: imports the list that a browser kept. The later time wins. - `DELETE /api/companies/:companyId/recent-tasks/me/:issueId`. - The server keeps the newest 200 rows for each person. Each change is in the activity log as `recent_tasks.*` with `entityType: "company"` and `details.userId`. The entry does not name the task. Viewers can change their own Recents, like workspace preferences. - Record, import, and list use the normal task read decision. A private or unreadable task gets the same 404 as a missing task. The import skips it, and the list does not return it. - `server/src/realtime/live-events-ws.ts`: sends `recent_tasks.*` events only to the owner's connections, without details. - OpenAPI entries for the four routes. - `ui/src/lib/recent-tasks.ts`: the module is now a client mirror of the server list, not `localStorage`. Optimistic records and removals stay applied until a server list that was requested after the server saved them arrives. This prevents a stale list from hiding a new visit. - `ui/src/hooks/useRecentTasks.ts`: fetches the server list (`queryKeys.recentTasks`). On the first load it imports the old browser list one time and then deletes the browser copy. It does not delete ineligible rows anymore. It hides them, and it requests a new summary batch when new activity occurs on a hidden task. The `awaitingRead` flow is removed because nothing deletes the row while the read is in flight. - `LiveUpdatesProvider`: a `recent_tasks.*` event refreshes Recents. Other company views do not refresh. - A failed save is tried again one time. If it fails again, the client loads the server list again, so an unsaved change does not look saved. - The import reads only the newest browser storage version. - `SidebarRecentTasks`: the "Archive" action removes the task from the server list. - `doc/PRODUCT.md`: describes the shared list. ## Verification - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts` (embedded Postgres): 5 passed. The tests cover: two clients of the same person see the same order; touch and passive seed; personal and company scope (teammate, other company, agent, viewer, suspended member); removal plus activity log plus live events; import, and the 200-row limit. - `cd server && npx vitest run src/__tests__/openapi-routes.test.ts`: 59 passed. - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts src/__tests__/live-events-toast.test.ts`: 21 passed. This includes private-task checks and owner-only socket delivery. - `cd ui && npx vitest run src/lib/recent-tasks.test.ts src/hooks/useRecentTasks.test.tsx src/context/LiveUpdatesProvider.test.ts`: all passed. New tests cover: the same list on a second client, legacy import (success and failure), the record-and-list race, server-time adoption, and live-event scoping. - `packages/db`: `migration-compatibility.ts` classifies `0515` as `online_compatible`. - `packages/shared` typecheck: no errors. `ui` typecheck: no errors in changed files (errors exist only in the ungenerated Storybook feature-map indexes). - `server`: a typecheck of the route, service, and test graph passes. The full `server` typecheck was killed by the local memory limit (exit 137). CI covers it. - `pnpm verify` returned exit 2 (the migration needs broad CI coverage). Required CI supplies that coverage. ## Risks - Medium. This adds a table and changes where Recents is kept. - Each task open now sends one more request and writes one activity row (the same as `issue.read_marked`). The live socket sends the event only to the owner's connections. - Rows that are not eligible stay in the server list (hidden) until they fall out of the newest 200. Before, the client deleted them. - The import reads `paperclip.recentTasks.v3`, `v2`, and the oldest key one time for each browser. If the import fails, the browser copy stays and the next load tries again. - An old tab from the previous release still writes to `localStorage`. The next load of a new tab imports those entries. The later time wins, so this does not reorder newer server entries. > 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 - 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 - [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 🤖 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>
372 lines
19 KiB
TypeScript
372 lines
19 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_RESYNC_EVENT,
|
|
RECENT_TASKS_UPDATED_EVENT,
|
|
applyServerRecentTasks,
|
|
beginRecentTasksFetch,
|
|
getRecentTasksStorageKey,
|
|
importLegacyRecentTasks,
|
|
readRecentTasks,
|
|
recordRecentTask,
|
|
recordStartedRoutineRunTask,
|
|
removeRecentTask,
|
|
resetRecentTasksForTests,
|
|
updateRecentTaskSnapshots,
|
|
} from "./recent-tasks";
|
|
|
|
const api = vi.hoisted(() => ({
|
|
list: vi.fn(),
|
|
record: vi.fn(),
|
|
importEntries: vi.fn(),
|
|
remove: vi.fn(),
|
|
}));
|
|
vi.mock("@/api/recentTasks", () => ({ recentTasksApi: api }));
|
|
|
|
const issue = (id: string, companyId = "company-1") => ({
|
|
id,
|
|
companyId,
|
|
title: `Task ${id}`,
|
|
identifier: `PAP-${id}`,
|
|
status: "todo" as const,
|
|
updatedAt: new Date(0),
|
|
});
|
|
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
|
|
describe("recent task client mirror", () => {
|
|
beforeEach(() => {
|
|
window.localStorage.clear();
|
|
resetRecentTasksForTests();
|
|
api.record.mockReset().mockResolvedValue({ entry: null });
|
|
api.remove.mockReset().mockResolvedValue(undefined);
|
|
});
|
|
|
|
it("sends explicit visits as touches and only seeds new passive visits", () => {
|
|
recordRecentTask(issue("1"), "user-1", 10);
|
|
recordRecentTask(issue("2"), "user-1");
|
|
recordRecentTask(issue("2"), "user-1");
|
|
recordRecentTask({ ...issue("3"), conversationAgentId: "agent-1" } as never, "user-1", 20);
|
|
expect(api.record.mock.calls).toEqual([
|
|
["company-1", { issueId: "1", touch: true }],
|
|
["company-1", { issueId: "2", touch: false }],
|
|
]);
|
|
});
|
|
|
|
it("adopts the server time so every client orders the list the same way", async () => {
|
|
api.record.mockResolvedValueOnce({ entry: { issueId: "1", recordedAt: new Date(5_000).toISOString() } });
|
|
recordRecentTask(issue("1"), "user-1", 10);
|
|
await flush();
|
|
expect(readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1")[0]?.recordedAt).toBe(5_000);
|
|
});
|
|
|
|
it("replaces the mirror with the server list, keeping snapshots and in-flight records", () => {
|
|
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
|
api.record.mockReturnValue(new Promise(() => {}));
|
|
recordRecentTask({ ...issue("known"), title: "Known" }, "user-1", 10);
|
|
recordStartedRoutineRunTask("company-1", "in-flight", "user-1", 50);
|
|
applyServerRecentTasks(storageKey, "company-1", [
|
|
{ issueId: "other-device", recordedAt: new Date(40).toISOString() },
|
|
{ issueId: "known", recordedAt: new Date(30).toISOString() },
|
|
]);
|
|
expect(readRecentTasks(storageKey, "company-1").map(({ id, title, recordedAt }) => [id, title, recordedAt])).toEqual([
|
|
["in-flight", "", 50],
|
|
["other-device", "", 40],
|
|
["known", "Known", 30],
|
|
]);
|
|
});
|
|
|
|
it("keeps a record that the server saved after an older list was requested", async () => {
|
|
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
|
const olderList = beginRecentTasksFetch(storageKey);
|
|
api.record.mockResolvedValueOnce({ entry: { issueId: "new", recordedAt: new Date(2_000).toISOString() } });
|
|
recordRecentTask(issue("new"), "user-1", 10);
|
|
await flush();
|
|
// The list requested before the record lacks it; the record stays.
|
|
applyServerRecentTasks(storageKey, "company-1", [], olderList);
|
|
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(["new"]);
|
|
// A list requested after the save is authoritative (for example a removal elsewhere).
|
|
applyServerRecentTasks(storageKey, "company-1", [], beginRecentTasksFetch(storageKey));
|
|
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
|
|
});
|
|
|
|
it.each(["record", "remove"] as const)("retries a failed %s once, then reloads the server list instead of looking saved", async (kind) => {
|
|
vi.useFakeTimers();
|
|
const resync = vi.fn();
|
|
window.addEventListener(RECENT_TASKS_RESYNC_EVENT, resync);
|
|
try {
|
|
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
|
if (kind === "remove") recordRecentTask(issue("1"), "user-1", 10);
|
|
await vi.runAllTimersAsync();
|
|
const failing = kind === "record" ? api.record : api.remove;
|
|
failing.mockReset().mockRejectedValue(new Error("offline"));
|
|
if (kind === "record") recordRecentTask(issue("1"), "user-1", 10);
|
|
else removeRecentTask("company-1", "1", "user-1");
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(failing).toHaveBeenCalledTimes(1);
|
|
expect(resync).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(failing).toHaveBeenCalledTimes(2);
|
|
expect(resync).toHaveBeenCalledOnce();
|
|
expect(resync.mock.calls[0]?.[0].detail).toEqual({ storageKey });
|
|
// The server list now decides: the unsaved change is not kept.
|
|
applyServerRecentTasks(storageKey, "company-1",
|
|
kind === "record" ? [] : [{ issueId: "1", recordedAt: new Date(10).toISOString() }], beginRecentTasksFetch(storageKey));
|
|
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(kind === "record" ? [] : ["1"]);
|
|
} finally {
|
|
window.removeEventListener(RECENT_TASKS_RESYNC_EVENT, resync);
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("does not retry a failed removal after a newer visit replaces it", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
recordRecentTask(issue("1"), "user-1", 10);
|
|
await vi.runAllTimersAsync();
|
|
api.remove.mockReset().mockRejectedValue(new Error("offline"));
|
|
removeRecentTask("company-1", "1", "user-1");
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(api.remove).toHaveBeenCalledTimes(1);
|
|
// The person opens the task again during the retry wait.
|
|
recordRecentTask(issue("1"), "user-1", 20);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(api.remove).toHaveBeenCalledTimes(1);
|
|
expect(api.record).toHaveBeenLastCalledWith("company-1", { issueId: "1", touch: true });
|
|
expect(readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1").map(entry => entry.id)).toEqual(["1"]);
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("imports only the newest browser storage version and deletes every old copy", async () => {
|
|
const id = (n: number) => `${n}${n}${n}${n}${n}${n}${n}${n}-${n}${n}${n}${n}-4${n}${n}${n}-8${n}${n}${n}-${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}`;
|
|
const keys = ["paperclip.recentTasks.v3:company-1:user-1", "paperclip.recentTasks.v2:company-1:user-1", "paperclip.recentTasks:company-1:user-1"];
|
|
localStorage.setItem(keys[0]!, JSON.stringify([{ ...issue(id(1)), recordedAt: 100 }]));
|
|
// An old tab promoted machine activity here after the v3 migration.
|
|
localStorage.setItem(keys[1]!, JSON.stringify([{ ...issue(id(2)), recordedAt: 999 }]));
|
|
localStorage.setItem(keys[2]!, JSON.stringify([{ ...issue(id(1)), recordedAt: 999 }]));
|
|
api.importEntries.mockReset().mockResolvedValue({ entries: [] });
|
|
await importLegacyRecentTasks("company-1", "user-1");
|
|
expect(api.importEntries).toHaveBeenCalledWith("company-1", { entries: [{ issueId: id(1), recordedAt: new Date(100).toISOString() }] });
|
|
expect(keys.map(key => localStorage.getItem(key))).toEqual([null, null, null]);
|
|
});
|
|
|
|
it("removes a task everywhere and does not let a stale list bring it back", () => {
|
|
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
|
api.remove.mockReturnValue(new Promise(() => {}));
|
|
recordRecentTask(issue("1"), "user-1", 10);
|
|
removeRecentTask("company-1", "1", "user-1");
|
|
expect(api.remove).toHaveBeenCalledWith("company-1", "1");
|
|
applyServerRecentTasks(storageKey, "company-1", [{ issueId: "1", recordedAt: new Date(10).toISOString() }]);
|
|
expect(readRecentTasks(storageKey, "company-1")).toEqual([]);
|
|
});
|
|
|
|
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("seeds unseen passive visits by latest activity timestamp without re-sorting on revisit", () => {
|
|
const key = getRecentTasksStorageKey("company-1", "user-1");
|
|
recordRecentTask(issue("personal"), "user-1", 500);
|
|
recordRecentTask({ ...issue("older-visit"), updatedAt: new Date(100) }, "user-1");
|
|
recordRecentTask({ ...issue("newer-visit"), updatedAt: new Date(1_000) }, "user-1");
|
|
recordRecentTask({ ...issue("canonical-activity"), updatedAt: new Date(50), lastActivityAt: new Date(750) }, "user-1");
|
|
recordRecentTask(issue("no-timestamp"), "user-1");
|
|
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
|
"newer-visit",
|
|
"canonical-activity",
|
|
"personal",
|
|
"older-visit",
|
|
"no-timestamp",
|
|
]);
|
|
|
|
// Revisiting/clicking existing entries passively must not move them to the top.
|
|
recordRecentTask({ ...issue("older-visit"), updatedAt: new Date(100) }, "user-1");
|
|
recordRecentTask(issue("personal"), "user-1");
|
|
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
|
"newer-visit",
|
|
"canonical-activity",
|
|
"personal",
|
|
"older-visit",
|
|
"no-timestamp",
|
|
]);
|
|
|
|
// Explicit local activity (comment, edit, create, interaction) advances recency.
|
|
recordRecentTask(issue("older-visit"), "user-1", 2_000);
|
|
expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual([
|
|
"older-visit",
|
|
"newer-visit",
|
|
"canonical-activity",
|
|
"personal",
|
|
"no-timestamp",
|
|
]);
|
|
});
|
|
|
|
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("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("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("ignores conversation, archived, and hidden tasks consistently", () => {
|
|
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
|
|
recordRecentTask({ ...issue("chat"), conversationAgentId: "agent-1" }, "user-1", 100);
|
|
recordRecentTask({ ...issue("archived"), archivedAt: new Date(50) }, "user-1", 100);
|
|
recordRecentTask({ ...issue("hidden"), hiddenAt: new Date(50) }, "user-1", 100);
|
|
recordRecentTask({ ...issue("visible"), hiddenAt: null }, "user-1", 100);
|
|
|
|
expect(readRecentTasks(storageKey, "company-1").map((entry) => entry.id)).toEqual(["visible"]);
|
|
});
|
|
});
|