diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 82bb69adc23..a3c9d23f40d 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -127,7 +127,11 @@ an existing item in Recents does not move it to the top; items re-sort only when new activity occurs. 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. +once, before they open it. Neither of these adds the task to Mine. The server +keeps each person’s recent tasks per company (the newest 200), so every browser +and device shows the same list in the same order, and a change on one client +reaches the others through live updates. The first visit after this change +imports the list that the browser kept locally. Standard Recents also shows recent chats and projects. The Coordinator sidebar pins **Plugins** above **More** by default. Users can diff --git a/packages/db/src/migrations/0515_fixed_grandmaster.sql b/packages/db/src/migrations/0515_fixed_grandmaster.sql new file mode 100644 index 00000000000..e886580940a --- /dev/null +++ b/packages/db/src/migrations/0515_fixed_grandmaster.sql @@ -0,0 +1,15 @@ +CREATE TABLE "user_recent_tasks" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "user_id" text NOT NULL, + "issue_id" uuid NOT NULL, + "recorded_at" timestamp with time zone DEFAULT now() NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "user_recent_tasks" ADD CONSTRAINT "user_recent_tasks_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_recent_tasks" ADD CONSTRAINT "user_recent_tasks_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "user_recent_tasks_company_user_recorded_idx" ON "user_recent_tasks" USING btree ("company_id","user_id","recorded_at");--> statement-breakpoint +CREATE INDEX "user_recent_tasks_issue_idx" ON "user_recent_tasks" USING btree ("issue_id");--> statement-breakpoint +CREATE UNIQUE INDEX "user_recent_tasks_company_user_issue_uq" ON "user_recent_tasks" USING btree ("company_id","user_id","issue_id"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0510_snapshot.json b/packages/db/src/migrations/meta/0515_snapshot.json similarity index 97% rename from packages/db/src/migrations/meta/0510_snapshot.json rename to packages/db/src/migrations/meta/0515_snapshot.json index 529b1ab23cb..7c5211a1d1e 100644 --- a/packages/db/src/migrations/meta/0510_snapshot.json +++ b/packages/db/src/migrations/meta/0515_snapshot.json @@ -1,6 +1,6 @@ { - "id": "bd7706ab-f548-43f0-9dbb-4f1d52d9c135", - "prevId": "01f5b33d-2353-4095-8b32-86aec4f8df2c", + "id": "3a2aed10-7ad5-43cc-bb02-2dbc2e8066aa", + "prevId": "74dc138b-0555-4b0b-8ca7-5cd3c84cd4e1", "version": "7", "dialect": "postgresql", "tables": { @@ -1842,6 +1842,12 @@ "primaryKey": false, "notNull": false }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "last_used_at": { "name": "last_used_at", "type": "timestamp with time zone", @@ -6878,6 +6884,24 @@ "primaryKey": false, "notNull": true }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "locked_profile": { + "name": "locked_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "name": { "name": "name", "type": "text", @@ -6946,6 +6970,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "board_api_keys_company_idx": { + "name": "board_api_keys_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -6961,6 +7000,19 @@ ], "onDelete": "cascade", "onUpdate": "no action" + }, + "board_api_keys_company_id_companies_id_fk": { + "name": "board_api_keys_company_id_companies_id_fk", + "tableFrom": "board_api_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -10363,6 +10415,345 @@ }, "isRLSEnabled": false }, + "public.channel_access_members": { + "name": "channel_access_members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "channel_access_members_channel_subject_uq": { + "name": "channel_access_members_channel_subject_uq", + "columns": [ + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channel_access_members_subject_lookup_idx": { + "name": "channel_access_members_subject_lookup_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channel_access_members_company_id_companies_id_fk": { + "name": "channel_access_members_company_id_companies_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channel_access_members_channel_id_channels_id_fk": { + "name": "channel_access_members_channel_id_channels_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channel_access_members_subject_type_check": { + "name": "channel_access_members_subject_type_check", + "value": "\"channel_access_members\".\"subject_type\" in ('user', 'agent')" + } + }, + "isRLSEnabled": false + }, + "public.channels": { + "name": "channels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "default_project_id": { + "name": "default_project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "queue_config": { + "name": "queue_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "channels_company_path_uq": { + "name": "channels_company_path_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channels_company_activity_idx": { + "name": "channels_company_activity_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_activity_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channels_company_id_companies_id_fk": { + "name": "channels_company_id_companies_id_fk", + "tableFrom": "channels", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channels_default_project_id_projects_id_fk": { + "name": "channels_default_project_id_projects_id_fk", + "tableFrom": "channels", + "tableTo": "projects", + "columnsFrom": [ + "default_project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "channels_created_by_agent_id_agents_id_fk": { + "name": "channels_created_by_agent_id_agents_id_fk", + "tableFrom": "channels", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channels_visibility_check": { + "name": "channels_visibility_check", + "value": "\"channels\".\"visibility\" in ('open', 'private')" + }, + "channels_path_check": { + "name": "channels_path_check", + "value": "\"channels\".\"path\" ~ '^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)*$'" + } + }, + "isRLSEnabled": false + }, "public.chat_actions": { "name": "chat_actions", "schema": "", @@ -16464,6 +16855,25 @@ "notNull": true, "default": "'board'" }, + "challenge_kind": { + "name": "challenge_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, + "requested_agent_name": { + "name": "requested_agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_agent_role": { + "name": "requested_agent_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, "requested_company_id": { "name": "requested_company_id", "type": "uuid", @@ -16494,6 +16904,12 @@ "primaryKey": false, "notNull": false }, + "approved_agent_id": { + "name": "approved_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "approved_at": { "name": "approved_at", "type": "timestamp with time zone", @@ -16613,6 +17029,19 @@ ], "onDelete": "set null", "onUpdate": "no action" + }, + "cli_auth_challenges_approved_agent_id_agents_id_fk": { + "name": "cli_auth_challenges_approved_agent_id_agents_id_fk", + "tableFrom": "cli_auth_challenges", + "tableTo": "agents", + "columnsFrom": [ + "approved_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -16754,6 +17183,12 @@ "primaryKey": false, "notNull": false }, + "agent_identity_policy": { + "name": "agent_identity_policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -16790,7 +17225,12 @@ "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, - "checkConstraints": {}, + "checkConstraints": { + "companies_agent_identity_policy_check": { + "name": "companies_agent_identity_policy_check", + "value": "\"companies\".\"agent_identity_policy\" is null or \"companies\".\"agent_identity_policy\" in ('open_local_profiles', 'delegated_profiles', 'strict_agent_keys')" + } + }, "isRLSEnabled": false }, "public.company_logos": { @@ -17326,6 +17766,141 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_schemas": { + "name": "company_schemas", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "json_schema": { + "name": "json_schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_schemas_company_name_version_uq": { + "name": "company_schemas_company_name_version_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_schemas_company_id_companies_id_fk": { + "name": "company_schemas_company_id_companies_id_fk", + "tableFrom": "company_schemas", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "company_schemas_created_by_agent_id_agents_id_fk": { + "name": "company_schemas_created_by_agent_id_agents_id_fk", + "tableFrom": "company_schemas", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_schemas_version_check": { + "name": "company_schemas_version_check", + "value": "\"company_schemas\".\"version\" >= 1" + } + }, + "isRLSEnabled": false + }, "public.company_secret_bindings": { "name": "company_secret_bindings", "schema": "", @@ -35248,6 +35823,546 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.board_events": { + "name": "board_events", + "schema": "", + "columns": { + "seq": { + "name": "seq", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "channel_path": { + "name": "channel_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "board_events_company_seq_idx": { + "name": "board_events_company_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_channel_seq_idx": { + "name": "board_events_company_channel_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_issue_seq_idx": { + "name": "board_events_company_issue_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "board_events_company_id_companies_id_fk": { + "name": "board_events_company_id_companies_id_fk", + "tableFrom": "board_events", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "board_events_channel_id_channels_id_fk": { + "name": "board_events_channel_id_channels_id_fk", + "tableFrom": "board_events", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "board_events_issue_id_issues_id_fk": { + "name": "board_events_issue_id_issues_id_fk", + "tableFrom": "board_events", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.issue_batch_idempotency_keys": { + "name": "issue_batch_idempotency_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "response_payload": { + "name": "response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_batch_idempotency_keys_company_key_uq": { + "name": "issue_batch_idempotency_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_batch_idempotency_keys_company_id_companies_id_fk": { + "name": "issue_batch_idempotency_keys_company_id_companies_id_fk", + "tableFrom": "issue_batch_idempotency_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_board_posts": { + "name": "scheduled_board_posts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "post_only": { + "name": "post_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "interval_ms": { + "name": "interval_ms", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "until_at": { + "name": "until_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "author_agent_id": { + "name": "author_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "author_profile": { + "name": "author_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scheduled_board_posts_due_idx": { + "name": "scheduled_board_posts_due_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_board_posts\".\"status\" = 'scheduled'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_board_posts_company_idx": { + "name": "scheduled_board_posts_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scheduled_board_posts_company_id_companies_id_fk": { + "name": "scheduled_board_posts_company_id_companies_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_channel_id_channels_id_fk": { + "name": "scheduled_board_posts_channel_id_channels_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_issue_id_issues_id_fk": { + "name": "scheduled_board_posts_issue_id_issues_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_author_agent_id_agents_id_fk": { + "name": "scheduled_board_posts_author_agent_id_agents_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "agents", + "columnsFrom": [ + "author_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scheduled_board_posts_status_check": { + "name": "scheduled_board_posts_status_check", + "value": "\"scheduled_board_posts\".\"status\" in ('scheduled', 'cancelled', 'completed')" + } + }, + "isRLSEnabled": false + }, "public.heartbeat_run_events": { "name": "heartbeat_run_events", "schema": "", @@ -39003,6 +40118,13 @@ "primaryKey": false, "notNull": false }, + "issue_level": { + "name": "issue_level", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -39303,6 +40425,33 @@ "primaryKey": false, "notNull": false }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "no_sync": { + "name": "no_sync", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, "source_trust": { "name": "source_trust", "type": "jsonb", @@ -44230,6 +45379,12 @@ "primaryKey": false, "notNull": false }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "project_workspace_id": { "name": "project_workspace_id", "type": "uuid", @@ -44293,6 +45448,13 @@ "notNull": true, "default": "'backlog'" }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, "status_version": { "name": "status_version", "type": "bigint", @@ -44380,12 +45542,88 @@ "primaryKey": false, "notNull": false }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, "responsible_user_id": { "name": "responsible_user_id", "type": "text", "primaryKey": false, "notNull": false }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "result_schema_ref": { + "name": "result_schema_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_epoch": { + "name": "claim_epoch", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_agent_id": { + "name": "claim_holder_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "claim_holder_user_id": { + "name": "claim_holder_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_profile": { + "name": "claim_holder_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_leased_at": { + "name": "claim_leased_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_lease_expires_at": { + "name": "claim_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_attempt_count": { + "name": "claim_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, "issue_number": { "name": "issue_number", "type": "integer", @@ -44659,6 +45897,60 @@ "method": "btree", "with": {} }, + "issues_company_scope_status_idx": { + "name": "issues_company_scope_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issues_company_scope_updated_idx": { + "name": "issues_company_scope_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "issues_company_harness_kind_idx": { "name": "issues_company_harness_kind_idx", "columns": [ @@ -45349,6 +46641,119 @@ "concurrently": false, "method": "btree", "with": {} + }, + "issues_company_channel_created_idx": { + "name": "issues_company_channel_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_kv_labels_gin_idx": { + "name": "issues_kv_labels_gin_idx", + "columns": [ + { + "expression": "kv_labels", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": {} + }, + "issues_ready_pool_queue_idx": { + "name": "issues_ready_pool_queue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'todo'\n and \"issues\".\"assignee_agent_id\" is null\n and \"issues\".\"assignee_user_id\" is null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"conversation_agent_id\" is null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_active_claim_lease_due_idx": { + "name": "issues_active_claim_lease_due_idx", + "columns": [ + { + "expression": "claim_lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'in_progress'\n and \"issues\".\"claim_lease_expires_at\" is not null\n and \"issues\".\"claim_token_hash\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_company_issue_number_idx": { + "name": "issues_company_issue_number_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -45391,6 +46796,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_channel_id_channels_id_fk": { + "name": "issues_channel_id_channels_id_fk", + "tableFrom": "issues", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_project_workspace_id_project_workspaces_id_fk": { "name": "issues_project_workspace_id_project_workspaces_id_fk", "tableFrom": "issues", @@ -45508,6 +46926,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_claim_holder_agent_id_agents_id_fk": { + "name": "issues_claim_holder_agent_id_agents_id_fk", + "tableFrom": "issues", + "tableTo": "agents", + "columnsFrom": [ + "claim_holder_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_origin_issue_id_issues_id_fk": { "name": "issues_origin_issue_id_issues_id_fk", "tableFrom": "issues", @@ -45552,9 +46983,17 @@ "name": "issues_visibility_check", "value": "\"issues\".\"visibility\" in ('open', 'private')" }, + "issues_scope_check": { + "name": "issues_scope_check", + "value": "\"issues\".\"scope\" in ('board', 'channel', 'agent', 'chat')" + }, "issues_conversation_identity_check": { "name": "issues_conversation_identity_check", "value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )" + }, + "issues_conversation_channel_exclusion_check": { + "name": "issues_conversation_channel_exclusion_check", + "value": "(\"issues\".\"conversation_agent_id\" is null) or (\"issues\".\"channel_id\" is null)" } }, "isRLSEnabled": false @@ -67099,6 +68538,162 @@ }, "isRLSEnabled": false }, + "public.user_recent_tasks": { + "name": "user_recent_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_recent_tasks_company_user_recorded_idx": { + "name": "user_recent_tasks_company_user_recorded_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recorded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_recent_tasks_issue_idx": { + "name": "user_recent_tasks_issue_idx", + "columns": [ + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_recent_tasks_company_user_issue_uq": { + "name": "user_recent_tasks_company_user_issue_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_recent_tasks_company_id_companies_id_fk": { + "name": "user_recent_tasks_company_id_companies_id_fk", + "tableFrom": "user_recent_tasks", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_recent_tasks_issue_id_issues_id_fk": { + "name": "user_recent_tasks_issue_id_issues_id_fk", + "tableFrom": "user_recent_tasks", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.user_secret_declarations": { "name": "user_secret_declarations", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 1a4b92305c8..873876d754d 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3592,6 +3592,13 @@ "when": 1796346310107, "tag": "0514_lame_ricochet", "breakpoints": true + }, + { + "idx": 515, + "version": "7", + "when": 1796362090964, + "tag": "0515_fixed_grandmaster", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 4f5288a6def..da81a9dca5d 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -137,6 +137,7 @@ export { } from "./decision_queues.js"; export { feedbackExports } from "./feedback_exports.js"; export { issueReadStates } from "./issue_read_states.js"; +export { userRecentTasks } from "./user_recent_tasks.js"; export { assets } from "./assets.js"; export { runnerApiResponseReservations } from "./runner_api_response_reservations.js"; export { issueAttachments } from "./issue_attachments.js"; diff --git a/packages/db/src/schema/user_recent_tasks.ts b/packages/db/src/schema/user_recent_tasks.ts new file mode 100644 index 00000000000..19eda147288 --- /dev/null +++ b/packages/db/src/schema/user_recent_tasks.ts @@ -0,0 +1,33 @@ +import { pgTable, uuid, text, timestamp, index, uniqueIndex } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; +import { issues } from "./issues.js"; + +/** + * One row per task in a person's sidebar Recents for a company. The server + * keeps the list so every browser and device shows the same Recents. + */ +export const userRecentTasks = pgTable( + "user_recent_tasks", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + userId: text("user_id").notNull(), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => ({ + companyUserRecordedIdx: index("user_recent_tasks_company_user_recorded_idx").on( + table.companyId, + table.userId, + table.recordedAt, + ), + issueIdx: index("user_recent_tasks_issue_idx").on(table.issueId), + companyUserIssueUq: uniqueIndex("user_recent_tasks_company_user_issue_uq").on( + table.companyId, + table.userId, + table.issueId, + ), + }), +); diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6dd91e7caab..7bf44c13018 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1907,6 +1907,17 @@ export { upsertSidebarOrderPreferenceSchema, type UpsertSidebarOrderPreference, } from "./validators/sidebar-preferences.js"; +export { + importRecentTasksSchema, + recordRecentTaskSchema, + type ImportRecentTasks, + type RecordRecentTask, +} from "./validators/recent-tasks.js"; +export { + RECENT_TASKS_MAX_ENTRIES, + type RecentTaskList, + type RecentTaskRecord, +} from "./types/recent-tasks.js"; export { resourceMembershipStateSchema, updateDocumentResourceMembershipSchema, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index f8eedd126cf..66574aca258 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -1080,6 +1080,7 @@ export type { } from "./user-profile.js"; export type { SidebarBadges } from "./sidebar-badges.js"; export type { SidebarOrderPreference } from "./sidebar-preferences.js"; +export { RECENT_TASKS_MAX_ENTRIES, type RecentTaskList, type RecentTaskRecord } from "./recent-tasks.js"; export type { ResourceMembershipResourceType, ResourceMembershipState, diff --git a/packages/shared/src/types/recent-tasks.ts b/packages/shared/src/types/recent-tasks.ts new file mode 100644 index 00000000000..03125eb32ba --- /dev/null +++ b/packages/shared/src/types/recent-tasks.ts @@ -0,0 +1,12 @@ +/** Most tasks the server keeps in one person's Recents for a company. */ +export const RECENT_TASKS_MAX_ENTRIES = 200; + +export interface RecentTaskRecord { + issueId: string; + /** When the person last acted on the task (server time, ISO 8601). */ + recordedAt: string; +} + +export interface RecentTaskList { + entries: RecentTaskRecord[]; +} diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index 0739d0fdc6a..da4f0ba5ada 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -131,6 +131,12 @@ export { upsertSidebarOrderPreferenceSchema, type UpsertSidebarOrderPreference, } from "./sidebar-preferences.js"; +export { + importRecentTasksSchema, + recordRecentTaskSchema, + type ImportRecentTasks, + type RecordRecentTask, +} from "./recent-tasks.js"; export { resourceMembershipStateSchema, updateDocumentResourceMembershipSchema, diff --git a/packages/shared/src/validators/recent-tasks.ts b/packages/shared/src/validators/recent-tasks.ts new file mode 100644 index 00000000000..8664fd1e88e --- /dev/null +++ b/packages/shared/src/validators/recent-tasks.ts @@ -0,0 +1,21 @@ +import { z } from "zod"; +import { RECENT_TASKS_MAX_ENTRIES } from "../types/recent-tasks.js"; + +export const recordRecentTaskSchema = z.object({ + issueId: z.string().uuid(), + /** + * true moves the task to the top of Recents (an explicit visit or action). + * false only adds the task below existing history when it is not there yet. + */ + touch: z.boolean().default(true), +}); + +export const importRecentTasksSchema = z.object({ + entries: z.array(z.object({ + issueId: z.string().uuid(), + recordedAt: z.string().datetime({ offset: true }), + })).max(RECENT_TASKS_MAX_ENTRIES), +}); + +export type RecordRecentTask = z.input; +export type ImportRecentTasks = z.infer; diff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.ts index 1fd34deded5..5e24511c3cb 100644 --- a/server/src/__tests__/live-events-toast.test.ts +++ b/server/src/__tests__/live-events-toast.test.ts @@ -239,6 +239,43 @@ describe("authenticated activity notifications", () => { } }); + it("delivers personal Recents receipts only to the owner's connections, without details", async () => { + const server = createServer(); + setupLiveEventsWebSocketServer(server, database() as never, { + deploymentMode: "authenticated", + resolveCloudActor: async (req) => ({ userId: String(req.headers["x-test-viewer"]), companyIds: ["company"] }), + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const url = `ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`; + const alice = new WebSocket(url, { headers: { "x-test-viewer": "alice" } }); + const bob = new WebSocket(url, { headers: { "x-test-viewer": "bob" } }); + try { + await Promise.all([once(alice, "open"), once(bob, "open")]); + const bobMessages: unknown[] = []; + bob.on("message", (data) => bobMessages.push(JSON.parse(data.toString()))); + const aliceMessage = once(alice, "message"); + publishLiveEvent({ companyId: "company", type: "activity.logged", payload: { + action: "recent_tasks.recorded", entityType: "company", entityId: "company", + actorType: "user", actorId: "alice", details: { userId: "alice" }, + } }); + const [data] = await aliceMessage; + expect(JSON.parse(data.toString()).payload).toEqual({ action: "recent_tasks.recorded", entityType: "company", entityId: "company" }); + // A later event for Bob proves the earlier one was withheld, not just slow. + const bobMessage = once(bob, "message"); + publishLiveEvent({ companyId: "company", type: "activity.logged", payload: { + action: "recent_tasks.removed", entityType: "company", entityId: "company", + actorType: "user", actorId: "bob", details: { userId: "bob" }, + } }); + await bobMessage; + expect(bobMessages).toHaveLength(1); + expect(bobMessages[0]).toMatchObject({ payload: { action: "recent_tasks.removed" } }); + } finally { + alice.terminate(); bob.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + it("uses the persisted local-board user identity for local task eligibility", async () => { vi.mocked(taskToastEligible).mockImplementation(async (_db, _event, userId) => userId === "local-board"); const server = createServer(); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 8927ad02732..21c7ae14aca 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -105,6 +105,7 @@ const apiPrefixes: Record = { "secrets.ts": "/api", "sidebar-badges.ts": "/api", "sidebar-preferences.ts": "/api", + "recent-tasks.ts": "/api", "summary-slots.ts": "/api", "status-cards.ts": "/api", "tailscale-connections.ts": "/api", diff --git a/server/src/__tests__/recent-tasks-routes.test.ts b/server/src/__tests__/recent-tasks-routes.test.ts new file mode 100644 index 00000000000..04fb150a17e --- /dev/null +++ b/server/src/__tests__/recent-tasks-routes.test.ts @@ -0,0 +1,213 @@ +import { randomUUID } from "node:crypto"; +import request from "supertest"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, expect, it } from "vitest"; +import { activityLog, companyMemberships, issues, userRecentTasks } from "@paperclipai/db"; +import { RECENT_TASKS_MAX_ENTRIES } from "@paperclipai/shared"; +import { recentTaskRoutes } from "../routes/recent-tasks.js"; +import { subscribeCompanyLiveEvents } from "../services/live-events.js"; +import { + describeEmbeddedPostgres, + routeApp, + seedCompanyWithBoardAccess, + useEmbeddedPostgres, + type BoardActor, +} from "./helpers/route-test-harness.js"; + +describeEmbeddedPostgres("server-side Recents", () => { + const ctx = useEmbeddedPostgres("paperclip-recent-tasks-"); + const oldPrivacy = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE; + beforeAll(() => { process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce"; }); + afterAll(() => { + if (oldPrivacy === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE; + else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = oldPrivacy; + }); + + async function fixture() { + const company = await seedCompanyWithBoardAccess(ctx.db, "Recents"); + const rows = await ctx.db.insert(issues).values( + ["One", "Two", "Three"].map((title) => ({ companyId: company.companyId, title, status: "todo" })), + ).returning(); + return { ...company, rows }; + } + const url = (companyId: string) => `/api/companies/${companyId}/recent-tasks/me`; + const app = (actor: BoardActor) => routeApp(ctx.db, actor, recentTaskRoutes); + + it("shares one list across clients of the same person, newest first", async () => { + const f = await fixture(); + const [one, two] = f.rows; + // Two separate clients of the same account. + const laptop = app(f.actor); + const phone = app(f.actor); + + expect((await request(laptop).post(url(f.companyId)).send({ issueId: one!.id })).status).toBe(200); + expect((await request(phone).post(url(f.companyId)).send({ issueId: two!.id })).status).toBe(200); + + const fromLaptop = await request(laptop).get(url(f.companyId)); + const fromPhone = await request(phone).get(url(f.companyId)); + expect(fromLaptop.status).toBe(200); + expect(fromLaptop.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([two!.id, one!.id]); + expect(fromPhone.body).toEqual(fromLaptop.body); + + // Touching an older task on one client moves it to the top on every client. + await request(phone).post(url(f.companyId)).send({ issueId: one!.id, touch: true }); + const after = await request(laptop).get(url(f.companyId)); + expect(after.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([one!.id, two!.id]); + }); + + it("places a passive task by its last update and never moves an existing one", async () => { + const f = await fixture(); + const [one, two, three] = f.rows; + const client = app(f.actor); + await request(client).post(url(f.companyId)).send({ issueId: one!.id, touch: true }); + await request(client).post(url(f.companyId)).send({ issueId: two!.id, touch: true }); + const list = async () => (await request(client).get(url(f.companyId))).body.entries + .map((entry: { issueId: string }) => entry.issueId); + const [twoAt, oneAt] = (await request(client).get(url(f.companyId))).body.entries + .map((entry: { recordedAt: string }) => new Date(entry.recordedAt).getTime()); + + // Last updated between the two visits: it slots in between, not at the top. + await ctx.db.update(issues).set({ updatedAt: new Date((oneAt + twoAt) / 2) }).where(eq(issues.id, three!.id)); + const seeded = await request(client).post(url(f.companyId)).send({ issueId: three!.id, touch: false }); + expect(seeded.body.entry.issueId).toBe(three!.id); + expect(await list()).toEqual([two!.id, three!.id, one!.id]); + + // Opening an existing task passively keeps the order. + const repeated = await request(client).post(url(f.companyId)).send({ issueId: one!.id, touch: false }); + expect(repeated.body.entry).toBeNull(); + expect(await list()).toEqual([two!.id, three!.id, one!.id]); + }); + + it("adds a passive task updated before all history at the bottom", async () => { + const f = await fixture(); + const [one, two] = f.rows; + const client = app(f.actor); + await ctx.db.update(issues).set({ updatedAt: new Date(1_000) }).where(eq(issues.id, two!.id)); + await request(client).post(url(f.companyId)).send({ issueId: one!.id, touch: true }); + await request(client).post(url(f.companyId)).send({ issueId: two!.id, touch: false }); + const list = await request(client).get(url(f.companyId)); + expect(list.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([one!.id, two!.id]); + }); + + it("keeps Recents personal and company-scoped", async () => { + const f = await fixture(); + const other = await fixture(); + const [one] = f.rows; + await request(app(f.actor)).post(url(f.companyId)).send({ issueId: one!.id }); + + // Another member of the same company has their own list. + const teammateId = `user-${randomUUID()}`; + await ctx.db.insert(companyMemberships).values({ + companyId: f.companyId, principalType: "user", principalId: teammateId, status: "active", membershipRole: "owner", updatedAt: new Date(), + }); + const teammate: BoardActor = { ...f.actor, userId: teammateId }; + expect((await request(app(teammate)).get(url(f.companyId))).body.entries).toEqual([]); + + // A task from another company cannot be recorded, and the other company is not readable. + const foreign = await request(app(f.actor)).post(url(f.companyId)).send({ issueId: other.rows[0]!.id }); + expect(foreign.status).toBe(404); + expect((await request(app(f.actor)).get(url(other.companyId))).status).toBe(403); + + // A read-only viewer still keeps their own Recents. + const viewerId = `user-${randomUUID()}`; + await ctx.db.insert(companyMemberships).values({ + companyId: f.companyId, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer", updatedAt: new Date(), + }); + const viewer: BoardActor = { ...f.actor, userId: viewerId, memberships: [{ companyId: f.companyId, membershipRole: "viewer", status: "active" }] }; + expect((await request(app(viewer)).post(url(f.companyId)).send({ issueId: one!.id })).status).toBe(200); + expect((await request(app(viewer)).get(url(f.companyId))).body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([one!.id]); + // A suspended member cannot change Recents. + const suspended: BoardActor = { ...f.actor, memberships: [{ companyId: f.companyId, membershipRole: "owner", status: "suspended" }] }; + expect((await request(app(suspended)).post(url(f.companyId)).send({ issueId: one!.id })).status).toBe(403); + + // Agents have no personal Recents. + const agentApp = routeApp(ctx.db, { type: "agent", agentId: randomUUID(), companyId: f.companyId } as never, recentTaskRoutes); + expect((await request(agentApp).get(url(f.companyId))).status).toBe(403); + }); + + it("never stores, returns, or confirms a task the caller cannot read", async () => { + const f = await fixture(); + const privateId = randomUUID(); + await ctx.db.insert(issues).values({ + id: privateId, companyId: f.companyId, title: "Private", visibility: "private", privacyRootIssueId: privateId, + responsibleUserId: "someone-else", createdByUserId: "someone-else", + }); + const client = app(f.actor); + // The same 404 as a task that does not exist. + const privateRes = await request(client).post(url(f.companyId)).send({ issueId: privateId }); + const missingRes = await request(client).post(url(f.companyId)).send({ issueId: randomUUID() }); + expect(privateRes.status).toBe(404); + expect(privateRes.body).toEqual(missingRes.body); + + const imported = await request(client).post(`${url(f.companyId)}/import`).send({ + entries: [ + { issueId: privateId, recordedAt: new Date(2_000).toISOString() }, + { issueId: f.rows[0]!.id, recordedAt: new Date(1_000).toISOString() }, + ], + }); + expect(imported.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([f.rows[0]!.id]); + + // A row that becomes unreadable later is not returned. + await ctx.db.insert(userRecentTasks).values({ companyId: f.companyId, userId: f.userId, issueId: privateId, recordedAt: new Date() }); + const list = await request(client).get(url(f.companyId)); + expect(list.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([f.rows[0]!.id]); + }); + + it("removes a task, logs each change, and tells only the owner's clients to refresh", async () => { + const f = await fixture(); + const [one] = f.rows; + const events: Array<{ type: string; payload: Record }> = []; + const unsubscribe = subscribeCompanyLiveEvents(f.companyId, (event) => events.push(event as never)); + try { + await request(app(f.actor)).post(url(f.companyId)).send({ issueId: one!.id }); + const removed = await request(app(f.actor)).delete(`${url(f.companyId)}/${one!.id}`); + expect(removed.status).toBe(204); + expect((await request(app(f.actor)).get(url(f.companyId))).body.entries).toEqual([]); + // Removing again changes nothing and logs nothing. + expect((await request(app(f.actor)).delete(`${url(f.companyId)}/${one!.id}`)).status).toBe(204); + expect((await request(app(f.actor)).delete(`${url(f.companyId)}/not-a-uuid`)).status).toBe(400); + } finally { + unsubscribe(); + } + const logged = await ctx.db.select({ action: activityLog.action, entityType: activityLog.entityType, details: activityLog.details }) + .from(activityLog).where(eq(activityLog.companyId, f.companyId)); + expect(logged.map((row) => row.action).sort()).toEqual(["recent_tasks.recorded", "recent_tasks.removed"]); + // The company feed never names the task someone opened. + expect(logged.every((row) => row.entityType === "company" && (row.details as { userId?: string }).userId === f.userId)).toBe(true); + expect(JSON.stringify(logged)).not.toContain(one!.id); + const published = events.filter((event) => event.type === "activity.logged").map((event) => event.payload.action); + expect(published).toEqual(["recent_tasks.recorded", "recent_tasks.removed"]); + }); + + it("imports a browser list once, keeps later times, and caps the list", async () => { + const f = await fixture(); + const [one, two] = f.rows; + const client = app(f.actor); + await request(client).post(url(f.companyId)).send({ issueId: one!.id }); + + const imported = await request(client).post(`${url(f.companyId)}/import`).send({ + entries: [ + { issueId: one!.id, recordedAt: new Date(1_000).toISOString() }, + { issueId: two!.id, recordedAt: new Date(2_000).toISOString() }, + { issueId: randomUUID(), recordedAt: new Date(3_000).toISOString() }, + ], + }); + expect(imported.status).toBe(200); + // The later server time for `one` wins; the unknown task is ignored. + expect(imported.body.entries.map((entry: { issueId: string }) => entry.issueId)).toEqual([one!.id, two!.id]); + + const many = await ctx.db.insert(issues).values(Array.from({ length: RECENT_TASKS_MAX_ENTRIES }, (_, index) => ({ + companyId: f.companyId, title: `Bulk ${index}`, status: "todo", + }))).returning({ id: issues.id }); + await request(client).post(`${url(f.companyId)}/import`).send({ + entries: many.map((row, index) => ({ issueId: row.id, recordedAt: new Date(10_000 + index).toISOString() })), + }); + const stored = await ctx.db.select({ issueId: userRecentTasks.issueId }).from(userRecentTasks) + .where(and(eq(userRecentTasks.companyId, f.companyId), eq(userRecentTasks.userId, f.userId))); + expect(stored).toHaveLength(RECENT_TASKS_MAX_ENTRIES); + // The newest (server-time) entry survives the cap; the oldest import does not. + const ids = new Set(stored.map((row) => row.issueId)); + expect(ids.has(one!.id)).toBe(true); + expect(ids.has(two!.id)).toBe(false); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index 667802fe65a..91e9f7d2029 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -189,6 +189,7 @@ import type { DecisionServiceOptions } from "./services/decisions.js"; import { userProfileRoutes } from "./routes/user-profiles.js"; import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js"; import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js"; +import { recentTaskRoutes } from "./routes/recent-tasks.js"; import { announcementRoutes } from "./routes/announcements.js"; import { serverVersion } from "./version.js"; import { workspacePreferenceRoutes } from "./routes/workspace-preferences.js"; @@ -970,6 +971,7 @@ export async function createApp( api.use(userProfileRoutes(db)); api.use(sidebarBadgeRoutes(db)); api.use(sidebarPreferenceRoutes(db)); + api.use(recentTaskRoutes(db)); api.use(announcementRoutes(db, { ...opts.announcements, version: opts.hostVersion ?? serverVersion })); api.use(resourceMembershipRoutes(db)); api.use(primaryAgentRoutes(db)); diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index c1f28549721..b515cc44b2d 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -290,6 +290,17 @@ export function setupLiveEventsWebSocketServer( async function visibleEvent(event: LiveEvent, reads: LiveDeliveryReads): Promise { if (event.payload.entityType === "case" && (typeof event.payload.entityId !== "string" || !(await canActorReadCase(db, context!.actor, { id: event.payload.entityId, companyId: event.companyId })))) return null; + if (event.type === "activity.logged" && String(event.payload.action ?? "").startsWith("recent_tasks.")) { + // Recents receipts are personal: only the owner's connections receive + // them, with no details, so the owner's other clients refetch the list. + const details = event.payload.details && typeof event.payload.details === "object" && !Array.isArray(event.payload.details) + ? event.payload.details as Record : {}; + const viewerId = context!.actor.type === "board" ? context!.actor.userId : null; + if (!viewerId || details.userId !== viewerId) return null; + return { ...event, payload: { + action: event.payload.action, entityType: event.payload.entityType, entityId: event.payload.entityId, + } }; + } if (context!.actor.source === "local_implicit") { if (event.type === "activity.logged" && event.payload.entityType === "issue") { const identity = await readActivityIdentity(event); diff --git a/server/src/routes/index.ts b/server/src/routes/index.ts index d8e6d325ba5..90136be4ada 100644 --- a/server/src/routes/index.ts +++ b/server/src/routes/index.ts @@ -43,6 +43,7 @@ export { decisionRoutes } from "./decisions.js"; export { decisionQueueRoutes } from "./decision-queues.js"; export { sidebarBadgeRoutes } from "./sidebar-badges.js"; export { sidebarPreferenceRoutes } from "./sidebar-preferences.js"; +export { recentTaskRoutes } from "./recent-tasks.js"; export { resourceMembershipRoutes } from "./resource-memberships.js"; export { inboxDismissalRoutes } from "./inbox-dismissals.js"; export { llmRoutes } from "./llms.js"; diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index a9b91695b5e..1c507249226 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -194,6 +194,8 @@ import { adjustCostSchema, // Sidebar upsertSidebarOrderPreferenceSchema, + recordRecentTaskSchema, + importRecentTasksSchema, // Announcements announcementIdSchema, announcementSchema, @@ -7540,6 +7542,48 @@ registry.registerPath({ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized }, }); +registry.registerPath({ + method: "get", + path: "/api/companies/{companyId}/recent-tasks/me", + tags: ["sidebar"], + summary: "List your sidebar Recents for a company, newest first", + request: { params: z.object({ companyId: z.string() }) }, + responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden }, +}); + +registry.registerPath({ + method: "post", + path: "/api/companies/{companyId}/recent-tasks/me", + tags: ["sidebar"], + summary: "Record a task in your sidebar Recents", + request: { + params: z.object({ companyId: z.string() }), + body: jsonBody(recordRecentTaskSchema), + }, + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + +registry.registerPath({ + method: "post", + path: "/api/companies/{companyId}/recent-tasks/me/import", + tags: ["sidebar"], + summary: "Import Recents that a browser kept locally", + request: { + params: z.object({ companyId: z.string() }), + body: jsonBody(importRecentTasksSchema), + }, + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden }, +}); + +registry.registerPath({ + method: "delete", + path: "/api/companies/{companyId}/recent-tasks/me/{issueId}", + tags: ["sidebar"], + summary: "Remove a task from your sidebar Recents", + request: { params: z.object({ companyId: z.string(), issueId: z.string() }) }, + responses: { 204: r.noContent, 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden }, +}); + const primaryAgentPreferenceResponse = z.object({ companyId: z.string().uuid(), userId: z.string(), diff --git a/server/src/routes/recent-tasks.ts b/server/src/routes/recent-tasks.ts new file mode 100644 index 00000000000..f11efaa6919 --- /dev/null +++ b/server/src/routes/recent-tasks.ts @@ -0,0 +1,167 @@ +import { Router, type Request, type Response } from "express"; +import { and, eq, inArray } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { issues } from "@paperclipai/db"; +import { importRecentTasksSchema, recordRecentTaskSchema } from "@paperclipai/shared"; +import { validate } from "../middleware/validate.js"; +import { forbidden } from "../errors.js"; +import { accessService, logActivity, recentTaskService } from "../services/index.js"; +import { dashboardConversationReadable } from "../services/responsibility-privacy.js"; +import { assertBoard, assertCompanyAccess, getActorInfo, hasCompanyAccess } from "./authz.js"; + +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function requireBoardUserId(req: Request, res: Response): string | null { + assertBoard(req); + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return null; + } + return req.actor.userId; +} + +/** + * Recents are personal navigation state, like workspace preferences: an active + * member may change their own list without write access to company data, so + * viewers keep Recents too. + */ +function assertPersonalCompanyAccess(req: Request, companyId: string) { + // API keys keep the full company rules, including scoped-key restrictions. + if (req.actor.type === "board" && req.actor.source === "board_key") { + assertCompanyAccess(req, companyId); + return; + } + if (!hasCompanyAccess(req, companyId)) throw forbidden("User does not have access to this company"); + if (req.actor.type === "board" && req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin + && Array.isArray(req.actor.memberships) + && !req.actor.memberships.some((member) => member.companyId === companyId && member.status === "active")) { + throw forbidden("User does not have active company access"); + } +} + +/** Personal sidebar Recents, kept on the server so every client shows the same list. */ +export function recentTaskRoutes(db: Db) { + const router = Router(); + const svc = recentTaskService(db); + const access = accessService(db); + + /** + * The task IDs the caller may read, with the same rules as task reads + * (private tasks, personal conversations). Recents never stores, returns, + * or confirms a task the caller cannot read. + */ + async function readableIssueIds(req: Request, companyId: string, ids: readonly string[]) { + const unique = [...new Set(ids)]; + if (unique.length === 0) return new Set(); + const rows = await db.select({ + id: issues.id, + companyId: issues.companyId, + projectId: issues.projectId, + parentId: issues.parentId, + assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId, + status: issues.status, + originKind: issues.originKind, + originId: issues.originId, + responsibleUserId: issues.responsibleUserId, + }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, unique))); + const decisions = await access.decideReads(req.actor, rows.map((row) => ({ + type: "issue" as const, + companyId: row.companyId, + issueId: row.id, + projectId: row.projectId, + parentIssueId: row.parentId, + assigneeAgentId: row.assigneeAgentId, + assigneeUserId: row.assigneeUserId, + status: row.status, + }))); + return new Set(rows.filter((row, index) => decisions[index]?.allowed && dashboardConversationReadable(req.actor, row)) + .map((row) => row.id)); + } + + async function readableList(req: Request, companyId: string, userId: string) { + const list = await svc.list(companyId, userId); + const readable = await readableIssueIds(req, companyId, list.entries.map((entry) => entry.issueId)); + return { entries: list.entries.filter((entry) => readable.has(entry.issueId)) }; + } + + async function logChange( + req: Request, + companyId: string, + action: "recent_tasks.recorded" | "recent_tasks.imported" | "recent_tasks.removed", + details: Record, + ) { + const actor = getActorInfo(req); + // A company entry keeps these personal navigation receipts out of task + // activity. It never names a task, so the company activity feed cannot + // reveal which (possibly private) task someone opened. The live event + // reaches only the owner's clients (see live-events-ws). + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + agentApiKeyId: actor.agentApiKeyId, + action, + entityType: "company", + entityId: companyId, + details, + }); + } + + router.get("/companies/:companyId/recent-tasks/me", async (req, res) => { + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + res.setHeader("Cache-Control", "private, no-store"); + res.json(await readableList(req, companyId, userId)); + }); + + router.post("/companies/:companyId/recent-tasks/me", validate(recordRecentTaskSchema), async (req, res) => { + const companyId = req.params.companyId as string; + assertPersonalCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + const { issueId, touch } = req.body as { issueId: string; touch: boolean }; + // One 404 for missing, cross-company, and unreadable tasks: no existence oracle. + if (!(await readableIssueIds(req, companyId, [issueId])).has(issueId)) { + res.status(404).json({ error: "Issue not found" }); + return; + } + const entry = await svc.record(companyId, userId, issueId, touch); + if (entry) await logChange(req, companyId, "recent_tasks.recorded", { userId }); + res.json({ entry }); + }); + + router.post("/companies/:companyId/recent-tasks/me/import", validate(importRecentTasksSchema), async (req, res) => { + const companyId = req.params.companyId as string; + assertPersonalCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + const entries = req.body.entries as Array<{ issueId: string; recordedAt: string }>; + // Unknown and unreadable tasks are skipped alike. + const readable = await readableIssueIds(req, companyId, entries.map((entry) => entry.issueId)); + const imported = await svc.importEntries(companyId, userId, entries.filter((entry) => readable.has(entry.issueId))); + if (imported > 0) await logChange(req, companyId, "recent_tasks.imported", { userId, count: imported }); + res.json(await readableList(req, companyId, userId)); + }); + + router.delete("/companies/:companyId/recent-tasks/me/:issueId", async (req, res) => { + const companyId = req.params.companyId as string; + assertPersonalCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + const issueId = req.params.issueId as string; + if (!UUID_PATTERN.test(issueId)) { + res.status(400).json({ error: "issueId must be a UUID" }); + return; + } + const removed = await svc.remove(companyId, userId, issueId); + if (removed) await logChange(req, companyId, "recent_tasks.removed", { userId }); + res.status(204).end(); + }); + + return router; +} diff --git a/server/src/services/index.ts b/server/src/services/index.ts index 82bf138bf77..b87b704297c 100644 --- a/server/src/services/index.ts +++ b/server/src/services/index.ts @@ -120,6 +120,7 @@ export { classifyIssueGraphLiveness, type IssueLivenessFinding } from "./recover export { dashboardService } from "./dashboard.js"; export { sidebarBadgeService } from "./sidebar-badges.js"; export { sidebarPreferenceService } from "./sidebar-preferences.js"; +export { recentTaskService } from "./recent-tasks.js"; export { resourceMembershipService, type ResourceMembershipPolicyHook } from "./resource-memberships.js"; export { inboxDismissalService } from "./inbox-dismissals.js"; export { accessService } from "./access.js"; diff --git a/server/src/services/recent-tasks.ts b/server/src/services/recent-tasks.ts new file mode 100644 index 00000000000..0fc6bd67131 --- /dev/null +++ b/server/src/services/recent-tasks.ts @@ -0,0 +1,144 @@ +import { and, desc, eq, inArray, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { issues, userRecentTasks } from "@paperclipai/db"; +import { RECENT_TASKS_MAX_ENTRIES, type RecentTaskList, type RecentTaskRecord } from "@paperclipai/shared"; + +type RecentTaskRow = { issueId: string; recordedAt: Date }; + +function toRecord(row: RecentTaskRow): RecentTaskRecord { + return { issueId: row.issueId, recordedAt: row.recordedAt.toISOString() }; +} + +/** + * A person's sidebar Recents for one company. The server keeps the list so + * every client shows the same tasks in the same order. Eligibility (whether a + * row is shown) is judged by navigation summaries, not here. + */ +export function recentTaskService(db: Db) { + const scope = (companyId: string, userId: string) => and( + eq(userRecentTasks.companyId, companyId), + eq(userRecentTasks.userId, userId), + ); + + async function trim(companyId: string, userId: string) { + const keep = db + .select({ id: userRecentTasks.id }) + .from(userRecentTasks) + .where(scope(companyId, userId)) + .orderBy(desc(userRecentTasks.recordedAt), desc(userRecentTasks.id)) + .limit(RECENT_TASKS_MAX_ENTRIES); + await db.delete(userRecentTasks).where(and( + scope(companyId, userId), + sql`${userRecentTasks.id} NOT IN (${keep})`, + )); + } + + async function belowOldest(companyId: string, userId: string, now: Date): Promise { + const [oldest] = await db + .select({ recordedAt: sql`MIN(${userRecentTasks.recordedAt})` }) + .from(userRecentTasks) + .where(scope(companyId, userId)); + const oldestAt = oldest?.recordedAt ? new Date(oldest.recordedAt).getTime() : NaN; + return Number.isFinite(oldestAt) ? Math.min(now.getTime(), oldestAt - 1) : now.getTime(); + } + + return { + async list(companyId: string, userId: string): Promise { + const rows = await db + .select({ issueId: userRecentTasks.issueId, recordedAt: userRecentTasks.recordedAt }) + .from(userRecentTasks) + .where(scope(companyId, userId)) + .orderBy(desc(userRecentTasks.recordedAt), desc(userRecentTasks.id)) + .limit(RECENT_TASKS_MAX_ENTRIES); + return { entries: rows.map(toRecord) }; + }, + + /** + * Records a task. `touch` moves it to the top; otherwise a missing task is + * placed by the task's last update (or below all history when that is + * unknown) and an existing task does not move. + * Returns null when nothing changed. + */ + async record(companyId: string, userId: string, issueId: string, touch: boolean): Promise { + const now = new Date(); + if (touch) { + const [row] = await db + .insert(userRecentTasks) + .values({ companyId, userId, issueId, recordedAt: now, updatedAt: now }) + .onConflictDoUpdate({ + target: [userRecentTasks.companyId, userRecentTasks.userId, userRecentTasks.issueId], + set: { recordedAt: now, updatedAt: now }, + }) + .returning({ issueId: userRecentTasks.issueId, recordedAt: userRecentTasks.recordedAt }); + await trim(companyId, userId); + return row ? toRecord(row) : null; + } + // A passive seed never jumps to the top: it goes where the task's own + // last update puts it, so opening an unseen task does not re-sort Recents. + const [issue] = await db + .select({ updatedAt: issues.updatedAt }) + .from(issues) + .where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))); + const activityAt = issue?.updatedAt ? new Date(issue.updatedAt).getTime() : NaN; + const recordedAt = new Date(Number.isFinite(activityAt) && activityAt > 0 + ? Math.min(now.getTime(), activityAt) + : await belowOldest(companyId, userId, now)); + const [row] = await db + .insert(userRecentTasks) + .values({ companyId, userId, issueId, recordedAt, updatedAt: now }) + .onConflictDoNothing({ + target: [userRecentTasks.companyId, userRecentTasks.userId, userRecentTasks.issueId], + }) + .returning({ issueId: userRecentTasks.issueId, recordedAt: userRecentTasks.recordedAt }); + if (row) await trim(companyId, userId); + return row ? toRecord(row) : null; + }, + + /** + * Imports a list that a browser kept before Recents moved to the server. + * Tasks outside the company are ignored. An existing row keeps the later + * of the two times, so an import never moves a task down. + */ + async importEntries( + companyId: string, + userId: string, + entries: ReadonlyArray<{ issueId: string; recordedAt: string }>, + ): Promise { + const latest = new Map(); + const now = Date.now(); + for (const entry of entries) { + const at = new Date(Math.min(new Date(entry.recordedAt).getTime(), now)); + if (!Number.isFinite(at.getTime())) continue; + const current = latest.get(entry.issueId); + if (!current || current < at) latest.set(entry.issueId, at); + } + if (latest.size === 0) return 0; + const known = await db + .select({ id: issues.id }) + .from(issues) + .where(and(eq(issues.companyId, companyId), inArray(issues.id, [...latest.keys()]))); + if (known.length === 0) return 0; + const updatedAt = new Date(); + await db + .insert(userRecentTasks) + .values(known.map(({ id }) => ({ companyId, userId, issueId: id, recordedAt: latest.get(id)!, updatedAt }))) + .onConflictDoUpdate({ + target: [userRecentTasks.companyId, userRecentTasks.userId, userRecentTasks.issueId], + set: { + recordedAt: sql`GREATEST(${userRecentTasks.recordedAt}, excluded.recorded_at)`, + updatedAt, + }, + }); + await trim(companyId, userId); + return known.length; + }, + + async remove(companyId: string, userId: string, issueId: string): Promise { + const rows = await db + .delete(userRecentTasks) + .where(and(scope(companyId, userId), eq(userRecentTasks.issueId, issueId))) + .returning({ id: userRecentTasks.id }); + return rows.length > 0; + }, + }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index d4e66104f39..d53f51a7381 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -290,7 +290,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "6dd91e7caab503a5509cde3dbf01f92998fae253", + "packages/shared/src/index.ts": "7bf44c1301810437c498310577d3fe62206505b5", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -460,7 +460,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428", + "packages/shared/src/types/index.ts": "66574aca258c08267c036a747cb16669b9fedfd4", "packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "c926a6a56874b18b3a61e22defaf9aca54172ca7", @@ -469,6 +469,7 @@ "packages/shared/src/types/plugin.ts": "b347626917795b3c343d609426ee52d030b4b427", "packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", + "packages/shared/src/types/recent-tasks.ts": "03125eb32ba60dfb07cec1ebb064f412286938f6", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", "packages/shared/src/types/responsibility.ts": "a2b1dc01cefaf3e1a495f9035b7bd0293469bc57", "packages/shared/src/types/routine.ts": "6b2f2fd27187c19f98afe99f926460ded2752f20", @@ -540,7 +541,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "0739d0fdc6aa48a681def520bb28b22b91f7aca3", + "packages/shared/src/validators/index.ts": "da4f0ba5ada6714241599bac06172ecf3c2d2ef3", "packages/shared/src/validators/instance.test.ts": "a8eac3e9a6eed97d6aa4f54e14e77c44720600af", "packages/shared/src/validators/instance.ts": "9cfe716ebf4dc1e24324e162ca096cdacbe97c4a", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", @@ -556,6 +557,7 @@ "packages/shared/src/validators/plugin.ts": "d1538168a6ad800cf537a1449aa7d457c6701d60", "packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219", "packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82", + "packages/shared/src/validators/recent-tasks.ts": "8664fd1e88ec1c8060ef1a867cef925fb961982d", "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", "packages/shared/src/validators/responsibility.ts": "7c61a734fca7cfb23ea386a82bf0bef0ef438819", "packages/shared/src/validators/routine.test.ts": "1501907ade577c1ab4c4b3098397e5d080446878", diff --git a/ui/src/api/index.ts b/ui/src/api/index.ts index f73368a5eee..6b36fd7b0a2 100644 --- a/ui/src/api/index.ts +++ b/ui/src/api/index.ts @@ -18,6 +18,7 @@ export { heartbeatsApi } from "./heartbeats"; export { instanceSettingsApi } from "./instanceSettings"; export { sidebarBadgesApi } from "./sidebarBadges"; export { sidebarPreferencesApi } from "./sidebarPreferences"; +export { recentTasksApi } from "./recentTasks"; export { resourceMembershipsApi } from "./resourceMemberships"; export { inboxDismissalsApi } from "./inboxDismissals"; export { companySkillsApi } from "./companySkills"; diff --git a/ui/src/api/recentTasks.ts b/ui/src/api/recentTasks.ts new file mode 100644 index 00000000000..e9eff86369b --- /dev/null +++ b/ui/src/api/recentTasks.ts @@ -0,0 +1,15 @@ +import type { ImportRecentTasks, RecentTaskList, RecentTaskRecord, RecordRecentTask } from "@paperclipai/shared"; +import { api } from "./client"; + +const base = (companyId: string) => `/companies/${encodeURIComponent(companyId)}/recent-tasks/me`; + +export const recentTasksApi = { + list: (companyId: string, options?: { signal?: AbortSignal }) => + api.get(base(companyId), options), + record: (companyId: string, data: RecordRecentTask) => + api.post<{ entry: RecentTaskRecord | null }>(base(companyId), data), + importEntries: (companyId: string, data: ImportRecentTasks) => + api.post(`${base(companyId)}/import`, data), + remove: (companyId: string, issueId: string) => + api.delete(`${base(companyId)}/${encodeURIComponent(issueId)}`), +}; diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsx index 60c5eba140f..bed018a6a37 100644 --- a/ui/src/components/SidebarRecentTasks.tsx +++ b/ui/src/components/SidebarRecentTasks.tsx @@ -9,8 +9,8 @@ import { useRecentTaskOpenWarmup } from "@/hooks/useRecentTaskOpenWarmup"; import { useAccountIdentity } from "@/api/companies-query"; import { useOptionalToastActions } from "@/context/ToastContext"; import { - pruneRecentTasks, recordRecentTask, + removeRecentTask, type RecentTaskEntry, } from "@/lib/recent-tasks"; import { Button } from "@/components/ui/button"; @@ -101,7 +101,7 @@ function RecentTasksList({ userId: string | null; liveIssueIds: ReadonlySet; }) { - const { entries, storageKey } = useRecentTasks({ companyId, userId }); + const { entries } = useRecentTasks({ companyId, userId }); const { pathname } = useLocation(); const queryClient = useQueryClient(); const toastActions = useOptionalToastActions(); @@ -157,7 +157,7 @@ function RecentTasksList({ setPendingAction("archive"); try { await issuesApi.archiveFromInbox(entry.id); - if (storageKey) pruneRecentTasks(storageKey, companyId, new Set([entry.id])); + removeRecentTask(companyId, entry.id, userId); await refreshIssueQueries(entry.id); await queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId), diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index 224dd395a8c..cd477ad2261 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -913,6 +913,27 @@ describe("LiveUpdatesProvider issue invalidation", () => { } }); + it("refreshes server-side Recents only on the owner's clients", () => { + const client = new QueryClient(); + const recentsKey = queryKeys.recentTasks.list("company-1", "user-1"); + const badgesKey = queryKeys.sidebarBadges("company-1"); + client.setQueryData(recentsKey, { entries: [] }); + client.setQueryData(badgesKey, {}); + const event = (userId: string) => ({ + entityType: "company", entityId: "company-1", action: "recent_tasks.recorded", + actorType: "user", actorId: userId, details: { userId, issueId: "issue-1" }, + }); + + __liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", event("user-2"), { userId: "user-1", agentId: null }); + expect(client.getQueryState(recentsKey)?.isInvalidated).toBe(false); + + __liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", event("user-1"), { userId: "user-1", agentId: null }); + expect(client.getQueryState(recentsKey)?.isInvalidated).toBe(true); + // Personal navigation receipts do not refresh shared company views. + expect(client.getQueryState(badgesKey)?.isInvalidated).toBe(false); + client.clear(); + }); + it.each(["issue.comment_added", "issue.read_marked"])("does not refresh case work for %s", (action) => { const client = new QueryClient(); const detailKey = queryKeys.cases.detail("case-1"); diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 5848887a169..abddc72d21b 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -1651,6 +1651,16 @@ function invalidateActivityQueries( const details = readRecord(payload.details); const subtaskParents = Array.isArray(payload.recentSubtaskParentIds) ? payload.recentSubtaskParentIds.filter((id): id is string => typeof id === "string") : undefined; + if (action?.startsWith("recent_tasks.")) { + // Recents are personal and kept on the server. The live socket delivers + // these events only to the owner's connections and strips details; a + // payload that still names another person is not for this client. + const ownerId = readString(details?.userId); + if (!ownerId || ownerId === (currentActor.userId ?? "local-board")) { + queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks.all(companyId) }); + } + return; + } queryClient.invalidateQueries({ queryKey: queryKeys.activity(companyId) }); if (entityType === "issue" && (action === "issue.read_marked" || action === "issue.read_unmarked")) { // Audit views show read receipts, while unread state belongs to one person. diff --git a/ui/src/hooks/useRecentTasks.test.tsx b/ui/src/hooks/useRecentTasks.test.tsx index 74439fc5517..b65e16209d1 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -12,13 +12,56 @@ import { readRecentTasks, recordRecentTask, recordStartedRoutineRunTask, - settleRecentTaskVisit, - RECENT_TASKS_UPDATED_EVENT, + removeRecentTask, + resetRecentTasksForTests, } from "@/lib/recent-tasks"; import { RECENT_TASK_SUMMARY_CONCURRENCY, useRecentTasks } from "./useRecentTasks"; -const { getIssue, summaries } = vi.hoisted(() => ({ getIssue: vi.fn(), summaries: vi.fn() })); +const { getIssue, summaries, server } = vi.hoisted(() => { + /** A fake of the server-side Recents store, keyed by company. */ + const rows = new Map>(); + let clock = 1_000; + const scope = (companyId: string) => { + let value = rows.get(companyId); + if (!value) rows.set(companyId, value = new Map()); + return value; + }; + const list = (companyId: string) => ({ + entries: [...scope(companyId).entries()].sort((a, b) => b[1] - a[1]) + .map(([issueId, at]) => ({ issueId, recordedAt: new Date(at).toISOString() })), + }); + return { + getIssue: vi.fn(), + summaries: vi.fn(), + server: { + rows, + reset() { rows.clear(); clock = 1_000; }, + /** Simulates another client of the same person recording a task. */ + touch(companyId: string, issueId: string) { scope(companyId).set(issueId, ++clock); }, + api: { + list: vi.fn(async (companyId: string) => list(companyId)), + record: vi.fn(async (companyId: string, data: { issueId: string; touch?: boolean }) => { + const current = scope(companyId); + if (data.touch === false) { + if (current.has(data.issueId)) return { entry: null }; + current.set(data.issueId, Math.min(...current.values(), clock) - 1); + } else current.set(data.issueId, ++clock); + return { entry: { issueId: data.issueId, recordedAt: new Date(current.get(data.issueId)!).toISOString() } }; + }), + importEntries: vi.fn(async (companyId: string, data: { entries: Array<{ issueId: string; recordedAt: string }> }) => { + const current = scope(companyId); + for (const entry of data.entries) { + current.set(entry.issueId, Math.max(current.get(entry.issueId) ?? 0, new Date(entry.recordedAt).getTime())); + } + return list(companyId); + }), + remove: vi.fn(async (companyId: string, issueId: string) => { scope(companyId).delete(issueId); }), + }, + }, + }; +}); vi.mock("@/api/issues", () => ({ issuesApi: { get: getIssue, summaries } })); +vi.mock("@/api/recentTasks", () => ({ recentTasksApi: server.api })); (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = true; @@ -27,9 +70,7 @@ const task = (updatedAt: number, title: string, status: "todo" | "done" = "todo" updatedAt: new Date(updatedAt), hiddenAt: null, projectId: null, isParticipantForMe: true, }); const storageKey = getRecentTasksStorageKey("company-1", "user-1"); -// Node 24 uses jsdom Storage; newer Node versions use the setup's storage shim. -// jsdom's Storage proxy does not support spying on instance methods. -const storageMethods = window.localStorage instanceof window.Storage ? window.Storage.prototype : window.localStorage; +const ids = () => readRecentTasks(storageKey, "company-1").map(entry => entry.id); describe("recent task synchronization", () => { let container: HTMLDivElement; @@ -56,13 +97,18 @@ describe("recent task synchronization", () => { } async function flush() { - await act(async () => { - for (let index = 0; index < 5; index += 1) await new Promise((resolve) => setTimeout(resolve, 0)); - }); + // The server list, the mirror update, and the summary batch each commit a render. + for (let round = 0; round < 3; round += 1) { + await act(async () => { + for (let index = 0; index < 5; index += 1) await new Promise((resolve) => setTimeout(resolve, 0)); + }); + } } beforeEach(() => { localStorage.clear(); + resetRecentTasksForTests(); + server.reset(); getIssue.mockReset(); summaries.mockReset(); container = document.createElement("div"); @@ -116,7 +162,6 @@ describe("recent task synchronization", () => { recordRecentTask(older, "user-1"); const staleClient = client(older); const freshClient = client(newer); - const setItem = vi.spyOn(storageMethods, "setItem"); await act(async () => root.render(<> @@ -124,7 +169,6 @@ describe("recent task synchronization", () => { await flush(); expect(container.querySelector('[data-tab="stale"]')?.textContent).toBe("New title:done"); expect(container.querySelector('[data-tab="fresh"]')?.textContent).toBe("New title:done"); - expect(setItem).toHaveBeenCalledTimes(1); expect(getIssue).not.toHaveBeenCalled(); const settledRenders = renders; await flush(); @@ -137,51 +181,6 @@ describe("recent task synchronization", () => { await flush(); expect(container.querySelector('[data-tab="stale"]')?.textContent).toBe("Renamed:done"); expect(readRecentTasks(storageKey, "company-1")[0]?.snapshotUpdatedAt).toBe(30); - expect(setItem).toHaveBeenCalledTimes(2); - }); - - it("receives storage updates without republishing cached data", async () => { - const cached = task(20, "Cached", "done"); - recordRecentTask(cached, "user-1"); - await act(async () => root.render( - , - )); - await flush(); - // Simulate a concurrent write from another tab with an older snapshot. - const incoming = { ...readRecentTasks(storageKey, "company-1")[0], title: "Older", snapshotUpdatedAt: 10 }; - localStorage.setItem(storageKey, JSON.stringify([incoming])); - const setItem = vi.spyOn(storageMethods, "setItem"); - const publish = vi.fn(); - window.addEventListener(RECENT_TASKS_UPDATED_EVENT, publish); - try { - await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: storageKey })); }); - await flush(); - expect(container.textContent).toBe("Cached:done"); - expect(setItem).not.toHaveBeenCalled(); - expect(publish).not.toHaveBeenCalled(); - } finally { - window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, publish); - } - }); - - it("ignores writes from the old application after migration", async () => { - const legacyKey = "paperclip.recentTasks:company-1:user-1"; - localStorage.setItem(legacyKey, JSON.stringify([{ ...task(10, "Legacy"), recordedAt: 100 }])); - await act(async () => root.render( - , - )); - await flush(); - expect(container.textContent).toBe("Current:done"); - const settledRenders = renders; - await act(async () => { - localStorage.setItem(legacyKey, "[]"); - window.dispatchEvent(new StorageEvent("storage", { key: legacyKey })); - window.dispatchEvent(new CustomEvent(RECENT_TASKS_UPDATED_EVENT, { detail: { storageKey: legacyKey, entries: [] } })); - }); - await flush(); - expect(renders).toBe(settledRenders); - expect(container.textContent).toBe("Current:done"); - expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(100); }); it.each([403, 500])("retains snapshots when the batch fails with %s", async (status) => { @@ -227,16 +226,17 @@ describe("recent task synchronization", () => { summaries.mockResolvedValue([cancelled]); await refresh(); expect(container.textContent).toBe("Recent task:cancelled"); - expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(10); - - await act(async () => recordRecentTask(cancelled, "user-1", 30)); - expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(30); summaries.mockResolvedValue([{ ...cancelled, isArchivedForMe: true }]); await refresh(); expect(container.textContent).toBe(""); expect(container.querySelector("[data-pins]")?.getAttribute("data-pins")).toBe("Recent task"); - expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + // Archiving from the Recents menu removes it from the shared list too. + await act(async () => removeRecentTask("company-1", opened.id, "user-1")); + await flush(); + expect(ids()).toEqual([]); + expect(server.api.remove).toHaveBeenCalledWith("company-1", opened.id); + expect(server.rows.get("company-1")?.has(opened.id)).toBe(false); }); it("keeps loaded navigation state on a failed refresh without storing personal unread projections", async () => { @@ -311,7 +311,7 @@ describe("recent task synchronization", () => { } }); - it("hides unverified visits and removes automated history only after a successful participation read", async () => { + it("hides unverified visits and ineligible automated history without deleting it", async () => { const personal = { ...task(10, "My work"), isParticipantForMe: true }; const automated = { ...task(20, "Routine scan"), id: "routine", isParticipantForMe: false }; recordRecentTask(personal, "user-1"); @@ -324,19 +324,20 @@ describe("recent task synchronization", () => { await act(async () => { resolve([personal, automated]); }); await flush(); expect(container.textContent).toBe("My work:todo"); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([personal.id]); + // The shared list keeps it: eligibility can change later (for example after a read). + expect(ids().sort()).toEqual([personal.id, automated.id].sort()); expect(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("isParticipantForMe"); }); - it("does not trust a participation flag from local storage or a full-detail cache", async () => { - localStorage.setItem(storageKey, JSON.stringify([{ ...task(10, "Imported review"), recordedAt: 10 }])); + it("does not trust a participation flag from an imported entry or a full-detail cache", async () => { + localStorage.setItem("paperclip.recentTasks.v3:company-1:user-1", JSON.stringify([{ ...task(10, "Imported review"), id: "11111111-1111-4111-8111-111111111111", recordedAt: 10 }])); const cache = client(); - cache.setQueryData(queryKeys.issues.detail("issue-1"), task(20, "Cached review")); - summaries.mockResolvedValue([{ ...task(30, "Review finished"), isParticipantForMe: false }]); + const importedId = "11111111-1111-4111-8111-111111111111"; + cache.setQueryData(queryKeys.issues.detail(importedId), { ...task(20, "Cached review"), id: importedId }); + summaries.mockResolvedValue([{ ...task(30, "Review finished"), id: importedId, isParticipantForMe: false }]); await act(async () => root.render()); await flush(); expect(container.textContent).toBe(""); - expect(readRecentTasks(storageKey, "company-1")).toEqual([]); }); it("admits an automated task after the viewer participates despite a cached negative result", async () => { @@ -346,12 +347,11 @@ describe("recent task synchronization", () => { const cache = client(); await act(async () => root.render()); await flush(); - expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + expect(container.textContent).toBe(""); summaries.mockResolvedValue([{ ...automated, isParticipantForMe: true }]); await act(async () => { recordRecentTask(automated, "user-1", 100); }); await flush(); expect(container.textContent).toBe("Review:todo"); - 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 () => { @@ -366,60 +366,43 @@ describe("recent task synchronization", () => { 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 }); + expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ id: "routine-task", title: "Daily scan", identifier: "TASK-2" }); }); - it("drops a routine run task when the server does not confirm the viewer started it", async () => { + it("hides 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", () => { + it("moves an existing entry up when the viewer runs its routine again without losing its snapshot", async () => { 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]]); + await flush(); + // The server confirms the order with its own time. + expect(server.api.record).toHaveBeenLastCalledWith("company-1", { issueId: "older", touch: true }); + expect(ids()).toEqual(["older", "existing"]); }); - it("keeps an opened automatic task until its read is saved, then shows it", async () => { + it("shows an opened automatic task once its read makes it eligible", async () => { const opened = { ...task(10, "Routine result"), id: "opened", isParticipantForMe: false }; - recordRecentTask(opened, "user-1", 100, { awaitingRead: true }); + recordRecentTask(opened, "user-1", 100); // 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"]); + expect(ids()).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 act(async () => { 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 () => { @@ -459,7 +442,8 @@ describe("recent task synchronization", () => { }); it("limits how many summary chunks are in flight at once", async () => { - const count = ISSUE_SUMMARIES_MAX_IDS * 5; + // The server keeps at most four chunks of history (RECENT_TASKS_MAX_ENTRIES). + const count = ISSUE_SUMMARIES_MAX_IDS * 4; const tasks = Array.from({ length: count }, (_, i) => ({ ...task(i + 1, `Task ${i}`), id: `issue-${String(i).padStart(3, "0")}` })); tasks.forEach(issue => recordRecentTask(issue, "user-1")); const pending: Array<() => void> = []; @@ -474,11 +458,11 @@ describe("recent task synchronization", () => { pending.splice(0).forEach(resolve => resolve()); await flush(); } - expect(summaries).toHaveBeenCalledTimes(5); + expect(summaries).toHaveBeenCalledTimes(4); expect(readRecentTasks(storageKey, "company-1")).toHaveLength(count); }); - it("prunes successful omissions without resurrecting cached full details", async () => { + it("hides successful omissions without resurrecting cached full details", async () => { const missing = task(10, "Removed"); recordRecentTask(missing, "user-1"); const cache = client(); @@ -486,7 +470,6 @@ describe("recent task synchronization", () => { summaries.mockResolvedValue([]); await act(async () => root.render()); await flush(); - expect(readRecentTasks(storageKey, "company-1")).toEqual([]); expect(container.textContent).toBe(""); }); @@ -516,61 +499,55 @@ describe("recent task synchronization", () => { await act(async () => { resolveOld([task(30, "Old response")]); }); await flush(); expect(container.textContent).toBe("New account task:todo"); - expect(readRecentTasks(getRecentTasksStorageKey("company-1", "user-2"), "company-1")[0]?.id).toBe("issue-2"); - expect(summaries.mock.calls.map(call => call[1])).toEqual([["issue-1"], ["issue-2"]]); + expect(readRecentTasks(getRecentTasksStorageKey("company-1", "user-2"), "company-1").map(entry => entry.id)).toContain("issue-2"); }); - it("refreshes a cached omission when the user revisits an accessible task", async () => { - const first = task(10, "First"); - const second = { ...task(20, "Second"), id: "issue-2" }; - recordRecentTask(first, "user-1"); - recordRecentTask(second, "user-1"); - summaries.mockResolvedValue([second]); - const cache = client(); - await act(async () => root.render()); - await flush(); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([second.id]); - await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); }); - expect(cache.getQueryState(queryKeys.issues.summaryBatch("company-1", "user-1", [second.id]))?.status).toBe("success"); + it("shows the same list on every client of the same person", async () => { + const first = { ...task(10, "First"), id: "first" }; + const second = { ...task(20, "Second"), id: "second" }; summaries.mockResolvedValue([first, second]); - await act(async () => { recordRecentTask(first, "user-1", 30); }); + server.touch("company-1", first.id); + server.touch("company-1", second.id); + // A fresh client (another browser) starts with nothing local. + const cache = client(); + await act(async () => root.render()); await flush(); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id).sort()).toEqual([first.id, second.id]); - expect(summaries.mock.calls.filter(call => call[1].length === 2)).toHaveLength(2); + expect(container.textContent).toBe("Second:todo,First:todo"); + + // Another client opens the older task; a live event invalidates this client's list. + server.touch("company-1", first.id); + await act(async () => { await cache.invalidateQueries({ queryKey: queryKeys.recentTasks.all("company-1") }); }); + await flush(); + // Display reorders are debounced; the mirror already has the shared order. + expect(ids()).toEqual(["first", "second"]); + + // A removal elsewhere leaves this client too. + server.rows.get("company-1")!.delete(second.id); + await act(async () => { await cache.invalidateQueries({ queryKey: queryKeys.recentTasks.all("company-1") }); }); + await flush(); + expect(container.textContent).toBe("First:todo"); }); - it("keeps a revisited task when refreshing its cached omission fails", async () => { - const first = task(10, "First"); - const second = { ...task(20, "Second"), id: "issue-2" }; - recordRecentTask(first, "user-1"); - recordRecentTask(second, "user-1"); - summaries.mockResolvedValue([second]); - const cache = client(); - await act(async () => root.render()); + it("imports Recents kept in this browser once, then reads only the server list", async () => { + const legacyId = "22222222-2222-4222-8222-222222222222"; + const legacyKey = "paperclip.recentTasks.v3:company-1:user-1"; + localStorage.setItem(legacyKey, JSON.stringify([{ ...task(10, "Legacy"), id: legacyId, recordedAt: 500 }])); + summaries.mockResolvedValue([{ ...task(10, "Legacy"), id: legacyId }]); + await act(async () => root.render()); await flush(); - await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); }); - summaries.mockRejectedValue(new ApiError("Unavailable", 500, null)); - await act(async () => { recordRecentTask(first, "user-1", 30); }); - await flush(); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id).sort()).toEqual([first.id, second.id]); - expect(cache.getQueryState(queryKeys.issues.summaryBatch("company-1", "user-1", [first.id, second.id]))?.status).toBe("error"); - expect(summaries.mock.calls.filter(call => call[1].length === 2)).toHaveLength(2); + expect(server.api.importEntries).toHaveBeenCalledTimes(1); + expect(server.api.importEntries.mock.calls[0]?.[1]).toEqual({ entries: [{ issueId: legacyId, recordedAt: new Date(500).toISOString() }] }); + expect(localStorage.getItem(legacyKey)).toBeNull(); + expect(container.textContent).toBe("Legacy:todo"); }); - it("prunes a revisited task when a fresh response repeats the cached omission", async () => { - const first = task(10, "First"); - const second = { ...task(20, "Second"), id: "issue-2" }; - recordRecentTask(first, "user-1"); - recordRecentTask(second, "user-1"); - const rows = [second]; - summaries.mockResolvedValue(rows); - const cache = client(); - await act(async () => root.render()); + it("keeps the browser copy when the import fails", async () => { + const legacyKey = "paperclip.recentTasks.v3:company-1:user-1"; + const value = JSON.stringify([{ ...task(10, "Legacy"), id: "33333333-3333-4333-8333-333333333333", recordedAt: 500 }]); + localStorage.setItem(legacyKey, value); + server.api.importEntries.mockRejectedValueOnce(new ApiError("Unavailable", 503, null)); + await act(async () => root.render()); await flush(); - await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); }); - await act(async () => { recordRecentTask(first, "user-1", 30); }); - await flush(); - expect(summaries.mock.calls.filter(call => call[1].length === 2)).toHaveLength(2); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([second.id]); + expect(localStorage.getItem(legacyKey)).toBe(value); }); }); diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index 947f6008c9b..0b455b92411 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -3,13 +3,16 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ISSUE_SUMMARIES_MAX_IDS, type Issue, type IssueSummary } from "@paperclipai/shared"; import { ApiError } from "@/api/client"; import { issuesApi } from "@/api/issues"; +import { recentTasksApi } from "@/api/recentTasks"; import { queryKeys } from "@/lib/queryKeys"; import { + RECENT_TASKS_RESYNC_EVENT, RECENT_TASKS_UPDATED_EVENT, + applyServerRecentTasks, + beginRecentTasksFetch, getRecentTasksStorageKey, + importLegacyRecentTasks, mergeRecentTaskSnapshot, - migrateRecentTasks, - pruneRecentTasks, readRecentTasks, updateRecentTaskSnapshots, type RecentTaskEntry, @@ -56,41 +59,50 @@ export function useRecentTasks({ const setEntries = (next: RecentTaskEntry[]) => setSnapshot({ storageKey, entries: next }); useEffect(() => { - if (storageKey && companyId) migrateRecentTasks(storageKey, companyId); setEntries(storageKey && companyId ? readRecentTasks(storageKey, companyId) : []); - }, [companyId, storageKey]); - - useEffect(() => { if (!storageKey || !companyId) return; - - const sync = () => setEntries(readRecentTasks(storageKey, companyId)); - const onStorage = (event: StorageEvent) => { - if (event.key === storageKey) sync(); - }; const onRecentTasksUpdated = (event: Event) => { const detail = (event as CustomEvent).detail; if (detail?.storageKey === storageKey) setEntries(detail.entries); }; - - window.addEventListener("storage", onStorage); window.addEventListener(RECENT_TASKS_UPDATED_EVENT, onRecentTasksUpdated); - return () => { - window.removeEventListener("storage", onStorage); - window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, onRecentTasksUpdated); - }; + return () => window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, onRecentTasksUpdated); }, [companyId, storageKey]); + // The server keeps the list, so every client shows the same Recents. Live + // `recent_tasks.*` activity for this person invalidates the query. + const listKey = queryKeys.recentTasks.list(companyId ?? "__none__", userId); + const listQuery = useQuery({ + queryKey: listKey, + queryFn: async ({ signal }) => { + const fetchToken = beginRecentTasksFetch(getRecentTasksStorageKey(companyId!, userId)); + // A browser that kept Recents locally imports them once. + const imported = await importLegacyRecentTasks(companyId!, userId); + const list = imported ?? await recentTasksApi.list(companyId!, { signal }); + return { ...list, fetchToken }; + }, + enabled: Boolean(companyId), + staleTime: 30_000, + }); + const serverList = listQuery.data; + useEffect(() => { + if (!storageKey || !companyId) return; + const onResync = (event: Event) => { + if ((event as CustomEvent<{ storageKey: string }>).detail?.storageKey !== storageKey) return; + void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks.list(companyId, userId) }); + }; + window.addEventListener(RECENT_TASKS_RESYNC_EVENT, onResync); + return () => window.removeEventListener(RECENT_TASKS_RESYNC_EVENT, onResync); + }, [companyId, queryClient, storageKey, userId]); + useEffect(() => { + if (storageKey && companyId && serverList) { + applyServerRecentTasks(storageKey, companyId, serverList.entries, serverList.fetchToken); + } + }, [companyId, serverList, storageKey]); + const recentIds = useMemo(() => entries.map((entry) => entry.id).sort(), [entries]); const queryIds = useMemo(() => pinnedTaskIds.length ? [...new Set([...recentIds, ...pinnedTaskIds])].sort() : recentIds, [recentIds, pinnedTaskIds]); - const scope = JSON.stringify([storageKey, recentIds, queryIds]); const summaryKey = queryKeys.issues.summaryBatch(companyId ?? "__none__", userId, queryIds); - // A cached omission predates IDs that the user has just added back. Only a - // response completed during this visit to the batch may remove those IDs. - const batchVisit = useMemo(() => ({ - initialUpdateCount: queryClient.getQueryState(summaryKey)?.dataUpdateCount ?? 0, - // The serialized scope includes the account, company, and sorted ID set. - // eslint-disable-next-line react-hooks/exhaustive-deps - }), [queryClient, scope]); const summaryQuery = useQuery({ queryKey: summaryKey, queryFn: async ({ signal }) => { @@ -118,10 +130,6 @@ export function useRecentTasks({ placeholderData: (previous, previousQuery) => previousQuery?.queryKey[1] === companyId && previousQuery?.queryKey[3] === (userId ?? "__local_board__") ? previous : undefined, }); - // Observe completion even when structural sharing preserves the data object. - // The successful-update counter itself is only available on the cache state. - const fetchingSummaries = summaryQuery.isFetching; - const updateCount = queryClient.getQueryState(summaryKey)?.dataUpdateCount ?? 0; const summaries = summaryQuery.isSuccess ? summaryQuery.data : undefined; const [lastConfirmed, setLastConfirmed] = useState<{ storageKey: string | null; @@ -141,35 +149,36 @@ export function useRecentTasks({ const issue = confirmed.get(id); return issue ? [issue] : []; }), [confirmed, denied, pinnedTaskIds]); - // 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 + // A stored entry is only a candidate. The navigation summary 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 || 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); - useEffect(() => { if (!storageKey || !companyId || !summaries || summaryQuery.isPlaceholderData) return; - if (processed.current?.visit === batchVisit && processed.current.revision === updateCount) return; - 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 && 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) { - void summaryQuery.refetch({ cancelRefetch: false }); - return; - } - // Never prune IDs added after this particular batch was requested. - pruneRecentTasks(storageKey, companyId, omittedIds); - // A storage notification must not republish the same successful revision. + }, [companyId, summaries, summaryQuery.isPlaceholderData, storageKey]); + + // New activity on a task that the loaded batch omits or calls ineligible + // (for example a task just opened or started again) asks for a fresh batch, + // because the cached answer predates that activity. + const lastActivity = useRef<{ storageKey: string | null; recordedAt: Map }>({ storageKey, recordedAt: new Map() }); + useEffect(() => { + const previous = lastActivity.current.storageKey === storageKey ? lastActivity.current.recordedAt : new Map(); + lastActivity.current = { storageKey, recordedAt: new Map(entries.map((entry) => [entry.id, entry.recordedAt])) }; + if (previous.size === 0 || !summaries || summaryQuery.isPlaceholderData || summaryQuery.isFetching) return; + const loaded = new Map(summaries.map((issue) => [issue.id, issue])); + const needsFreshBatch = entries.some((entry) => { + const before = previous.get(entry.id); + if (before !== undefined && before >= entry.recordedAt) return false; + const issue = loaded.get(entry.id); + return !issue || recentEligibility(issue) !== true; + }); + if (needsFreshBatch) void summaryQuery.refetch({ cancelRefetch: false }); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [batchVisit, companyId, fetchingSummaries, scope, updateCount, summaries, storageKey, summaryQuery.isPlaceholderData]); + }, [entries, storageKey]); useEffect(() => { if (!storageKey || !companyId || !summaries) return; diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index fa284935f9f..68b1c326c20 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -687,6 +687,11 @@ export const queryKeys = { projectOrder: (companyId: string, userId: string) => ["sidebar-preferences", "project-order", companyId, userId] as const, }, + recentTasks: { + all: (companyId: string) => ["recent-tasks", companyId] as const, + list: (companyId: string, userId: string | null | undefined) => + ["recent-tasks", companyId, userId ?? "__local_board__"] as const, + }, primaryAgent: { mine: (companyId: string, userId: string) => ["primary-agent", companyId, userId] as const, }, diff --git a/ui/src/lib/recent-tasks.test.ts b/ui/src/lib/recent-tasks.test.ts index c3646bb2d24..45a72831460 100644 --- a/ui/src/lib/recent-tasks.test.ts +++ b/ui/src/lib/recent-tasks.test.ts @@ -4,18 +4,28 @@ import type { Issue } from "@paperclipai/shared"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { - AWAITING_READ_TTL_MS, + RECENT_TASKS_RESYNC_EVENT, RECENT_TASKS_UPDATED_EVENT, + applyServerRecentTasks, + beginRecentTasksFetch, getRecentTasksStorageKey, - migrateRecentTasks, - pruneRecentTasks, + importLegacyRecentTasks, readRecentTasks, recordRecentTask, - settleRecentTaskVisit, + recordStartedRoutineRunTask, + removeRecentTask, + resetRecentTasksForTests, updateRecentTaskSnapshots, - writeRecentTasks, } 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, @@ -24,11 +34,135 @@ const issue = (id: string, companyId = "company-1") => ({ 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; +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); -describe("recent task persistence", () => { - beforeEach(() => window.localStorage.clear()); +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( @@ -70,16 +204,6 @@ describe("recent task persistence", () => { }); }); - 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 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); @@ -187,84 +311,6 @@ 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("keeps passive awaitingRead visits in chronological order without bumping existing entries", () => { - const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000); - try { - recordRecentTask(issue("older"), "user-1", 100); - recordRecentTask(issue("newer"), "user-1", 200); - const storageKey = getRecentTasksStorageKey("company-1", "user-1"); - - // Revisiting an existing task with awaitingRead must not bump it above newer items. - recordRecentTask(issue("older"), "user-1", undefined, { awaitingRead: true }); - // Opening an unseen task with awaitingRead seeds chronologically and resists pruning until settled. - recordRecentTask({ ...issue("unseen"), updatedAt: new Date(150) }, "user-1", undefined, { awaitingRead: true }); - - expect(readRecentTasks(storageKey, "company-1").map(entry => [entry.id, entry.recordedAt])).toEqual([ - ["newer", 200], - ["unseen", 150], - ["older", 100], - ]); - - pruneRecentTasks(storageKey, "company-1", new Set(["older", "unseen"])); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([ - "newer", - "unseen", - "older", - ]); - - settleRecentTaskVisit("company-1", "unseen", "user-1"); - pruneRecentTasks(storageKey, "company-1", new Set(["unseen"])); - expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([ - "newer", - "older", - ]); - } finally { - now.mockRestore(); - } - }); - - 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); @@ -295,42 +341,6 @@ describe("recent task persistence", () => { }); }); - 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"); @@ -349,46 +359,6 @@ describe("recent task persistence", () => { 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("ignores conversation, archived, and hidden tasks consistently", () => { const storageKey = getRecentTasksStorageKey("company-1", "user-1"); recordRecentTask({ ...issue("chat"), conversationAgentId: "agent-1" }, "user-1", 100); @@ -398,12 +368,4 @@ describe("recent task persistence", () => { expect(readRecentTasks(storageKey, "company-1").map((entry) => entry.id)).toEqual(["visible"]); }); - - 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([]); - }); }); diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.ts index e39f1bccbfe..f2a8297a03a 100644 --- a/ui/src/lib/recent-tasks.ts +++ b/ui/src/lib/recent-tasks.ts @@ -1,8 +1,55 @@ -import type { Issue, IssueStatus, IssueSummary } from "@paperclipai/shared"; +import type { Issue, IssueStatus, IssueSummary, RecentTaskRecord } from "@paperclipai/shared"; +import { RECENT_TASKS_MAX_ENTRIES } from "@paperclipai/shared"; +import { recentTasksApi } from "@/api/recentTasks"; +/** + * Sidebar Recents. The server keeps each person's list per company, so every + * browser and device shows the same tasks in the same order. This module holds + * the client mirror: the last server list, optimistic local changes that are + * still in flight, and display snapshots (title, status) that the navigation + * summaries and cached task details supply. + */ export const RECENT_TASKS_UPDATED_EVENT = "paperclip:recent-tasks-updated"; -const STORAGE_PREFIX = "paperclip.recentTasks.v3:"; -const LEGACY_STORAGE_PREFIXES = ["paperclip.recentTasks.v2:", "paperclip.recentTasks:"]; +/** Asks mounted Recents to reload the server list after a change failed to save. */ +export const RECENT_TASKS_RESYNC_EVENT = "paperclip:recent-tasks-resync"; +/** One retry absorbs a brief network error before the client gives up. */ +const SAVE_RETRY_DELAY_MS = 2_000; + +interface RecentTasksResyncDetail { + storageKey: string; +} + +/** + * A change that the server did not save must not look saved. The mirror goes + * back to the server list, so this tab shows what every other client shows. + */ +function requestResync(storageKey: string) { + if (typeof window === "undefined") return; + window.dispatchEvent(new CustomEvent(RECENT_TASKS_RESYNC_EVENT, { detail: { storageKey } })); +} + +class SupersededChangeError extends Error {} + +/** + * Sends a change and retries it once. The retry only runs while the change is + * still the latest one for its task: a newer visit or removal replaces it, and + * an old write must never undo the newer one. + */ +async function withRetry(request: () => Promise, isCurrent: () => boolean): Promise { + try { + return await request(); + } catch (error) { + if (!isCurrent()) throw error; + await new Promise((resolve) => setTimeout(resolve, SAVE_RETRY_DELAY_MS)); + if (!isCurrent()) throw new SupersededChangeError(); + return request(); + } +} +/** + * Browser storage that held Recents before the server kept them, newest version + * first. Read once to import. + */ +const LEGACY_STORAGE_PREFIXES = ["paperclip.recentTasks.v3:", "paperclip.recentTasks.v2:", "paperclip.recentTasks:"]; export interface RecentTaskEntry { id: string; @@ -17,25 +64,8 @@ export interface RecentTaskEntry { isUnreadForMe?: boolean; recordedAt: number; // Server version of the title/status snapshot, independent of comment activity. - // Legacy entries have no version until a detail query refreshes them. + // Entries from the server list have no version until a summary 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; } export type RecentTaskSource = Pick< @@ -72,53 +102,52 @@ export function parseRecentActivityTimestamp( return Number.isFinite(timestamp) && timestamp > 0 ? timestamp : null; } -export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) { - // Old tabs still promote machine activity. Keep their writes out of v3. - return `${STORAGE_PREFIX}${companyId}:${userId ?? "__local_board__"}`; +interface PendingChange { + /** Local time of the optimistic record; unused for removals. */ + recordedAt: number; + /** + * The last server list fetch started before the server acknowledged this + * change, or null while it is in flight. A list from a fetch that started + * later already includes the change, so the change stops overriding it. + */ + acknowledgedAfterFetch: number | null; } -function isRecentTaskEntry(value: unknown, companyId: string): value is RecentTaskEntry { - if (!value || typeof value !== "object") return false; - const entry = value as Partial; - return entry.companyId === companyId - && typeof entry.id === "string" - && entry.id.length > 0 - && typeof entry.title === "string" - && (entry.identifier === null || typeof entry.identifier === "string") - && typeof entry.status === "string" - && typeof entry.recordedAt === "number" - && Number.isFinite(entry.recordedAt) - && (entry.snapshotUpdatedAt === undefined || ( - typeof entry.snapshotUpdatedAt === "number" && Number.isFinite(entry.snapshotUpdatedAt) - )); +interface RecentTasksScope { + entries: RecentTaskEntry[]; + /** Optimistic records, by task ID. */ + pendingRecords: Map; + /** Optimistic removals, by task ID. */ + pendingRemovals: Map; + /** Counts server list fetches, so a list can be ordered against local changes. */ + fetchCount: number; +} + +const scopes = new Map(); +const importedScopes = new Set(); + +function scopeFor(storageKey: string): RecentTasksScope { + let scope = scopes.get(storageKey); + if (!scope) { + scope = { entries: [], pendingRecords: new Map(), pendingRemovals: new Map(), fetchCount: 0 }; + scopes.set(storageKey, scope); + } + return scope; +} + +/** Test helper: forget every client mirror. */ +export function resetRecentTasksForTests() { + scopes.clear(); + importedScopes.clear(); +} + +/** Identifies one person's Recents for one company in this client. */ +export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) { + return `${companyId}:${userId ?? "__local_board__"}`; } export function readRecentTasks(storageKey: string, companyId: string): RecentTaskEntry[] { - if (typeof window === "undefined") return []; - try { - const keys = storageKey.startsWith(STORAGE_PREFIX) - ? [storageKey, ...LEGACY_STORAGE_PREFIXES.map(prefix => prefix + storageKey.slice(STORAGE_PREFIX.length))] - : [storageKey]; - const raw = keys.map(key => window.localStorage.getItem(key)).find(value => value !== null); - const parsed = JSON.parse(raw ?? "[]") as unknown; - if (!Array.isArray(parsed)) return []; - return normalizeRecentTasks( - parsed.filter((entry): entry is RecentTaskEntry => isRecentTaskEntry(entry, companyId)), - ); - } catch { - return []; - } -} - -export function migrateRecentTasks(storageKey: string, companyId: string) { - if (typeof window === "undefined") return; - try { - if (window.localStorage.getItem(storageKey) !== null) return; - } catch { - return; - } - // Persist even an empty list so an old tab cannot seed it again later. - writeRecentTasks(storageKey, readRecentTasks(storageKey, companyId)); + return (scopes.get(storageKey)?.entries ?? []).filter((entry) => entry.companyId === companyId); } function normalizeRecentTasks(entries: RecentTaskEntry[]) { @@ -129,27 +158,107 @@ function normalizeRecentTasks(entries: RecentTaskEntry[]) { if (seen.has(entry.id)) return false; seen.add(entry.id); return true; - }); + }) + .slice(0, RECENT_TASKS_MAX_ENTRIES); } -function publishRecentTasks(storageKey: string, entries: RecentTaskEntry[]) { +function sameEntries(left: RecentTaskEntry[], right: RecentTaskEntry[]) { + return left.length === right.length && left.every((entry, index) => entry === right[index]); +} + +function writeRecentTasks(storageKey: string, entries: RecentTaskEntry[]) { + const scope = scopeFor(storageKey); + const normalized = normalizeRecentTasks(entries); + if (sameEntries(scope.entries, normalized)) return; + scope.entries = normalized; if (typeof window === "undefined") return; window.dispatchEvent(new CustomEvent(RECENT_TASKS_UPDATED_EVENT, { - detail: { storageKey, entries }, + detail: { storageKey, entries: normalized }, })); } -export function writeRecentTasks(storageKey: string, entries: RecentTaskEntry[]) { - if (typeof window === "undefined") return; - const normalized = normalizeRecentTasks(entries); - try { - const serialized = JSON.stringify(normalized); - if (window.localStorage.getItem(storageKey) === serialized) return; - window.localStorage.setItem(storageKey, serialized); - } catch { - // The in-tab event still keeps mounted navigation current for this session. +function placeholderEntry(companyId: string, issueId: string, recordedAt: number): RecentTaskEntry { + // The navigation summary supplies title and status before the row is shown. + return { id: issueId, companyId, title: "", identifier: null, status: "todo", recordedAt }; +} + +/** Call when a server list fetch starts; pass the result to applyServerRecentTasks. */ +export function beginRecentTasksFetch(storageKey: string) { + const scope = scopeFor(storageKey); + scope.fetchCount += 1; + return scope.fetchCount; +} + +function settledBy(change: PendingChange, fetchToken: number) { + return change.acknowledgedAfterFetch !== null && change.acknowledgedAfterFetch < fetchToken; +} + +/** + * Replaces the mirror with the server list. Snapshots already known for a task + * are kept, and local changes that the list cannot include yet stay applied. + * `fetchToken` comes from beginRecentTasksFetch when the list request started. + */ +export function applyServerRecentTasks( + storageKey: string, + companyId: string, + records: ReadonlyArray, + fetchToken = Number.POSITIVE_INFINITY, +) { + const scope = scopeFor(storageKey); + for (const [issueId, change] of scope.pendingRecords) { + if (settledBy(change, fetchToken)) scope.pendingRecords.delete(issueId); } - publishRecentTasks(storageKey, normalized); + for (const [issueId, change] of scope.pendingRemovals) { + if (settledBy(change, fetchToken)) scope.pendingRemovals.delete(issueId); + } + const known = new Map(scope.entries.map((entry) => [entry.id, entry])); + const next = new Map(); + for (const record of records) { + if (scope.pendingRemovals.has(record.issueId)) continue; + const recordedAt = new Date(record.recordedAt).getTime(); + if (!Number.isFinite(recordedAt)) continue; + const existing = known.get(record.issueId); + const entry = existing + ? (existing.recordedAt === recordedAt ? existing : { ...existing, recordedAt }) + : placeholderEntry(companyId, record.issueId, recordedAt); + next.set(record.issueId, entry); + } + for (const [issueId, { recordedAt }] of scope.pendingRecords) { + const existing = next.get(issueId) ?? known.get(issueId); + const entry = existing ?? placeholderEntry(companyId, issueId, recordedAt); + next.set(issueId, entry.recordedAt >= recordedAt ? entry : { ...entry, recordedAt }); + } + writeRecentTasks(storageKey, [...next.values()]); +} + +function trackRecord(storageKey: string, companyId: string, issueId: string, recordedAt: number, touch: boolean) { + const scope = scopeFor(storageKey); + const change: PendingChange = { recordedAt, acknowledgedAfterFetch: null }; + scope.pendingRecords.set(issueId, change); + scope.pendingRemovals.delete(issueId); + const settle = (record: RecentTaskRecord | null, failed: boolean) => { + if (scope.pendingRecords.get(issueId) !== change) return; + // The next list fetch decides a failed record. + if (failed) { + scope.pendingRecords.delete(issueId); + requestResync(storageKey); + return; + } + change.acknowledgedAfterFetch = scope.fetchCount; + // Adopt server time so the order matches every other client. + const serverAt = record ? new Date(record.recordedAt).getTime() : NaN; + if (!Number.isFinite(serverAt)) return; + change.recordedAt = serverAt; + writeRecentTasks(storageKey, scope.entries.map((entry) => + entry.id === issueId && entry.recordedAt !== serverAt ? { ...entry, recordedAt: serverAt } : entry)); + }; + void withRetry( + () => recentTasksApi.record(companyId, { issueId, touch }), + () => scope.pendingRecords.get(issueId) === change, + ).then( + (response) => settle(response?.entry ?? null, false), + () => settle(null, true), + ); } type TaskSnapshot = Omit & Pick; @@ -184,22 +293,27 @@ export function mergeRecentTaskSnapshot(entry: RecentTaskEntry, issue: TaskSnaps }; } +/** + * Records a task in Recents. With `recordedAt` (an explicit visit or action) + * the task moves to the top on every client. Without it, the task is only added + * below existing history when it is not there yet, and its snapshot refreshes. + */ export function recordRecentTask( issue: RecentTaskSource, userId: string | null | undefined, recordedAt?: number, - options?: { awaitingRead?: boolean }, ) { if (!isEligibleRecentTask(issue)) return; const storageKey = getRecentTasksStorageKey(issue.companyId, userId); const current = readRecentTasks(storageKey, issue.companyId); const existing = current.find((candidate) => candidate.id === issue.id); const snapshotUpdatedAt = new Date(issue.updatedAt).getTime(); - // Passive opens never re-sort an existing entry. When seeding an unseen task - // passively, place it chronologically by its latest activity timestamp (or - // below existing history when no valid timestamp is available). Only explicit - // local user actions advance recency via `recordedAt`. - const activityAt = recordedAt !== undefined && Number.isFinite(recordedAt) + const touch = recordedAt !== undefined && Number.isFinite(recordedAt); + // Passive opens never re-sort an existing entry. An unseen task seeded + // passively goes where its latest activity puts it (or below existing + // history when that is unknown); the server confirms the time it chose. + // Only explicit user actions advance recency via `recordedAt`. + const activityAt = touch ? recordedAt : existing?.recordedAt ?? parseRecentActivityTimestamp(issue.lastActivityAt) @@ -217,12 +331,8 @@ export function recordRecentTask( recordedAt: activityAt, ...(Number.isFinite(snapshotUpdatedAt) ? { snapshotUpdatedAt } : {}), }; - const entry: RecentTaskEntry = { - ...snapshot, - // A comment can promote activity even when its task details are stale. - recordedAt: Math.max(activityAt, snapshot.recordedAt), - ...(options?.awaitingRead ? { awaitingRead: Date.now() } : {}), - }; + const entry: RecentTaskEntry = { ...snapshot, recordedAt: Math.max(activityAt, snapshot.recordedAt) }; + if (touch || !existing) trackRecord(storageKey, issue.companyId, issue.id, entry.recordedAt, touch); if ( existing && existing.title === entry.title @@ -233,7 +343,6 @@ export function recordRecentTask( && sameBlockerAttention(existing.blockerAttention, entry.blockerAttention) && existing.recordedAt === entry.recordedAt && existing.snapshotUpdatedAt === entry.snapshotUpdatedAt - && existing.awaitingRead === entry.awaitingRead ) return; writeRecentTasks( @@ -260,39 +369,32 @@ export function recordStartedRoutineRunTask( const current = readRecentTasks(storageKey, companyId); const existing = current.find((candidate) => candidate.id === issueId); if (existing && existing.recordedAt >= recordedAt) return; + trackRecord(storageKey, companyId, issueId, recordedAt, true); const entry: RecentTaskEntry = existing ? { ...existing, recordedAt } - : { id: issueId, companyId, title: "", identifier: null, status: "todo", recordedAt }; + : placeholderEntry(companyId, issueId, recordedAt); writeRecentTasks(storageKey, [entry, ...current.filter((candidate) => candidate.id !== issueId)]); } -export function pruneRecentTasks( - storageKey: string, - companyId: string, - removeIds: ReadonlySet, -) { - if (removeIds.size === 0) return; - const current = readRecentTasks(storageKey, companyId); - // 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) { +/** Removes a task from Recents on every client. */ +export function removeRecentTask(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; - })); + const scope = scopeFor(storageKey); + scope.pendingRecords.delete(issueId); + const change: PendingChange = { recordedAt: 0, acknowledgedAfterFetch: null }; + scope.pendingRemovals.set(issueId, change); + writeRecentTasks(storageKey, scope.entries.filter((entry) => entry.id !== issueId)); + void withRetry( + () => recentTasksApi.remove(companyId, issueId), + () => scope.pendingRemovals.get(issueId) === change, + ).then( + () => { if (scope.pendingRemovals.get(issueId) === change) change.acknowledgedAfterFetch = scope.fetchCount; }, + () => { + if (scope.pendingRemovals.get(issueId) !== change) return; + scope.pendingRemovals.delete(issueId); + requestResync(storageKey); + }, + ); } export function updateRecentTaskSnapshots( @@ -312,3 +414,67 @@ export function updateRecentTaskSnapshots( }); if (changed) writeRecentTasks(storageKey, next); } + +function legacyStorageKeys(companyId: string, userId: string | null | undefined) { + const suffix = `${companyId}:${userId ?? "__local_board__"}`; + return LEGACY_STORAGE_PREFIXES.map((prefix) => prefix + suffix); +} + +function readLegacyRecords(companyId: string, keys: string[]) { + const latest = new Map(); + for (const key of keys) { + let parsed: unknown; + try { + parsed = JSON.parse(window.localStorage.getItem(key) ?? "[]"); + } catch { + continue; + } + if (!Array.isArray(parsed)) continue; + for (const value of parsed) { + if (!value || typeof value !== "object") continue; + const entry = value as Partial; + if (entry.companyId !== companyId || typeof entry.id !== "string" || !entry.id) continue; + // Passive candidates were stored with times at or below zero. + const recordedAt = typeof entry.recordedAt === "number" && Number.isFinite(entry.recordedAt) && entry.recordedAt > 0 + ? entry.recordedAt : 1; + if ((latest.get(entry.id) ?? -Infinity) < recordedAt) latest.set(entry.id, recordedAt); + } + } + return [...latest.entries()] + .sort((left, right) => right[1] - left[1]) + .slice(0, RECENT_TASKS_MAX_ENTRIES) + .map(([issueId, recordedAt]) => ({ issueId, recordedAt: new Date(recordedAt).toISOString() })); +} + +/** + * Imports the Recents that this browser kept before the server stored them, + * then removes the browser copy. Returns the server list after the import, or + * null when there was nothing to import. + */ +export async function importLegacyRecentTasks(companyId: string, userId: string | null | undefined) { + const storageKey = getRecentTasksStorageKey(companyId, userId); + if (typeof window === "undefined" || importedScopes.has(storageKey)) return null; + importedScopes.add(storageKey); + const keys = legacyStorageKeys(companyId, userId); + let present: string[]; + try { + present = keys.filter((key) => window.localStorage.getItem(key) !== null); + } catch { + return null; + } + if (present.length === 0) return null; + // Only the newest version is the browser's history. Older keys may hold + // writes from tabs of earlier releases that promoted machine activity. + const entries = readLegacyRecords(companyId, present.slice(0, 1)); + const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const valid = entries.filter((entry) => UUID.test(entry.issueId)); + try { + const result = valid.length ? await recentTasksApi.importEntries(companyId, { entries: valid }) : null; + for (const key of present) window.localStorage.removeItem(key); + return result; + } catch { + // Keep the browser copy so a later visit can try again. + importedScopes.delete(storageKey); + return null; + } +} diff --git a/ui/src/pages/IssueDetail.mobile.test.tsx b/ui/src/pages/IssueDetail.mobile.test.tsx index 442c2c20204..57ac6cd4cae 100644 --- a/ui/src/pages/IssueDetail.mobile.test.tsx +++ b/ui/src/pages/IssueDetail.mobile.test.tsx @@ -11,7 +11,7 @@ import { PanelProvider } from "../context/PanelContext"; import { ThemeProvider } from "../context/ThemeContext"; import { ToastProvider, useToastState } from "../context/ToastContext"; import { DialogProvider } from "../context/DialogContext"; -import { getRecentTasksStorageKey, readRecentTasks, recordRecentTask } from "../lib/recent-tasks"; +import { getRecentTasksStorageKey, readRecentTasks, recordRecentTask, resetRecentTasksForTests } from "../lib/recent-tasks"; import { IssueDetail, TaskDetailSurface } from "./IssueDetail"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -315,6 +315,7 @@ describe("IssueDetail & AgentChat mobile parity", () => { beforeEach(() => { window.localStorage.clear(); + resetRecentTasksForTests(); testState.issue = BASE_ISSUE; testState.issuesByRef = {}; testState.onPostComment = null; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index a2e67aa9b0d..c9626e64584 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -220,11 +220,7 @@ import { upsertInterruptedRun, } from "../lib/optimistic-issue-runs"; import { useProjectOrder } from "../hooks/useProjectOrder"; -import { - isEligibleRecentTask, - recordRecentTask, - settleRecentTaskVisit, -} from "../lib/recent-tasks"; +import { isEligibleRecentTask, recordRecentTask } from "../lib/recent-tasks"; import { modelStillUnavailableToast } from "../lib/model-retry-refusal"; import { relativeTime, @@ -3904,7 +3900,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS enabled: !!selectedCompanyId, }); const currentUserId = session?.user?.id ?? session?.session?.userId ?? null; - const recentTaskVisit = useRef(null); const canTrackRecents = (streamlinedUiEnabled || coordinatorWorkspaceEnabled) && sessionResolved @@ -3927,17 +3922,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS : null; useEffect(() => { if (!canTrackRecents || !loadedIssue || !isEligibleRecentTask(loadedIssue)) return; - const visit = `${loadedIssue.companyId}:${currentUserId}:${loadedIssue.id}`; - 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, - undefined, - freshVisit && !readConfirmed ? { awaitingRead: true } : undefined, - ); - recentTaskVisit.current = visit; + // Opening a task seeds it but never moves an existing row to the top. + recordRecentTask(loadedIssue, currentUserId); }, [canTrackRecents, loadedIssue, currentUserId]); const { data: boardAccess } = useQuery({ queryKey: queryKeys.access.currentBoardAccess, @@ -4683,8 +4669,7 @@ 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); + // The saved read makes an opened automatic task eligible for Recents. // A late receipt belongs to its original company, even after navigation. queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(receipt.companyId) }); if (selectedCompanyId) { @@ -4704,10 +4689,6 @@ 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); },