From 856f14e507c09ceb6ffc7cdc084bf6b207efc8f5 Mon Sep 17 00:00:00 2001 From: scotttong Date: Sat, 21 Nov 2026 13:59:00 -0800 Subject: [PATCH] fix(dashboard): scope areas and responsibilities to each user (#22513) --- doc/PRODUCT.md | 5 + .../migrations/0500_funny_malcolm_colcord.sql | 80 + ...{0490_snapshot.json => 0500_snapshot.json} | 2019 ++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/responsibilities.ts | 20 +- packages/shared/src/types/responsibility.ts | 4 +- server/src/__tests__/activity-routes.test.ts | 4 + .../issue-access-grants-routes.test.ts | 26 + server/src/__tests__/responsibilities.test.ts | 146 +- ...nsibility-automation-conversations.test.ts | 7 +- .../responsibility-automation.test.ts | 8 +- .../src/__tests__/responsibility-bars.test.ts | 12 +- .../responsibility-dashboard.test.ts | 114 +- .../__tests__/responsibility-metrics.test.ts | 10 +- .../src/__tests__/responsibility-runs.test.ts | 4 +- .../responsibility-status-reports.test.ts | 20 +- .../responsibility-summaries-routes.test.ts | 7 +- .../src/__tests__/routine-suggestions.test.ts | 1 + server/src/routes/activity.ts | 5 +- server/src/routes/agent-person-authz.ts | 7 +- server/src/routes/authz.ts | 5 +- server/src/routes/responsibilities.ts | 75 +- server/src/routes/responsibility-areas.ts | 32 +- .../src/routes/responsibility-automation.ts | 15 +- server/src/routes/responsibility-bars.ts | 6 +- server/src/routes/responsibility-dashboard.ts | 29 +- server/src/routes/responsibility-metrics.ts | 8 +- server/src/routes/responsibility-owner.ts | 22 + server/src/routes/responsibility-runs.ts | 2 + .../routes/responsibility-status-reports.ts | 15 +- server/src/routes/responsibility-summaries.ts | 10 +- server/src/routes/routines.ts | 4 +- server/src/services/activity-log.ts | 25 +- server/src/services/activity.ts | 3 + server/src/services/agent-action-audit.ts | 3 + server/src/services/authorization.ts | 27 +- server/src/services/responsibilities.ts | 22 +- .../services/responsibility-agent-changes.ts | 5 +- server/src/services/responsibility-areas.ts | 59 +- ...responsibility-automation-conversations.ts | 35 +- .../src/services/responsibility-automation.ts | 2 +- server/src/services/responsibility-bars.ts | 2 + .../responsibility-dashboard-guidance.ts | 36 +- .../responsibility-dashboard-versions.ts | 58 +- .../src/services/responsibility-dashboard.ts | 53 +- server/src/services/responsibility-privacy.ts | 68 + .../services/responsibility-status-reports.ts | 2 + server/src/services/routine-suggestions.ts | 8 +- server/src/services/routines.ts | 3 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/api/responsibilities.ts | 3 +- .../responsibilities/AreaDialogs.tsx | 8 +- .../responsibilities/DashboardAgentStatus.tsx | 4 +- .../responsibilities/DashboardAutomation.tsx | 2 +- .../responsibilities/DashboardOutlineV2.tsx | 13 +- .../ResponsibilityBarCard.tsx | 2 +- .../ResponsibilityNarrative.tsx | 6 +- .../routine-page/useRoutineFormOptions.ts | 6 +- ui/src/lib/queryKeys.ts | 2 +- ui/src/lib/responsibility-outline-v2.test.ts | 16 +- ui/src/lib/responsibility-outline-v2.ts | 8 +- ui/src/pages/Responsibilities.test.tsx | 5 +- ui/src/pages/Responsibilities.tsx | 17 +- ui/src/pages/Responsibilities.views.test.tsx | 10 +- ui/src/pages/ResponsibilityDetail.test.tsx | 2 + ui/src/pages/ResponsibilityDetail.tsx | 8 +- ui/src/pages/RoutineDetail.test.tsx | 3 + ui/src/pages/RoutineDetail.tsx | 10 +- 68 files changed, 2708 insertions(+), 559 deletions(-) create mode 100644 packages/db/src/migrations/0500_funny_malcolm_colcord.sql rename packages/db/src/migrations/meta/{0490_snapshot.json => 0500_snapshot.json} (97%) create mode 100644 server/src/routes/responsibility-owner.ts create mode 100644 server/src/services/responsibility-privacy.ts diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 0edb2caa397..ff6a11815ff 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -38,6 +38,11 @@ Example: A CEO agent's adapter config tells it to "review what your executives a Then you define who reports to the CEO: a CTO managing programmers, a CMO managing the marketing team, and so on. Every agent in the tree gets their own adapter configuration. +When Areas & Responsibilities is enabled, each person has a private dashboard in each company. +People can use the same area names independently. Dashboard conversations, saved versions and +the way a person files shared work are visible only to that person and their authorized agent +where the workflow requires it. Filing an existing task or project keeps its existing access rules. + Each person also has a personal primary agent per company. Their first human-created agent becomes primary automatically; they can choose another from its profile. An existing primary is replaced only after confirmation. The crown appears on the diff --git a/packages/db/src/migrations/0500_funny_malcolm_colcord.sql b/packages/db/src/migrations/0500_funny_malcolm_colcord.sql new file mode 100644 index 00000000000..08a5559616c --- /dev/null +++ b/packages/db/src/migrations/0500_funny_malcolm_colcord.sql @@ -0,0 +1,80 @@ +-- paperclip:migration-compat requires_staging: pause old A&R writers while assigning owners and replacing the company-wide title index. +ALTER TABLE responsibility_areas ADD COLUMN owner_user_id text; +--> statement-breakpoint +DROP INDEX responsibility_areas_company_title_uq; +--> statement-breakpoint +-- Keep the original ID for one owner and fork it for each additional owner. +-- Empty areas without attributable activity or history stay hidden under a NULL owner. +CREATE TEMP TABLE dashboard_area_owners ON COMMIT DROP AS +WITH evidence AS ( + SELECT company_id, area_id AS old_id, owner_user_id FROM responsibilities WHERE area_id IS NOT NULL + UNION + SELECT a.company_id, a.id, CASE WHEN l.actor_type = 'user' THEN l.actor_id + ELSE l.details->>'onBehalfOfUserId' END + FROM responsibility_areas a JOIN activity_log l ON l.company_id = a.company_id + AND l.entity_type = 'responsibility_area' AND l.entity_id = a.id::text AND l.action = 'responsibility_area.created' + UNION + SELECT a.company_id, a.id, v.owner_user_id FROM responsibility_dashboard_versions v + CROSS JOIN LATERAL jsonb_array_elements(v.snapshot->'areas') e + JOIN responsibility_areas a ON a.id::text = e->>'id' AND a.company_id = v.company_id +), ranked AS ( + SELECT *, row_number() OVER (PARTITION BY company_id, old_id ORDER BY owner_user_id) AS position + FROM evidence WHERE owner_user_id IS NOT NULL +) +SELECT company_id, old_id, owner_user_id, CASE WHEN position = 1 THEN old_id ELSE gen_random_uuid() END AS new_id FROM ranked; +--> statement-breakpoint +CREATE UNIQUE INDEX ON dashboard_area_owners(company_id, owner_user_id, old_id); +--> statement-breakpoint +UPDATE responsibility_areas a SET owner_user_id = m.owner_user_id FROM dashboard_area_owners m +WHERE a.id = m.old_id AND m.old_id = m.new_id; +--> statement-breakpoint +INSERT INTO responsibility_areas (id, company_id, owner_user_id, title, description, status, source, proposed_by_agent_id, sort_order, created_at, updated_at) +SELECT m.new_id, a.company_id, m.owner_user_id, a.title, a.description, a.status, a.source, a.proposed_by_agent_id, a.sort_order, a.created_at, a.updated_at +FROM dashboard_area_owners m JOIN responsibility_areas a ON a.id = m.old_id WHERE m.old_id <> m.new_id; +--> statement-breakpoint +UPDATE responsibilities r SET area_id = m.new_id FROM dashboard_area_owners m +WHERE r.company_id = m.company_id AND r.owner_user_id = m.owner_user_id AND r.area_id = m.old_id AND m.new_id <> m.old_id; +--> statement-breakpoint +-- Only rewrite typed ID fields. Titles, evidence and other free text remain verbatim. +WITH mappings AS ( + SELECT company_id, owner_user_id, jsonb_object_agg(old_id::text, new_id::text) AS ids + FROM dashboard_area_owners WHERE new_id <> old_id GROUP BY company_id, owner_user_id +) +UPDATE responsibility_dashboard_versions v SET snapshot = v.snapshot || jsonb_build_object( + 'areas', COALESCE((SELECT jsonb_agg(CASE WHEN m.ids ? (e->>'id') THEN jsonb_set(e, '{id}', m.ids->(e->>'id')) ELSE e END ORDER BY n) + FROM jsonb_array_elements(v.snapshot->'areas') WITH ORDINALITY AS a(e,n)), '[]'::jsonb), + 'responsibilities', COALESCE((SELECT jsonb_agg(CASE WHEN m.ids ? (e->>'areaId') THEN jsonb_set(e,'{areaId}',m.ids->(e->>'areaId')) ELSE e END ORDER BY n) + FROM jsonb_array_elements(v.snapshot->'responsibilities') WITH ORDINALITY AS r(e,n)), '[]'::jsonb), + 'createdAreaIds', COALESCE((SELECT jsonb_agg(COALESCE(m.ids->e,to_jsonb(e)) ORDER BY n) + FROM jsonb_array_elements_text(v.snapshot->'createdAreaIds') WITH ORDINALITY AS c(e,n)), '[]'::jsonb) +), snapshot_hash = 'remapped' +FROM mappings m WHERE v.company_id = m.company_id AND v.owner_user_id = m.owner_user_id; +--> statement-breakpoint +-- Keep outstanding change cards usable when their owner's existing area was split. +WITH mappings AS ( + SELECT company_id, owner_user_id, jsonb_object_agg(old_id::text, new_id::text) AS ids + FROM dashboard_area_owners WHERE new_id <> old_id GROUP BY company_id, owner_user_id +) +UPDATE issue_thread_interactions t SET payload = jsonb_set(t.payload, '{changes}', ( + SELECT jsonb_agg(e || CASE WHEN m.ids ? (e->>'groupAreaId') THEN jsonb_build_object('groupAreaId',m.ids->(e->>'groupAreaId')) ELSE '{}'::jsonb END + || CASE WHEN m.ids ? (e->>'fromAreaId') THEN jsonb_build_object('fromAreaId',m.ids->(e->>'fromAreaId')) ELSE '{}'::jsonb END ORDER BY n) + FROM jsonb_array_elements(t.payload->'changes') WITH ORDINALITY AS c(e,n) +)) +FROM mappings m WHERE t.company_id = m.company_id AND t.payload->>'ownerUserId' = m.owner_user_id + AND t.kind = 'propose_dashboard_changes' AND t.status = 'pending' AND jsonb_array_length(t.payload->'changes') > 0; +--> statement-breakpoint +CREATE UNIQUE INDEX responsibility_areas_identity_uq ON responsibility_areas(company_id,owner_user_id,id); +--> statement-breakpoint +CREATE UNIQUE INDEX responsibility_areas_owner_title_uq ON responsibility_areas(company_id,owner_user_id,lower(title)) WHERE status <> 'archived'; +--> statement-breakpoint +ALTER TABLE responsibilities ADD CONSTRAINT responsibilities_owned_area_fk FOREIGN KEY (company_id,owner_user_id,area_id) +REFERENCES responsibility_areas(company_id,owner_user_id,id); +--> statement-breakpoint +UPDATE issues SET visibility = 'private', privacy_root_issue_id = id, responsible_user_id = origin_id +WHERE origin_kind = 'responsibility_dashboard' AND origin_id IS NOT NULL; +--> statement-breakpoint +UPDATE issues i SET visibility = 'private', privacy_root_issue_id = i.id, responsible_user_id = r.owner_user_id +FROM responsibilities r WHERE i.company_id = r.company_id AND i.origin_id = r.id::text AND i.origin_kind IN ('responsibility_bar','responsibility_status_update'); +--> statement-breakpoint +UPDATE issues SET visibility = 'private', privacy_root_issue_id = id, responsible_user_id = created_by_user_id +WHERE origin_kind = 'automation_conversation' AND created_by_user_id IS NOT NULL; diff --git a/packages/db/src/migrations/meta/0490_snapshot.json b/packages/db/src/migrations/meta/0500_snapshot.json similarity index 97% rename from packages/db/src/migrations/meta/0490_snapshot.json rename to packages/db/src/migrations/meta/0500_snapshot.json index 6a945283d61..c63960459a8 100644 --- a/packages/db/src/migrations/meta/0490_snapshot.json +++ b/packages/db/src/migrations/meta/0500_snapshot.json @@ -1,6 +1,6 @@ { - "id": "a8bc890a-cc97-4b54-b426-5687b134a8b0", - "prevId": "dc61c7f3-cf3d-44c5-9296-86973e5f0925", + "id": "51525362-c4bc-44be-b4a7-95cb4aae7748", + "prevId": "a80ac568-accd-4c40-b63a-82b870052e0a", "version": "7", "dialect": "postgresql", "tables": { @@ -428,6 +428,12 @@ "primaryKey": false, "notNull": false }, + "responsibility_summary_invocation_id": { + "name": "responsibility_summary_invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "agent_id": { "name": "agent_id", "type": "uuid", @@ -537,6 +543,27 @@ "method": "btree", "with": {} }, + "budget_reservations_responsibility_summary_idx": { + "name": "budget_reservations_responsibility_summary_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "responsibility_summary_invocation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, "budget_reservations_run_idx": { "name": "budget_reservations_run_idx", "columns": [ @@ -634,7 +661,7 @@ "checkConstraints": { "budget_reservations_source_check": { "name": "budget_reservations_source_check", - "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int + (\"budget_reservations\".\"prompt_injection_invocation_id\" is not null)::int = 1" + "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int + (\"budget_reservations\".\"prompt_injection_invocation_id\" is not null)::int + (\"budget_reservations\".\"responsibility_summary_invocation_id\" is not null)::int = 1" }, "budget_reservations_state_check": { "name": "budget_reservations_state_check", @@ -21928,6 +21955,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_workload_identity_keys": { + "name": "company_workload_identity_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 + }, + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "algorithm": { + "name": "algorithm", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_jwk": { + "name": "public_jwk", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "private_key_material": { + "name": "private_key_material", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status_changed_at": { + "name": "status_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_workload_identity_keys_company_key_uq": { + "name": "company_workload_identity_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_active_uq": { + "name": "company_workload_identity_keys_one_active_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'active'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_next_uq": { + "name": "company_workload_identity_keys_one_next_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'next'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_workload_identity_keys_company_id_companies_id_fk": { + "name": "company_workload_identity_keys_company_id_companies_id_fk", + "tableFrom": "company_workload_identity_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_workload_identity_keys_algorithm_check": { + "name": "company_workload_identity_keys_algorithm_check", + "value": "\"company_workload_identity_keys\".\"algorithm\" = 'ES256'" + }, + "company_workload_identity_keys_status_check": { + "name": "company_workload_identity_keys_status_check", + "value": "\"company_workload_identity_keys\".\"status\" in ('next', 'active', 'retiring', 'retired')" + } + }, + "isRLSEnabled": false + }, "public.completion_contracts": { "name": "completion_contracts", "schema": "", @@ -23092,7 +23266,7 @@ "checkConstraints": { "cost_events_usage_kind_check": { "name": "cost_events_usage_kind_check", - "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response', 'prompt_injection') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" + "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response', 'prompt_injection', 'responsibility_summary') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" }, "cost_events_nonnegative_amounts": { "name": "cost_events_nonnegative_amounts", @@ -52317,6 +52491,1492 @@ }, "isRLSEnabled": false }, + "public.responsibilities": { + "name": "responsibilities", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "area_id": { + "name": "area_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "standard": { + "name": "standard", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_kind": { + "name": "metric_kind", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_name": { + "name": "metric_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_unit": { + "name": "metric_unit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_target": { + "name": "metric_target", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_low": { + "name": "metric_low", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_high": { + "name": "metric_high", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_current": { + "name": "metric_current", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_direction": { + "name": "metric_direction", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'at_least'" + }, + "metric_updated_at": { + "name": "metric_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "run_by_agent_id": { + "name": "run_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "evidence": { + "name": "evidence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "health_override": { + "name": "health_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "health_note": { + "name": "health_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "proposed_by_agent_id": { + "name": "proposed_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "confirmed_at": { + "name": "confirmed_at", + "type": "timestamp with time zone", + "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": { + "responsibilities_company_owner_status_idx": { + "name": "responsibilities_company_owner_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibilities_area_idx": { + "name": "responsibilities_area_idx", + "columns": [ + { + "expression": "area_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibilities_company_id_companies_id_fk": { + "name": "responsibilities_company_id_companies_id_fk", + "tableFrom": "responsibilities", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibilities_area_id_responsibility_areas_id_fk": { + "name": "responsibilities_area_id_responsibility_areas_id_fk", + "tableFrom": "responsibilities", + "tableTo": "responsibility_areas", + "columnsFrom": [ + "area_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_run_by_agent_id_agents_id_fk": { + "name": "responsibilities_run_by_agent_id_agents_id_fk", + "tableFrom": "responsibilities", + "tableTo": "agents", + "columnsFrom": [ + "run_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_proposed_by_agent_id_agents_id_fk": { + "name": "responsibilities_proposed_by_agent_id_agents_id_fk", + "tableFrom": "responsibilities", + "tableTo": "agents", + "columnsFrom": [ + "proposed_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_owned_area_fk": { + "name": "responsibilities_owned_area_fk", + "tableFrom": "responsibilities", + "tableTo": "responsibility_areas", + "columnsFrom": [ + "company_id", + "owner_user_id", + "area_id" + ], + "columnsTo": [ + "company_id", + "owner_user_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibilities_status_check": { + "name": "responsibilities_status_check", + "value": "\"responsibilities\".\"status\" in ('proposed', 'active', 'let_go', 'dismissed')" + }, + "responsibilities_source_check": { + "name": "responsibilities_source_check", + "value": "\"responsibilities\".\"source\" in ('manual', 'onboarding')" + }, + "responsibilities_health_override_check": { + "name": "responsibilities_health_override_check", + "value": "\"responsibilities\".\"health_override\" is null or \"responsibilities\".\"health_override\" in ('behind', 'at_risk', 'on_track')" + }, + "responsibilities_metric_direction_check": { + "name": "responsibilities_metric_direction_check", + "value": "\"responsibilities\".\"metric_direction\" is null or \"responsibilities\".\"metric_direction\" in ('at_least', 'at_most')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_areas": { + "name": "responsibility_areas", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "proposed_by_agent_id": { + "name": "proposed_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "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": { + "responsibility_areas_company_status_idx": { + "name": "responsibility_areas_company_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_areas_identity_uq": { + "name": "responsibility_areas_identity_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_areas_owner_title_uq": { + "name": "responsibility_areas_owner_title_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"title\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_areas\".\"status\" <> 'archived'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_areas_company_id_companies_id_fk": { + "name": "responsibility_areas_company_id_companies_id_fk", + "tableFrom": "responsibility_areas", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_areas_proposed_by_agent_id_agents_id_fk": { + "name": "responsibility_areas_proposed_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_areas", + "tableTo": "agents", + "columnsFrom": [ + "proposed_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_areas_status_check": { + "name": "responsibility_areas_status_check", + "value": "\"responsibility_areas\".\"status\" in ('proposed', 'active', 'archived')" + }, + "responsibility_areas_source_check": { + "name": "responsibility_areas_source_check", + "value": "\"responsibility_areas\".\"source\" in ('manual', 'onboarding')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_dashboard_versions": { + "name": "responsibility_dashboard_versions", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cause": { + "name": "cause", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "snapshot_hash": { + "name": "snapshot_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_agent_id": { + "name": "actor_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "interaction_id": { + "name": "interaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "previous_version_id": { + "name": "previous_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "restored_from_version_id": { + "name": "restored_from_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_dashboard_versions_owner_created_idx": { + "name": "responsibility_dashboard_versions_owner_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_dashboard_versions_company_id_companies_id_fk": { + "name": "responsibility_dashboard_versions_company_id_companies_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_actor_agent_id_agents_id_fk": { + "name": "responsibility_dashboard_versions_actor_agent_id_agents_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "agents", + "columnsFrom": [ + "actor_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_issue_id_issues_id_fk": { + "name": "responsibility_dashboard_versions_issue_id_issues_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_previous_version_id_responsibility_dashboard_versions_id_fk": { + "name": "responsibility_dashboard_versions_previous_version_id_responsibility_dashboard_versions_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "responsibility_dashboard_versions", + "columnsFrom": [ + "previous_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_restored_from_version_id_responsibility_dashboard_versions_id_fk": { + "name": "responsibility_dashboard_versions_restored_from_version_id_responsibility_dashboard_versions_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "responsibility_dashboard_versions", + "columnsFrom": [ + "restored_from_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_dashboard_versions_cause_check": { + "name": "responsibility_dashboard_versions_cause_check", + "value": "\"responsibility_dashboard_versions\".\"cause\" in ('change_set', 'person', 'restore')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_links": { + "name": "responsibility_links", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "routine_id": { + "name": "routine_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "skill_id": { + "name": "skill_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_links_responsibility_idx": { + "name": "responsibility_links_responsibility_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_project_uq": { + "name": "responsibility_links_responsibility_project_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"project_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_issue_uq": { + "name": "responsibility_links_responsibility_issue_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"issue_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_routine_uq": { + "name": "responsibility_links_responsibility_routine_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "routine_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"routine_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_skill_uq": { + "name": "responsibility_links_responsibility_skill_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"skill_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_project_idx": { + "name": "responsibility_links_project_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_issue_idx": { + "name": "responsibility_links_issue_idx", + "columns": [ + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_routine_idx": { + "name": "responsibility_links_routine_idx", + "columns": [ + { + "expression": "routine_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_skill_idx": { + "name": "responsibility_links_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_links_company_id_companies_id_fk": { + "name": "responsibility_links_company_id_companies_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_links_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_project_id_projects_id_fk": { + "name": "responsibility_links_project_id_projects_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_issue_id_issues_id_fk": { + "name": "responsibility_links_issue_id_issues_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_routine_id_routines_id_fk": { + "name": "responsibility_links_routine_id_routines_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "routines", + "columnsFrom": [ + "routine_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_skill_id_company_skills_id_fk": { + "name": "responsibility_links_skill_id_company_skills_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "company_skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_links_single_target_check": { + "name": "responsibility_links_single_target_check", + "value": "(\"responsibility_links\".\"project_id\" is not null)::int + (\"responsibility_links\".\"issue_id\" is not null)::int + (\"responsibility_links\".\"routine_id\" is not null)::int + (\"responsibility_links\".\"skill_id\" is not null)::int = 1" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_metric_readings": { + "name": "responsibility_metric_readings", + "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 + }, + "metric_id": { + "name": "metric_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "recorded_by_agent_id": { + "name": "recorded_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "recorded_by_user_id": { + "name": "recorded_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_metric_readings_metric_recorded_idx": { + "name": "responsibility_metric_readings_metric_recorded_idx", + "columns": [ + { + "expression": "metric_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recorded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_metric_readings_company_id_companies_id_fk": { + "name": "responsibility_metric_readings_company_id_companies_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metric_readings_metric_id_responsibility_metrics_id_fk": { + "name": "responsibility_metric_readings_metric_id_responsibility_metrics_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "responsibility_metrics", + "columnsFrom": [ + "metric_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metric_readings_recorded_by_agent_id_agents_id_fk": { + "name": "responsibility_metric_readings_recorded_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "agents", + "columnsFrom": [ + "recorded_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.responsibility_metrics": { + "name": "responsibility_metrics", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display": { + "name": "display", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target": { + "name": "target", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "direction": { + "name": "direction", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "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_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": { + "responsibility_metrics_responsibility_status_position_idx": { + "name": "responsibility_metrics_responsibility_status_position_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_metrics_company_id_companies_id_fk": { + "name": "responsibility_metrics_company_id_companies_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metrics_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_metrics_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metrics_created_by_agent_id_agents_id_fk": { + "name": "responsibility_metrics_created_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_metrics_display_check": { + "name": "responsibility_metrics_display_check", + "value": "\"responsibility_metrics\".\"display\" in ('number', 'percent', 'line', 'bar')" + }, + "responsibility_metrics_direction_check": { + "name": "responsibility_metrics_direction_check", + "value": "\"responsibility_metrics\".\"direction\" is null or \"responsibility_metrics\".\"direction\" in ('at_least', 'at_most')" + }, + "responsibility_metrics_status_check": { + "name": "responsibility_metrics_status_check", + "value": "\"responsibility_metrics\".\"status\" in ('active', 'archived')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_status_reports": { + "name": "responsibility_status_reports", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_status_reports_responsibility_created_idx": { + "name": "responsibility_status_reports_responsibility_created_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_status_reports_company_id_companies_id_fk": { + "name": "responsibility_status_reports_company_id_companies_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_status_reports_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_status_reports_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_status_reports_agent_id_agents_id_fk": { + "name": "responsibility_status_reports_agent_id_agents_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_status_reports_status_check": { + "name": "responsibility_status_reports_status_check", + "value": "\"responsibility_status_reports\".\"status\" in ('behind', 'at_risk', 'on_track', 'unknown')" + }, + "responsibility_status_reports_author_check": { + "name": "responsibility_status_reports_author_check", + "value": "not (\"responsibility_status_reports\".\"agent_id\" is not null and \"responsibility_status_reports\".\"user_id\" is not null)" + } + }, + "isRLSEnabled": false + }, "public.routine_documents": { "name": "routine_documents", "schema": "", @@ -59417,7 +61077,7 @@ }, "tool_connections_transport_check": { "name": "tool_connections_transport_check", - "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth')" + "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth', 'plugin')" }, "tool_connections_purpose_check": { "name": "tool_connections_purpose_check", @@ -70108,6 +71768,355 @@ } }, "isRLSEnabled": false + }, + "public.responsibility_summary_invocations": { + "name": "responsibility_summary_invocations", + "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 + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt_version": { + "name": "prompt_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_request_id": { + "name": "provider_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cost_event_id": { + "name": "cost_event_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "responsibility_summary_invocations_company_started_idx": { + "name": "responsibility_summary_invocations_company_started_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_summary_invocations_pending_idx": { + "name": "responsibility_summary_invocations_pending_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"responsibility_summary_invocations\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_summary_invocations_cost_idx": { + "name": "responsibility_summary_invocations_cost_idx", + "columns": [ + { + "expression": "cost_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_summary_invocations_company_id_companies_id_fk": { + "name": "responsibility_summary_invocations_company_id_companies_id_fk", + "tableFrom": "responsibility_summary_invocations", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_summary_invocations_cost_event_id_cost_events_id_fk": { + "name": "responsibility_summary_invocations_cost_event_id_cost_events_id_fk", + "tableFrom": "responsibility_summary_invocations", + "tableTo": "cost_events", + "columnsFrom": [ + "cost_event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_summary_invocations_feature_check": { + "name": "responsibility_summary_invocations_feature_check", + "value": "\"responsibility_summary_invocations\".\"feature\" in ('where_things_stand', 'what_is_affecting_the_number')" + }, + "responsibility_summary_invocations_status_check": { + "name": "responsibility_summary_invocations_status_check", + "value": "\"responsibility_summary_invocations\".\"status\" in ('running', 'succeeded', 'failed', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.plugin_connector_legacy_access": { + "name": "plugin_connector_legacy_access", + "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 + }, + "plugin_key": { + "name": "plugin_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "plugin_connector_legacy_access_company_plugin_uq": { + "name": "plugin_connector_legacy_access_company_plugin_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "plugin_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_connector_legacy_access_company_id_companies_id_fk": { + "name": "plugin_connector_legacy_access_company_id_companies_id_fk", + "tableFrom": "plugin_connector_legacy_access", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "plugin_connector_legacy_access_connection_id_tool_connections_id_fk": { + "name": "plugin_connector_legacy_access_connection_id_tool_connections_id_fk", + "tableFrom": "plugin_connector_legacy_access", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false } }, "enums": {}, diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 3f8b34ca8e2..dac3100b055 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3487,6 +3487,13 @@ "when": 1795048062306, "tag": "0499_numerous_whizzer", "breakpoints": true + }, + { + "idx": 500, + "version": "7", + "when": 1795206084746, + "tag": "0500_funny_malcolm_colcord", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/responsibilities.ts b/packages/db/src/schema/responsibilities.ts index 15b8655992d..a574a42c237 100644 --- a/packages/db/src/schema/responsibilities.ts +++ b/packages/db/src/schema/responsibilities.ts @@ -1,6 +1,7 @@ import { sql } from "drizzle-orm"; import { check, + foreignKey, index, integer, numeric, @@ -18,17 +19,13 @@ import { issues } from "./issues.js"; import { projects } from "./projects.js"; import { routines } from "./routines.js"; -/** - * A broad area a company cares about ("Fundraising", "Customers"). An area - * has no owner and no deadline; responsibilities are filed under it. Agents - * can only propose areas; a board user (or confirming a responsibility under - * it) makes one active. - */ +/** A person's dashboard grouping. Unattributable legacy areas have no owner and are hidden. */ export const responsibilityAreas = pgTable( "responsibility_areas", { id: uuid("id").primaryKey().defaultRandom(), companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + ownerUserId: text("owner_user_id"), title: text("title").notNull(), description: text("description"), status: text("status").notNull().default("active"), @@ -40,9 +37,9 @@ export const responsibilityAreas = pgTable( }, (table) => ({ companyStatusIdx: index("responsibility_areas_company_status_idx").on(table.companyId, table.status), - // At most one non-archived area per company per case-insensitive title. - companyTitleUq: uniqueIndex("responsibility_areas_company_title_uq") - .on(table.companyId, sql`lower(${table.title})`) + ownerIdentity: uniqueIndex("responsibility_areas_identity_uq").on(table.companyId, table.ownerUserId, table.id), + ownerTitleUq: uniqueIndex("responsibility_areas_owner_title_uq") + .on(table.companyId, table.ownerUserId, sql`lower(${table.title})`) .where(sql`${table.status} <> 'archived'`), statusCheck: check( "responsibility_areas_status_check", @@ -106,6 +103,11 @@ export const responsibilities = pgTable( table.ownerUserId, table.status, ), + ownedArea: foreignKey({ + name: "responsibilities_owned_area_fk", + columns: [table.companyId, table.ownerUserId, table.areaId], + foreignColumns: [responsibilityAreas.companyId, responsibilityAreas.ownerUserId, responsibilityAreas.id], + }), areaIdx: index("responsibilities_area_idx").on(table.areaId), statusCheck: check( "responsibilities_status_check", diff --git a/packages/shared/src/types/responsibility.ts b/packages/shared/src/types/responsibility.ts index f577647e59d..ca7eb329f98 100644 --- a/packages/shared/src/types/responsibility.ts +++ b/packages/shared/src/types/responsibility.ts @@ -16,7 +16,7 @@ import type { } from "../constants.js"; /** - * A broad area a company cares about ("Fundraising"). No owner, no deadline. + * A broad area on the acting person's dashboard ("Fundraising"). * Responsibilities are filed under an area (experimental, `enableResponsibilities`). */ export interface ResponsibilityArea { @@ -354,7 +354,7 @@ export interface ResponsibilityLooseWork { export interface ResponsibilityOverview { ownerUserId: string; /** - * Every active area in the company, plus any other area (proposed or + * Every active area on this person's dashboard, plus any other area (proposed or * archived) that a returned responsibility is filed under. By sortOrder, * then title. */ diff --git a/server/src/__tests__/activity-routes.test.ts b/server/src/__tests__/activity-routes.test.ts index 77d3354b1ec..5553bd190fd 100644 --- a/server/src/__tests__/activity-routes.test.ts +++ b/server/src/__tests__/activity-routes.test.ts @@ -212,6 +212,7 @@ describe("activity routes", () => { expect(res.status).toBe(200); expect(mockAgentActionAuditService.list).toHaveBeenCalledWith({ companyId: "company-1", + dashboardUserId: "user-1", actorScope: "all", limit: 50, caseReadCondition, @@ -261,6 +262,7 @@ describe("activity routes", () => { expect(res.status).toBe(200); expect(mockAgentActionAuditService.list).toHaveBeenCalledWith({ companyId: "company-1", + dashboardUserId: "user-1", actorScope: "all", actorType: "system", limit: 50, @@ -284,6 +286,7 @@ describe("activity routes", () => { expect(res.status).toBe(200); expect(mockActivityService.list).toHaveBeenCalledWith({ companyId: "company-1", + dashboardUserId: "user-1", agentId: undefined, entityType: undefined, entityId: undefined, @@ -304,6 +307,7 @@ describe("activity routes", () => { expect(res.status).toBe(200); expect(mockActivityService.list).toHaveBeenCalledWith({ companyId: "company-1", + dashboardUserId: "user-1", agentId: undefined, entityType: "issue", entityId: undefined, diff --git a/server/src/__tests__/issue-access-grants-routes.test.ts b/server/src/__tests__/issue-access-grants-routes.test.ts index c6e5dae4c73..4ba7af26ee7 100644 --- a/server/src/__tests__/issue-access-grants-routes.test.ts +++ b/server/src/__tests__/issue-access-grants-routes.test.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import express from "express"; +import { eq } from "drizzle-orm"; import request from "supertest"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { @@ -214,6 +215,31 @@ describeEmbeddedPostgres("issue access grant and locked edge routes", { concurre }; } + it("protects personal dashboard conversations from break-glass and title writes by teammates", async () => { + const fixture = await seedFixture(); + const issueId = fixture.privateIssueId; + await db.update(issues).set({ + originKind: "responsibility_dashboard", + originId: fixture.ownerId, + projectId: null, + }).where(eq(issues.id, issueId)); + const owner = await createApp(db, boardActor(fixture.companyId, fixture.ownerId)); + const admin = await createApp(db, boardActor(fixture.companyId, fixture.adminId)); + const member = await createApp(db, boardActor(fixture.companyId, fixture.memberId)); + + await request(admin).get(`/api/issues/${issueId}?breakGlass=true&view=core`).expect(404); + await request(member).put(`/api/issues/${issueId}/title`).send({ title: "Another title" }).expect(404); + await request(member).put(`/api/issues/${issueId}/title`).send({ + title: "Another title", onlyIfProvisional: true, + }).expect(404); + await request(admin).post(`/api/issues/${issueId}/admin/force-release`).expect(404); + const original = await request(owner).get(`/api/issues/${issueId}?view=core`).expect(200); + expect(original.body.title).toBe("Confidential root"); + const renamed = await request(owner).put(`/api/issues/${issueId}/title`).send({ title: "My dashboard" }).expect(200); + expect(renamed.body.title).toBe("My dashboard"); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "issue.break_glass_read"))).toEqual([]); + }); + it("requires explicit owner/admin break-glass and records both audit evidence and an owner-visible notice", async () => { const fixture = await seedFixture(); const adminApp = await createApp(db, boardActor(fixture.companyId, fixture.adminId)); diff --git a/server/src/__tests__/responsibilities.test.ts b/server/src/__tests__/responsibilities.test.ts index be6e1e0995d..65955c6e660 100644 --- a/server/src/__tests__/responsibilities.test.ts +++ b/server/src/__tests__/responsibilities.test.ts @@ -240,12 +240,11 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(created.status).toBe(201); expect(created.body).toMatchObject({ ownerUserId: OWNER, status: "active" }); - // A named owner still wins, and a run that works for no person must name one. + // A caller-supplied owner cannot change the verified dashboard. const other = await request(forOwner).get(`/api/companies/${company.id}/responsibilities?ownerUserId=other-user`); - expect(other.body.ownerUserId).toBe("other-user"); + expect(other.status).toBe(404); const unbound = await request(createApp(db, agentActor(company.id, agent.id))).get(`/api/companies/${company.id}/responsibilities`); - expect(unbound.status).toBe(422); - expect(unbound.body.error).toContain("this run works for no person"); + expect(unbound.status).toBe(403); }); it("refuses a half-filled bar, and derives status from the metric", async () => { @@ -367,68 +366,22 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(halfAgain.status).toBe(422); }); - it("lets agents only propose, and confirming activates a proposed area in the same step", async () => { + it("keeps proposals inside the directing person's dashboard and activates their area on confirmation", async () => { await enable(); const company = await seedCompany(); const guide = await seedAgent(company.id); - const agentApp = createApp(db, agentActor(company.id, guide.id)); - const boardApp = createApp(db, localBoardActor()); - - const area = await request(agentApp).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Fundraising", status: "active" }); - expect(area.status).toBe(201); - expect(area.body).toMatchObject({ status: "proposed", source: "onboarding", proposedByAgentId: guide.id }); - - expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Pipeline", ...METRIC })).status).toBe(422); - expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "Pipeline", ...METRIC, ownerUserId: "stranger" })).status).toBe(404); - // An agent always proposes the whole bar: a title alone, or the sentence alone, is refused. - expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "Pipeline", ownerUserId: OWNER })).status).toBe(400); - expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "Pipeline", ownerUserId: OWNER, standard: METRIC.standard })).status).toBe(400); - expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "Pipeline", ownerUserId: OWNER, standard: METRIC.standard, metricName: METRIC.metricName })).status).toBe(400); - - const proposed = await request(agentApp).post(`/api/companies/${company.id}/responsibilities`).send({ - title: "Pipeline", - ...METRIC, - ownerUserId: OWNER, - areaId: area.body.id, - status: "active", - evidence: "Three pipeline reviews on the calendar every week", - }); - expect(proposed.status).toBe(201); - expect(proposed.body).toMatchObject({ status: "proposed", source: "onboarding", proposedByAgentId: guide.id, confirmedAt: null, areaId: area.body.id }); - - const listed = await request(agentApp).get(`/api/companies/${company.id}/responsibilities?ownerUserId=${OWNER}`); - expect(listed.body.proposed.map((row: { id: string }) => row.id)).toEqual([proposed.body.id]); - // A proposed area a returned responsibility references is included. - expect(listed.body.areas.map((row: { id: string; status: string }) => [row.id, row.status])).toEqual([[area.body.id, "proposed"]]); - - expect((await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ status: "active" })).status).toBe(403); - const edited = await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ title: "Deal pipeline" }); - expect(edited.status).toBe(200); - - const confirmed = await request(boardApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ status: "active" }); - expect(confirmed.status).toBe(200); - expect(confirmed.body.confirmedAt).not.toBeNull(); - const [areaRow] = await db.select().from(responsibilityAreas).where(eq(responsibilityAreas.id, area.body.id)); - expect(areaRow?.status).toBe("active"); - const logged = await actions(company.id); - expect(logged).toEqual(expect.arrayContaining([ - expect.objectContaining({ action: "responsibility_area.created", entityId: area.body.id }), - expect.objectContaining({ action: "responsibility_area.activated", entityId: area.body.id }), - ])); - - // Once confirmed, the agent can no longer edit it (beyond the metric) and cannot delete it. - expect((await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ title: "x" })).status).toBe(403); - expect((await request(agentApp).delete(`/api/responsibilities/${proposed.body.id}`)).status).toBe(403); - - const dismissible = await request(agentApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "Portfolio", ...METRIC, ownerUserId: OWNER }); - const dismissed = await request(agentApp).patch(`/api/responsibilities/${dismissible.body.id}`).send({ status: "dismissed" }); - expect(dismissed.status).toBe(200); - expect(dismissed.body.status).toBe("dismissed"); + const agent = await actingAgent(company.id, guide.id); + const unbound = createApp(db, agentActor(company.id, guide.id)); + const board = createApp(db, localBoardActor()); + const path = `/api/companies/${company.id}/responsibilities`; + const areas = `/api/companies/${company.id}/responsibility-areas`; + await request(unbound).post(areas).send({ title: "Fundraising" }).expect(403); + await request(unbound).post(path).send({ title: "Pipeline", ...METRIC, ownerUserId: OWNER }).expect(403); + const area = (await request(agent).post(areas).send({ title: "Fundraising", status: "proposed" }).expect(201)).body; + const item = (await request(agent).post(path).send({ title: "Pipeline", ...METRIC, areaId: area.id, status: "proposed" }).expect(201)).body; + expect((await request(board).get(path)).body.proposed.map((r: Created) => r.id)).toEqual([item.id]); + await request(board).patch(`/api/responsibilities/${item.id}`).send({ status: "active" }).expect(200); + expect((await request(board).get(areas)).body[0]).toMatchObject({ id: area.id, status: "active" }); }); it("lets only the running or assigned agent report the metric on an active responsibility", async () => { @@ -474,16 +427,16 @@ describeEmbeddedPostgres("responsibility routes", () => { expect((await actions(company.id)).some((entry) => entry.action === "responsibility.updated")).toBe(false); }); - it("keeps board users to their own responsibilities unless they administer the company", async () => { + it("keeps board users to their own responsibilities including company administrators", async () => { await enable(); const company = await seedCompany(); const ownerApp = createApp(db, localBoardActor()); const area = await createResponsibility(ownerApp, company.id); const operatorApp = createApp(db, sessionBoardActor(company.id, "other-user")); - expect((await request(operatorApp).get(`/api/responsibilities/${area.id}`)).status).toBe(200); - expect((await request(operatorApp).patch(`/api/responsibilities/${area.id}`).send({ title: "Mine now" })).status).toBe(403); + expect((await request(operatorApp).get(`/api/responsibilities/${area.id}`)).status).toBe(404); + expect((await request(operatorApp).patch(`/api/responsibilities/${area.id}`).send({ title: "Mine now" })).status).toBe(404); expect((await request(operatorApp).post(`/api/companies/${company.id}/responsibilities`) - .send({ title: "For someone else", ...METRIC, ownerUserId: OWNER })).status).toBe(403); + .send({ title: "For someone else", ...METRIC, ownerUserId: OWNER })).status).toBe(404); const own = await createResponsibility(operatorApp, company.id, { title: "Ops" }); expect(own.ownerUserId).toBe("other-user"); }); @@ -519,7 +472,7 @@ describeEmbeddedPostgres("responsibility routes", () => { expect((await request(boardApp).patch(`/api/responsibilities/${area.id}`).send({ areaId: otherArea.body.id })).status).toBe(404); expect((await request(boardApp).post(`/api/companies/${company.id}/responsibilities`) .send({ title: "x", ...METRIC, runByAgentId: otherAgent.id })).status).toBe(404); - expect((await request(boardApp).patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(200); + expect((await request(boardApp).patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(404); expect((await request(createApp(db, sessionBoardActor(company.id, OWNER, "owner"))) .patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(404); expect(await db.select().from(responsibilityLinks).where(eq(responsibilityLinks.companyId, company.id))).toHaveLength(0); @@ -622,8 +575,7 @@ describeEmbeddedPostgres("responsibility routes", () => { const guide = await seedAgent(company.id); const agentLookup = await request(createApp(db, agentActor(company.id, guide.id))) .get(`/api/companies/${company.id}/responsibility-links/lookup?issueId=${task.id}`); - expect(agentLookup.status).toBe(200); - expect(agentLookup.body.responsibilities).toHaveLength(2); + expect(agentLookup.status).toBe(403); }); it("manages areas: idempotent create, board-only edits, delete keeps responsibilities", async () => { @@ -641,17 +593,17 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(same.status).toBe(200); expect(same.body.id).toBe(created.body.id); const agentSame = await request(agentApp).post(areasPath).send({ title: "FUNDRAISING" }); - expect(agentSame.status).toBe(200); - expect(agentSame.body).toMatchObject({ id: created.body.id, status: "active" }); - const customers = await request(agentApp).post(areasPath).send({ title: "Customers" }); + expect(agentSame.status).toBe(403); + const customers = await request(boardApp).post(areasPath).send({ title: "Customers", status: "proposed" }); expect(customers.body.status).toBe("proposed"); expect((await request(agentApp).patch(`/api/responsibility-areas/${created.body.id}`).send({ title: "x" })).status).toBe(403); expect((await request(agentApp).delete(`/api/responsibility-areas/${created.body.id}`)).status).toBe(403); expect((await request(createApp(db, sessionBoardActor(company.id, "viewer", "viewer"))).post(areasPath).send({ title: "Viewers" })).status).toBe(403); - // Any board user with write access manages areas: they have no owner. + // The owner alone can activate the area. const operatorApp = createApp(db, sessionBoardActor(company.id, "other-user")); - expect((await request(operatorApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 })).status).toBe(200); + expect((await request(operatorApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 })).status).toBe(404); + await request(boardApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 }).expect(200); const clash = await request(boardApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ title: "fundraising" }); expect(clash.status).toBe(409); @@ -1049,7 +1001,7 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(unfiled.body.unfiled).toHaveLength(1); }); - it("may not change what the person could not, and stays propose-only without a person", async () => { + it("may not change what the person could not, and needs a directing person for proposals", async () => { await enable(); const company = await seedCompany(); const agent = await seedAgent(company.id); @@ -1058,21 +1010,15 @@ describeEmbeddedPostgres("responsibility routes", () => { // An operator may not manage the owner's responsibilities, so neither may an agent acting for one. const forOperator = await actingAgent(company.id, agent.id, "other-user", "operator"); - expect((await request(forOperator).patch(`/api/responsibilities/${mine.id}`).send({ title: "x" })).status).toBe(403); - expect((await request(forOperator).post(`/api/responsibilities/${mine.id}/file`).send({ items: [{ kind: "routine", id: randomUUID() }], moveFrom: "all" })).status).toBe(403); + expect((await request(forOperator).patch(`/api/responsibilities/${mine.id}`).send({ title: "x" })).status).toBe(404); + expect((await request(forOperator).post(`/api/responsibilities/${mine.id}/file`).send({ items: [{ kind: "routine", id: randomUUID() }], moveFrom: "all" })).status).toBe(404); const alone = createApp(db, agentActor(company.id, agent.id)); expect((await request(alone).patch(`/api/responsibility-areas/${randomUUID()}`).send({ title: "x" })).status).toBe(404); const area = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "People" }); expect((await request(alone).patch(`/api/responsibility-areas/${area.body.id}`).send({ title: "x" })).status).toBe(403); const proposal = await request(alone).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops", ownerUserId: OWNER, ...METRIC }); - expect(proposal.body.status).toBe("proposed"); - // Filing under its proposal works as with /links (what create_responsibility's fileItems does); moving does not. - const routine = await db.insert(routines).values({ companyId: company.id, title: "Weekly ops" }).returning().then((r) => r[0]!); - const filed = await request(alone).post(`/api/responsibilities/${proposal.body.id}/file`).send({ items: [{ kind: "routine", id: routine.id }] }); - expect(filed.status).toBe(200); - expect(filed.headers["x-paperclip-dashboard-version"]).toBeUndefined(); - expect((await request(alone).post(`/api/responsibilities/${proposal.body.id}/file`).send({ items: [{ kind: "routine", id: routine.id }], moveFrom: mine.id })).status).toBe(403); + expect(proposal.status).toBe(403); }); it("does not borrow the authority of a person someone else named, or of the company default", async () => { @@ -1097,7 +1043,7 @@ describeEmbeddedPostgres("responsibility routes", () => { expect((await request(app).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops" })).status).toBe(400); } const proposal = await request(noTask).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops", ...METRIC }); - expect(proposal.body).toMatchObject({ ownerUserId: OWNER, status: "proposed" }); + expect(proposal.status).toBe(403); const [row] = await db.select().from(responsibilities).where(eq(responsibilities.id, mine.id)); expect(row?.status).toBe("active"); }); @@ -1248,30 +1194,12 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(areaRow?.description).toBe("Who we hire"); }); - it("reports no Undo for a shared area's new description, and Undo of a delete brings the description back", async () => { + it("restores the private area description after a confirmed deletion", async () => { await enable(); const company = await seedCompany(); const agent = await seedAgent(company.id); const app = await actingAgent(company.id, agent.id); const board = createApp(db, localBoardActor()); - const shared = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "People", description: "Who we hire" }); - await createResponsibility(board, company.id, { title: "Hiring", areaId: shared.body.id }); - // The other person's responsibility there is only proposed; the area is still shared. - const other = await createResponsibility(board, company.id, { title: "Onboarding", areaId: shared.body.id, ownerUserId: "other-user" }); - await db.update(responsibilities).set({ status: "proposed" }).where(eq(responsibilities.id, other.id)); - const before = await latestVersion(company.id); - const described = await request(app).patch(`/api/responsibility-areas/${shared.body.id}`).send({ description: "Hiring and onboarding" }); - expect(described.status).toBe(200); - expect(described.headers["x-paperclip-dashboard-version"]).toBeUndefined(); - // No version is saved, so no Dashboard offers an Undo that would leave the description as it is. - expect((await latestVersion(company.id))?.id).toBe(before?.id); - // Nor for a shared area's status change Undo cannot reverse, such as confirming a proposed area. - await db.update(responsibilityAreas).set({ status: "proposed" }).where(eq(responsibilityAreas.id, shared.body.id)); - const confirmed = await request(app).patch(`/api/responsibility-areas/${shared.body.id}`).send({ status: "active" }); - expect(confirmed.status).toBe(200); - expect(confirmed.headers["x-paperclip-dashboard-version"]).toBeUndefined(); - expect((await latestVersion(company.id))?.id).toBe(before?.id); - const mine = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Money", description: "Cash and runway" }); await createResponsibility(board, company.id, { title: "Runway", areaId: mine.body.id }); const [card] = await db.insert(issueThreadInteractions).values({ @@ -1352,7 +1280,7 @@ describeEmbeddedPostgres("responsibility routes", () => { // An agent acting for an operator may not change the owner's active responsibility: no area is left behind. const refused = await request(await actingAgent(company.id, agent.id, "other-user", "operator")) .patch(`/api/responsibilities/${created.body.id}`).send({ areaTitle: "Elsewhere" }); - expect(refused.status).toBe(403); + expect(refused.status).toBe(404); expect(await db.select().from(responsibilityAreas).where(eq(responsibilityAreas.title, "Elsewhere"))).toHaveLength(0); expect((await request(await actingAgent(company.id, agent.id)).patch(`/api/responsibilities/${created.body.id}`) .send({ areaTitle: "People", areaId: people!.id })).status).toBe(422); @@ -1374,14 +1302,14 @@ describeEmbeddedPostgres("responsibility routes", () => { expect(deleted.status).toBe(200); }); - it("saves a version for everyone whose responsibilities an area delete moves", async () => { + it("saves the moved responsibilities in the owner’s history", async () => { await enable(); const company = await seedCompany(); const agent = await seedAgent(company.id); const board = createApp(db, localBoardActor()); const from = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Money" }); const to = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Finance" }); - await createResponsibility(board, company.id, { title: "Runway", areaId: from.body.id, ownerUserId: "other-user" }); + await createResponsibility(board, company.id, { title: "Runway", areaId: from.body.id }); const chat = await db.insert(issues).values({ companyId: company.id, title: "Chat", status: "in_progress", priority: "medium" }).returning().then((r) => r[0]!); const [card] = await db.insert(issueThreadInteractions).values({ companyId: company.id, issueId: chat.id, kind: "request_confirmation", status: "accepted", createdByAgentId: agent.id, @@ -1391,7 +1319,7 @@ describeEmbeddedPostgres("responsibility routes", () => { const removed = await request(await actingAgent(company.id, agent.id)) .delete(`/api/responsibility-areas/${from.body.id}?confirmationId=${card!.id}&moveResponsibilitiesTo=${to.body.id}`); expect(removed.status).toBe(200); - expect(await latestVersion(company.id, "other-user")).toMatchObject({ cause: "change_set", actorAgentId: agent.id }); + expect(await latestVersion(company.id, "other-user")).toBeNull(); // The response names the acting person's version, not the other owner's. expect(removed.headers["x-paperclip-dashboard-owner"]).toBe(OWNER); expect(removed.headers["x-paperclip-dashboard-version"]).toBe((await latestVersion(company.id))?.id); diff --git a/server/src/__tests__/responsibility-automation-conversations.test.ts b/server/src/__tests__/responsibility-automation-conversations.test.ts index 3b7d9b41a07..afd24de212b 100644 --- a/server/src/__tests__/responsibility-automation-conversations.test.ts +++ b/server/src/__tests__/responsibility-automation-conversations.test.ts @@ -274,14 +274,14 @@ describeEmbeddedPostgres("automation conversations and standing checks", () => { expect(started.body.details?.code ?? started.body.code).toBe("routine_from_task_private"); expect(await db.select().from(issues).where(eq(issues.originId, privateId))).toHaveLength(0); const [open] = await db.select().from(issues).where(eq(issues.id, (await start(seeded, seeded.tasks.weekly.id, { agentId: seeded.agents.analyst.id })).body.conversation.issueId)); - expect(open).toMatchObject({ visibility: "open" }); + expect(open).toMatchObject({ visibility: "private", responsibleUserId: OWNER }); }); it("lets only the conversation's agent propose, validates, keeps one pending, and creates nothing", async () => { const seeded = await seed(); const started = await start(seeded, seeded.tasks.weekly.id, { agentId: seeded.agents.analyst.id }); const issueId = started.body.conversation.issueId as string; - expect((await propose(seeded, seeded.agents.watcher.id, issueId, SCHEDULE)).status).toBe(403); + expect((await propose(seeded, seeded.agents.watcher.id, issueId, SCHEDULE)).status).toBe(404); expect((await request(seeded.app).post(`/api/issues/${issueId}/automation-proposals`).send(SCHEDULE)).status).toBe(403); expect((await propose(seeded, seeded.agents.analyst.id, seeded.tasks.weekly.id, SCHEDULE)).status).toBe(422); expect((await propose(seeded, seeded.agents.analyst.id, issueId, { ...SCHEDULE, trigger: { kind: "schedule", cadence: { frequency: "weekly", time: "16:00" } } })).status).toBe(400); @@ -318,9 +318,8 @@ describeEmbeddedPostgres("automation conversations and standing checks", () => { const before = row(await read(seeded), seeded.responsibilities.finance.id); expect(before).toMatchObject({ level: "manual", automationCount: 0, manualTaskCount: 3 }); const { issueId, interactionId } = await proposed(seeded, seeded.tasks.weekly.id, seeded.agents.analyst.id, SCHEDULE); - // A person without the assignment permission cannot accept. expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))) - .post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "UTC" })).status).toBe(403); + .post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "UTC" })).status).toBe(404); const accepts = await Promise.all([1, 2].map(() => request(seeded.app).post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "America/New_York" }))); diff --git a/server/src/__tests__/responsibility-automation.test.ts b/server/src/__tests__/responsibility-automation.test.ts index 20080c907dd..dc82f4a75e4 100644 --- a/server/src/__tests__/responsibility-automation.test.ts +++ b/server/src/__tests__/responsibility-automation.test.ts @@ -284,14 +284,14 @@ describeEmbeddedPostgres("responsibility automation read", () => { const seeded = await seed(); // Agents name the person. const agent: Actor = { type: "agent", companyId: seeded.company.id, agentId: seeded.agent.id, source: "agent_jwt" }; - expect((await read(seeded.company.id, agent)).status).toBe(422); + expect((await read(seeded.company.id, agent)).status).toBe(403); const asAgent = await read(seeded.company.id, agent, `?ownerUserId=${OWNER}`); - expect(asAgent.status).toBe(200); - expect(asAgent.body.responsibilities).toHaveLength(4); + expect(asAgent.status).toBe(403); + expect(asAgent.body.responsibilities).toBeUndefined(); // Another person's dashboard by ownerUserId. const theirs = await read(seeded.company.id, boardActor(), "?ownerUserId=someone-else"); - expect(theirs.body.responsibilities.map((item: ResponsibilityAutomation) => item.responsibilityId)).toEqual([seeded.responsibilities.someoneElse.id]); + expect(theirs.status).toBe(404); // A board user from outside the company cannot read it. const outsider: Actor = { diff --git a/server/src/__tests__/responsibility-bars.test.ts b/server/src/__tests__/responsibility-bars.test.ts index b71c1691794..44e826664fe 100644 --- a/server/src/__tests__/responsibility-bars.test.ts +++ b/server/src/__tests__/responsibility-bars.test.ts @@ -292,7 +292,7 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", ( it("lets only the agent in the conversation propose, validates the bar, and writes nothing to the responsibility", async () => { const seeded = await seed(); const issueId = (await startConversation(seeded)).body.conversation.issueId as string; - expect((await propose(seeded.company.id, seeded.analyst.id, issueId)).status).toBe(403); + expect((await propose(seeded.company.id, seeded.analyst.id, issueId)).status).toBe(404); expect((await request(seeded.app).post(`/api/issues/${issueId}/bar-proposals`).send(RANGE_PROPOSAL)).status).toBe(403); // An agent from another company cannot reach it. const elsewhere = await seed(); @@ -356,11 +356,11 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", ( const accept = (actor: Actor) => request(createApp(actor)).post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/accept`).send({}); expect((await accept(agentActor(seeded.company.id, seeded.ceo.id))).status).toBe(403); - expect((await accept(sessionBoardActor(seeded.company.id, OTHER))).status).toBe(403); - // An admin who does not own it may. - const res = await accept(sessionBoardActor(seeded.company.id, OTHER, "admin")); + expect((await accept(sessionBoardActor(seeded.company.id, OTHER))).status).toBe(404); + await accept(sessionBoardActor(seeded.company.id, OTHER, "admin")).expect(404); + const res = await accept(localBoardActor()); expect(res.status).toBe(200); - expect(res.body.interaction).toMatchObject({ status: "accepted", resolvedByUserId: OTHER, result: { outcome: "accepted", responsibilityId: seeded.responsibility.id } }); + expect(res.body.interaction).toMatchObject({ status: "accepted", resolvedByUserId: OWNER, result: { outcome: "accepted", responsibilityId: seeded.responsibility.id } }); expect(res.body.responsibility).toMatchObject({ id: seeded.responsibility.id, standard: RANGE_PROPOSAL.standard, @@ -404,7 +404,7 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", ( const issueId = (await startConversation(seeded)).body.conversation.issueId as string; const offered = await propose(seeded.company.id, seeded.ceo.id, issueId); expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))) - .post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({})).status).toBe(403); + .post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({})).status).toBe(404); const declined = await request(seeded.app).post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({}); expect(declined.status).toBe(200); expect(declined.body).toMatchObject({ status: "rejected", result: { outcome: "declined" } }); diff --git a/server/src/__tests__/responsibility-dashboard.test.ts b/server/src/__tests__/responsibility-dashboard.test.ts index ec33b6699d6..348cb82ccd1 100644 --- a/server/src/__tests__/responsibility-dashboard.test.ts +++ b/server/src/__tests__/responsibility-dashboard.test.ts @@ -1,4 +1,5 @@ import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import express from "express"; import request from "supertest"; @@ -88,6 +89,54 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () await instanceSettingsService(db).updateExperimental({ enableResponsibilities: true }); }); + it("splits a previously shared area, preserves each owner's history and hides unattributed areas", async () => { + const migration = readFileSync(new URL("../../../packages/db/src/migrations/0500_funny_malcolm_colcord.sql", import.meta.url), "utf8"); + await db.$client.begin(async (tx) => { + await tx`set local search_path to pg_temp`; + await tx.unsafe(`create temp table responsibility_areas ( + id uuid primary key, company_id uuid, title text, description text, status text default 'active', + source text, proposed_by_agent_id uuid, sort_order integer, created_at timestamptz, updated_at timestamptz + ) on commit drop`); + await tx`create unique index responsibility_areas_company_title_uq on responsibility_areas(company_id, lower(title))`; + await tx`create temp table responsibilities (id uuid, company_id uuid, owner_user_id text, area_id uuid) on commit drop`; + await tx`create temp table activity_log (company_id uuid, actor_type text, actor_id text, action text, entity_type text, entity_id text, details jsonb) on commit drop`; + await tx`create temp table responsibility_dashboard_versions (company_id uuid, owner_user_id text, snapshot jsonb, snapshot_hash text) on commit drop`; + await tx`create temp table issues (id uuid, company_id uuid, visibility text, privacy_root_issue_id uuid, responsible_user_id text, origin_id text, created_by_user_id text, origin_kind text) on commit drop`; + await tx`create temp table issue_thread_interactions (company_id uuid, kind text, status text, payload jsonb) on commit drop`; + const company = randomUUID(); + const shared = randomUUID(); + const empty = randomUUID(); + const unknown = randomUUID(); + await tx`insert into responsibility_areas (id, company_id, title) values + (${shared}, ${company}, 'Operations'), (${empty}, ${company}, 'Future work'), (${unknown}, ${company}, 'Unattributed')`; + await tx`insert into responsibilities values (gen_random_uuid(), ${company}, 'Alex', ${shared}), (gen_random_uuid(), ${company}, 'Blair', ${shared})`; + await tx`insert into activity_log values (${company}, 'user', 'Alex', 'responsibility_area.created', 'responsibility_area', ${empty}, null)`; + await tx`insert into responsibility_dashboard_versions values (${company}, 'Blair', ${JSON.stringify({ + areas: [{ id: shared, title: "Operations" }], responsibilities: [{ areaId: shared }], createdAreaIds: [shared], + })}::jsonb, 'old')`; + await tx`insert into issue_thread_interactions values (${company}, 'propose_dashboard_changes', 'pending', ${JSON.stringify({ + ownerUserId: "Blair", changes: [{ groupAreaId: shared, fromAreaId: shared }], + })}::jsonb)`; + // The old overview included every active area, even for a newcomer. + expect(await tx`select id from responsibility_areas where company_id = ${company} and status = 'active'`).toHaveLength(3); + for (const statement of migration.split("--> statement-breakpoint")) await tx.unsafe(statement); + const rows = await tx`select r.owner_user_id as owner, a.id from responsibilities r + join responsibility_areas a on a.id = r.area_id and r.owner_user_id = a.owner_user_id order by owner`; + expect(rows).toHaveLength(2); + expect(rows[0]).toEqual({ owner: "Alex", id: shared }); + expect(rows[1].id).not.toBe(shared); + const [proposal] = await tx`select payload from issue_thread_interactions`; + expect(proposal.payload.changes).toEqual([{ groupAreaId: rows[1].id, fromAreaId: rows[1].id }]); + const [version] = await tx`select snapshot from responsibility_dashboard_versions`; + expect(version.snapshot).toMatchObject({ + areas: [{ id: rows[1].id, title: "Operations" }], responsibilities: [{ areaId: rows[1].id }], createdAreaIds: [rows[1].id], + }); + expect(await tx`select id from responsibility_areas where owner_user_id = 'Alex' and id = ${empty}`).toHaveLength(1); + expect(await tx`select id from responsibility_areas where owner_user_id is null`).toMatchObject([{ id: unknown }]); + expect(await tx`select id from responsibility_areas where owner_user_id = 'New member'`).toHaveLength(0); + }); + }); + function createApp(actor: Actor) { const app = express(); app.use(express.json()); @@ -103,6 +152,23 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () return app; } + it("keeps two dashboards private when teammates create the same area", async () => { + const { company, app } = await seed(); + const second = createApp(sessionBoardActor(company.id, OTHER, "owner")); + const path = `/api/companies/${company.id}/responsibility-areas`; + const overview = `/api/companies/${company.id}/responsibilities`; + await db.insert(responsibilityAreas).values(Array.from({ length: 22 }, (_, i) => ({ + companyId: company.id, ownerUserId: OWNER, title: `Area ${i}`, + }))); + expect((await request(second).get(overview).expect(200)).body.areas).toEqual([]); + const mine = (await request(second).post(path).send({ title: "Area 0" }).expect(201)).body; + const item = (await request(second).post(overview).send({ title: "Track operations", areaId: mine.id }).expect(201)).body; + expect((await request(second).get(overview)).body.areas.map((area: { id: string }) => area.id)).toEqual([mine.id]); + await request(app).get(`/api/responsibilities/${item.id}`).expect(404); + await request(app).patch(`/api/responsibility-areas/${mine.id}`).send({ title: "Renamed" }).expect(404); + expect((await request(app).get(overview)).body.areas).toHaveLength(22); + }); + async function seed(opts: { populated?: boolean } = {}) { const company = await db.insert(companies) .values({ name: "Dash Co", issuePrefix: `D${randomUUID().replace(/[^A-Z0-9]/gi, "").slice(0, 6).toUpperCase()}` }) @@ -226,9 +292,9 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () const seeded = await seed({ populated: true }); const url = `/api/companies/${seeded.company.id}/responsibility-dashboard`; const agentApp = createApp(agentActor(seeded.company.id, seeded.analyst.id)); - expect((await request(agentApp).get(url)).status).toBe(422); - expect((await request(agentApp).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(200); - expect((await request(agentApp).get(`${url}/versions?ownerUserId=${OWNER}`)).status).toBe(200); + expect((await request(agentApp).get(url)).status).toBe(403); + expect((await request(agentApp).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403); + expect((await request(agentApp).get(`${url}/versions?ownerUserId=${OWNER}`)).status).toBe(403); expect((await request(createApp(agentActor(randomUUID(), seeded.analyst.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403); // An agent's read never saves a version. expect(await versionsOf(seeded)).toHaveLength(0); @@ -313,14 +379,13 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () expect(second.body.conversation.issueId).not.toBe(issueId); }); - it("lets only the person or an admin start it, and says so when no agent can hold it", async () => { + it("lets only the dashboard owner start it, and says so when no agent can hold it", async () => { const seeded = await seed(); - expect((await start(seeded, { mode: "create", ownerUserId: OWNER }, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(403); + expect((await start(seeded, { mode: "create", ownerUserId: OWNER }, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(404); expect((await start(seeded, { mode: "create" }, createApp(agentActor(seeded.company.id, seeded.ceo.id)))).status).toBe(403); - // An admin may start one for someone else; their own dashboard is untouched. + // Company administration grants no access to personal dashboards. const forOther = await start(seeded, { mode: "create", ownerUserId: OTHER }); - expect(forOther.status).toBe(201); - expect(forOther.body.ownerUserId).toBe(OTHER); + expect(forOther.status).toBe(404); expect((await start(seeded, { mode: "create", ownerUserId: "stranger" })).status).toBe(404); const quiet = await seed(); @@ -371,7 +436,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () it("lets only the conversation's agent propose, and writes nothing", async () => { const seeded = await seed(); const issueId = (await start(seeded)).body.conversation.issueId as string; - expect((await propose(seeded, issueId, FIRST_DASHBOARD, seeded.analyst.id)).status).toBe(403); + expect((await propose(seeded, issueId, FIRST_DASHBOARD, seeded.analyst.id)).status).toBe(404); expect((await request(seeded.app).post(`/api/issues/${issueId}/dashboard-changes`).send(FIRST_DASHBOARD)).status).toBe(403); const elsewhere = await seed(); expect((await request(createApp(agentActor(elsewhere.company.id, elsewhere.ceo.id))).post(`/api/issues/${issueId}/dashboard-changes`).send(FIRST_DASHBOARD)).status).toBe(404); @@ -402,8 +467,9 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () it("validates each kind of change against the dashboard", async () => { const seeded = await seed({ populated: true }); const issueId = (await start(seeded, { mode: "edit" })).body.conversation.issueId as string; - const [archived] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, title: "Old area", status: "archived" }).returning(); - const [theirs] = await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Hiring }).returning(); + const [archived] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OWNER, title: "Old area", status: "archived" }).returning(); + const [otherArea] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Hiring" }).returning(); + const [theirs] = await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: otherArea!.id }).returning(); const fails = async (changes: object[], status: number, words?: string) => { const res = await propose(seeded, issueId, { changes }); expect(res.status, JSON.stringify(changes)).toBe(status); @@ -427,7 +493,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () await fails([{ op: "add_area", ref: "f", name: "fundraising" }], 422, "already exists"); await fails([{ op: "rename_area", areaId: fund, name: "Hiring" }], 422, "already called"); await fails([{ op: "rename_area", areaId: fund, name: "Fundraising" }], 422, "already has that name"); - await fails([{ op: "remove_area", areaId: hiring, reason: "Not yours" }], 422, "another person"); + await fails([{ op: "remove_area", areaId: otherArea!.id, reason: "Not yours" }], 422, "No area"); await fails([{ op: "reword_responsibility", responsibilityId: theirs!.id, sentence: "Mine now." }], 422, "not one of this person's"); await fails([{ op: "reword_responsibility", responsibilityId: deck, sentence: "The deck is always current." }], 422, "same as the one it has"); await fails([{ op: "move_responsibility", responsibilityId: deck, areaId: fund }], 422, "already in that area"); @@ -435,7 +501,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () // A rename of a shared area says who else sees it. const shared = await propose(seeded, issueId, { changes: [{ op: "rename_area", areaId: hiring, name: "Recruiting" }] }); expect(shared.status).toBe(201); - expect(shared.body.payload.changes[0]).toMatchObject({ fromName: "Hiring", name: "Recruiting", sharedWith: 1 }); + expect(shared.body.payload.changes[0]).toMatchObject({ fromName: "Hiring", name: "Recruiting", sharedWith: 0 }); // A removed area lists what goes with it, minus what is moved out. const removal = await propose(seeded, issueId, { changes: [ @@ -477,7 +543,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () expect(logged).toEqual(expect.arrayContaining(["responsibility_dashboard.changes_applied", "issue.thread_interaction_accepted"])); // Only the person or an admin applies. const next = await propose(seeded, issueId, { changes: [{ op: "add_area", ref: "x", name: "Ops" }] }); - expect((await accept(seeded, issueId, next.body.id, {}, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(403); + expect((await accept(seeded, issueId, next.body.id, {}, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(404); expect((await accept(seeded, issueId, next.body.id, {}, createApp(agentActor(seeded.company.id, seeded.ceo.id)))).status).toBe(403); }); @@ -538,12 +604,12 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () { op: "remove_area", areaId: seeded.areas.Fundraising, reason: "The raise is done." }, ], }); - // Someone else files a responsibility in Fundraising meanwhile. - await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Fundraising }); + // The destination is archived after the proposal was made. + await db.update(responsibilityAreas).set({ status: "archived" }).where(eq(responsibilityAreas.id, seeded.areas.Hiring)); const before = await dashboard(seeded); const refused = await accept(seeded, issueId, proposed.body.id); expect(refused.status).toBe(409); - expect(refused.body.error).toContain("Someone else now has responsibilities in \"Fundraising\""); + expect(refused.body.error).toContain("removed since"); expect(await dashboard(seeded)).toEqual(before); expect(await versionsOf(seeded)).toHaveLength(0); const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, proposed.body.id)); @@ -679,9 +745,10 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Talent", status: "archived" }); }); - it("leaves a shared area's name and order alone, and never archives what someone else still uses", async () => { + it("restores private area names and ordering without touching a teammate’s copy", async () => { const seeded = await seed({ populated: true }); - await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Hiring }); + const [otherArea] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Hiring" }).returning(); + await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: otherArea!.id }); const svc = responsibilityDashboardVersionService(db); const first = await db.transaction((tx) => svc.checkpoint(tx, seeded.company.id, OWNER, OWNER)); await request(seeded.app).patch(`/api/responsibility-areas/${seeded.areas.Hiring}`).send({ title: "Recruiting", sortOrder: 5 }); @@ -690,7 +757,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () await request(seeded.app).patch(`/api/responsibilities/${seeded.items.pipeline}`).send({ areaId: seeded.areas.Fundraising }); await request(seeded.app).post(`/api/responsibility-dashboard-versions/${first.row.id}/restore`).send({}); const areas = await areaRows(seeded); - expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Recruiting", sortOrder: 5, status: "active" }); + expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Hiring", sortOrder: 0, status: "active" }); expect(areas.find((row) => row.id === seeded.areas.Fundraising)).toMatchObject({ title: "Fundraising" }); expect((await ownRows(seeded)).find((row) => row.id === seeded.items.pipeline)).toMatchObject({ areaId: seeded.areas.Hiring }); @@ -700,17 +767,18 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", () })); await request(seeded.app).post(`/api/responsibility-dashboard-versions/${blank.row.id}/restore`).send({}); const after = await areaRows(seeded); - expect(after.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ status: "active" }); + expect(after.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ status: "archived" }); + expect(after.find((row) => row.id === otherArea!.id)).toMatchObject({ title: "Hiring", status: "active" }); expect(after.find((row) => row.id === seeded.areas.Fundraising)).toMatchObject({ status: "archived" }); expect((await ownRows(seeded)).every((row) => row.status === "let_go")).toBe(true); expect(await db.select().from(responsibilities).where(eq(responsibilities.ownerUserId, OTHER)).then((rows) => rows.filter((row) => row.companyId === seeded.company.id).map((row) => row.status))).toEqual(["active"]); }); - it("lets only the person or an admin restore", async () => { + it("lets only the dashboard owner restore", async () => { const seeded = await seed(); const { applied } = await createFirstDashboard(seeded); const url = `/api/responsibility-dashboard-versions/${applied.version.id}/restore`; - expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(url).send({})).status).toBe(403); + expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(url).send({})).status).toBe(404); expect((await request(createApp(agentActor(seeded.company.id, seeded.ceo.id))).post(url).send({})).status).toBe(403); expect((await request(createApp(sessionBoardActor(randomUUID(), OWNER))).post(url).send({})).status).toBe(404); expect((await request(seeded.app).post(`/api/responsibility-dashboard-versions/${randomUUID()}/restore`).send({})).status).toBe(404); diff --git a/server/src/__tests__/responsibility-metrics.test.ts b/server/src/__tests__/responsibility-metrics.test.ts index 189adb51c35..9c80cd4cede 100644 --- a/server/src/__tests__/responsibility-metrics.test.ts +++ b/server/src/__tests__/responsibility-metrics.test.ts @@ -154,8 +154,8 @@ describeEmbeddedPostgres("responsibility metric sets", () => { describe("the read", () => { it("is 404 with the flag off, and follows the detail route's access", async () => { const seeded = await seed(); - expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(200); - expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(200); + expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(404); + expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(403); // Another company's board user gets what the detail route gives them. const outsider = createApp(sessionBoardActor(randomUUID(), OTHER)); const detail = await request(outsider).get(`/api/responsibilities/${seeded.id}`); @@ -230,7 +230,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => { expect(row!.metricCurrent).toBe(11); expect((await record(analyst, seeded.id, "primary", { value: true })).status).toBe(422); // A teammate who does not own it may not record either. - expect((await record(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", { value: 3 })).status).toBe(403); + expect((await record(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", { value: 3 })).status).toBe(404); const logged = await db.select({ action: activityLog.action }).from(activityLog).where(eq(activityLog.companyId, seeded.company.id)); expect(logged.map((entry) => entry.action)).toEqual(expect.arrayContaining(["responsibility.metric_reading_recorded", "responsibility.metric_updated"])); }); @@ -300,7 +300,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => { describe("chosen sets", () => { it("lets the owner set and remove supporting metrics; others may not", async () => { const seeded = await seed(); - expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(403); + expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(404); expect((await request(createApp(agentActor(seeded.company.id, seeded.analyst.id))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(403); expect((await request(seeded.app).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: [...SUPPORTING, { ...SUPPORTING[1], title: "Third" }] })).status).toBe(400); const set = await request(seeded.app).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING, primaryDisplay: "line" }); @@ -348,7 +348,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => { expect(primary.body).toMatchObject({ source: "chosen", chosenBy: { userId: OWNER } }); expect((await showAs(seeded.app, seeded.id, "primary", "percent")).status).toBe(422); - expect((await showAs(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", "line")).status).toBe(403); + expect((await showAs(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", "line")).status).toBe(404); expect((await showAs(createApp(agentActor(seeded.company.id, seeded.analyst.id)), seeded.id, "primary", "line")).status).toBe(403); expect((await showAs(seeded.app, seeded.id, randomUUID(), "line")).status).toBe(404); const logged = await db.select({ details: activityLog.details }).from(activityLog) diff --git a/server/src/__tests__/responsibility-runs.test.ts b/server/src/__tests__/responsibility-runs.test.ts index 57e2161a54b..6c0c7b56d41 100644 --- a/server/src/__tests__/responsibility-runs.test.ts +++ b/server/src/__tests__/responsibility-runs.test.ts @@ -185,8 +185,8 @@ describeEmbeddedPostgres("a responsibility's recent runs", () => { const seeded = await seed(); await run(seeded, seeded.issues.direct.id, 5); // A teammate and an agent in the company read it, as they read the detail. - expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(200); - expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(200); + expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(404); + expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(403); // Another company's board user gets what the detail route gives them. const outsider = createApp(sessionBoardActor(randomUUID(), OTHER)); const detail = await request(outsider).get(`/api/responsibilities/${seeded.id}`); diff --git a/server/src/__tests__/responsibility-status-reports.test.ts b/server/src/__tests__/responsibility-status-reports.test.ts index a83e2a145e4..52b79473a16 100644 --- a/server/src/__tests__/responsibility-status-reports.test.ts +++ b/server/src/__tests__/responsibility-status-reports.test.ts @@ -192,8 +192,8 @@ describeEmbeddedPostgres("agent-written responsibility status", () => { expect(byOwner.status).toBe(201); expect(byOwner.body.current).toMatchObject({ status: "behind", agentId: null, userId: OWNER }); - expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER))).status).toBe(403); - expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER, "admin"))).status).toBe(201); + expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER))).status).toBe(404); + expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER, "admin"))).status).toBe(404); // Nobody names the author: the body is strict, and the record follows the caller. const forged = await write(seeded, agentActor(seeded.company.id, seeded.builder.id), { ...REPORT, agentId: seeded.ceo.id }); @@ -203,17 +203,17 @@ describeEmbeddedPostgres("agent-written responsibility status", () => { const rows = await db.select().from(responsibilityStatusReports).where(eq(responsibilityStatusReports.responsibilityId, seeded.responsibility.id)); expect(rows.map((row) => [row.agentId, row.userId]).sort()).toEqual([ - [null, OTHER], [null, OWNER], [seeded.analyst.id, null], [seeded.builder.id, null], + [null, OWNER], [seeded.analyst.id, null], [seeded.builder.id, null], ].sort()); const history = (await read(seeded)).body.history as Array<{ userId: string | null }>; - expect(history).toHaveLength(4); - expect(history[0]!.userId).toBe(OTHER); + expect(history).toHaveLength(3); + expect(history[0]!.userId).toBe(OWNER); const logged = await db.select({ action: activityLog.action, details: activityLog.details }).from(activityLog) .where(and(eq(activityLog.companyId, seeded.company.id), eq(activityLog.action, "responsibility.status_reported"))); - expect(logged).toHaveLength(4); - expect(logged.map((row) => (row.details as { writtenBy: string }).writtenBy).sort()).toEqual(["agent", "agent", "user", "user"]); + expect(logged).toHaveLength(3); + expect(logged.map((row) => (row.details as { writtenBy: string }).writtenBy).sort()).toEqual(["agent", "agent", "user"]); }); it("checks the message's shape", async () => { @@ -252,7 +252,7 @@ describeEmbeddedPostgres("agent-written responsibility status", () => { const ask = () => request(owner).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({}); // Someone who may not edit the responsibility cannot ask. - expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(403); + expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(404); expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(403); const first = await ask(); @@ -404,8 +404,8 @@ describeEmbeddedPostgres("agent-written responsibility status", () => { const seeded = await seed(); const url = `/api/companies/${seeded.company.id}/responsibilities/status-reports`; const agentRead = await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(url); - expect(agentRead.status).toBe(422); - expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(200); + expect(agentRead.status).toBe(403); + expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403); expect((await request(createApp(agentActor(randomUUID(), seeded.builder.id))).get(url)).status).toBe(403); await instanceSettingsService(db).updateExperimental({ enableResponsibilities: false }); diff --git a/server/src/__tests__/responsibility-summaries-routes.test.ts b/server/src/__tests__/responsibility-summaries-routes.test.ts index 32f0bf9b0c3..093c8d67450 100644 --- a/server/src/__tests__/responsibility-summaries-routes.test.ts +++ b/server/src/__tests__/responsibility-summaries-routes.test.ts @@ -200,9 +200,8 @@ describeEmbeddedPostgres("responsibility summary routes", () => { }).returning().then((rows) => rows[0]!); const agentApp = createApp(agentActor(company.id, agent.id)).app; const missingOwner = await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary`); - expect(missingOwner.status).toBe(422); - expect(missingOwner.body.error).toContain("ownerUserId is required"); - expect((await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary?ownerUserId=${OWNER}`)).status).toBe(200); - expect((await request(agentApp).get(`/api/responsibilities/${created.body.id}/summary`)).status).toBe(200); + expect(missingOwner.status).toBe(403); + expect((await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary?ownerUserId=${OWNER}`)).status).toBe(403); + expect((await request(agentApp).get(`/api/responsibilities/${created.body.id}/summary`)).status).toBe(403); }); }); diff --git a/server/src/__tests__/routine-suggestions.test.ts b/server/src/__tests__/routine-suggestions.test.ts index 12f66094ec2..809422f32ab 100644 --- a/server/src/__tests__/routine-suggestions.test.ts +++ b/server/src/__tests__/routine-suggestions.test.ts @@ -117,6 +117,7 @@ describeEmbeddedPostgres("routine suggestions", () => { priority: "medium", assigneeAgentId: agent.id, originKind: input.originKind ?? "manual", + responsibleUserId: OWNER, parentId: input.parentId ?? null, createdByUserId: OWNER, }).returning().then((rows) => rows[0]!); diff --git a/server/src/routes/activity.ts b/server/src/routes/activity.ts index 7e724832574..765e863ce7c 100644 --- a/server/src/routes/activity.ts +++ b/server/src/routes/activity.ts @@ -240,6 +240,7 @@ export function activityRoutes(db: Db) { entityId: req.query.entityId as string | undefined, limit: normalizeActivityLimit(Number(req.query.limit)), readCondition: await issueReadSqlCondition(db, req.actor), + dashboardUserId: req.actor.type === "board" ? req.actor.userId : null, caseReadCondition: await caseActivityReadSqlCondition(db, req.actor), }; const result = await svc.list(filters); @@ -267,6 +268,7 @@ export function activityRoutes(db: Db) { } if (parsedQuery.data.actorScope === "agents") { const result = await agentAudit.list({ companyId, ...parsedQuery.data, + dashboardUserId: req.actor.type === "board" ? req.actor.userId : null, caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) }); res.json({ ...result, accessTier: "full" }); return; @@ -277,6 +279,7 @@ export function activityRoutes(db: Db) { throw forbidden("Audit filters require permission: audit:view_agent_actions"); } const result = await agentAudit.list({ companyId, ...parsedQuery.data, + dashboardUserId: req.actor.type === "board" ? req.actor.userId : null, caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) }); res.json({ ...(canViewAttribution ? result : stripAuditAttribution(result)), @@ -298,7 +301,7 @@ export function activityRoutes(db: Db) { const rows: Awaited>["items"] = []; let cursor: string | undefined; do { - const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, caseReadCondition }); + const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, dashboardUserId: req.actor.userId, caseReadCondition }); for (const item of page.items) { if (rows.length >= AUDIT_CSV_EXPORT_MAX_ROWS) break; rows.push(item); diff --git a/server/src/routes/agent-person-authz.ts b/server/src/routes/agent-person-authz.ts index 687e3d7ebc7..a2915a1fe91 100644 --- a/server/src/routes/agent-person-authz.ts +++ b/server/src/routes/agent-person-authz.ts @@ -81,15 +81,12 @@ export async function agentPersonInCompany(db: Db, req: Request, companyId: stri } /** - * The writer rule for an agent on a person's responsibilities: it acts for - * the person who directed its run and may change what that person could, so - * it manages that person's own responsibilities, and anyone's when that person - * is a company owner or admin. Returns that person's user id, or null. + * A directed agent run may manage the dashboard of the person who directed it. */ export async function agentActsForResponsibilityOwner(db: Db, req: Request, companyId: string, ownerUserId: string): Promise { const person = await agentPersonInCompany(db, req, companyId); if (!person) return null; - return person.userId === ownerUserId || person.role === "owner" || person.role === "admin" ? person.userId : null; + return person.userId === ownerUserId && (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId) ? person.userId : null; } /** Why an agent may not act for a person here, for its error messages. */ diff --git a/server/src/routes/authz.ts b/server/src/routes/authz.ts index 833f3554ca9..4a29aac022b 100644 --- a/server/src/routes/authz.ts +++ b/server/src/routes/authz.ts @@ -3,6 +3,7 @@ import type { SecretBindingTargetType } from "@paperclipai/shared"; import { forbidden, HttpError, unauthorized } from "../errors.js"; import { logger } from "../middleware/logger.js"; import { responsibleUserAuthzShadowMode } from "../services/authorization.js"; +import { dashboardConversationReadable, type DashboardConversationFields } from "../services/responsibility-privacy.js"; import { getHiddenSettings } from "../services/settings-visibility.js"; function throwOrShadowResponsibleUserCompanyAccessDeny( @@ -315,7 +316,7 @@ export function hasCompanyAccess(req: Request, companyId: string): boolean { * Routes with bespoke not-found behavior (legacy `200 []` contracts, * audit-logged denials) should still compose `hasCompanyAccess` directly. */ -export async function getAccessibleResource( +export async function getAccessibleResource( req: Request, res: Response, resource: T | null | undefined | Promise, @@ -323,7 +324,7 @@ export async function getAccessibleResource( notFoundBody: Record = { error: notFoundMessage }, ): Promise { const resolved = await resource; - if (!resolved || !hasCompanyAccess(req, resolved.companyId)) { + if (!resolved || !hasCompanyAccess(req, resolved.companyId) || !dashboardConversationReadable(req.actor, resolved)) { res.status(404).json(notFoundBody); return null; } diff --git a/server/src/routes/responsibilities.ts b/server/src/routes/responsibilities.ts index a9b28e849ab..e64128ceb04 100644 --- a/server/src/routes/responsibilities.ts +++ b/server/src/routes/responsibilities.ts @@ -1,3 +1,4 @@ +import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js"; import { Router, type NextFunction, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -72,27 +73,8 @@ function linkTarget(body: LinkResponsibility | ResponsibilityLinkLookupQuery): R return { kind: "routine", id: body.routineId! }; } -/** - * The writer rule: a board user manages their own responsibilities; company - * owners/admins and instance admins manage anyone's. - */ -export function boardCanManageResponsibilityOwner(req: Request, companyId: string, ownerUserId: string) { - if (req.actor.type !== "board") return false; - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; - if (req.actor.userId && req.actor.userId === ownerUserId) return true; - const membership = req.actor.memberships?.find((item) => item.companyId === companyId && item.status === "active"); - return membership?.membershipRole === "owner" || membership?.membershipRole === "admin"; -} - -/** - * Whose responsibilities a request means when it names no owner: a board user - * means their own, and an agent means the person its run works for (the - * person chatting, or the task's responsible person). - */ -export function defaultResponsibilityOwnerUserId(req: Request): string | undefined { - if (req.actor.type === "board") return req.actor.userId ?? undefined; - if (req.actor.type === "agent") return req.actor.onBehalfOfUserId ?? undefined; - return undefined; +export function boardCanManageResponsibilityOwner(req: Request, _companyId: string, ownerUserId: string) { + return req.actor.type === "board" && req.actor.userId === ownerUserId; } export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWakeupDeps } = {}) { @@ -157,14 +139,15 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment function assertBoardCanManage(req: Request, row: { companyId: string; ownerUserId: string }) { if (!boardCanManageOwner(req, row.companyId, row.ownerUserId)) { - throw forbidden("Only the person who owns this responsibility, or a company admin, can change it"); + throw forbidden("Only the person who owns this responsibility can change it"); } } - async function loadForRead(req: Request, res: Response) { + async function loadForRead(req: Request, res: Response, reporting = false) { const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND); if (!row) return null; await assertCompanyRead(req, row.companyId); + if (!(reporting && agentMayReportFor(req, row.ownerUserId) && row.status === "active")) await dashboardOwner(db, req, row.companyId, row.ownerUserId); return row; } @@ -191,7 +174,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment } const personUserId = await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId); if (!personUserId) { - throw forbidden(`Only the person who owns this responsibility, or a company admin, can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`); + throw forbidden(`Only the person who owns this responsibility can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`); } return { personUserId, agentId: getActorInfo(req).actorId }; } @@ -294,12 +277,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = listResponsibilitiesQuerySchema.parse(req.query); - const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req); - if (!ownerUserId) { - throw unprocessable(req.actor.type === "agent" - ? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read" - : "ownerUserId is required"); - } + const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId); res.json(await svc.overview(companyId, ownerUserId, { includeLetGo: query.includeLetGo, scope: await readScope(req, companyId), @@ -311,28 +289,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const actor = getActorInfo(req); - let ownerUserId: string; - // An agent acting for someone who may manage the owner creates what that person could. - let actsFor: string | null = null; - if (req.actor.type === "agent") { - const owner = req.body.ownerUserId ?? defaultResponsibilityOwnerUserId(req); - if (!owner) { - throw unprocessable("ownerUserId is required: this run works for no person, so name the person in this company the responsibility is for"); - } - ownerUserId = owner; - if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company"); - actsFor = await agentActsForResponsibilityOwner(db, req, companyId, ownerUserId); - } else { - const self = req.actor.userId; - ownerUserId = req.body.ownerUserId ?? self ?? ""; - if (!ownerUserId) throw unprocessable("ownerUserId is required"); - if (ownerUserId !== self) { - if (!boardCanManageOwner(req, companyId, ownerUserId)) { - throw forbidden("Only a company admin can create a responsibility for another person"); - } - if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company"); - } - } + const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId); + const actsFor = req.actor.type === "agent" ? ownerUserId : null; const { areaTitle, ...body } = req.body as typeof req.body & { areaTitle?: string }; if (areaTitle && body.areaId) throw unprocessable("Send areaId or areaTitle, not both"); const { responsibility: created, activatedArea, created: isNew, newArea } = await inChange(req, res, { @@ -341,7 +299,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []), }, async ({ svc: scoped, areas }: ScopedServices) => { // The area by title is made in the same transaction, so a refused create leaves no area behind. - const area = areaTitle ? await areas.create(companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null; + const area = areaTitle ? await areas.create(companyId, ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null; const result = await scoped.create( companyId, { ...body, ...(area ? { areaId: area.area.id } : {}) }, @@ -379,7 +337,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment router.patch("/responsibilities/:id", validate(updateResponsibilitySchema), async (req, res) => { await assertResponsibilitiesEnabled(); - const row = await loadForWrite(req, res); + const reporting = req.body.metricCurrent !== undefined && Object.keys(req.body).length === 1; + const row = await loadForRead(req, res, reporting); if (!row) return; const scope = await readScope(req, row.companyId); const actsFor = req.actor.type === "agent" ? await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId) : null; @@ -391,7 +350,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []), }, async ({ svc: scoped, areas }: ScopedServices) => { // The area by title is made in the same transaction, so a refused change leaves no area behind. - const area = areaTitle ? await areas.create(row.companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null; + const area = areaTitle ? await areas.create(row.companyId, row.ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null; if (area) patch.areaId = area.area.id; const result = await scoped.update( row, @@ -523,7 +482,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment moveFromIds = await svc.liveIdsOfOwner(row.companyId, row.ownerUserId, row.id); } else if (req.body.moveFrom && req.body.moveFrom !== row.id) { const source = await svc.getById(req.body.moveFrom); - if (!source || source.companyId !== row.companyId) throw notFound("Responsibility to move from not found"); + if (!source || source.companyId !== row.companyId || source.ownerUserId !== row.ownerUserId) throw notFound("Responsibility to move from not found"); await assertWriter(req, source); moveFromIds = [source.id]; owners.add(source.ownerUserId); @@ -612,7 +571,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment action: "issue.created", entityType: "issue", entityId: issue.id, - details: { title: issue.title, identifier: issue.identifier, responsibilityId: row.id }, + details: { title: issue.title, identifier: issue.identifier }, }); await logMutation(req, row.companyId, "responsibility.delegated", row.id, { issueId: issue.id, @@ -639,7 +598,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = responsibilityLinkLookupQuerySchema.parse(req.query); - const responsibilities = await svc.lookup(companyId, linkTarget(query), await readScope(req, companyId)); + const responsibilities = await svc.lookup(companyId, await dashboardOwner(db, req, companyId), linkTarget(query), await readScope(req, companyId)); res.json({ responsibilities }); }); diff --git a/server/src/routes/responsibility-areas.ts b/server/src/routes/responsibility-areas.ts index 9c1fecfb8a5..665e2113f97 100644 --- a/server/src/routes/responsibility-areas.ts +++ b/server/src/routes/responsibility-areas.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -19,11 +20,7 @@ import { assertBoardOrAgent, assertCompanyAccess, getAccessibleResource, getActo const NOT_FOUND = "Area not found"; /** - * Responsibility areas (experimental, `enableResponsibilities`). Areas have no - * owner: any board user with write access to the company manages them. An - * agent acting for a member of the company may do the same, each change saved - * as a version of that person's Dashboard they can undo (a delete only after - * the person accepts a confirmation card); other agents can only propose one. + * An owner or a run they directed can manage their areas. Agent changes are versioned. */ export function responsibilityAreaRoutes(db: Db) { const router = Router(); @@ -55,6 +52,8 @@ export function responsibilityAreaRoutes(db: Db) { async function loadForBoardWrite(req: Request, res: Response) { const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND); if (!row) return null; + await assertCompanyRead(req, row.companyId); + await dashboardOwner(db, req, row.companyId, row.ownerUserId); return row; } @@ -90,7 +89,7 @@ export function responsibilityAreaRoutes(db: Db) { const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = listResponsibilityAreasQuerySchema.parse(req.query); - res.json(await svc.list(companyId, { includeArchived: query.includeArchived })); + res.json(await svc.list(companyId, await dashboardOwner(db, req, companyId), { includeArchived: query.includeArchived })); }); router.post("/companies/:companyId/responsibility-areas", validate(createResponsibilityAreaSchema), async (req, res) => { @@ -99,8 +98,9 @@ export function responsibilityAreaRoutes(db: Db) { await assertCompanyRead(req, companyId); const actor = getActorInfo(req); const person = await agentPersonInCompany(db, req, companyId); + const ownerUserId = await dashboardOwner(db, req, companyId); const create = (tx: Db) => responsibilityAreaService(tx).create( - companyId, + companyId, ownerUserId, req.body, req.actor.type !== "agent" ? { type: "board" } : person ? { type: "board", viaAgentId: actor.actorId } @@ -131,20 +131,9 @@ export function responsibilityAreaRoutes(db: Db) { const row = await loadForBoardWrite(req, res); if (!row) return; const writer = await assertAreaWriter(req, row.companyId); - // On an area other people's proposed or active responsibilities share (the same test restore - // uses), Undo never changes the name, description or order, and of status changes only brings - // an archived area back. A change it cannot reverse saves no version, so no Dashboard offers an - // Undo that would do nothing; it stays in the activity log. - const sharedChange = Boolean(writer) - && (await svc.ownersInArea(row.companyId, row.id, ["proposed", "active"])).some((owner) => owner !== writer!.personUserId) - && ((req.body.title !== undefined && req.body.title !== row.title) - || (req.body.description !== undefined && req.body.description !== row.description) - || (req.body.sortOrder !== undefined && req.body.sortOrder !== row.sortOrder) - || (req.body.status !== undefined && req.body.status !== row.status && !(row.status === "active" && req.body.status === "archived"))); - // Otherwise everyone whose Dashboard shows the area gets a version. - const updated = writer && !sharedChange + const updated = writer ? await agentChanges.record({ - companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)], + companyId: row.companyId, ownerUserIds: [writer.personUserId], agentId: writer.agentId, touchedAreaIds: [row.id], onVersion: reportVersionOf(res, writer.personUserId), }, (tx) => responsibilityAreaService(tx).update(row, req.body)) @@ -172,6 +161,7 @@ export function responsibilityAreaRoutes(db: Db) { agentId: writer.agentId, interactionId: query.confirmationId, key: responsibilityDeletionKey("area", row.id), + ownerUserId: writer.personUserId, }); confirmationId = card.id; } @@ -179,7 +169,7 @@ export function responsibilityAreaRoutes(db: Db) { // Moving its responsibilities changes their owners' Dashboards too. const removed = writer ? await agentChanges.record({ - companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)], + companyId: row.companyId, ownerUserIds: [writer.personUserId], agentId: writer.agentId, touchedAreaIds: [row.id, ...(query.moveResponsibilitiesTo ? [query.moveResponsibilitiesTo] : [])], onVersion: reportVersionOf(res, writer.personUserId), diff --git a/server/src/routes/responsibility-automation.ts b/server/src/routes/responsibility-automation.ts index 85aebd75fb4..ebdff45879e 100644 --- a/server/src/routes/responsibility-automation.ts +++ b/server/src/routes/responsibility-automation.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -35,7 +36,6 @@ import { automationConversationService } from "../services/responsibility-automa import { standingCheckService } from "../services/routine-standing-checks.js"; import { routineSuggestionService, type RoutineSuggestionResponsibilityFiling } from "../services/routine-suggestions.js"; import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js"; -import { defaultResponsibilityOwnerUserId } from "./responsibilities.js"; import { getReadableIssue } from "./readable-issue.js"; const automationQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true }); @@ -147,12 +147,7 @@ export function responsibilityAutomationRoutes( const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = automationQuerySchema.parse(req.query); - const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req); - if (!ownerUserId) { - throw unprocessable(req.actor.type === "agent" - ? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read" - : "ownerUserId is required"); - } + const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId); res.json(await automation.overview(companyId, ownerUserId, { scope: await readScope(req) })); }); @@ -161,7 +156,7 @@ export function responsibilityAutomationRoutes( const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND); if (!issue) return; assertBoard(req); - res.json(await conversations.conversationFor(issue)); + res.json(await conversations.conversationFor(issue, boardUserId(req))); }); router.post("/issues/:id/automation-conversation", validate(startAutomationConversationSchema), async (req, res) => { @@ -171,7 +166,7 @@ export function responsibilityAutomationRoutes( assertBoard(req); await assertBoardCanAssignTasks(req, source.companyId); const actor = getActorInfo(req); - const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, req.body.responsibilityId); + const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, boardUserId(req), req.body.responsibilityId); if (agentId) { // The same assignment permission the delegate route checks. const decision = await access.decide({ @@ -224,7 +219,7 @@ export function responsibilityAutomationRoutes( requestedByActorId: actor.actorId, }); } - const body = await conversations.conversation(source); + const body = await conversations.conversation(source, boardUserId(req)); if (created) { res.status(201).json(body); return; diff --git a/server/src/routes/responsibility-bars.ts b/server/src/routes/responsibility-bars.ts index fcae40cee69..5bb7b1d5180 100644 --- a/server/src/routes/responsibility-bars.ts +++ b/server/src/routes/responsibility-bars.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -71,10 +72,10 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm }; } - /** The writer rule of the responsibilities routes: the owner, or a company admin. */ + /** The writer rule of the responsibilities routes: the owner. */ function assertWriter(req: Request, row: { companyId: string; ownerUserId: string }) { if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) { - throw forbidden("Only the person who owns this responsibility, or a company admin, can change its bar"); + throw forbidden("Only the person who owns this responsibility can change its bar"); } } @@ -95,6 +96,7 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND); if (!row) return; assertBoard(req); + await dashboardOwner(db, req, row.companyId, row.ownerUserId); res.json(await svc.conversation(row)); }); diff --git a/server/src/routes/responsibility-dashboard.ts b/server/src/routes/responsibility-dashboard.ts index 926c81ec44d..f8a122b12cc 100644 --- a/server/src/routes/responsibility-dashboard.ts +++ b/server/src/routes/responsibility-dashboard.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -22,10 +23,9 @@ import { toDashboardVersionSummary, type DashboardActivityEvent, } from "../services/responsibility-dashboard-versions.js"; -import { responsibilityService } from "../services/responsibilities.js"; import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js"; import { getReadableIssue } from "./readable-issue.js"; -import { boardCanManageResponsibilityOwner, defaultResponsibilityOwnerUserId } from "./responsibilities.js"; +import { boardCanManageResponsibilityOwner } from "./responsibilities.js"; const ISSUE_NOT_FOUND = "Issue not found"; const VERSION_NOT_FOUND = "Version not found"; @@ -35,7 +35,7 @@ const VERSION_NOT_FOUND = "Version not found"; * applied change saved as a version (experimental `enableResponsibilities`). * Reads follow the responsibilities overview: board users read their own by * default, agents name the person. A person who may edit that person's - * responsibilities (themselves, or a company admin) starts the conversation, + * responsibilities starts the conversation, * applies the agent's proposed changes and restores versions; only the agent * in the conversation proposes. */ @@ -44,7 +44,6 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA const access = accessService(db); const svc = responsibilityDashboardService(db); const versions = responsibilityDashboardVersionService(db); - const responsibilitiesSvc = responsibilityService(db); const issues = issueService(db); const references = issueReferenceService(db); const heartbeat = opts.heartbeat ?? heartbeatService(db); @@ -83,20 +82,9 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA } } - /** The overview route's ownerUserId rule: board users default to themselves, agents to the person their run works for. */ - function ownerFrom(req: Request, ownerUserId: string | undefined) { - const owner = ownerUserId ?? defaultResponsibilityOwnerUserId(req); - if (!owner) { - throw unprocessable(req.actor.type === "agent" - ? "ownerUserId is required: this run works for no person, so name the person whose dashboard to read" - : "ownerUserId is required"); - } - return owner; - } - function assertWriter(req: Request, companyId: string, ownerUserId: string) { if (!boardCanManageResponsibilityOwner(req, companyId, ownerUserId)) { - throw forbidden("Only the person whose dashboard this is, or a company admin, can change it"); + throw notFound("Dashboard item not found"); } } @@ -121,7 +109,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = responsibilityDashboardQuerySchema.parse(req.query); - res.json(await svc.state(companyId, ownerFrom(req, query.ownerUserId))); + res.json(await svc.state(companyId, await dashboardOwner(db, req, companyId, query.ownerUserId))); }); router.get("/companies/:companyId/responsibility-dashboard/versions", async (req, res) => { @@ -129,7 +117,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = responsibilityDashboardQuerySchema.parse(req.query); - const ownerUserId = ownerFrom(req, query.ownerUserId); + const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId); // Someone who may change this dashboard saves it as it is first, so the list starts with what they see. const writer = boardCanManageResponsibilityOwner(req, companyId, ownerUserId); const { list, saved } = await versions.list(companyId, ownerUserId, writer ? { checkpointBy: getActorInfo(req).actorId } : {}); @@ -150,11 +138,8 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA const companyId = req.params.companyId as string; assertBoard(req); assertCompanyAccess(req, companyId); - const ownerUserId = ownerFrom(req, req.body.ownerUserId); + const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId); assertWriter(req, companyId, ownerUserId); - if (ownerUserId !== req.actor.userId && !(await responsibilitiesSvc.isCompanyMember(companyId, ownerUserId))) { - throw notFound("Owner is not a member of this company"); - } const actor = getActorInfo(req); const agentId = req.body.agentId ?? await svc.defaultAgentId(companyId); if (agentId) { diff --git a/server/src/routes/responsibility-metrics.ts b/server/src/routes/responsibility-metrics.ts index 1cd7479ce7e..034a7416209 100644 --- a/server/src/routes/responsibility-metrics.ts +++ b/server/src/routes/responsibility-metrics.ts @@ -1,3 +1,4 @@ +import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -38,7 +39,7 @@ export function responsibilityMetricRoutes(db: Db) { } /** The detail route's read rule: company access, board or agent, and agents inside the company-scope boundary. */ - async function loadForRead(req: Request, res: Response) { + async function loadForRead(req: Request, res: Response, reporting = false) { const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND); if (!row) return null; if (req.actor.type !== "board" && req.actor.type !== "agent") throw forbidden("Board or agent access required"); @@ -48,12 +49,13 @@ export function responsibilityMetricRoutes(db: Db) { throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision)); } } + if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId); return row; } function assertOwnerOrAdmin(req: Request, row: { companyId: string; ownerUserId: string }) { if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) { - throw forbidden("Only the person who owns this responsibility, or a company admin, can change its metrics"); + throw forbidden("Only the person who owns this responsibility can change its metrics"); } } @@ -129,7 +131,7 @@ export function responsibilityMetricRoutes(db: Db) { validate(recordResponsibilityMetricReadingSchema), async (req, res) => { await svc.assertEnabled(); - const row = await loadForRead(req, res); + const row = await loadForRead(req, res, true); if (!row) return; const scope = await readScope(req); const actor = getActorInfo(req); diff --git a/server/src/routes/responsibility-owner.ts b/server/src/routes/responsibility-owner.ts new file mode 100644 index 00000000000..dcc0ba0099f --- /dev/null +++ b/server/src/routes/responsibility-owner.ts @@ -0,0 +1,22 @@ +import type { Request } from "express"; +import type { Db } from "@paperclipai/db"; +import { forbidden, notFound } from "../errors.js"; +import { agentPersonInCompany } from "./agent-person-authz.js"; + +/** A dashboard belongs to the signed-in person or the person who directed this agent run. */ +export async function dashboardOwner(db: Db, req: Request, companyId: string, requested?: string | null): Promise { + const userId = req.actor.type === "board" + ? req.actor.userId + : (await agentPersonInCompany(db, req, companyId))?.userId; + if (!userId) throw forbidden("A personal dashboard requires a user or a run directed by that user"); + if (req.actor.authorizingUserId && req.actor.authorizingUserId !== userId) throw forbidden("Dashboard access requires the authorizing user"); + if (requested !== undefined && userId !== requested) throw notFound("Dashboard item not found"); + return userId; +} + +/** Reporting permissions apply only within the user scope of the agent's credentials or run. */ +export function agentMayReportFor(req: Request, ownerUserId: string) { + return req.actor.type === "agent" + && (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId) + && (!req.actor.onBehalfOfUserId || req.actor.onBehalfOfUserId === ownerUserId); +} diff --git a/server/src/routes/responsibility-runs.ts b/server/src/routes/responsibility-runs.ts index f10e7baccf5..0d9a2bc77d9 100644 --- a/server/src/routes/responsibility-runs.ts +++ b/server/src/routes/responsibility-runs.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; import { forbidden } from "../errors.js"; @@ -39,6 +40,7 @@ export function responsibilityRunRoutes(db: Db) { throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision)); } } + await dashboardOwner(db, req, row.companyId, row.ownerUserId); return row; } diff --git a/server/src/routes/responsibility-status-reports.ts b/server/src/routes/responsibility-status-reports.ts index 926bc70bbe3..f3da9dae098 100644 --- a/server/src/routes/responsibility-status-reports.ts +++ b/server/src/routes/responsibility-status-reports.ts @@ -1,3 +1,4 @@ +import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; import { @@ -51,10 +52,11 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss } } - async function loadForRead(req: Request, res: Response) { + async function loadForRead(req: Request, res: Response, reporting = false) { const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND); if (!row) return null; await assertCompanyRead(req, row.companyId); + if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId); return row; } @@ -79,12 +81,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = ownerQuerySchema.parse(req.query); - const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined); - if (!ownerUserId) { - throw unprocessable(req.actor.type === "agent" - ? "ownerUserId is required: name the person whose responsibilities to read" - : "ownerUserId is required"); - } + const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId); res.json(await svc.overview(companyId, ownerUserId)); }); @@ -97,7 +94,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss router.post("/responsibilities/:id/status-report", validate(writeResponsibilityStatusReportSchema), async (req, res) => { await svc.assertEnabled(); - const row = await loadForRead(req, res); + const row = await loadForRead(req, res, true); if (!row) return; let author: StatusReportAuthor; if (req.actor.type === "agent") { @@ -130,7 +127,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss if (!row) return; assertBoard(req); if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) { - throw forbidden("Only the person who owns this responsibility, or a company admin, can ask for an update"); + throw forbidden("Only the person who owns this responsibility can ask for an update"); } const reporter = await svc.reporterOf(row); if (reporter) { diff --git a/server/src/routes/responsibility-summaries.ts b/server/src/routes/responsibility-summaries.ts index dae7e2003aa..b6f8ac35506 100644 --- a/server/src/routes/responsibility-summaries.ts +++ b/server/src/routes/responsibility-summaries.ts @@ -1,3 +1,4 @@ +import { dashboardOwner } from "./responsibility-owner.js"; import { Router, type Request } from "express"; import type { Db } from "@paperclipai/db"; import { listResponsibilitiesQuerySchema } from "@paperclipai/shared"; @@ -15,7 +16,6 @@ import { type ResponsibilitySummaryServiceOptions, } from "../services/responsibility-summaries.js"; import { assertCompanyAccess, getAccessibleResource } from "./authz.js"; -import { defaultResponsibilityOwnerUserId } from "./responsibilities.js"; const NOT_FOUND = "Responsibility not found"; const summaryQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true }); @@ -67,12 +67,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi const companyId = req.params.companyId as string; await assertCompanyRead(req, companyId); const query = summaryQuerySchema.parse(req.query); - const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req); - if (!ownerUserId) { - throw unprocessable(req.actor.type === "agent" - ? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to summarize" - : "ownerUserId is required"); - } + const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId); const overview = await responsibilities.overview(companyId, ownerUserId, { includeLetGo: false, scope: await readScope(req), @@ -85,6 +80,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi const row = await getAccessibleResource(req, res, responsibilities.getById(req.params.id as string), NOT_FOUND); if (!row) return; await assertCompanyRead(req, row.companyId); + await dashboardOwner(db, req, row.companyId, row.ownerUserId); const detail = await responsibilities.detail(row, await readScope(req), { actor: req.actor }); res.json(await summaries.affectingTheNumber({ detail, actor: req.actor })); }); diff --git a/server/src/routes/routines.ts b/server/src/routes/routines.ts index 1d865d63137..fd05deeb6e1 100644 --- a/server/src/routes/routines.ts +++ b/server/src/routes/routines.ts @@ -19,6 +19,7 @@ import { trackRoutineCreated } from "@paperclipai/shared/telemetry"; import { validate, validateIssueMutationBody } from "../middleware/validate.js"; import { accessService, documentAnnotationService, instanceSettingsService, logActivity, routineService } from "../services/index.js"; import { instanceSettingsService as experimentSettings } from "../services/instance-settings.js"; +import { dashboardOwner } from "./responsibility-owner.js"; import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js"; import { agentPersonInCompany } from "./agent-person-authz.js"; import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js"; @@ -207,7 +208,8 @@ export function routineRoutes( && (await experimentSettings(db).getExperimental()).enableResponsibilities !== true) { throw responsibilitiesDisabledError(); } - const result = await svc.list(companyId, { ...filters, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) }); + const ownerUserId = filters.responsibilityId || unfiled === "true" ? await dashboardOwner(db, req, companyId) : undefined; + const result = await svc.list(companyId, { ...filters, ownerUserId, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) }); res.json(result); }); diff --git a/server/src/services/activity-log.ts b/server/src/services/activity-log.ts index de1940acd24..14687c6665d 100644 --- a/server/src/services/activity-log.ts +++ b/server/src/services/activity-log.ts @@ -1,3 +1,4 @@ +import { isDashboardActivity } from "./responsibility-privacy.js"; import { notifyActiveRunSilence } from "./live-run-recovery-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { beginRunPhase } from "./execution-preparation-timing.js"; @@ -152,15 +153,21 @@ export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActi export function publishActivity(publication: ActivityPublication) { const finish = beginRunPhase("execution.realtime"); try { - publishLiveEvent({ - companyId: publication.companyId, - type: "activity.logged", - payload: publication.payload, - }); - if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent); - } catch (error) { - finish(true); - throw error; + if (isDashboardActivity(publication.payload.entityType)) { + // The company bus carries only an invalidation. Each viewer fetches their own data. + publishLiveEvent({ + companyId: publication.companyId, + type: "activity.logged", + payload: { action: "responsibility.dashboard_changed", entityType: "responsibility" }, + }); + return; + } + publishLiveEvent({ + companyId: publication.companyId, + type: "activity.logged", + payload: publication.payload, + }); + if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent); } finally { finish(); } } diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index be5a8a7da75..c30f4ce0e88 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -1,3 +1,4 @@ +import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { skillAccessService } from "./skill-access.js"; import { credentialAccessConnectionNameSql } from "./credential-access-visibility.js"; @@ -37,6 +38,7 @@ export interface ActivityFilters { limit?: number; readCondition?: SQL; caseReadCondition?: SQL; + dashboardUserId?: string | null; } const DEFAULT_ACTIVITY_LIMIT = 100; @@ -418,6 +420,7 @@ export function activityService(db: Db) { return { list: async (filters: ActivityFilters) => { const conditions = [eq(activityLog.companyId, filters.companyId), await skillAccessService(db).activityCondition(filters.companyId), + dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId), filters.caseReadCondition ?? sql`${activityLog.entityType} <> 'case'`]; const limit = normalizeActivityLimit(filters.limit); diff --git a/server/src/services/agent-action-audit.ts b/server/src/services/agent-action-audit.ts index e2dab4989b3..bb5dc4a2ca5 100644 --- a/server/src/services/agent-action-audit.ts +++ b/server/src/services/agent-action-audit.ts @@ -1,3 +1,4 @@ +import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js"; import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm"; import { z } from "zod"; import type { Db } from "@paperclipai/db"; @@ -22,6 +23,7 @@ export interface AgentActionAuditFilters { cursor?: string; limit: number; caseReadCondition?: SQL; + dashboardUserId?: string | null; } type CursorValue = { createdAt: string; id: string }; @@ -57,6 +59,7 @@ export function agentActionAuditService(db: Db) { if (filters.cursor && !cursor) throw badRequest("Invalid audit cursor"); const effectiveResponsibleUserId = sql`coalesce(${activityLog.responsibleUserId}, ${heartbeatRuns.responsibleUserId})`; const conditions = [eq(activityLog.companyId, filters.companyId), + dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId), filters.caseReadCondition ?? sql`${activityLog.entityType} <> 'case'`]; // Preserve the historical agent-audit query unless the caller opts into // the unified all-actors feed explicitly. diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index 3b21951b726..d8484ff41b9 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -1,3 +1,4 @@ +import { dashboardConversationCondition, dashboardConversationReadable } from "./responsibility-privacy.js"; import { readOncePerRequest } from "./authorization-read-scope.js"; import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -172,6 +173,7 @@ export type AuthorizationDecision = { | "deny_agent_interaction" | "deny_low_trust_boundary" | "deny_issue_private" + | "deny_dashboard_conversation_private" | "deny_project_private" | "deny_scope" | "deny_unsupported_action"; @@ -226,6 +228,7 @@ const PLAIN_DELEGATED_USER_DENIALS: Record `This company's limits for this agent do not let ${lowerFirst(subject)} ${action}.`, deny_agent_interaction: (_subject, action) => `Agents are not allowed to ${action} in this company; a person who manages permissions can change this.`, deny_issue_private: (subject) => `${subject} cannot see this private task.`, + deny_dashboard_conversation_private: (subject) => `${subject} cannot see this personal dashboard conversation.`, deny_project_private: (subject) => `${subject} cannot see this private project.`, inbox_target_user_unresolved: () => "Paperclip could not tell whose inbox this is.", inbox_management_disabled: () => "This person has turned off agent management of their inbox.", @@ -741,12 +744,13 @@ export async function readInstanceAdmin(db: Db | DbTransaction, userId: string): } export async function issueReadSqlCondition(db: Db | DbTransaction, actor: AuthorizationActor): Promise> { - if (actor.authorizingUserId) return issuePrivacyCondition(actor); - if (issuePrivacyMode() !== "enforce") return sql`true`; - if (actor.source === "local_implicit" || actor.isInstanceAdmin) return sql`true`; + const personal = dashboardConversationCondition(actor); + if (actor.authorizingUserId) return sql`(${personal} and ${issuePrivacyCondition(actor)})`; + if (issuePrivacyMode() !== "enforce") return personal; + if (actor.source === "local_implicit" || actor.isInstanceAdmin) return personal; if (actor.type === "board" && !actor.ignoreInstanceAdmin && actor.source !== "cloud_tenant" - && await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return sql`true`; - return issuePrivacyCondition(actor); + && await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return personal; + return sql`(${personal} and ${issuePrivacyCondition(actor)})`; } /** SQL equivalent used for project list/search pushdown. */ @@ -3017,9 +3021,6 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA || input.resource.type !== "issue" || !input.resource.issueId || !intersectedDecision.allowed - || intersectedDecision.reason === "allow_instance_admin" - || intersectedDecision.reason === "allow_local_board" - || (!input.actor.authorizingUserId && issuePrivacyMode() === "off") ) return intersectedDecision; const resource = input.resource; @@ -3029,6 +3030,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA .select({ id: issues.id, companyId: issues.companyId, + originKind: issues.originKind, originId: issues.originId, visibility: issues.visibility, privacyRootIssueId: issues.privacyRootIssueId, responsibleUserId: issues.responsibleUserId, @@ -3040,6 +3042,15 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA .from(issues) .where(and(eq(issues.id, resource.issueId!), eq(issues.companyId, resource.companyId))) .then((rows) => rows[0] ?? null); + if (issue && !dashboardConversationReadable(input.actor, issue)) { + return deny({ + action: input.action, + reason: "deny_dashboard_conversation_private", + explanation: "This personal dashboard conversation is private.", + }); + } + if (intersectedDecision.reason === "allow_instance_admin" || intersectedDecision.reason === "allow_local_board" + || (!input.actor.authorizingUserId && issuePrivacyMode() === "off")) return intersectedDecision; if (!issue || (retainedIssue?.companyId === resource.companyId ? retainedIssue.readable : await canActorReadIssuePrivacy(db, input.actor, issue))) return intersectedDecision; diff --git a/server/src/services/responsibilities.ts b/server/src/services/responsibilities.ts index 9cde26504b4..e5ee8964f00 100644 --- a/server/src/services/responsibilities.ts +++ b/server/src/services/responsibilities.ts @@ -885,11 +885,11 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType { + async function looseWork(companyId: string, ownerUserId: string, scope: ResponsibilityReadScope): Promise { const liveLink = (column: SQL) => sql`exists ( select 1 from ${responsibilityLinks} ll join ${responsibilities} lr on lr.id = ll.responsibility_id - where ${column} and lr.status in ${LIVE_STATUS_SQL})`; + where ${column} and lr.owner_user_id = ${ownerUserId} and lr.status in ${LIVE_STATUS_SQL})`; const projectLoose = sql`not ${liveLink(sql`ll.project_id = ${projects.id}`)}`; const issueLoose = sql`not ${liveLink(sql`ll.issue_id = ${issues.id}`)} and (${issues.projectId} is null or not ${liveLink(sql`ll.project_id = ${issues.projectId}`)})`; @@ -977,8 +977,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType { if (row.status !== "active" || !row.areaId) return null; - return areasSvc.activateIfProposed(tx, row.companyId, row.areaId); + return areasSvc.activateIfProposed(tx, row.companyId, row.ownerUserId, row.areaId); } /** Agent rule for an active responsibility: it runs it, or is assigned a member task or routine. */ @@ -1208,8 +1208,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType row.status !== "proposed"); const proposed = all.filter((row) => row.status === "proposed"); @@ -1271,7 +1271,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType { @@ -1752,6 +1753,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType forbidden( "A permanent delete needs the person's confirmation: post a confirmation card, then delete with its id after they accept it", @@ -129,8 +129,7 @@ export function responsibilityAgentChangeService(db: Db) { eq(companyMemberships.principalId, resolverUserId), eq(companyMemberships.status, "active"), )); - const allowed = membership && (!input.ownerUserId || resolverUserId === input.ownerUserId - || membership.role === "owner" || membership.role === "admin"); + const allowed = membership && resolverUserId === input.ownerUserId; if (!allowed) throw refuse(); return card; }, diff --git a/server/src/services/responsibility-areas.ts b/server/src/services/responsibility-areas.ts index 261d756c8f4..79f86ecc2b1 100644 --- a/server/src/services/responsibility-areas.ts +++ b/server/src/services/responsibility-areas.ts @@ -11,7 +11,7 @@ import { conflict, notFound } from "../errors.js"; type AreaRow = typeof responsibilityAreas.$inferSelect; type DbOrTransaction = Db | Parameters[0]>[0]; -const TITLE_UNIQUE_INDEX = "responsibility_areas_company_title_uq"; +const TITLE_UNIQUE_INDEX = "responsibility_areas_owner_title_uq"; /** `board` with `viaAgentId`: an agent acting for a member of the company, which creates what that person could. */ export type ResponsibilityAreaCreateActor = @@ -20,7 +20,14 @@ export type ResponsibilityAreaCreateActor = export function toResponsibilityArea(row: AreaRow): ResponsibilityArea { return { - ...row, + id: row.id, + companyId: row.companyId, + title: row.title, + description: row.description, + proposedByAgentId: row.proposedByAgentId, + sortOrder: row.sortOrder, + createdAt: row.createdAt, + updatedAt: row.updatedAt, status: row.status as ResponsibilityArea["status"], source: row.source as ResponsibilityArea["source"], }; @@ -46,15 +53,13 @@ const AREA_ORDER = [ ] as const; /** - * Areas: broad nouns a company cares about. No owner. Board users, and agents - * acting for a member of the company, manage them; other agents can only - * propose one (idempotently, by case-insensitive title). + * Area titles are unique within one person's dashboard in a company. */ export function responsibilityAreaService(db: Db) { - async function findLiveByTitle(companyId: string, title: string, database: DbOrTransaction = db) { + async function findLiveByTitle(companyId: string, ownerUserId: string, title: string, database: DbOrTransaction = db) { return database.select().from(responsibilityAreas) .where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), sql`lower(${responsibilityAreas.title}) = lower(${title})`, ne(responsibilityAreas.status, "archived"), )) @@ -66,16 +71,16 @@ export function responsibilityAreaService(db: Db) { getById: (id: string) => db.select().from(responsibilityAreas).where(eq(responsibilityAreas.id, id)).then((rows) => rows[0] ?? null), - async getInCompany(companyId: string, id: string, database: DbOrTransaction = db) { + async getInCompany(companyId: string, ownerUserId: string, id: string, database: DbOrTransaction = db) { return database.select().from(responsibilityAreas) - .where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.companyId, companyId))) + .where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId))) .then((rows) => rows[0] ?? null); }, - async list(companyId: string, opts: { includeArchived?: boolean } = {}): Promise { + async list(companyId: string, ownerUserId: string, opts: { includeArchived?: boolean } = {}): Promise { const rows = await db.select().from(responsibilityAreas) .where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), opts.includeArchived ? undefined : ne(responsibilityAreas.status, "archived"), )) .orderBy(...AREA_ORDER); @@ -83,10 +88,10 @@ export function responsibilityAreaService(db: Db) { }, /** Active areas in the company plus the listed ids (whatever their status). */ - async listActiveAnd(companyId: string, ids: readonly string[]): Promise { + async listActiveAnd(companyId: string, ownerUserId: string, ids: readonly string[]): Promise { const rows = await db.select().from(responsibilityAreas) .where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), ids.length > 0 ? or(eq(responsibilityAreas.status, "active"), inArray(responsibilityAreas.id, [...ids])) : eq(responsibilityAreas.status, "active"), @@ -102,13 +107,14 @@ export function responsibilityAreaService(db: Db) { */ async create( companyId: string, + ownerUserId: string, input: CreateResponsibilityArea, actor: ResponsibilityAreaCreateActor, ): Promise<{ area: ResponsibilityArea; created: boolean }> { - const existing = await findLiveByTitle(companyId, input.title); + const existing = await findLiveByTitle(companyId, ownerUserId, input.title); if (existing) return { area: toResponsibilityArea(existing), created: false }; const values: typeof responsibilityAreas.$inferInsert = { - companyId, + companyId, ownerUserId, title: input.title, description: input.description ?? null, sortOrder: input.sortOrder ?? 0, @@ -123,13 +129,14 @@ export function responsibilityAreaService(db: Db) { } catch (error) { if (!isTitleConflict(error)) throw error; // A concurrent request created the same title first; return it. - const winner = await findLiveByTitle(companyId, input.title); + const winner = await findLiveByTitle(companyId, ownerUserId, input.title); if (!winner) throw error; return { area: toResponsibilityArea(winner), created: false }; } }, async update(existing: AreaRow, patch: UpdateResponsibilityArea): Promise { + if (!existing.ownerUserId) throw notFound("Area not found"); const set: Partial = { updatedAt: new Date() }; for (const key of ["title", "description", "sortOrder", "status"] as const) { if (patch[key] !== undefined) (set as Record)[key] = patch[key]; @@ -137,7 +144,7 @@ export function responsibilityAreaService(db: Db) { const nextTitle = patch.title ?? existing.title; const nextStatus = patch.status ?? existing.status; if (nextStatus !== "archived" && (patch.title !== undefined || patch.status !== undefined)) { - const clash = await findLiveByTitle(existing.companyId, nextTitle); + const clash = await findLiveByTitle(existing.companyId, existing.ownerUserId, nextTitle); if (clash && clash.id !== existing.id) { throw conflict(`Another area is already called "${clash.title}"`, { areaId: clash.id }); } @@ -160,12 +167,14 @@ export function responsibilityAreaService(db: Db) { * otherwise left with `areaId` null (FK on delete set null). */ async remove(existing: AreaRow, opts: { moveTo?: string | null } = {}): Promise<{ area: ResponsibilityArea; moved: number } | null> { + const ownerUserId = existing.ownerUserId; + if (!ownerUserId) throw notFound("Area not found"); return db.transaction(async (tx) => { let moved = 0; if (opts.moveTo) { if (opts.moveTo === existing.id) throw conflict("Move its responsibilities to a different area"); const target = await tx.select().from(responsibilityAreas) - .where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.companyId, existing.companyId))) + .where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, existing.companyId))) .then((rows) => rows[0] ?? null); if (!target) throw notFound("Area to move responsibilities to not found"); if (target.status === "archived") throw conflict("That area is archived; restore it or choose another area"); @@ -181,23 +190,13 @@ export function responsibilityAreaService(db: Db) { }); }, - /** The people with an active responsibility in the area, whose Dashboards show it. */ - async ownersInArea(companyId: string, areaId: string, statuses: readonly string[] = ["active"]): Promise { - const rows = await db.selectDistinct({ ownerUserId: responsibilities.ownerUserId }).from(responsibilities).where(and( - eq(responsibilities.companyId, companyId), - eq(responsibilities.areaId, areaId), - inArray(responsibilities.status, [...statuses]), - )); - return rows.map((row) => row.ownerUserId); - }, - /** Inside `tx`: make a proposed area active. Returns the area when it changed. */ - async activateIfProposed(tx: DbOrTransaction, companyId: string, areaId: string): Promise { + async activateIfProposed(tx: DbOrTransaction, companyId: string, ownerUserId: string, areaId: string): Promise { const [row] = await tx.update(responsibilityAreas) .set({ status: "active", updatedAt: new Date() }) .where(and( eq(responsibilityAreas.id, areaId), - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), eq(responsibilityAreas.status, "proposed"), )) .returning(); diff --git a/server/src/services/responsibility-automation-conversations.ts b/server/src/services/responsibility-automation-conversations.ts index a71b7bf6aa5..5d99dfa8a6f 100644 --- a/server/src/services/responsibility-automation-conversations.ts +++ b/server/src/services/responsibility-automation-conversations.ts @@ -96,15 +96,15 @@ export function automationConversationService( * responsibility the task is under (the one the person started from first); * otherwise the organization's first-created agent that can be assigned. */ - async function defaultAgentId(source: Pick, responsibilityId?: string): Promise { + async function defaultAgentId(source: Pick, ownerUserId: string, responsibilityId?: string): Promise { const [{ rows, usable }, under] = await Promise.all([ companyAgents(source.companyId), - responsibilitiesSvc.lookup(source.companyId, { kind: "issue", id: source.id }, unrestricted).catch(() => []), + responsibilitiesSvc.lookup(source.companyId, ownerUserId, { kind: "issue", id: source.id }, unrestricted).catch(() => []), ]); const ids = [...new Set([responsibilityId, ...under.map((entry) => entry.id)].filter((id): id is string => !!id))]; const runners = ids.length === 0 ? [] : await db.select({ id: responsibilities.id, runByAgentId: responsibilities.runByAgentId }) .from(responsibilities) - .where(and(eq(responsibilities.companyId, source.companyId), inArray(responsibilities.id, ids))); + .where(and(eq(responsibilities.companyId, source.companyId), eq(responsibilities.ownerUserId, ownerUserId), inArray(responsibilities.id, ids))); const runnerIds = ids.map((id) => runners.find((row) => row.id === id)?.runByAgentId).filter((id): id is string => !!id); return responsibleAutomationAgentId({ taskAgentId: source.assigneeAgentId, @@ -114,11 +114,12 @@ export function automationConversationService( }); } - async function latestConversation(source: Pick): Promise { + async function latestConversation(source: Pick, ownerUserId: string): Promise { const [issue] = await db.select().from(issues).where(and( eq(issues.companyId, source.companyId), eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND), eq(issues.originId, source.id), + eq(issues.createdByUserId, ownerUserId), ne(issues.status, "cancelled"), )).orderBy(desc(issues.createdAt), desc(issues.id)).limit(1); return issue ?? null; @@ -168,8 +169,8 @@ export function automationConversationService( } /** Where the automation conversation for a task stands. */ - async function conversation(source: IssueRow): Promise { - const [issue, agentId] = await Promise.all([latestConversation(source), defaultAgentId(source)]); + async function conversation(source: IssueRow, ownerUserId: string): Promise { + const [issue, agentId] = await Promise.all([latestConversation(source, ownerUserId), defaultAgentId(source, ownerUserId)]); const proposal = issue ? await pendingProposal(issue) : null; const state: AutomationConversation["state"] = !issue ? "none" : proposal ? "proposal_waiting" @@ -201,7 +202,7 @@ export function automationConversationService( * not cancelled, while it is open or has a proposal waiting). Two queries * whatever the count. */ - async conversationsForTasks(companyId: string, taskIds: readonly string[]): Promise> { + async conversationsForTasks(companyId: string, taskIds: readonly string[], ownerUserId: string): Promise> { const found = new Map(); if (taskIds.length === 0) return found; const rows = await db.selectDistinctOn([issues.originId], { @@ -213,6 +214,7 @@ export function automationConversationService( }).from(issues).where(and( eq(issues.companyId, companyId), eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND), + eq(issues.createdByUserId, ownerUserId), inArray(issues.originId, [...new Set(taskIds)]), ne(issues.status, "cancelled"), )).orderBy(issues.originId, desc(issues.createdAt), desc(issues.id)); @@ -238,9 +240,9 @@ export function automationConversationService( return found; }, - async conversationFor(issueRef: { id: string; companyId: string }) { + async conversationFor(issueRef: { id: string; companyId: string }, ownerUserId: string) { await assertEnabled(); - return conversation(await loadSource(issueRef.companyId, issueRef.id)); + return conversation(await loadSource(issueRef.companyId, issueRef.id), ownerUserId); }, /** @@ -259,11 +261,11 @@ export function automationConversationService( await suggestions.assertCanBeAutomated(issueRef); const source = await loadSource(issueRef.companyId, issueRef.id); await assertNotAutomatedYet(source); - const existing = await latestConversation(source); + const existing = await latestConversation(source, actor.userId); if (existing && (!isClosed(existing.status) || (await pendingProposal(existing)))) { return { source, issue: existing, created: false }; } - const agentId = input.agentId ?? await defaultAgentId(source, input.responsibilityId); + const agentId = input.agentId ?? await defaultAgentId(source, actor.userId, input.responsibilityId); if (!agentId) { throw unprocessable("No agent in this organization can talk this through; set the automation up by hand", { code: "automation_conversation_no_agent", @@ -288,14 +290,9 @@ export function automationConversationService( ...(hint ? ["", `Quick suggestion from its title (only a guess): ${hint.why}`] : []), ...(backLink ? ["", backLink] : []), ].join("\n"); - // The conversation copies the task's title and identifier, so a private - // task's conversation is private too: only the person and the agent see it. - const sourceIsPrivate = source.visibility === "private" || source.privacyRootIssueId !== null - || (source.projectId !== null && await db.select({ id: projects.id }).from(projects) - .where(and(eq(projects.id, source.projectId), eq(projects.companyId, source.companyId), eq(projects.visibility, "private"))) - .limit(1).then((rows) => rows.length > 0)); const issue = await issuesSvc.create(source.companyId, { - ...(sourceIsPrivate ? { visibility: "private" as const } : {}), + visibility: "private", + responsibleUserId: actor.userId, title: clip(`Automate “${source.title}”`, 200), description, status: "todo", @@ -344,7 +341,7 @@ export function automationConversationService( code: "automation_standing_check_no_heartbeat", }); } - const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, { kind: "issue", id: source.id }, unrestricted)) + const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, issue.createdByUserId!, { kind: "issue", id: source.id }, unrestricted)) .map((entry) => ({ id: entry.id, title: entry.title })); const trigger: ProposeAutomationPayload["trigger"] = data.trigger.kind === "schedule" ? (() => { diff --git a/server/src/services/responsibility-automation.ts b/server/src/services/responsibility-automation.ts index 6348c841867..ce9745af6a9 100644 --- a/server/src/services/responsibility-automation.ts +++ b/server/src/services/responsibility-automation.ts @@ -93,7 +93,7 @@ export function responsibilityAutomationService( suggestions.unrepeatableIssueIds(companyId, taskIds), routinesSvc.liveOriginIds(companyId, ROUTINE_FROM_TASK_ORIGIN_KIND, taskIds), interactions.routineSuggestionsForIssues(companyId, taskIds), - conversations.conversationsForTasks(companyId, taskIds), + conversations.conversationsForTasks(companyId, taskIds, ownerUserId), conversations.companyAgents(companyId), standingChecks.lastResults(companyId, routineIds, opts.scope.issueReadCondition), ]); diff --git a/server/src/services/responsibility-bars.ts b/server/src/services/responsibility-bars.ts index 185a4718b8f..ea49a661f39 100644 --- a/server/src/services/responsibility-bars.ts +++ b/server/src/services/responsibility-bars.ts @@ -273,6 +273,8 @@ export function responsibilityBarService(db: Db) { status: "todo", priority: "medium", assigneeAgentId: agentId, + visibility: "private", + responsibleUserId: row.ownerUserId, originKind: RESPONSIBILITY_BAR_ORIGIN_KIND, originId: row.id, createdByUserId: actor.userId, diff --git a/server/src/services/responsibility-dashboard-guidance.ts b/server/src/services/responsibility-dashboard-guidance.ts index c64776201ac..234438b7822 100644 --- a/server/src/services/responsibility-dashboard-guidance.ts +++ b/server/src/services/responsibility-dashboard-guidance.ts @@ -1,4 +1,4 @@ -import { and, desc, eq, inArray, ne, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { authUsers, issueThreadInteractions, issues, responsibilities, responsibilityAreas } from "@paperclipai/db"; import { @@ -24,8 +24,6 @@ const OTHER_AREA_LIMIT = 40; export interface DashboardGuidanceArea { id: string; title: string; - /** How many other people have responsibilities in it. */ - others: number; /** This person's active responsibilities in it. */ items: Array<{ id: string; sentence: string }>; } @@ -40,8 +38,8 @@ export interface DashboardGuidanceInput { areas: DashboardGuidanceArea[]; /** The person's active responsibilities filed under no area. */ unfiled: Array<{ id: string; sentence: string }>; - /** Other live areas in the organization. */ - otherAreas: Array<{ id: string; title: string; others: number }>; + /** Their other live areas. */ + otherAreas: Array<{ id: string; title: string }>; /** Responsibilities proposed earlier that wait for the person. */ proposed: string[]; /** Newest first. */ @@ -61,7 +59,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: { return null; } const ownerUserId = issue.originId; - const [issueRow, owner, items, areaRows, others, history] = await Promise.all([ + const [issueRow, owner, items, areaRows, history] = await Promise.all([ db.select({ originFingerprint: issues.originFingerprint }).from(issues) .where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId))) .then((rows) => rows[0] ?? null), @@ -80,14 +78,8 @@ export async function loadDashboardConversationGuidance(db: Db, input: { )).orderBy(responsibilities.sortOrder, responsibilities.createdAt), db.select({ id: responsibilityAreas.id, title: responsibilityAreas.title, status: responsibilityAreas.status }) .from(responsibilityAreas) - .where(eq(responsibilityAreas.companyId, issue.companyId)) + .where(and(eq(responsibilityAreas.companyId, issue.companyId), eq(responsibilityAreas.ownerUserId, ownerUserId))) .orderBy(responsibilityAreas.sortOrder, sql`lower(${responsibilityAreas.title})`), - db.select({ areaId: responsibilities.areaId, count: sql`count(distinct ${responsibilities.ownerUserId})::int` }) - .from(responsibilities).where(and( - eq(responsibilities.companyId, issue.companyId), - ne(responsibilities.ownerUserId, ownerUserId), - inArray(responsibilities.status, ["active", "proposed"]), - )).groupBy(responsibilities.areaId), db.select({ status: issueThreadInteractions.status, payload: issueThreadInteractions.payload, result: issueThreadInteractions.result }) .from(issueThreadInteractions).where(and( eq(issueThreadInteractions.companyId, issue.companyId), @@ -96,7 +88,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: { )).orderBy(desc(issueThreadInteractions.createdAt)).limit(PROPOSAL_HISTORY), ]); if (!issueRow) return null; - const othersByArea = new Map(others.filter((row) => row.areaId).map((row) => [row.areaId!, row.count])); const active = items.filter((item) => item.status === "active"); const mine = new Set(active.map((item) => item.areaId).filter((id): id is string => id !== null)); const areas: DashboardGuidanceArea[] = areaRows @@ -104,7 +95,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: { .map((area) => ({ id: area.id, title: area.title, - others: othersByArea.get(area.id) ?? 0, items: active.filter((item) => item.areaId === area.id).map((item) => ({ id: item.id, sentence: responsibilityDashboardSentence(item) })), })); return buildDashboardConversationGuidance({ @@ -118,7 +108,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: { otherAreas: areaRows .filter((area) => area.status !== "archived" && !mine.has(area.id)) .slice(0, OTHER_AREA_LIMIT) - .map((area) => ({ id: area.id, title: area.title, others: othersByArea.get(area.id) ?? 0 })), + .map((area) => ({ id: area.id, title: area.title })), proposed: items.filter((item) => item.status === "proposed").map((item) => responsibilityDashboardSentence(item)), proposals: history.map((entry) => { const payload = entry.payload as Partial | null; @@ -137,9 +127,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: { }); } -function shared(others: number) { - return others === 0 ? "" : `; ${others === 1 ? "1 other person has" : `${others} other people have`} responsibilities in it`; -} + const CREATE_EXAMPLE = { message: "Here is a first dashboard from your answers and what I found in your calendar and mail.", @@ -169,7 +157,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput : "They asked you to help change the dashboard they have."} End it with one proposed set of changes they can accept with one tap. You never change the dashboard yourself: only the person can, by accepting your proposal, and they can undo it afterwards.`, "", "What a dashboard is made of (reason from this, not only from the rules):", - "- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". Nobody owns an area and it has no deadline; it groups what sits under it. Areas are shared across the organization, so other people may have responsibilities in the same area.", + "- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". An area belongs to this person and groups their responsibilities.", "- A responsibility is something this person owns and answers for, on an ongoing basis. Write it as one sentence saying what must be true and stay true: \"Every prospective LP hears from us at least every two weeks.\" \"Customers get a reply within one working day.\" If it can be finished, it is a task or a project, not a responsibility: \"Send the deck to two LPs\" is a task, and \"Close Fund VI\" is a project that serves a responsibility.", "- Each responsibility passes three tests. Ongoing: it still makes sense after the current project ships. Theirs: they answer for it, not just take part in it (attending a meeting series is not owning it; running it is). In their words: the words their answers, mail subjects and calendar titles use, not job-description words.", `- Keep it small. A person can hold perhaps five to seven areas in their head, and one to three responsibilities under each is plenty. A few that are right beat a full list: every line is something they will look at every day, and a list that is mostly wrong teaches them to ignore it. Each sentence is at most ${RESPONSIBILITY_DASHBOARD_SENTENCE_MAX} characters.`, @@ -183,7 +171,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput lines.push("- Empty: they own no responsibilities yet."); } for (const area of input.areas) { - lines.push(`- Area "${area.title}" (areaId ${area.id}${shared(area.others)}):`); + lines.push(`- Area "${area.title}" (areaId ${area.id}):`); for (const item of area.items) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`); } if (input.unfiled.length > 0) { @@ -191,8 +179,8 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput for (const item of input.unfiled) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`); } if (input.otherAreas.length > 0) { - lines.push("", "Other areas in the organization (file under one by its areaId rather than adding a near-duplicate):"); - for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id}${shared(area.others)})`); + lines.push("", "Their other areas (file under one by its areaId rather than adding a near-duplicate):"); + for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id})`); } if (input.proposed.length > 0) { lines.push("", "Proposed to them earlier and still waiting for them (do not propose these again):"); @@ -227,7 +215,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput "The changes, as an ordered list (each may carry a one-line reason; removals must):", "- { op: \"add_area\", ref, name }: ref is your own short key for the new area, used by later changes in the same list.", "- { op: \"rename_area\", areaId, name }: it is renamed for everyone with responsibilities in it.", - "- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping). Refused when other people have responsibilities in it.", + "- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping).", "- { op: \"add_responsibility\", areaId or areaRef, sentence }: one sentence of what must be true.", "- { op: \"reword_responsibility\", responsibilityId, sentence }", "- { op: \"move_responsibility\", responsibilityId, areaId or areaRef }", diff --git a/server/src/services/responsibility-dashboard-versions.ts b/server/src/services/responsibility-dashboard-versions.ts index 91ec534a8f9..4f84844e052 100644 --- a/server/src/services/responsibility-dashboard-versions.ts +++ b/server/src/services/responsibility-dashboard-versions.ts @@ -34,7 +34,6 @@ type VersionRow = typeof responsibilityDashboardVersions.$inferSelect; type AreaRow = typeof responsibilityAreas.$inferSelect; type ResponsibilityRow = typeof responsibilities.$inferSelect; -const LIVE = ["proposed", "active"] as const; /** One activity entry a restore or an applied change set writes after commit. */ export interface DashboardActivityEvent { @@ -121,7 +120,7 @@ export function responsibilityDashboardVersionService(db: Db) { createdNow: readonly string[] = [], touched: readonly string[] = [], ): Promise { - const [rows, linkRows, created] = await Promise.all([ + const [rows, linkRows] = await Promise.all([ database.select({ id: responsibilities.id, title: responsibilities.title, @@ -152,12 +151,6 @@ export function responsibilityDashboardVersionService(db: Db) { eq(responsibilities.ownerUserId, ownerUserId), eq(responsibilities.status, "active"), )), - database.selectDistinct({ id: sql`jsonb_array_elements_text(${responsibilityDashboardVersions.snapshot} -> 'createdAreaIds')` }) - .from(responsibilityDashboardVersions) - .where(and( - eq(responsibilityDashboardVersions.companyId, companyId), - eq(responsibilityDashboardVersions.ownerUserId, ownerUserId), - )), ]); const linksBy = new Map(); for (const link of linkRows) { @@ -179,20 +172,19 @@ export function responsibilityDashboardVersionService(db: Db) { ...item, links: sortedLinks(item.id), description, runByAgentId, evidence, healthOverride, healthNote, })); const referenced = [...new Set(items.map((item) => item.areaId).filter((value): value is string => value !== null))]; - const createdIds = [...new Set([...created.map((row) => row.id), ...createdNow])].filter((value) => !referenced.includes(value)); // An area a change is about to touch is held whatever its status, so undoing a restore archives it again. const touchedIds = touched.filter((value) => !referenced.includes(value)); - const areas = referenced.length + createdIds.length + touchedIds.length === 0 ? [] : await database.select({ + const areas = await database.select({ id: responsibilityAreas.id, title: responsibilityAreas.title, status: responsibilityAreas.status, sortOrder: responsibilityAreas.sortOrder, description: responsibilityAreas.description, }).from(responsibilityAreas).where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), or( referenced.length > 0 ? inArray(responsibilityAreas.id, referenced) : undefined, - createdIds.length > 0 ? and(inArray(responsibilityAreas.id, createdIds), ne(responsibilityAreas.status, "archived")) : undefined, + ne(responsibilityAreas.status, "archived"), touchedIds.length > 0 ? inArray(responsibilityAreas.id, touchedIds) : undefined, ), )); @@ -247,7 +239,9 @@ export function responsibilityDashboardVersionService(db: Db) { // A version saved before snapshots held filed items is compared on what it holds. const legacy = previousSnapshot ? isLegacySnapshot(previousSnapshot) : false; const comparable = legacy ? dashboardSnapshotHash(input.snapshot, { legacy: true }) : hash; - if (previous && previous.snapshotHash === comparable) { + const previousHash = previous?.snapshotHash === "remapped" && previousSnapshot + ? dashboardSnapshotHash(previousSnapshot, { legacy }) : previous?.snapshotHash; + if (previous && previousHash === comparable) { // One saved before skills could be filed hashes the same (no filed skills) but must hold the empty list too. if (!legacy && !lacksFiledSkills(previousSnapshot!)) return { row: previous, created: false }; // The same dashboard as an older version that held no filed items, @@ -307,8 +301,7 @@ export function responsibilityDashboardVersionService(db: Db) { * agent that runs it puts those back too (see restoreDetailsInTx); an older * version leaves them as they are. * - * Areas other people have responsibilities in keep their name and order - * (they see them too); a responsibility deleted since is created again with + * A responsibility deleted since is created again with * its sentence; an area deleted since is created again (or the live area now * holding its name is used); when an area's old name is now another area's, * that area is used instead. @@ -326,20 +319,11 @@ export function responsibilityDashboardVersionService(db: Db) { const now = new Date(); const areaIds = [...new Set([...target.areas.map((area) => area.id), ...current.areas.map((area) => area.id)])]; const targetItemIds = target.responsibilities.map((item) => item.id); - const [areaRows, liveAreas, othersByArea, ownRows] = await Promise.all([ + const [areaRows, liveAreas, ownRows] = await Promise.all([ areaIds.length === 0 ? Promise.resolve([] as AreaRow[]) : tx.select().from(responsibilityAreas) - .where(and(eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))), + .where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))), tx.select({ id: responsibilityAreas.id, title: responsibilityAreas.title }).from(responsibilityAreas) - .where(and(eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))), - areaIds.length === 0 ? Promise.resolve([] as Array<{ areaId: string | null; count: number }>) : tx.select({ - areaId: responsibilities.areaId, - count: sql`count(*)::int`, - }).from(responsibilities).where(and( - eq(responsibilities.companyId, companyId), - inArray(responsibilities.areaId, areaIds), - ne(responsibilities.ownerUserId, ownerUserId), - inArray(responsibilities.status, [...LIVE]), - )).groupBy(responsibilities.areaId), + .where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))), targetItemIds.length === 0 ? Promise.resolve([] as ResponsibilityRow[]) : tx.select().from(responsibilities).where(and( eq(responsibilities.companyId, companyId), eq(responsibilities.ownerUserId, ownerUserId), @@ -347,7 +331,6 @@ export function responsibilityDashboardVersionService(db: Db) { )), ]); const areasById = new Map(areaRows.map((row) => [row.id, row])); - const shared = new Set(othersByArea.filter((row) => row.areaId && row.count > 0).map((row) => row.areaId!)); // Live titles, kept current as this restore renames and archives, for the one-live-name-per-area rule. const liveTitle = new Map(liveAreas.map((row) => [lower(row.title), row.id])); const setLive = (row: { id: string; title: string; status: string }) => { @@ -368,7 +351,7 @@ export function responsibilityDashboardVersionService(db: Db) { return true; } const [created] = await tx.insert(responsibilityAreas).values({ - companyId, + companyId, ownerUserId, title: want.title, description: want.description ?? null, status: want.status === "archived" ? "archived" : "active", @@ -380,13 +363,8 @@ export function responsibilityDashboardVersionService(db: Db) { events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: created!.status, ...source } }); return true; } - const isShared = shared.has(row.id); - // Other people see a shared area: only bring it back if it was archived, never rename or reorder it. - const nextTitle = isShared ? row.title : want.title; - const nextStatus = isShared ? (row.status === "archived" && want.status !== "archived" ? "active" : row.status) : want.status; - const nextOrder = isShared ? row.sortOrder : want.sortOrder; - // A version that holds the description puts it back, except on an area others share. - const nextDescription = isShared || want.description === undefined ? row.description : want.description; + const { title: nextTitle, status: nextStatus, sortOrder: nextOrder } = want; + const nextDescription = want.description === undefined ? row.description : want.description; if (nextTitle === row.title && nextStatus === row.status && nextOrder === row.sortOrder && nextDescription === row.description) { areaFor.set(want.id, row.id); return true; @@ -402,7 +380,7 @@ export function responsibilityDashboardVersionService(db: Db) { } const [updated] = await tx.update(responsibilityAreas) .set({ title: nextTitle, status: nextStatus, sortOrder: nextOrder, description: nextDescription, updatedAt: now }) - .where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.companyId, companyId))) + .where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId))) .returning(); areasById.set(row.id, updated!); setLive(updated!); @@ -505,7 +483,7 @@ export function responsibilityDashboardVersionService(db: Db) { // Areas the snapshot does not hold that are now empty of anyone's live responsibilities: archived. const kept = new Set(areaFor.values()); const candidates = [...new Set([...current.areas.map((area) => area.id), ...touchedAreas])].filter((areaId) => !kept.has(areaId)); - events.push(...await archiveIfEmpty(tx, companyId, candidates, source)); + events.push(...await archiveIfEmpty(tx, companyId, ownerUserId, candidates, source)); return { events, createdAreaIds }; } @@ -611,10 +589,10 @@ export function responsibilityDashboardVersionService(db: Db) { } /** Inside `tx`: archive each listed area that is not archived and holds no proposed or active responsibility of anyone. */ - async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, areaIds: readonly string[], source: Record) { + async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, ownerUserId: string, areaIds: readonly string[], source: Record) { if (areaIds.length === 0) return []; const archived = await tx.update(responsibilityAreas).set({ status: "archived", updatedAt: new Date() }).where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, [...areaIds]), ne(responsibilityAreas.status, "archived"), sql`not exists (select 1 from ${responsibilities} r where r.area_id = ${responsibilityAreas.id} and r.status in ('proposed', 'active'))`, diff --git a/server/src/services/responsibility-dashboard.ts b/server/src/services/responsibility-dashboard.ts index 4009480fd0c..a1dac016a22 100644 --- a/server/src/services/responsibility-dashboard.ts +++ b/server/src/services/responsibility-dashboard.ts @@ -38,7 +38,6 @@ import { type IssueRow = typeof issues.$inferSelect; type AreaRow = typeof responsibilityAreas.$inferSelect; -const LIVE = ["proposed", "active"] as const; const NO_AREA = "No area"; function isClosed(status: string) { @@ -77,14 +76,15 @@ export function responsibilityDashboardService(db: Db) { if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError(); } - /** Empty: no active responsibility and none proposed. One query. */ async function isEmpty(companyId: string, ownerUserId: string) { - const [row] = await db.select({ id: responsibilities.id }).from(responsibilities).where(and( - eq(responsibilities.companyId, companyId), - eq(responsibilities.ownerUserId, ownerUserId), - inArray(responsibilities.status, [...LIVE]), - )).limit(1); - return !row; + const [state] = await db.execute<{ empty: boolean }>(sql`select not exists ( + select 1 from ${responsibilityAreas} where ${responsibilityAreas.companyId} = ${companyId} + and ${responsibilityAreas.ownerUserId} = ${ownerUserId} and ${responsibilityAreas.status} <> 'archived' + ) and not exists ( + select 1 from ${responsibilities} where ${responsibilities.companyId} = ${companyId} + and ${responsibilities.ownerUserId} = ${ownerUserId} and ${responsibilities.status} in ('active', 'proposed') + ) as empty`); + return state.empty; } async function latestConversation(companyId: string, ownerUserId: string): Promise { @@ -123,7 +123,7 @@ export function responsibilityDashboardService(db: Db) { /** * Check a change set against the person's dashboard as it is and resolve - * the words the card shows. Three queries. + * the words the card shows. Two queries. */ async function buildPayload( companyId: string, @@ -132,7 +132,7 @@ export function responsibilityDashboardService(db: Db) { data: CreateDashboardChangeSet, ): Promise { const namedAreaIds = [...new Set(data.changes.flatMap((change) => ("areaId" in change && change.areaId ? [change.areaId] : [])))]; - const [own, areaRows, others] = await Promise.all([ + const [own, areaRows] = await Promise.all([ db.select({ id: responsibilities.id, title: responsibilities.title, @@ -144,23 +144,15 @@ export function responsibilityDashboardService(db: Db) { eq(responsibilities.status, "active"), )), db.select().from(responsibilityAreas).where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), namedAreaIds.length > 0 ? or(ne(responsibilityAreas.status, "archived"), inArray(responsibilityAreas.id, namedAreaIds)) : ne(responsibilityAreas.status, "archived"), )), - db.select({ areaId: responsibilities.areaId, count: sql`count(distinct ${responsibilities.ownerUserId})::int` }) - .from(responsibilities).where(and( - eq(responsibilities.companyId, companyId), - ne(responsibilities.ownerUserId, ownerUserId), - inArray(responsibilities.status, [...LIVE]), - sql`${responsibilities.areaId} is not null`, - )).groupBy(responsibilities.areaId), ]); const ownById = new Map(own.map((row) => [row.id, row])); const areasById = new Map(areaRows.map((row) => [row.id, row])); const liveByTitle = new Map(areaRows.filter((row) => row.status !== "archived").map((row) => [lower(row.title), row])); - const sharedWith = new Map(others.map((row) => [row.areaId!, row.count])); const refs = new Map(); const problems: string[] = []; const problem = (index: number, message: string) => problems.push(`changes[${index}]: ${message}`); @@ -239,16 +231,12 @@ export function responsibilityDashboardService(db: Db) { groupName: area.title, name: change.name.trim(), fromName: area.title, - sharedWith: sharedWith.get(area.id) ?? 0, + sharedWith: 0, }; } case "remove_area": { const area = usableArea(index, change.areaId); if (!area) return base; - const shared = sharedWith.get(area.id) ?? 0; - if (shared > 0) { - problem(index, `"${area.title}" holds responsibilities of ${shared === 1 ? "another person" : `${shared} other people`}, so it stays; move or remove this person's responsibilities in it instead`); - } return { ...base, groupAreaId: area.id, @@ -338,12 +326,12 @@ export function responsibilityDashboardService(db: Db) { const stale = (message: string) => conflict(`${message}. Ask for the proposal again.`, { code: "responsibility_dashboard_changes_stale" }); const loadArea = async (areaId: string) => { const [row] = await tx.select().from(responsibilityAreas) - .where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.companyId, companyId))).for("update"); + .where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId))).for("update"); return row ?? null; }; const liveAreaNamed = async (title: string, except?: string) => { const [row] = await tx.select().from(responsibilityAreas).where(and( - eq(responsibilityAreas.companyId, companyId), + eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), sql`lower(${responsibilityAreas.title}) = lower(${title})`, ne(responsibilityAreas.status, "archived"), except ? ne(responsibilityAreas.id, except) : undefined, @@ -378,7 +366,7 @@ export function responsibilityDashboardService(db: Db) { refToArea.set(change.groupRef!, existing.id); continue; } - const [created] = await tx.insert(responsibilityAreas).values({ companyId, title: change.name!, status: "active", source: "manual" }).returning(); + const [created] = await tx.insert(responsibilityAreas).values({ companyId, ownerUserId, title: change.name!, status: "active", source: "manual" }).returning(); refToArea.set(change.groupRef!, created!.id); createdAreaIds.push(created!.id); events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: "active", source: "manual", ...source } }); @@ -435,13 +423,6 @@ export function responsibilityDashboardService(db: Db) { for (const change of byOp("remove_area")) { const area = await loadArea(change.groupAreaId!); if (!area || area.status === "archived") continue; - const [others] = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and( - eq(responsibilities.companyId, companyId), - eq(responsibilities.areaId, area.id), - ne(responsibilities.ownerUserId, ownerUserId), - inArray(responsibilities.status, [...LIVE]), - )).limit(1); - if (others) throw stale(`Someone else now has responsibilities in "${area.title}", so it stays`); const remaining = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and( eq(responsibilities.companyId, companyId), eq(responsibilities.areaId, area.id), @@ -449,7 +430,7 @@ export function responsibilityDashboardService(db: Db) { eq(responsibilities.status, "active"), )); for (const row of remaining) await letGo(row.id); - events.push(...await versions.archiveIfEmpty(tx, companyId, [area.id], source)); + events.push(...await versions.archiveIfEmpty(tx, companyId, ownerUserId, [area.id], source)); } return { events, createdAreaIds }; } @@ -543,6 +524,8 @@ export function responsibilityDashboardService(db: Db) { status: "todo", priority: "medium", assigneeAgentId: agentId, + visibility: "private", + responsibleUserId: ownerUserId, originKind: RESPONSIBILITY_DASHBOARD_ORIGIN_KIND, originId: ownerUserId, originFingerprint: input.mode, diff --git a/server/src/services/responsibility-privacy.ts b/server/src/services/responsibility-privacy.ts new file mode 100644 index 00000000000..33410dd392a --- /dev/null +++ b/server/src/services/responsibility-privacy.ts @@ -0,0 +1,68 @@ +import { sql } from "drizzle-orm"; +import { activityLog, issues } from "@paperclipai/db"; +import type { AuthorizationActor } from "./authorization.js"; + +const conversationKinds = ["responsibility_dashboard", "responsibility_bar", "responsibility_status_update", "automation_conversation"]; +export function isPersonalDashboardConversation(kind: string | null) { + return kind !== null && conversationKinds.includes(kind); +} + +export type DashboardConversationFields = { + originKind?: string | null; + originId?: string | null; + responsibleUserId?: string | null; + assigneeAgentId?: string | null; +}; + +export function dashboardConversationReadable(actor: AuthorizationActor, issue: DashboardConversationFields) { + if (!isPersonalDashboardConversation(issue.originKind ?? null)) return true; + const ownerId = issue.originKind === "responsibility_dashboard" ? issue.originId : issue.responsibleUserId; + if (!ownerId) return false; + if (actor.type === "board") return actor.userId === ownerId; + return actor.type === "agent" && !!issue.assigneeAgentId && actor.agentId === issue.assigneeAgentId + && (!actor.onBehalfOfUserId || actor.onBehalfOfUserId === ownerId) + && (!actor.authorizingUserId || actor.authorizingUserId === ownerId); +} + +const personalConversationKinds = sql.join(conversationKinds.map(kind => sql`${kind}`), sql`, `); + +export function dashboardConversationCondition(actor: AuthorizationActor) { + const owner = sql`case when ${issues.originKind} = 'responsibility_dashboard' then ${issues.originId} else ${issues.responsibleUserId} end`; + const allowed = actor.type === "board" ? sql`${owner} = ${actor.userId ?? null}` + : actor.type === "agent" ? sql`${issues.assigneeAgentId} = ${actor.agentId ?? null} + and ${actor.onBehalfOfUserId ? sql`${owner} = ${actor.onBehalfOfUserId}` : sql`true`} + and ${actor.authorizingUserId ? sql`${owner} = ${actor.authorizingUserId}` : sql`true`}` : sql`false`; + return sql`(${issues.originKind} not in (${personalConversationKinds}) or (${owner} is not null and ${allowed}))`; +} + +const entities = ["responsibility", "responsibility_area", "responsibility_dashboard_version"]; +export function isDashboardActivity(entityType: unknown) { + return typeof entityType === "string" && entities.includes(entityType); +} + +/** Activity without a current owner stays in the audit store and is invisible in company feeds. */ +export function dashboardActivityCondition(userId?: string | null) { + const ordinary = sql`${activityLog.entityType} not in ('responsibility', 'responsibility_area', 'responsibility_dashboard_version')`; + if (!userId) return sql`${ordinary}`; + return sql`(${ordinary} or case ${activityLog.entityType} + when 'responsibility' then exists (select 1 from responsibilities r where r.id::text = ${activityLog.entityId} and r.company_id = ${activityLog.companyId} and r.owner_user_id = ${userId}) + when 'responsibility_area' then exists (select 1 from responsibility_areas a where a.id::text = ${activityLog.entityId} and a.company_id = ${activityLog.companyId} and a.owner_user_id = ${userId}) + when 'responsibility_dashboard_version' then exists (select 1 from responsibility_dashboard_versions v where v.id::text = ${activityLog.entityId} and v.company_id = ${activityLog.companyId} and v.owner_user_id = ${userId}) + else false end)`; +} + +/** Audit entries can refer to a conversation directly, through a comment or through a document. */ +export function dashboardAuditConversationCondition(userId?: string | null) { + const entity = activityLog.entityId; + const privateIssue = sql`select 1 from issues i where i.company_id = ${activityLog.companyId} + and i.origin_kind in (${personalConversationKinds}) + and (${userId ?? null}::text is null or (case when i.origin_kind = 'responsibility_dashboard' then i.origin_id else i.responsible_user_id end) + is distinct from ${userId ?? null})`; + return sql`case ${activityLog.entityType} + when 'issue' then not exists (${privateIssue} and i.id::text = ${entity}) + when 'issue_comment' then not exists (${privateIssue} and i.id in + (select c.issue_id from issue_comments c where c.id::text = ${entity})) + when 'issue_document' then not exists (${privateIssue} and i.id in + (select d.issue_id from issue_documents d where d.id::text = ${entity} or d.document_id::text = ${entity})) + else true end`; +} diff --git a/server/src/services/responsibility-status-reports.ts b/server/src/services/responsibility-status-reports.ts index fc289755e2d..2880e917265 100644 --- a/server/src/services/responsibility-status-reports.ts +++ b/server/src/services/responsibility-status-reports.ts @@ -197,6 +197,8 @@ export function responsibilityStatusReportService(db: Db) { status: "todo", priority: "low", assigneeAgentId: reporter.agentId, + visibility: "private", + responsibleUserId: row.ownerUserId, originKind: RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND, originId: row.id, createdByUserId: actor.userId, diff --git a/server/src/services/routine-suggestions.ts b/server/src/services/routine-suggestions.ts index 09c4ccdc742..e11feef2a53 100644 --- a/server/src/services/routine-suggestions.ts +++ b/server/src/services/routine-suggestions.ts @@ -44,7 +44,7 @@ const ROUTINE_EXECUTION_ORIGIN_KIND = "routine_execution"; */ export interface RoutineSuggestionResponsibilityFiling { /** Every responsibility the task is under (directly or through its project); empty when loose. */ - responsibilitiesForIssue(companyId: string, issueId: string): Promise>; + responsibilitiesForIssue(companyId: string, issueId: string, ownerUserId: string): Promise>; /** File the routine under one responsibility. Linking is additive and idempotent. */ fileRoutine(responsibilityId: string, routineId: string): Promise<{ linkId: string; created: boolean } | null>; } @@ -60,8 +60,8 @@ export function responsibilityFilingForRoutineSuggestions(db: Db): RoutineSugges // linking a routine reads no task or project rows, so no further read scope applies. const unrestricted = { issueReadCondition: sql`true`, projectReadCondition: sql`true` }; return { - async responsibilitiesForIssue(companyId, issueId) { - return svc.lookup(companyId, { kind: "issue", id: issueId }, unrestricted); + async responsibilitiesForIssue(companyId, issueId, ownerUserId) { + return svc.lookup(companyId, ownerUserId, { kind: "issue", id: issueId }, unrestricted); }, async fileRoutine(responsibilityId, routineId) { const row = await svc.getById(responsibilityId); @@ -346,7 +346,7 @@ export function routineSuggestionService( const filed: FiledUnder = []; try { - for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id)) { + for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id, actor.userId)) { try { const link = await filing.fileRoutine(responsibility.id, routine.id); if (link) filed.push({ responsibilityId: responsibility.id, ...link }); diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts index dbc13574522..8b935241c49 100644 --- a/server/src/services/routines.ts +++ b/server/src/services/routines.ts @@ -2180,6 +2180,7 @@ export function routineService( responsibleUserId?: string; /** Filed under this responsibility, directly or through its project. */ responsibilityId?: string; + ownerUserId?: string; /** Filed under no proposed or active responsibility, directly or through its project. */ unfiled?: boolean; }, @@ -2197,7 +2198,7 @@ export function routineService( const filedUnder = (responsibility: SQL) => sql`exists ( select 1 from ${responsibilityLinks} fl join ${responsibilities} fr on fr.id = fl.responsibility_id - where ${responsibility} and fr.company_id = ${companyId} + where ${responsibility} and fr.company_id = ${companyId} and fr.owner_user_id = ${filters?.ownerUserId ?? null} and (fl.routine_id = ${routines.id} or (${routines.projectId} is not null and fl.project_id = ${routines.projectId})))`; if (filters?.responsibilityId) conditions.push(filedUnder(sql`fr.id = ${filters.responsibilityId}`)); if (filters?.unfiled) conditions.push(sql`not ${filedUnder(sql`fr.status in ('proposed', 'active')`)}`); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 1d36afd3004..320c3acddef 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -439,7 +439,7 @@ "packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", - "packages/shared/src/types/responsibility.ts": "f577647e59db25b6bba04fb2f9ab36a00afbb371", + "packages/shared/src/types/responsibility.ts": "ca7eb329f98b9fc20fef3d8d25017edcfb230a0e", "packages/shared/src/types/routine.ts": "6b2f2fd27187c19f98afe99f926460ded2752f20", "packages/shared/src/types/runtime-exposure.ts": "785f053a7ad5448cde94f36738cdb90585bbc92e", "packages/shared/src/types/search.ts": "4e208a9b1942991bfe5f29ef58ec71625e2693e9", diff --git a/ui/src/api/responsibilities.ts b/ui/src/api/responsibilities.ts index d134b5cb261..92f9d2620c2 100644 --- a/ui/src/api/responsibilities.ts +++ b/ui/src/api/responsibilities.ts @@ -100,8 +100,7 @@ export const responsibilitiesApi = { }; /** - * Areas: broad things a company cares about, with no owner. Any board user - * manages them. Creating one whose title already exists returns that area. + * Areas on the acting person's dashboard. A repeated title returns their existing area. */ export const responsibilityAreasApi = { list: (companyId: string, options?: { includeArchived?: boolean }) => diff --git a/ui/src/components/responsibilities/AreaDialogs.tsx b/ui/src/components/responsibilities/AreaDialogs.tsx index 584da30dcdf..4946cdcb3c7 100644 --- a/ui/src/components/responsibilities/AreaDialogs.tsx +++ b/ui/src/components/responsibilities/AreaDialogs.tsx @@ -21,17 +21,19 @@ import { DialogHeader, DialogTitle, } from "@/components/ui/dialog"; +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { Input } from "@/components/ui/input"; import { queryKeys } from "@/lib/queryKeys"; type AreaRef = Pick; -/** The company's areas that can take a responsibility (active and proposed). */ +/** The viewer's areas that can take a responsibility (active and proposed). */ export function useResponsibilityAreas(companyId: string | null | undefined, enabled = true) { + const { userId } = useResolvedViewerId({ enabled }); return useQuery({ - queryKey: queryKeys.responsibilities.areas(companyId ?? "__none__"), + queryKey: [...queryKeys.responsibilities.areas(companyId ?? "__none__"), userId], queryFn: () => responsibilityAreasApi.list(companyId!), - enabled: enabled && !!companyId, + enabled: enabled && !!companyId && !!userId, }); } diff --git a/ui/src/components/responsibilities/DashboardAgentStatus.tsx b/ui/src/components/responsibilities/DashboardAgentStatus.tsx index c2b58ed2e33..83454f5162f 100644 --- a/ui/src/components/responsibilities/DashboardAgentStatus.tsx +++ b/ui/src/components/responsibilities/DashboardAgentStatus.tsx @@ -458,7 +458,7 @@ function AgentStatusBody({ mutationFn: (row: AgentStatusRow) => responsibilitiesApi.requestStatusUpdate(row.responsibility.id), onSuccess: async (_state, row) => { await Promise.all([ - queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.statusReports(companyId) }), + queryClient.invalidateQueries({ queryKey: ["responsibilities", "status-reports", companyId] }), queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.statusReport(row.responsibility.id) }), ]); }, @@ -577,7 +577,7 @@ export function DashboardAgentStatus(props: DashboardViewProps) { const active = useMemo(() => activeResponsibilities(overview.responsibilities), [overview.responsibilities]); const { data: session } = useQuery({ queryKey: queryKeys.auth.session, queryFn: () => authApi.getSession() }); const query = useQuery({ - queryKey: queryKeys.responsibilities.statusReports(companyId), + queryKey: queryKeys.responsibilities.statusReports(companyId, props.overview.ownerUserId), queryFn: () => responsibilitiesApi.statusReports(companyId), enabled: active.length > 0, }); diff --git a/ui/src/components/responsibilities/DashboardAutomation.tsx b/ui/src/components/responsibilities/DashboardAutomation.tsx index 46d781b954c..a17b81e6e50 100644 --- a/ui/src/components/responsibilities/DashboardAutomation.tsx +++ b/ui/src/components/responsibilities/DashboardAutomation.tsx @@ -671,7 +671,7 @@ function AutomationSkeleton() { export function DashboardAutomation({ companyId, overview, agents, agentsById, now, onAddResponsibility, onReviewProposals }: DashboardViewProps) { const active = useMemo(() => activeResponsibilities(overview.responsibilities), [overview.responsibilities]); const query = useQuery({ - queryKey: queryKeys.responsibilities.automation(companyId), + queryKey: queryKeys.responsibilities.automation(companyId, overview.ownerUserId), queryFn: () => responsibilitiesApi.automation(companyId), enabled: active.length > 0, }); diff --git a/ui/src/components/responsibilities/DashboardOutlineV2.tsx b/ui/src/components/responsibilities/DashboardOutlineV2.tsx index 7b5fc195f25..6237c34e247 100644 --- a/ui/src/components/responsibilities/DashboardOutlineV2.tsx +++ b/ui/src/components/responsibilities/DashboardOutlineV2.tsx @@ -20,17 +20,17 @@ import { ProposalsNotice } from "./ResponsibilityViewParts"; import type { DashboardViewProps } from "./view-props"; /** Which areas are folded, remembered in the browser; works without storage. */ -function useCollapsedAreas(): [ReadonlySet, (key: string) => void] { - const [collapsed, setCollapsed] = useState>(() => readCollapsedAreas()); +function useCollapsedAreas(scope: string): [ReadonlySet, (key: string) => void] { + const [collapsed, setCollapsed] = useState>(() => readCollapsedAreas(scope)); const toggle = useCallback((key: string) => { setCollapsed((current) => { const next = new Set(current); if (next.has(key)) next.delete(key); else next.add(key); - writeCollapsedAreas(next); + writeCollapsedAreas(next, scope); return next; }); - }, []); + }, [scope]); return [collapsed, toggle]; } @@ -146,7 +146,7 @@ export function DashboardOutlineV2({ () => outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas), [overview.areas, overview.responsibilities, keepEmptyAreas], ); - const [collapsed, toggle] = useCollapsedAreas(); + const [collapsed, toggle] = useCollapsedAreas(JSON.stringify([companyId, overview.ownerUserId])); const query = search.trim(); const shown = useMemo(() => searchOutlineV2Groups(groups, query), [groups, query]); @@ -161,7 +161,7 @@ export function DashboardOutlineV2({ ); // Nothing owned and nothing proposed: only the module, and any area just added by hand. - if (active.length === 0 && overview.proposed.length === 0) { + if (groups.length === 0 && active.length === 0 && overview.proposed.length === 0) { return (
- {groups.filter((group) => keepEmptyAreas.has(group.key)).map(renderArea)}
); } diff --git a/ui/src/components/responsibilities/ResponsibilityBarCard.tsx b/ui/src/components/responsibilities/ResponsibilityBarCard.tsx index de95d6fca71..ea54e0b0a1b 100644 --- a/ui/src/components/responsibilities/ResponsibilityBarCard.tsx +++ b/ui/src/components/responsibilities/ResponsibilityBarCard.tsx @@ -61,7 +61,7 @@ function useUpdateResponsibility(id: string) { return useMutation({ mutationFn: (patch: UpdateResponsibility) => responsibilitiesApi.update(id, patch), onSuccess: (updated) => { - queryClient.setQueryData(queryKeys.responsibilities.detail(id), (old) => + queryClient.setQueriesData({ queryKey: queryKeys.responsibilities.detail(id) }, (old) => old ? { ...old, ...updated } : old); void queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.all }); }, diff --git a/ui/src/components/responsibilities/ResponsibilityNarrative.tsx b/ui/src/components/responsibilities/ResponsibilityNarrative.tsx index 06a700febf4..262f4ecfb0d 100644 --- a/ui/src/components/responsibilities/ResponsibilityNarrative.tsx +++ b/ui/src/components/responsibilities/ResponsibilityNarrative.tsx @@ -4,6 +4,7 @@ import type { ResponsibilitySummary as Narrative } from "@paperclipai/shared"; import { responsibilitiesApi } from "@/api/responsibilities"; import { queryKeys } from "@/lib/queryKeys"; import { summaryAttribution, summaryRefetchDelay } from "@/lib/responsibility-summary"; +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { cn } from "@/lib/utils"; /** @@ -28,10 +29,11 @@ function useNarrative(queryKey: readonly unknown[], queryFn: () => Promise responsibilitiesApi.companySummary(companyId!), - !!companyId, + !!companyId && !!userId, ); } diff --git a/ui/src/components/routine-page/useRoutineFormOptions.ts b/ui/src/components/routine-page/useRoutineFormOptions.ts index 7088dbf97a9..7ef3c8d6713 100644 --- a/ui/src/components/routine-page/useRoutineFormOptions.ts +++ b/ui/src/components/routine-page/useRoutineFormOptions.ts @@ -7,6 +7,7 @@ import { responsibilitiesApi } from "@/api/responsibilities"; import { secretsApi } from "@/api/secrets"; import type { MentionOption } from "@/components/MarkdownEditor"; import { useQueryView } from "@/components/QueryView"; +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { useResponsibilitiesEnabled } from "@/hooks/useResponsibilitiesEnabled"; import { companyProjectsQuery } from "@/lib/company-projects-query"; import { buildCompanyUserProfileMap, buildMarkdownMentionOptions } from "@/lib/company-members"; @@ -34,6 +35,7 @@ export function useRoutineFormOptions( const enabled = Boolean(companyId) && active; const { enabled: responsibilitiesOn } = useResponsibilitiesEnabled(); + const { userId } = useResolvedViewerId({ enabled: enabled && responsibilitiesOn }); const agentsQuery = useQuery({ queryKey: queryKeys.agents.list(companyId ?? ""), queryFn: () => agentsApi.list(companyId!), @@ -51,9 +53,9 @@ export function useRoutineFormOptions( enabled, }); const responsibilitiesQuery = useQuery({ - queryKey: queryKeys.responsibilities.overview(companyId ?? ""), + queryKey: queryKeys.responsibilities.overview(companyId ?? "", { ownerUserId: userId }), queryFn: () => responsibilitiesApi.overview(companyId!), - enabled: enabled && responsibilitiesOn, + enabled: enabled && responsibilitiesOn && !!userId, }); // Failed reads are reported, never shown as empty choices. diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index d2c71d2f2bb..66431d2be6e 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -591,7 +591,7 @@ export const queryKeys = { /** The responsibilities one routine is under, directly or through its project. */ routineLinks: (companyId: string, routineId: string) => ["responsibilities", "links", companyId, "routine", routineId] as const, - /** The company's areas (active and proposed). */ + /** The viewer's active and proposed areas. */ areas: (companyId: string) => ["responsibilities", "areas", companyId] as const, /** Recent activity on one responsibility, for who last reported its reading. */ activity: (id: string) => ["responsibilities", "activity", id] as const, diff --git a/ui/src/lib/responsibility-outline-v2.test.ts b/ui/src/lib/responsibility-outline-v2.test.ts index b3b21657a39..121347ff608 100644 --- a/ui/src/lib/responsibility-outline-v2.test.ts +++ b/ui/src/lib/responsibility-outline-v2.test.ts @@ -126,12 +126,12 @@ describe("searchOutlineV2Groups", () => { describe("collapsed areas in storage", () => { it("round-trips, and ignores anything that is not a list of keys", () => { - writeCollapsedAreas(new Set(["area-a", OUTLINE_V2_NO_AREA_KEY])); - expect([...readCollapsedAreas()]).toEqual(["area-a", OUTLINE_V2_NO_AREA_KEY]); - localStorage.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, "{not json"); - expect(readCollapsedAreas().size).toBe(0); - localStorage.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, JSON.stringify({ a: 1 })); - expect(readCollapsedAreas().size).toBe(0); + writeCollapsedAreas(new Set(["area-a", OUTLINE_V2_NO_AREA_KEY]), "owner"); + expect([...readCollapsedAreas("owner")]).toEqual(["area-a", OUTLINE_V2_NO_AREA_KEY]); + localStorage.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:owner`, "{not json"); + expect(readCollapsedAreas("owner").size).toBe(0); + localStorage.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:owner`, JSON.stringify({ a: 1 })); + expect(readCollapsedAreas("owner").size).toBe(0); }); it("never throws when storage is blocked", () => { @@ -141,7 +141,7 @@ describe("collapsed areas in storage", () => { vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("blocked"); }); - expect(readCollapsedAreas().size).toBe(0); - expect(() => writeCollapsedAreas(new Set(["area-a"]))).not.toThrow(); + expect(readCollapsedAreas("owner").size).toBe(0); + expect(() => writeCollapsedAreas(new Set(["area-a"]), "owner")).not.toThrow(); }); }); diff --git a/ui/src/lib/responsibility-outline-v2.ts b/ui/src/lib/responsibility-outline-v2.ts index 42c2f1da55e..8eea890dc95 100644 --- a/ui/src/lib/responsibility-outline-v2.ts +++ b/ui/src/lib/responsibility-outline-v2.ts @@ -105,9 +105,9 @@ export function outlineV2Href(responsibilityId: string): string { } /** The collapsed groups' keys as stored; empty when nothing is stored or storage is unavailable. Never throws. */ -export function readCollapsedAreas(): Set { +export function readCollapsedAreas(scope: string): Set { try { - const stored = globalThis.localStorage?.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY); + const stored = globalThis.localStorage?.getItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`); const parsed: unknown = stored ? JSON.parse(stored) : []; return new Set(Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === "string") : []); } catch { @@ -116,9 +116,9 @@ export function readCollapsedAreas(): Set { } /** Remembers the collapsed groups when storage is available; silently does nothing otherwise. */ -export function writeCollapsedAreas(keys: ReadonlySet): void { +export function writeCollapsedAreas(keys: ReadonlySet, scope: string): void { try { - globalThis.localStorage?.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, JSON.stringify([...keys])); + globalThis.localStorage?.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`, JSON.stringify([...keys])); } catch { // Private windows and blocked storage: the choice lasts for this visit only. } diff --git a/ui/src/pages/Responsibilities.test.tsx b/ui/src/pages/Responsibilities.test.tsx index 59ac8bde156..5cf03e87496 100644 --- a/ui/src/pages/Responsibilities.test.tsx +++ b/ui/src/pages/Responsibilities.test.tsx @@ -27,10 +27,12 @@ const routinesApi = vi.hoisted(() => ({ update: vi.fn() })); const projectsApi = vi.hoisted(() => ({ update: vi.fn() })); const areasApi = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn() })); const agentsApi = vi.hoisted(() => ({ list: vi.fn() })); +const authApi = vi.hoisted(() => ({ getSession: vi.fn() })); const autoOpen = vi.hoisted(() => vi.fn()); const breadcrumbs = vi.hoisted(() => vi.fn()); vi.mock("@/api/responsibilities", () => ({ responsibilitiesApi: api, responsibilityAreasApi: areasApi })); vi.mock("@/api/agents", () => ({ agentsApi })); +vi.mock("@/api/auth", () => ({ authApi })); vi.mock("@/api/issues", () => ({ issuesApi })); vi.mock("@/api/routines", () => ({ routinesApi })); vi.mock("@/api/projects", () => ({ projectsApi })); @@ -87,6 +89,7 @@ beforeEach(() => { // These tests cover the full layout, which the Dashboard shows only when the address names it. location.search = "?view=full"; agentsApi.list.mockResolvedValue([guide, codex]); + authApi.getSession.mockResolvedValue({ user: { id: "user-storybook" } }); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -301,7 +304,7 @@ describe("Responsibilities home", () => { expect(text()).not.toContain("Old fund"); await act(async () => buttonByText("Show let-go responsibilities")!.click()); await flush(); - expect(api.overview).toHaveBeenLastCalledWith("company-storybook", { includeLetGo: true }); + expect(api.overview).toHaveBeenLastCalledWith("company-storybook", { includeLetGo: true, ownerUserId: "user-storybook" }); expect(text()).toContain("Old fund"); }); }); diff --git a/ui/src/pages/Responsibilities.tsx b/ui/src/pages/Responsibilities.tsx index 430fb9a0cd9..87d861af722 100644 --- a/ui/src/pages/Responsibilities.tsx +++ b/ui/src/pages/Responsibilities.tsx @@ -1,5 +1,6 @@ +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { keepPreviousData, useQuery } from "@tanstack/react-query"; +import { useQuery } from "@tanstack/react-query"; import type { ResponsibilityArea, ResponsibilityWithRollup } from "@paperclipai/shared"; import { Plus } from "lucide-react"; import { describeError } from "@/api/errors"; @@ -82,6 +83,13 @@ function ProvenanceLine({ */ export function Responsibilities() { const { selectedCompanyId } = useCompany(); + const viewer = useResolvedViewerId(); + if (viewer.error) return { void viewer.retry(); }} />; + if (!selectedCompanyId || !viewer.userId) return ; + return ; +} + +function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId: string; ownerUserId: string }) { const { setBreadcrumbs } = useBreadcrumbs(); const [includeLetGo, setIncludeLetGo] = useState(false); const [adding, setAdding] = useState<{ areaId: string | null } | null>(null); @@ -107,10 +115,9 @@ export function Responsibilities() { }, [setBreadcrumbs]); const overviewQuery = useQuery({ - queryKey: queryKeys.responsibilities.overview(selectedCompanyId ?? "__none__", { includeLetGo }), - queryFn: () => responsibilitiesApi.overview(selectedCompanyId!, { includeLetGo }), + queryKey: queryKeys.responsibilities.overview(selectedCompanyId ?? "__none__", { includeLetGo, ownerUserId }), + queryFn: () => responsibilitiesApi.overview(selectedCompanyId!, { includeLetGo, ownerUserId }), enabled: !!selectedCompanyId, - placeholderData: keepPreviousData, }); const overview = overviewQuery.data; const areasForNew = useMemo( @@ -128,7 +135,7 @@ export function Responsibilities() { if (!overview) return null; const counts = outlineV2Counts(outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas)); // The same rule as the view's empty state, which shows only the create module. - return counts.responsibilities > 0 || overview.proposed.length > 0 ? counts : null; + return counts.areas > 0 || counts.responsibilities > 0 || overview.proposed.length > 0 ? counts : null; }, [overview, keepEmptyAreas]); const openAdd = useCallback((areaId: string | null) => setAdding({ areaId }), []); diff --git a/ui/src/pages/Responsibilities.views.test.tsx b/ui/src/pages/Responsibilities.views.test.tsx index d7174d6623c..cdf615ebc1f 100644 --- a/ui/src/pages/Responsibilities.views.test.tsx +++ b/ui/src/pages/Responsibilities.views.test.tsx @@ -757,7 +757,7 @@ describe("Dashboard views", () => { expect(bar("area-fundraising").getAttribute("aria-expanded")).toBe("false"); // Nothing to search or count on an empty dashboard. - api.overview.mockResolvedValue(responsibilityOverviewFixture([], [])); + api.overview.mockResolvedValue(responsibilityOverviewFixture([], [], { areas: [] })); await remount(); await flush(); expect(host.querySelector("header [data-toolbar-search]")).toBeNull(); @@ -794,7 +794,7 @@ describe("Dashboard views", () => { }); it("on an empty dashboard shows only the create module, naming the agent, with adding an area by hand kept quiet", async () => { - api.overview.mockResolvedValue(responsibilityOverviewFixture([], [])); + api.overview.mockResolvedValue(responsibilityOverviewFixture([], [], { areas: [] })); await openOutlineV2(); const root = outlineV2(); expect(root.querySelector("[data-outline-v2-area]")).toBeNull(); @@ -847,7 +847,9 @@ describe("Dashboard views", () => { await act(async () => toggle.click()); expect(toggle.getAttribute("aria-expanded")).toBe("false"); expect(list.hidden).toBe(true); - expect(JSON.parse(localStorage.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY)!)).toEqual(["area-fundraising"]); + const scope = JSON.stringify(["company-storybook", homeOverviewFixture.ownerUserId]); + const storageKey = `${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`; + expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual(["area-fundraising"]); // A native button: Enter and Space press it, and it takes focus in tab order. toggle.focus(); @@ -860,7 +862,7 @@ describe("Dashboard views", () => { expect(bar("area-portfolio").getAttribute("aria-expanded")).toBe("true"); await act(async () => bar("area-fundraising").click()); expect(bar("area-fundraising").getAttribute("aria-expanded")).toBe("true"); - expect(JSON.parse(localStorage.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY)!)).toEqual([]); + expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual([]); }); it("folds without storage", async () => { diff --git a/ui/src/pages/ResponsibilityDetail.test.tsx b/ui/src/pages/ResponsibilityDetail.test.tsx index 8b3d684e9d5..3be4cba0e9b 100644 --- a/ui/src/pages/ResponsibilityDetail.test.tsx +++ b/ui/src/pages/ResponsibilityDetail.test.tsx @@ -7,6 +7,7 @@ import { ApiError } from "@/api/client"; import { describeLinkError } from "@/components/responsibilities/AddExistingWorkPicker"; import { artifactsTruncationNote } from "@/components/responsibilities/ResponsibilitySkillsAndArtifacts"; import { TooltipProvider } from "@/components/ui/tooltip"; +import { queryKeys } from "@/lib/queryKeys"; import { areaFundraising, areaPortfolio, @@ -124,6 +125,7 @@ beforeEach(() => { document.body.append(host); root = createRoot(host); client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(queryKeys.auth.session, { user: { id: "user-storybook" } }); }); afterEach(async () => { diff --git a/ui/src/pages/ResponsibilityDetail.tsx b/ui/src/pages/ResponsibilityDetail.tsx index 8f1cb87693e..b002e980fc3 100644 --- a/ui/src/pages/ResponsibilityDetail.tsx +++ b/ui/src/pages/ResponsibilityDetail.tsx @@ -34,6 +34,7 @@ import { } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { useBreadcrumbs } from "@/context/BreadcrumbContext"; +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { useCompany } from "@/context/CompanyContext"; import { Link, useNavigate, useParams } from "@/lib/router"; import { queryKeys } from "@/lib/queryKeys"; @@ -58,7 +59,7 @@ function useResponsibilityPage(responsibility: ResponsibilityDetailData, company const [removed, setRemoved] = useState<{ label: string; relink: LinkResponsibility } | null>(null); const directory = useAgentDirectory(companyId); const areasQuery = useResponsibilityAreas(companyId); - const detailKey = queryKeys.responsibilities.detail(responsibility.id); + const detailKey = [...queryKeys.responsibilities.detail(responsibility.id), companyId, responsibility.ownerUserId]; const refreshAll = () => queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.all }); const update = useMutation({ @@ -247,10 +248,11 @@ export function ResponsibilityDetail() { const { responsibilityId } = useParams<{ responsibilityId: string }>(); const { selectedCompanyId } = useCompany(); const { setBreadcrumbs } = useBreadcrumbs(); + const { userId } = useResolvedViewerId(); const detailQuery = useQuery({ - queryKey: queryKeys.responsibilities.detail(responsibilityId ?? "__none__"), + queryKey: [...queryKeys.responsibilities.detail(responsibilityId ?? "__none__"), selectedCompanyId, userId], queryFn: () => responsibilitiesApi.get(responsibilityId!), - enabled: !!responsibilityId, + enabled: !!responsibilityId && !!selectedCompanyId && !!userId, }); const title = detailQuery.data?.title; diff --git a/ui/src/pages/RoutineDetail.test.tsx b/ui/src/pages/RoutineDetail.test.tsx index b3591ae613a..d7e597decf2 100644 --- a/ui/src/pages/RoutineDetail.test.tsx +++ b/ui/src/pages/RoutineDetail.test.tsx @@ -48,6 +48,9 @@ vi.mock("../api/routines", () => ({ }, })); vi.mock("../api/issues", () => ({ issuesApi: { list: vi.fn() } })); +vi.mock("../api/auth", () => ({ + authApi: { getSession: vi.fn(async () => ({ user: { id: "user-1" } })) }, +})); vi.mock("../api/agents", () => ({ agentsApi: { list: vi.fn(async () => [{ id: "agent-1", name: "Digest Bot", status: "active", role: "engineer", title: null }]) }, })); diff --git a/ui/src/pages/RoutineDetail.tsx b/ui/src/pages/RoutineDetail.tsx index 83f900953f0..1b964f1287e 100644 --- a/ui/src/pages/RoutineDetail.tsx +++ b/ui/src/pages/RoutineDetail.tsx @@ -46,6 +46,7 @@ import { useToastActions } from "@/context/ToastContext"; import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled"; import { configurationWarningMessages } from "@/lib/configuration-warnings"; import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb"; +import { useResolvedViewerId } from "@/hooks/useResolvedViewerId"; import { queryKeys } from "@/lib/queryKeys"; import { Navigate, useLocation, useNavigate, useParams, useSearchParams } from "@/lib/router"; @@ -141,10 +142,11 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string; [historyQuery.data], ); + const { userId } = useResolvedViewerId({ enabled: options.responsibilitiesOn }); const linksQuery = useQuery({ - queryKey: queryKeys.responsibilities.routineLinks(companyId, routineId), + queryKey: [...queryKeys.responsibilities.routineLinks(companyId, routineId), userId], queryFn: () => responsibilitiesApi.lookupRoutineLinks(companyId, routineId), - enabled: options.responsibilitiesOn, + enabled: options.responsibilitiesOn && !!userId, }); const linkEntries = linksQuery.data?.responsibilities; const linksView = useQueryView(linksQuery); @@ -308,11 +310,11 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string; const loadDirectResponsibility = useCallback(async () => { if (!options.responsibilitiesOn) return ""; const links = await queryClient.fetchQuery({ - queryKey: queryKeys.responsibilities.routineLinks(companyId, routineId), + queryKey: [...queryKeys.responsibilities.routineLinks(companyId, routineId), userId], queryFn: () => responsibilitiesApi.lookupRoutineLinks(companyId, routineId), }); return links.responsibilities.find((entry) => entry.via === "direct")?.id ?? ""; - }, [companyId, options.responsibilitiesOn, queryClient, routineId]); + }, [companyId, options.responsibilitiesOn, queryClient, routineId, userId]); const openEdit = useCallback(async () => { const current = routineRef.current;