diff --git a/doc/connections/AWS.md b/doc/connections/AWS.md index 42a6b5951bb..c499166951b 100644 --- a/doc/connections/AWS.md +++ b/doc/connections/AWS.md @@ -103,8 +103,15 @@ already exists. The setup screen walks through them: account the CLI uses, checks for an existing identity provider, deploys the template with `aws cloudformation deploy` and reports the stack's `RoleArn` output. For full access it asks which policy to attach. The - prompt holds no secret. - - Paste that role ARN into the field below the prompt. + prompt holds no AWS credential, but its progress token is a credential + for this setup's checklist: give the prompt only to your own agent, not + to a shared chat or public place. The token only updates that checklist + and stops working after six hours. + - While the agent works, the step shows its live checklist (it sets and + ticks off its steps with the URLs and token in the prompt; see + `docs/api/agent-setup-progress.md`), and its finish summary carries the + role ARN. + - Paste that role ARN into the Role ARN field. **Or do it by hand** shows the same setup without an agent: - **With CloudFormation.** Download the template, create a stack from it in diff --git a/docs/api/agent-setup-progress.md b/docs/api/agent-setup-progress.md new file mode 100644 index 00000000000..170c932cba1 --- /dev/null +++ b/docs/api/agent-setup-progress.md @@ -0,0 +1,49 @@ +--- +title: Agent Setup Progress +summary: A live checklist a person's own agent fills in while it sets something up for them +--- + +When Paperclip offers "Set it up with your agent", the setup page can show a live checklist of what the person's own agent (for example Claude Code on their computer) is doing. The page creates the checklist and puts its URLs and a token in the setup prompt. The agent sets the checklist, updates each step and finishes; each change appears on the page right away. + +The agent needs no Paperclip sign-in. Its token can only write to this one checklist, works for six hours, and allows up to 300 updates. Paperclip keeps only a hash of the token. The prompt that carries the token is a credential for this checklist: it is meant for the person's own agent, not for sharing. The create response is sent with `Cache-Control: no-store`. A finished checklist refuses further updates (`409`), and checklists are deleted a day after they expire: a company's own when it creates a new one, and every company's once at server start (never as a recurring scan). + +## Create a Checklist (Board) + +``` +POST /api/companies/{companyId}/agent-setup-progress +{ "purpose": "aws_connection", "subjectId": "" } +``` + +Board only. For `aws_connection`, `subjectId` must name a connection of this company, and the caller must be allowed to configure it (its creator or a connection manager); otherwise `422`, `404` or `403`. The `201` response returns the checklist, the token (shown only here) and the agent's URLs: + +```json +{ + "progress": { "id": "…", "status": "waiting", "items": [], "summary": null, "expiresAt": "…" }, + "token": "pcsp_…", + "urls": { + "checklist": "https://paperclip.example.com/api/agent-setup-progress/{id}/checklist", + "item": "https://paperclip.example.com/api/agent-setup-progress/{id}/items/{key}", + "finish": "https://paperclip.example.com/api/agent-setup-progress/{id}/finish" + } +} +``` + +`GET /api/agent-setup-progress/{id}` reads it. Only the person who started the setup can read it; anyone else, including another company, gets the same `404` as for a missing checklist. Each agent update is also sent as an `agent_setup_progress.updated` live event carrying only the checklist ID. + +## Agent Requests + +Each request sends `Authorization: Bearer ` and JSON. + +| Request | Body | Effect | +| --- | --- | --- | +| `PUT …/checklist` | `{ "items": [{ "key": "check-account", "title": "Check the AWS account" }] }` | Replaces the checklist: 1 to 20 items; keys are lowercase letters, numbers, `-` and `_` (up to 40); titles up to 120 characters. | +| `POST …/items/{key}` | `{ "status": "in_progress", "detail": "…" }` | Sets one step's status (`pending`, `in_progress`, `done` or `failed`) and an optional detail (up to 500 characters); omit `detail` to keep it, or send `null` to clear it. | +| `POST …/finish` | `{ "status": "done", "summary": "…" }` | Finishes the setup. `done` ticks off every step (the agent's verdict); `failed` keeps the steps as they were. The summary is shown on the page. After either, further updates get `409`. | + +The checklist stays `in_progress` until the agent finishes, even with every step done, because only the finish carries the summary. Each change is recorded on the activity history (never the token). The setup page keeps the same checklist if the person leaves the step and comes back, and offers to start again once a prompt expires. + +Errors: `400` for an invalid body, `401` when the token is missing or does not open this checklist, `404` for an unknown item, `409` when another update changed the checklist at the same time (send it again) or the setup already finished, `410` once the token expired, and `429` after 300 updates. + +## Adding It to Another Setup Page + +In the UI, `useAgentSetupProgress` (in `ui/src/components/AgentSetupProgress.tsx`) creates the checklist. `agentSetupProgressInstructions` writes the prompt section with the agent's commands, and `AgentSetupProgressPanel` shows the checklist. A new page adds its purpose to `AGENT_SETUP_PROGRESS_PURPOSES` in `@paperclipai/shared`. diff --git a/docs/docs.json b/docs/docs.json index 9136f75fa7f..5fd272d833b 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -131,6 +131,7 @@ "api/secrets", "api/tool-gateway-tokens", "api/tool-connections", + "api/agent-setup-progress", "api/activity", "api/dashboard", "api/cloud" diff --git a/packages/db/src/migrations/0504_lucky_pepper_potts.sql b/packages/db/src/migrations/0504_lucky_pepper_potts.sql new file mode 100644 index 00000000000..aa4c4886a51 --- /dev/null +++ b/packages/db/src/migrations/0504_lucky_pepper_potts.sql @@ -0,0 +1,23 @@ +CREATE TABLE IF NOT EXISTS "agent_setup_progress" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "purpose" text NOT NULL, + "subject_id" text, + "token_hash" text NOT NULL, + "status" text DEFAULT 'waiting' NOT NULL, + "items" jsonb DEFAULT '[]'::jsonb NOT NULL, + "summary" text, + "update_count" integer DEFAULT 0 NOT NULL, + "created_by_user_id" text, + "expires_at" timestamp with time zone NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "agent_setup_progress_status_check" CHECK ("agent_setup_progress"."status" in ('waiting', 'in_progress', 'done', 'failed')) +); +--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "agent_setup_progress" ADD CONSTRAINT "agent_setup_progress_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$;--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "agent_setup_progress_company_idx" ON "agent_setup_progress" USING btree ("company_id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "agent_setup_progress_expires_idx" ON "agent_setup_progress" USING btree ("expires_at"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0499_snapshot.json b/packages/db/src/migrations/meta/0504_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0499_snapshot.json rename to packages/db/src/migrations/meta/0504_snapshot.json index 9827e288ac6..64f5339817f 100644 --- a/packages/db/src/migrations/meta/0499_snapshot.json +++ b/packages/db/src/migrations/meta/0504_snapshot.json @@ -1,6 +1,6 @@ { - "id": "a80ac568-accd-4c40-b63a-82b870052e0a", - "prevId": "00aaeb32-9423-4cdd-ae8d-dc721ac83170", + "id": "5d1d8cc7-e7f6-40ce-94c5-dc84dd4210b9", + "prevId": "6d216ee0-8a1e-45e1-a71a-38c1e51b0ec1", "version": "7", "dialect": "postgresql", "tables": { @@ -3313,6 +3313,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.agent_setup_progress": { + "name": "agent_setup_progress", + "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 + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'waiting'" + }, + "items": { + "name": "items", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "update_count": { + "name": "update_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "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": { + "agent_setup_progress_company_idx": { + "name": "agent_setup_progress_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_setup_progress_expires_idx": { + "name": "agent_setup_progress_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_setup_progress_company_id_companies_id_fk": { + "name": "agent_setup_progress_company_id_companies_id_fk", + "tableFrom": "agent_setup_progress", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "agent_setup_progress_status_check": { + "name": "agent_setup_progress_status_check", + "value": "\"agent_setup_progress\".\"status\" in ('waiting', 'in_progress', 'done', 'failed')" + } + }, + "isRLSEnabled": false + }, "public.agent_session_goal_actions": { "name": "agent_session_goal_actions", "schema": "", @@ -34245,6 +34392,163 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.google_pending_revocations": { + "name": "google_pending_revocations", + "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 + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "source_secret_id": { + "name": "source_secret_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "profile": { + "name": "profile", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_material": { + "name": "token_material", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "token_sha256": { + "name": "token_sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "give_up_at": { + "name": "give_up_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "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": { + "google_pending_revocations_due_idx": { + "name": "google_pending_revocations_due_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "google_pending_revocations_token_idx": { + "name": "google_pending_revocations_token_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.grok_bot_dispatches": { "name": "grok_bot_dispatches", "schema": "", @@ -39070,6 +39374,169 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_connection_content_deletions": { + "name": "issue_connection_content_deletions", + "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 + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "requested_by_actor_type": { + "name": "requested_by_actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_by_actor_id": { + "name": "requested_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "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 + }, + "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": { + "issue_connection_content_deletions_issue_idx": { + "name": "issue_connection_content_deletions_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_connection_content_deletions_pending_idx": { + "name": "issue_connection_content_deletions_pending_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issue_connection_content_deletions\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_connection_content_deletions_company_id_companies_id_fk": { + "name": "issue_connection_content_deletions_company_id_companies_id_fk", + "tableFrom": "issue_connection_content_deletions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_create_idempotency_keys": { "name": "issue_create_idempotency_keys", "schema": "", @@ -52761,6 +53228,23 @@ ], "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": {}, @@ -52803,6 +53287,12 @@ "primaryKey": false, "notNull": true }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "title": { "name": "title", "type": "text", @@ -52879,8 +53369,8 @@ "method": "btree", "with": {} }, - "responsibility_areas_company_title_uq": { - "name": "responsibility_areas_company_title_uq", + "responsibility_areas_identity_uq": { + "name": "responsibility_areas_identity_uq", "columns": [ { "expression": "company_id", @@ -52888,6 +53378,39 @@ "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, @@ -57732,6 +58255,114 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.stored_object_deletions": { + "name": "stored_object_deletions", + "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 + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "log_store": { + "name": "log_store", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "stored_object_deletions_due_idx": { + "name": "stored_object_deletions_due_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "stored_object_deletions_company_idx": { + "name": "stored_object_deletions_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.summary_slots": { "name": "summary_slots", "schema": "", @@ -61273,6 +61904,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "token_hash": { "name": "token_hash", "type": "text", @@ -63717,6 +64354,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "identity_context_id": { "name": "identity_context_id", "type": "uuid", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index a6b08e79ac6..2a863e13abf 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3515,6 +3515,13 @@ "when": 1795461974140, "tag": "0503_melted_meggan", "breakpoints": true + }, + { + "idx": 504, + "version": "7", + "when": 1795469468402, + "tag": "0504_lucky_pepper_potts", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/agent_setup_progress.ts b/packages/db/src/schema/agent_setup_progress.ts new file mode 100644 index 00000000000..973117b4efa --- /dev/null +++ b/packages/db/src/schema/agent_setup_progress.ts @@ -0,0 +1,45 @@ +import { sql } from "drizzle-orm"; +import { check, index, integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; + +export type AgentSetupProgressStatus = "waiting" | "in_progress" | "done" | "failed"; +export type AgentSetupProgressItemStatus = "pending" | "in_progress" | "done" | "failed"; +export interface AgentSetupProgressItemRecord { + key: string; + title: string; + status: AgentSetupProgressItemStatus; + detail: string | null; +} + +/** + * A checklist that a person's own agent (outside Paperclip, such as Claude Code + * on their laptop) fills in while it sets something up for them. The setup page + * creates one, hands the agent its URLs and a token in the setup prompt, and + * shows the agent's updates live. Only the token's hash is stored, and the + * token can do nothing but update this one checklist until it expires. + */ +export const agentSetupProgress = pgTable("agent_setup_progress", { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + /** What is being set up, such as `aws_connection`; the page that created it reads it back. */ + purpose: text("purpose").notNull(), + /** The thing being set up, such as a connection id. */ + subjectId: text("subject_id"), + tokenHash: text("token_hash").notNull(), + status: text("status").$type().notNull().default("waiting"), + items: jsonb("items").$type().notNull().default([]), + summary: text("summary"), + updateCount: integer("update_count").notNull().default(0), + createdByUserId: text("created_by_user_id"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), +}, (table) => ({ + companyIdx: index("agent_setup_progress_company_idx").on(table.companyId), + /** Cleanup removes checklists a day past expiry. */ + expiresIdx: index("agent_setup_progress_expires_idx").on(table.expiresAt), + statusCheck: check( + "agent_setup_progress_status_check", + sql`${table.status} in ('waiting', 'in_progress', 'done', 'failed')`, + ), +})); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 60886157221..c7b5688aad6 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -305,3 +305,9 @@ export { issueConnectionContentDeletions } from "./issue_connection_content_dele export { storedObjectDeletions } from "./stored_object_deletions.js"; export { googlePendingRevocations } from "./google_pending_revocations.js"; export * from "./plugin_connector_legacy_access.js"; +export { + agentSetupProgress, + type AgentSetupProgressStatus, + type AgentSetupProgressItemStatus, + type AgentSetupProgressItemRecord, +} from "./agent_setup_progress.js"; diff --git a/packages/shared/src/agent-setup-progress.ts b/packages/shared/src/agent-setup-progress.ts new file mode 100644 index 00000000000..44e3b42853c --- /dev/null +++ b/packages/shared/src/agent-setup-progress.ts @@ -0,0 +1,98 @@ +import { z } from "zod"; + +/** + * Agent setup progress: a checklist a person's own agent (outside Paperclip, + * such as Claude Code on their computer) fills in while it sets something up + * for them. The setup page creates it and shows the agent's updates live; the + * agent writes to it with a token from the setup prompt. + */ + +export const AGENT_SETUP_PROGRESS_STATUSES = ["waiting", "in_progress", "done", "failed"] as const; +export type AgentSetupProgressStatus = (typeof AGENT_SETUP_PROGRESS_STATUSES)[number]; + +export const AGENT_SETUP_PROGRESS_ITEM_STATUSES = ["pending", "in_progress", "done", "failed"] as const; +export type AgentSetupProgressItemStatus = (typeof AGENT_SETUP_PROGRESS_ITEM_STATUSES)[number]; + +/** What can be set up with progress; each page that offers agent setup adds its own. */ +export const AGENT_SETUP_PROGRESS_PURPOSES = ["aws_connection"] as const; +export type AgentSetupProgressPurpose = (typeof AGENT_SETUP_PROGRESS_PURPOSES)[number]; + +export const AGENT_SETUP_PROGRESS_LIMITS = { + maxItems: 20, + maxTitleLength: 120, + maxDetailLength: 500, + /** Updates the agent may send to one checklist, so a looping agent cannot flood the page. */ + maxUpdates: 300, + /** How long the agent's token works after the page creates it. */ + lifetimeMs: 6 * 60 * 60 * 1000, +} as const; + +export interface AgentSetupProgressItem { + key: string; + title: string; + status: AgentSetupProgressItemStatus; + detail: string | null; +} + +export interface AgentSetupProgress { + id: string; + companyId: string; + purpose: AgentSetupProgressPurpose; + subjectId: string | null; + status: AgentSetupProgressStatus; + items: AgentSetupProgressItem[]; + summary: string | null; + expiresAt: string; + createdAt: string; + updatedAt: string; +} + +/** Returned once, when the page creates the checklist: everything the agent needs to write to it. */ +export interface AgentSetupProgressHandoff { + progress: AgentSetupProgress; + /** Sent as `Authorization: Bearer `. Shown only in this response; Paperclip keeps a hash. */ + token: string; + urls: { + /** PUT: replace the checklist. */ + checklist: string; + /** POST: update one item; `{key}` is the item's key. */ + item: string; + /** POST: say the whole setup is done or failed. */ + finish: string; + }; +} + +/** An item key: also part of the item URL, so the Cloud front door can match it exactly. */ +export const agentSetupItemKeyPattern = /^[a-z0-9][a-z0-9_-]{0,39}$/; +const itemKey = z.string().trim().regex(agentSetupItemKeyPattern, "Use lowercase letters, numbers, - and _ (up to 40)"); +const text = (max: number) => z.string().trim().min(1).max(max); + +export const createAgentSetupProgressSchema = z.object({ + purpose: z.enum(AGENT_SETUP_PROGRESS_PURPOSES), + subjectId: z.string().trim().min(1).max(200).optional(), +}).strict(); +export type CreateAgentSetupProgress = z.infer; + +export const setAgentSetupChecklistSchema = z.object({ + items: z.array(z.object({ + key: itemKey, + title: text(AGENT_SETUP_PROGRESS_LIMITS.maxTitleLength), + status: z.enum(AGENT_SETUP_PROGRESS_ITEM_STATUSES).optional(), + detail: text(AGENT_SETUP_PROGRESS_LIMITS.maxDetailLength).optional(), + }).strict()).min(1).max(AGENT_SETUP_PROGRESS_LIMITS.maxItems) + .refine((items) => new Set(items.map((item) => item.key)).size === items.length, "Each item needs its own key"), +}).strict(); +export type SetAgentSetupChecklist = z.infer; + +export const updateAgentSetupItemSchema = z.object({ + status: z.enum(AGENT_SETUP_PROGRESS_ITEM_STATUSES), + /** Omit to keep the step's detail; send null to clear it (such as after a retry fixed an earlier error). */ + detail: text(AGENT_SETUP_PROGRESS_LIMITS.maxDetailLength).nullable().optional(), +}).strict(); +export type UpdateAgentSetupItem = z.infer; + +export const finishAgentSetupSchema = z.object({ + status: z.enum(["done", "failed"]), + summary: text(AGENT_SETUP_PROGRESS_LIMITS.maxDetailLength).optional(), +}).strict(); +export type FinishAgentSetup = z.infer; diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 8df4ffc512b..2cb07762a02 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -1130,6 +1130,7 @@ export const LIVE_EVENT_TYPES = [ "plugin.ui.updated", "plugin.worker.crashed", "plugin.worker.restarted", + "agent_setup_progress.updated", ] as const; export type LiveEventType = (typeof LIVE_EVENT_TYPES)[number]; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 773b1934c94..583f640ffdc 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3148,3 +3148,4 @@ export * from "./mcp-apps.js"; export * from "./tool-call-progress.js"; export * from "./mcp-skills.js"; export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscale.js"; +export * from "./agent-setup-progress.js"; diff --git a/server/src/__tests__/agent-setup-progress.test.ts b/server/src/__tests__/agent-setup-progress.test.ts new file mode 100644 index 00000000000..8eb50a54d84 --- /dev/null +++ b/server/src/__tests__/agent-setup-progress.test.ts @@ -0,0 +1,251 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import express from "express"; +import request from "supertest"; +import { eq, inArray } from "drizzle-orm"; +import { activityLog, agentSetupProgress, companies, companyMemberships, createDb, principalPermissionGrants, toolApplications, toolConnections } from "@paperclipai/db"; +import { AGENT_SETUP_PROGRESS_LIMITS, type AgentSetupProgressHandoff, type LiveEvent } from "@paperclipai/shared"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { agentSetupProgressAgentRoutes, agentSetupProgressBoardRoutes } from "../routes/agent-setup-progress.js"; +import { subscribeCompanyLiveEvents } from "../services/live-events.js"; +import { agentSetupProgressService } from "../services/agent-setup-progress.js"; +import { errorHandler } from "../middleware/error-handler.js"; + +const userId = "setup-progress-user"; + +describe("agent setup progress", () => { + let fixture: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://acme.paperclip.app"); + fixture = await startEmbeddedPostgresTestDatabase("agent-setup-progress-"); + db = createDb(fixture.connectionString); + }, 120_000); + afterAll(async () => { + await fixture?.cleanup(); + vi.unstubAllEnvs(); + }); + + async function company() { + const [row] = await db.insert(companies).values({ name: `Setup ${randomUUID()}`, issuePrefix: `S${randomUUID().slice(0, 5)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: row!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "admin" }); + const [application] = await db.insert(toolApplications).values({ companyId: row!.id, name: "AWS", type: "mcp_http" }).returning(); + const [connection] = await db.insert(toolConnections).values({ + companyId: row!.id, applicationId: application!.id, name: "AWS", uid: `aws-${randomUUID()}`, transport: "mcp_remote", createdByUserId: userId, + }).returning(); + return { ...row!, connectionId: connection!.id, applicationId: application!.id }; + } + + /** The real app splits these: the agent's routes need no sign-in, the board's do. */ + function app(boardCompanyIds: string[], actorUserId = userId) { + const server = express(); + server.use(express.json()); + server.use(agentSetupProgressAgentRoutes(db)); + const api = express.Router(); + api.use((req, _res, next) => { + req.actor = { type: "board", userId: actorUserId, source: "session", companyIds: boardCompanyIds, isInstanceAdmin: false } as Express.Request["actor"]; + next(); + }); + api.use(agentSetupProgressBoardRoutes(db)); + server.use("/api", api); + server.use(errorHandler); + return server; + } + + const path = (url: string) => new URL(url).pathname; + + it("lets the agent set and tick off its checklist with the prompt's token, live, then finish", async () => { + const org = await company(); + const server = app([org.id]); + const created = await request(server).post(`/api/companies/${org.id}/agent-setup-progress`) + .send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201); + const handoff = created.body as AgentSetupProgressHandoff; + expect(handoff.progress).toMatchObject({ status: "waiting", items: [], purpose: "aws_connection", subjectId: org.connectionId }); + expect(handoff.urls.checklist).toBe(`https://acme.paperclip.app/api/agent-setup-progress/${handoff.progress.id}/checklist`); + expect(handoff.urls.item).toContain("/items/{key}"); + expect(handoff.token).toMatch(/^pcsp_/); + // Only the token's hash is stored. + const [stored] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id)); + expect(stored!.tokenHash).not.toContain(handoff.token); + + const events: LiveEvent[] = []; + const stop = subscribeCompanyLiveEvents(org.id, (event) => events.push(event)); + const auth = { Authorization: `Bearer ${handoff.token}` }; + await request(server).put(path(handoff.urls.checklist)).set(auth).send({ items: [ + { key: "check-account", title: "Check the AWS account" }, + { key: "deploy-stack", title: "Create the role" }, + ] }).expect(200); + const item = (key: string) => path(handoff.urls.item.replace("{key}", key)); + await request(server).post(item("check-account")).set(auth).send({ status: "done", detail: "Account 123456789012" }).expect(200); + const working = await request(server).post(item("deploy-stack")).set(auth).send({ status: "in_progress" }).expect(200); + expect(working.body).toMatchObject({ status: "in_progress", items: [ + { key: "check-account", status: "done", detail: "Account 123456789012" }, + { key: "deploy-stack", status: "in_progress", detail: null }, + ] }); + // Every step ticked off is still in progress: only the finish carries the summary, and the page keeps refreshing until it. + // A detail is kept when omitted and cleared with null, so a retry can drop an earlier error. + const keptDetail = await request(server).post(item("check-account")).set(auth).send({ status: "done" }).expect(200); + expect(keptDetail.body.items[0].detail).toBe("Account 123456789012"); + await request(server).post(item("deploy-stack")).set(auth).send({ status: "failed", detail: "Access denied" }).expect(200); + const cleared = await request(server).post(item("deploy-stack")).set(auth).send({ status: "in_progress", detail: null }).expect(200); + expect(cleared.body.items[1].detail).toBeNull(); + const ticked = await request(server).post(item("deploy-stack")).set(auth).send({ status: "done" }).expect(200); + expect(ticked.body.status).toBe("in_progress"); + const finished = await request(server).post(path(handoff.urls.finish)).set(auth) + .send({ status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1" }).expect(200); + // Finishing done ticks off what is left. + expect(finished.body).toMatchObject({ status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1", + items: [{ status: "done" }, { status: "done" }] }); + stop(); + const progressEvents = events.filter((event) => event.type === "agent_setup_progress.updated"); + expect(progressEvents).toHaveLength(8); + expect(progressEvents.every((event) => event.payload.progressId === handoff.progress.id)).toBe(true); + + const read = await request(server).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(200); + expect(read.body.status).toBe("done"); + const actions = (await db.select().from(activityLog).where(eq(activityLog.entityId, handoff.progress.id))).map((row) => row.action).sort(); + // Every change is on the activity history, and no entry holds the token. + expect(actions).toEqual([ + "agent_setup_progress.created", "agent_setup_progress.finished", + "agent_setup_progress.item_updated", "agent_setup_progress.item_updated", "agent_setup_progress.item_updated", + "agent_setup_progress.item_updated", "agent_setup_progress.item_updated", "agent_setup_progress.item_updated", + "agent_setup_progress.started", + ]); + const history = await db.select().from(activityLog).where(eq(activityLog.entityId, handoff.progress.id)); + expect(JSON.stringify(history)).not.toContain(handoff.token); + }); + + it("refuses a missing or wrong token, an unknown item, an expired checklist and too many updates", async () => { + const org = await company(); + const server = app([org.id]); + const handoff = (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff; + const checklist = path(handoff.urls.checklist); + const items = { items: [{ key: "step-1", title: "Step one" }] }; + await request(server).put(checklist).send(items).expect(401); + await request(server).put(checklist).set({ Authorization: "Bearer pcsp_wrong" }).send(items).expect(401); + // A real token for another checklist opens nothing else. + const other = (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff; + await request(server).put(checklist).set({ Authorization: `Bearer ${other.token}` }).send(items).expect(401); + + const auth = { Authorization: `Bearer ${handoff.token}` }; + await request(server).put(checklist).set(auth).send({ items: [{ key: "Bad Key", title: "x" }] }).expect(400); + await request(server).put(checklist).set(auth).send(items).expect(200); + await request(server).post(path(handoff.urls.item.replace("{key}", "nope"))).set(auth).send({ status: "done" }).expect(404); + + await db.update(agentSetupProgress).set({ updateCount: AGENT_SETUP_PROGRESS_LIMITS.maxUpdates }).where(eq(agentSetupProgress.id, handoff.progress.id)); + await request(server).put(checklist).set(auth).send(items).expect(429); + await db.update(agentSetupProgress).set({ updateCount: 0, expiresAt: new Date(Date.now() - 1000) }).where(eq(agentSetupProgress.id, handoff.progress.id)); + await request(server).put(checklist).set(auth).send(items).expect(410); + }); + + it("finishes as failed, keeps finished final, never loses a concurrent update, and cleans up old checklists", async () => { + const org = await company(); + const server = app([org.id]); + const create = async () => (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff; + const handoff = await create(); + const auth = { Authorization: `Bearer ${handoff.token}` }; + const item = (key: string) => path(handoff.urls.item.replace("{key}", key)); + await request(server).put(path(handoff.urls.checklist)).set(auth).send({ items: [ + { key: "a", title: "A" }, { key: "b", title: "B" }, { key: "c", title: "C" }, + ] }).expect(200); + + // Concurrent writes either land or answer 409 to be sent again: none is silently lost. + const results = await Promise.all(["a", "b", "c"].map((key) => request(server).post(item(key)).set(auth).send({ status: "in_progress" }))); + expect(results.every((res) => res.status === 200 || res.status === 409)).toBe(true); + const [afterRace] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id)); + expect(afterRace!.updateCount).toBe(1 + results.filter((res) => res.status === 200).length); + expect(afterRace!.items.filter((entry) => entry.status === "in_progress")).toHaveLength(results.filter((res) => res.status === 200).length); + + await request(server).post(item("b")).set(auth).send({ status: "failed", detail: "No permission" }).expect(200); + const failed = await request(server).post(path(handoff.urls.finish)).set(auth).send({ status: "failed", summary: "Stopped: no permission" }).expect(200); + expect(failed.body).toMatchObject({ status: "failed", summary: "Stopped: no permission" }); + expect(failed.body.items.find((entry: { key: string }) => entry.key === "b")).toMatchObject({ status: "failed", detail: "No permission" }); + // A late or retried write cannot reopen a finished setup. + const late = await request(server).post(item("a")).set(auth).send({ status: "done" }).expect(409); + expect(late.body.details).toMatchObject({ code: "agent_setup_progress_finished" }); + await request(server).post(path(handoff.urls.finish)).set(auth).send({ status: "done" }).expect(409); + + // Finishing done is the agent's verdict: every step is ticked off, including one that failed along the way. + const second = await create(); + const auth2 = { Authorization: `Bearer ${second.token}` }; + await request(server).put(path(second.urls.checklist)).set(auth2).send({ items: [{ key: "a", title: "A" }, { key: "b", title: "B" }] }).expect(200); + await request(server).post(path(second.urls.item.replace("{key}", "a"))).set(auth2).send({ status: "failed" }).expect(200); + const done = await request(server).post(path(second.urls.finish)).set(auth2).send({ status: "done" }).expect(200); + expect(done.body.items.map((entry: { status: string }) => entry.status)).toEqual(["done", "done"]); + + // Checklists a day past expiry are removed as new ones are created; recent ones stay. + await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 25 * 3600_000) }).where(eq(agentSetupProgress.id, handoff.progress.id)); + await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 3600_000) }).where(eq(agentSetupProgress.id, second.progress.id)); + // Another company's long-expired checklist is never touched by this company's cleanup. + const other = await company(); + const foreign = (await request(app([other.id])).post(`/api/companies/${other.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: other.connectionId }).expect(201)).body as AgentSetupProgressHandoff; + await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 48 * 3600_000) }).where(eq(agentSetupProgress.id, foreign.progress.id)); + await create(); + expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, foreign.progress.id))).toHaveLength(1); + expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id))).toHaveLength(0); + expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, second.progress.id))).toHaveLength(1); + }); + + it("clears long-expired checklists across companies once at startup, and keeps the rest", async () => { + const first = await company(); + const second = await company(); + const make = async (org: Awaited>) => ((await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`) + .send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff).progress.id; + const oldA = await make(first); + const oldB = await make(second); + const recent = await make(second); + await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 48 * 3600_000) }).where(inArray(agentSetupProgress.id, [oldA, oldB])); + await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 3600_000) }).where(eq(agentSetupProgress.id, recent)); + // Batches of one: the sweep keeps going until no old checklist is left, not just one batch. + expect(await agentSetupProgressService(db).sweepExpired({ batchSize: 1 })).toBeGreaterThanOrEqual(2); + const left = (await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress).where(inArray(agentSetupProgress.id, [oldA, oldB, recent]))).map((row) => row.id); + expect(left).toEqual([recent]); + }); + + it("does not let a cache keep the agent's token", async () => { + const org = await company(); + const res = await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201); + expect(res.headers["cache-control"]).toBe("no-store"); + expect(res.headers.pragma).toBe("no-cache"); + }); + + it("keeps checklists inside their company", async () => { + const org = await company(); + const outsider = await company(); + const handoff = (await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff; + // Another company's checklist answers exactly like a missing one. + const hidden = await request(app([outsider.id])).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(404); + const missing = await request(app([outsider.id])).get(`/api/agent-setup-progress/${randomUUID()}`).expect(404); + expect(hidden.body).toEqual(missing.body); + await request(app([outsider.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403); + + // Inside the company: only someone who may configure the connection starts its setup, + // and only the person who started it reads the checklist back. + const viewerId = `viewer-${randomUUID()}`; + await db.insert(companyMemberships).values({ companyId: org.id, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer" }); + await request(app([org.id], viewerId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403); + // A manager whose permission covers just this connection may set it up; one scoped to another connection may not. + const scopedId = `scoped-${randomUUID()}`; + const elsewhereId = `elsewhere-${randomUUID()}`; + const [otherConnection] = await db.insert(toolConnections).values({ + companyId: org.id, applicationId: org.applicationId, name: "Other", uid: `other-${randomUUID()}`, transport: "mcp_remote", createdByUserId: userId, + }).returning(); + await db.insert(companyMemberships).values([scopedId, elsewhereId].map((principalId) => ({ companyId: org.id, principalType: "user", principalId, status: "active", membershipRole: "member" }))); + await db.insert(principalPermissionGrants).values([ + { companyId: org.id, principalType: "user", principalId: scopedId, permissionKey: "tools:manage_connections", scope: { connectionIds: [org.connectionId] } }, + { companyId: org.id, principalType: "user", principalId: elsewhereId, permissionKey: "tools:manage_connections", scope: { connectionIds: [otherConnection!.id] } }, + ]); + await request(app([org.id], scopedId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201); + await request(app([org.id], elsewhereId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403); + const otherMember = await request(app([org.id], viewerId)).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(404); + expect(otherMember.body).toEqual(missing.body); + const own = await request(app([org.id])).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(200); + expect(own.body.createdByUserId).toBeUndefined(); + // A checklist always names a real connection of this company. + await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection" }).expect(422); + await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: outsider.connectionId }).expect(404); + // A malformed id is a clean not-found, never a server error. + await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: "abc" }).expect(404); + }); +}); diff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.ts index ce8e7eaf978..352a5e0bece 100644 --- a/server/src/__tests__/live-events-toast.test.ts +++ b/server/src/__tests__/live-events-toast.test.ts @@ -218,6 +218,27 @@ describe("authenticated activity notifications", () => { } }); + it("delivers an agent setup progress update to the page with only the checklist id", async () => { + const server = createServer(); + setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated", + resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`); + try { + await once(socket, "open"); + const message = once(socket, "message"); + publishLiveEvent({ companyId: "company", type: "agent_setup_progress.updated", payload: { progressId: "progress-1", token: "never-sent" } }); + const [data] = await message; + const event = JSON.parse(data.toString()); + expect(event).toMatchObject({ type: "agent_setup_progress.updated", payload: { progressId: "progress-1" } }); + expect(event.payload).toEqual({ progressId: "progress-1" }); + } finally { + socket.terminate(); + await new Promise(resolve => server.close(() => resolve())); + } + }); + it("uses the persisted local-board user identity for local task eligibility", async () => { vi.mocked(taskToastEligible).mockImplementation(async (_db, _event, userId) => userId === "local-board"); const server = createServer(); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 143b9f3ddef..1592f802ba9 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -119,6 +119,7 @@ const apiPrefixes: Record = { "user-profiles.ts": "/api", "workspace-preferences.ts": "/api", "workload-identity.ts": "/api", + "agent-setup-progress.ts": "/api", }; const ROUTE_LITERAL_PATTERN = @@ -216,6 +217,7 @@ function normalizeExpressPath(routePath: string) { function resolveMountedPath(file: string, prefix: string, routePath: string) { if (file === "connection-event-wake.ts") return routePath; if (file === "workload-identity.ts" && routePath.startsWith("/oidc/")) return routePath; + if (file === "agent-setup-progress.ts" && routePath.startsWith("/api/")) return routePath; if (file === "public-mcp.ts" && (routePath.startsWith("/mcp/oauth/") || routePath.startsWith("/.well-known/"))) return routePath; if ( (file === "chat-channels.ts" || file === "email.ts") && @@ -425,6 +427,21 @@ describe("openapi routes", () => { expect(operation.requestBody.content).toHaveProperty("application/json"); expect(spec.paths).not.toHaveProperty("/api/routine-triggers/public/{publicId}/sentry-run-failures"); }); + it("documents the agent's setup progress routes as needing the checklist's bearer token", () => { + const spec = buildOpenApiSpec() as any; + expect(spec.components.securitySchemes.AgentSetupTokenAuth).toMatchObject({ type: "http", scheme: "bearer" }); + for (const [path, method] of [ + ["/api/agent-setup-progress/{id}/checklist", "put"], + ["/api/agent-setup-progress/{id}/items/{key}", "post"], + ["/api/agent-setup-progress/{id}/finish", "post"], + ] as const) { + const operation = spec.paths[path][method]; + expect(operation.security, `${method} ${path}`).toEqual([{ AgentSetupTokenAuth: [] }]); + expect(operation["x-paperclip-authorization"]).toEqual({ actor: "setup_token" }); + expect(operation.responses).toHaveProperty("401"); + } + expect(spec.paths["/api/agent-setup-progress/{id}"].get["x-paperclip-authorization"]).toEqual({ actor: "board" }); + }); it("documents connected-app skill review as board only and file reads as agent-run only", () => { const spec = buildOpenApiSpec() as any; const files = spec.paths["/api/agents/me/mcp-skills/{skillId}/files"].get; diff --git a/server/src/app.ts b/server/src/app.ts index c89df4ef844..c88f27a962b 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -140,6 +140,7 @@ import { routineSuggestionRoutes } from "./routes/routine-suggestions.js"; import { environmentRoutes } from "./routes/environments.js"; import { tailscaleConnectionRoutes } from "./routes/tailscale-connections.js"; import { workloadIdentityPublicRoutes, workloadIdentityRoutes } from "./routes/workload-identity.js"; +import { agentSetupProgressAgentRoutes, agentSetupProgressBoardRoutes } from "./routes/agent-setup-progress.js"; import { setWorkloadIdentityConfiguredPublicOrigin } from "./services/workload-identity.js"; import { executionWorkspaceRoutes } from "./routes/execution-workspaces.js"; import { goalRoutes } from "./routes/goals.js"; @@ -623,6 +624,8 @@ export async function createApp( // Outside clouds fetch these anonymously to verify connection identity tokens. setWorkloadIdentityConfiguredPublicOrigin(opts.authPublicBaseUrl); app.use(workloadIdentityPublicRoutes(db)); + // A person's own agent reports setup progress with the bearer token from its setup prompt. + app.use(agentSetupProgressAgentRoutes(db)); // Connection-intent tools carry their own short-lived, run-bound bearer and // must be reachable by remote adapters that intentionally do not receive an // agent API key. Every request revalidates the active heartbeat row. @@ -872,6 +875,7 @@ export async function createApp( api.use(routineRoutes(db, { pluginWorkerManager: workerManager })); api.use(tailscaleConnectionRoutes(db)); api.use(workloadIdentityRoutes(db)); + api.use(agentSetupProgressBoardRoutes(db)); api.use(routineSuggestionRoutes(db, { pluginWorkerManager: workerManager })); api.use( environmentRoutes(db, { diff --git a/server/src/index.ts b/server/src/index.ts index 2401cd626d9..56c2b46acd1 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,4 +1,5 @@ import { tailscaleNetworks } from "./services/connectors/tailscale/network.js"; +import { agentSetupProgressService } from "./services/agent-setup-progress.js"; import type { IdleDeadlineOwners } from "./services/idle-deadline-types.js"; import { closeProcessRunAdmission, isProcessRunAdmissionClosed } from "./services/heartbeat/run-admission.js"; import { registerReattachPhaseWork } from "./services/heartbeat/reattach-phase.js"; @@ -2050,6 +2051,8 @@ async function startServerWithDatabaseTeardown( () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready); await step("approval_queue_seeding", () => registerApprovalQueueSeedingWork(deliveryWork, approvalQueueSeedingService(db as any), () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready); + // Once per start, not a recurring scan: clear agent setup checklists a day past expiry. + await step("agent_setup_progress_cleanup", () => agentSetupProgressService(db).sweepExpired()); await step("approval_retention", () => registerApprovalRetentionWork(deliveryWork, approvalRetentionService(db as any), () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready); await step("join_request_retention", () => registerJoinRequestRetentionWork(deliveryWork, joinRequestRetentionService(db as any), diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index 076985c141d..e22587341c3 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -391,6 +391,8 @@ export function setupLiveEventsWebSocketServer( if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } }; if (event.type === "agent.runtime_state.updated") return { ...event, payload: { agentId: payload.agentId } }; if (event.type === "external_object.updated") return { ...event, payload: { externalObjectId: payload.externalObjectId } }; + // Only the id: reading the checklist itself goes through the board-only API. + if (event.type === "agent_setup_progress.updated") return { ...event, payload: { progressId: payload.progressId } }; if (event.type.startsWith("plugin.")) return event; return null; } diff --git a/server/src/routes/agent-setup-progress.ts b/server/src/routes/agent-setup-progress.ts new file mode 100644 index 00000000000..d80ae252a7c --- /dev/null +++ b/server/src/routes/agent-setup-progress.ts @@ -0,0 +1,115 @@ +import { Router, type Request, type Response } from "express"; +import { and, eq } from "drizzle-orm"; +import { toolConnections } from "@paperclipai/db"; +import type { Db } from "@paperclipai/db"; +import { z } from "zod"; +import { + agentSetupItemKeyPattern, + createAgentSetupProgressSchema, + finishAgentSetupSchema, + setAgentSetupChecklistSchema, + updateAgentSetupItemSchema, + type CreateAgentSetupProgress, +} from "@paperclipai/shared"; +import { notFound, unprocessable } from "../errors.js"; +import { connectionManagementGuard } from "./connection-management-authz.js"; +import { validate } from "../middleware/validate.js"; +import { agentSetupProgressService } from "../services/agent-setup-progress.js"; +import { workloadIdentityPublicOrigin } from "../services/workload-identity.js"; +import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js"; + +const idSchema = z.string().uuid(); + +/** + * The agent's side of a setup checklist. A person's own agent (outside + * Paperclip) calls these with the bearer token from the setup prompt; they + * need no Paperclip sign-in, so the token is the only credential and it can + * only write to this one checklist. + */ +export function agentSetupProgressAgentRoutes(db: Db) { + const router = Router(); + const service = agentSetupProgressService(db); + const progressId = (req: Request) => { + const parsed = idSchema.safeParse(req.params.id); + if (!parsed.success) throw notFound("Setup progress not found"); + return parsed.data; + }; + router.put("/api/agent-setup-progress/:id/checklist", validate(setAgentSetupChecklistSchema), async (req, res) => { + res.setHeader("Cache-Control", "no-store"); + res.json(await service.setChecklist(progressId(req), req.header("authorization"), req.body)); + }); + router.post("/api/agent-setup-progress/:id/items/:key", validate(updateAgentSetupItemSchema), async (req, res) => { + res.setHeader("Cache-Control", "no-store"); + const key = String(req.params.key); + if (!agentSetupItemKeyPattern.test(key)) throw notFound("Checklist item not found"); + res.json(await service.updateItem(progressId(req), key, req.header("authorization"), req.body)); + }); + router.post("/api/agent-setup-progress/:id/finish", validate(finishAgentSetupSchema), async (req, res) => { + res.setHeader("Cache-Control", "no-store"); + res.json(await service.finish(progressId(req), req.header("authorization"), req.body)); + }); + return router; +} + +/** The address the agent should call: the instance's public address, else the one the page used. */ +function agentOrigin(req: Request) { + return workloadIdentityPublicOrigin() ?? `${req.protocol}://${req.get("host")}`; +} + +/** + * The page's side. A checklist describes the setup of one thing (for AWS, one + * connection), so only someone who may configure that thing creates one, and + * only the person who started the setup reads it back. + */ +export function agentSetupProgressBoardRoutes(db: Db) { + const router = Router(); + const service = agentSetupProgressService(db); + + // Same rule as the AWS setup screen: the connection-management check for configuring this + // connection, which honours permissions granted for just this connection. + const configureConnection = connectionManagementGuard(db, "tool")("connections:configure", "POST /companies/:companyId/agent-setup-progress"); + + async function assertCanSetUpSubject(req: Request, res: Response, companyId: string, body: CreateAgentSetupProgress) { + if (body.purpose !== "aws_connection") return; + if (!body.subjectId) throw unprocessable("Name the connection being set up.", { code: "agent_setup_progress_subject_required" }); + // A connection id is a UUID; anything else is simply not a connection (and must not reach the uuid column). + if (!idSchema.safeParse(body.subjectId).success) throw notFound("Tool connection not found"); + const [connection] = await db.select({ id: toolConnections.id }).from(toolConnections) + .where(and(eq(toolConnections.id, body.subjectId), eq(toolConnections.companyId, companyId))); + if (!connection) throw notFound("Tool connection not found"); + req.params.connectionId = connection.id; + await new Promise((resolve, reject) => { + void configureConnection(req, res, (error?: unknown) => (error ? reject(error) : resolve())); + }); + } + router.post("/companies/:companyId/agent-setup-progress", validate(createAgentSetupProgressSchema), async (req, res) => { + assertBoard(req); + const companyId = idSchema.parse(req.params.companyId); + assertCompanyAccess(req, companyId); + const body = req.body as CreateAgentSetupProgress; + await assertCanSetUpSubject(req, res, companyId, body); + const { actorId } = getActorInfo(req); + // The response carries the agent's token: never cache it. + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Pragma", "no-cache"); + res.status(201).json(await service.create({ + companyId, purpose: body.purpose, subjectId: body.subjectId ?? null, userId: actorId, origin: agentOrigin(req), + })); + }); + router.get("/agent-setup-progress/:id", async (req, res) => { + assertBoard(req); + const id = idSchema.safeParse(req.params.id); + // Another company's checklist, or another person's, answers exactly like a missing one. + const progress = await getAccessibleResource(req, res, id.success ? service.get(id.data) : null, "Setup progress not found"); + if (!progress) return; + const { actorId } = getActorInfo(req); + const unrestricted = req.actor.source === "local_implicit" || req.actor.isInstanceAdmin; + if (!unrestricted && progress.createdByUserId !== actorId) { + res.status(404).json({ error: "Setup progress not found" }); + return; + } + const { createdByUserId: _creator, ...visible } = progress; + res.json(visible); + }); + return router; +} diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 5e94729cfe8..dbcfb955189 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1,3 +1,4 @@ +import { createAgentSetupProgressSchema, setAgentSetupChecklistSchema, updateAgentSetupItemSchema, finishAgentSetupSchema } from "@paperclipai/shared"; import { catalogTeamInstallSchema, catalogTeamPreviewSchema, updateWorkspacePreferenceSchema, issueDocumentBatchQuerySchema } from "@paperclipai/shared"; import { MUSE_ASSET_VERSION, museStopBoundarySchema, museDetectorCleanupAttestationSchema, createGrokInvitationSchema, configureGrokRoutineSchema, verifyGrokRoutineSchema, recoverGrokRoutineSchema, pairGrokBindingSchema, stopGrokWorkSchema, retryGrokDeliverySchema, updateFastResponseSchema } from "@paperclipai/shared"; import { slackTestMessageSchema, slackTestMessageResultSchema, slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared"; @@ -1363,6 +1364,7 @@ type OpenApiAuthLevel = | "agent_run" | "agent_heartbeat" | "runtime_tools" + | "agent_setup_token" | "authenticated" | "board" | "instance_admin"; @@ -1372,6 +1374,7 @@ const BOARD_API_KEY_AUTH_SCHEME = "BoardApiKeyAuth"; const AGENT_BEARER_AUTH_SCHEME = "AgentBearerAuth"; const AGENT_RUN_AUTH_SCHEME = "AgentRunAuth"; const RUNTIME_TOOLS_BEARER_AUTH_SCHEME = "RuntimeToolsBearerAuth"; +const AGENT_SETUP_TOKEN_AUTH_SCHEME = "AgentSetupTokenAuth"; function securityRequirement(name: string): Record { return { [name]: [] }; @@ -1399,6 +1402,13 @@ const RUNTIME_TOOLS_OPERATIONS = new Set([ "POST /runtime-tools/connections/request", ]); +/** A person's own agent reports setup progress with the checklist's bearer token, not a Paperclip sign-in (routes/agent-setup-progress.ts). */ +const AGENT_SETUP_TOKEN_OPERATIONS = new Set([ + "PUT /api/agent-setup-progress/{id}/checklist", + "POST /api/agent-setup-progress/{id}/items/{key}", + "POST /api/agent-setup-progress/{id}/finish", +]); + const PUBLIC_OPERATIONS = new Set([ "GET /api/agent-avatars/{version}/{palette}/{file}", "GET /api/health", @@ -1473,6 +1483,9 @@ const BOARD_ONLY_OPERATIONS = new Set([ // Workload identity status and key rotation are board-only (assertBoard in routes/workload-identity.ts). "GET /api/companies/{companyId}/workload-identity", "POST /api/companies/{companyId}/workload-identity/rotation", + // Setup progress checklists are created and read by board members (assertBoard in routes/agent-setup-progress.ts). + "POST /api/companies/{companyId}/agent-setup-progress", + "GET /api/agent-setup-progress/{id}", "POST /api/companies/{companyId}/chats/{agentRef}/onboarding", "POST /api/companies/{companyId}/chats/{agentRef}/onboarding/greeting", "PATCH /api/agents/{id}/permission-grants", @@ -1657,6 +1670,7 @@ const INSTANCE_ADMIN_OPERATIONS = new Set([ ]); const CREATED_OPERATIONS = new Set([ + "POST /api/companies/{companyId}/agent-setup-progress", "POST /api/adapters/install", "POST /api/companies/{companyId}/agent-hires", "POST /api/companies/{companyId}/agents", @@ -1758,6 +1772,7 @@ function resolveOperationAuthLevel( if (path === "/api/companies/{companyId}/grok-invitations" || /^\/api\/companies\/\{companyId\}\/agents\/\{agentId\}\/grok-binding(?:\/(?:routine|verify|retry|stop|recover))?$/.test(path)) return "board"; if (PUBLIC_OPERATIONS.has(key)) return "public"; + if (AGENT_SETUP_TOKEN_OPERATIONS.has(key)) return "agent_setup_token"; if (key === "POST /api/companies/{companyId}/agent-commentary") return "agent_heartbeat"; if (key === "POST /api/agents/me/chat/messages") return "agent_heartbeat"; // An approved connected-app skill's file: an agent in an active run only. @@ -1817,6 +1832,12 @@ function applyDocumentFixups(document: any): any { description: "Scoped token bound to an active heartbeat run and presented in the Authorization bearer header. The GitHub credential endpoint requires the distinct github_credentials scope.", }, + [AGENT_SETUP_TOKEN_AUTH_SCHEME]: { + type: "http", + scheme: "bearer", + bearerFormat: "Setup checklist token (pcsp_…)", + description: "The token from a setup prompt, presented in the Authorization bearer header. It updates only its own setup checklist, until the checklist finishes or expires.", + }, [AGENT_RUN_AUTH_SCHEME]: { type: "http", scheme: "bearer", @@ -1839,6 +1860,8 @@ function applyDocumentFixups(document: any): any { operation.security = [securityRequirement(AGENT_BEARER_AUTH_SCHEME)]; } else if (authLevel === "runtime_tools") { operation.security = RUNTIME_TOOLS_SECURITY; + } else if (authLevel === "agent_setup_token") { + operation.security = [securityRequirement(AGENT_SETUP_TOKEN_AUTH_SCHEME)]; } else if (authLevel === "authenticated") { operation.security = AUTHENTICATED_SECURITY; } else { @@ -1856,6 +1879,8 @@ function applyDocumentFixups(document: any): any { ? { actor: "agent", heartbeatBound: true } : authLevel === "runtime_tools" ? { actor: "runtime_tools", heartbeatBound: true } + : authLevel === "agent_setup_token" + ? { actor: "setup_token" } : authLevel === "authenticated" ? { actor: "board_or_agent" } : { actor: "public" }; @@ -1866,7 +1891,8 @@ function applyDocumentFixups(document: any): any { } const key = operationKey(method, path); - if (authLevel !== "public") { + // The setup token is only ever valid or not (401); it has no permissions to be refused. + if (authLevel !== "public" && authLevel !== "agent_setup_token") { const responses = (operation.responses ??= {}) as Record< string, unknown @@ -9770,6 +9796,64 @@ registry.registerPath({ }).strict()) }).strict()), ...workloadIdentityPublicNotFound }, }); +const agentSetupItem = z.object({ + key: z.string(), title: z.string(), status: z.enum(["pending", "in_progress", "done", "failed"]), detail: z.string().nullable(), +}).strict(); +const agentSetupProgressDoc = z.object({ + id: z.string().uuid(), companyId: z.string().uuid(), purpose: z.string(), subjectId: z.string().nullable(), + status: z.enum(["waiting", "in_progress", "done", "failed"]), items: z.array(agentSetupItem), summary: z.string().nullable(), + expiresAt: z.string().datetime(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(), +}).strict(); +const agentSetupProgressId = z.object({ id: z.string().uuid() }); +const agentSetupAgentErrors = { + 400: r.badRequest, 401: { description: "The bearer token is missing or does not open this checklist" }, + 404: r.notFound, 409: { description: "Another update changed the checklist at the same time; send it again" }, + 410: { description: "The checklist's token expired" }, 429: { description: "The checklist reached its update limit" }, +}; + +registry.registerPath({ + method: "post", path: "/api/companies/{companyId}/agent-setup-progress", tags: ["agent-setup-progress"], + summary: "Create a setup checklist for a person's own agent", + description: "Board only. For aws_connection, subjectId must be a connection of this company that the caller may configure. Creates an empty checklist and returns it with a bearer token (shown once; only its hash is kept) and the URLs the agent uses to set the checklist, update items and finish. The token works for six hours and can only write to this checklist.", + request: { params: z.object({ companyId: z.string().uuid() }), body: { content: { "application/json": { schema: createAgentSetupProgressSchema } } } }, + responses: { + 201: r.ok(z.object({ progress: agentSetupProgressDoc, token: z.string(), urls: z.object({ checklist: z.string().url(), item: z.string(), finish: z.string().url() }).strict() }).strict()), + 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, + }, +}); + +registry.registerPath({ + method: "get", path: "/api/agent-setup-progress/{id}", tags: ["agent-setup-progress"], + summary: "Read a setup checklist", + description: "Board only, for the person who started the setup; anyone else gets 404. Updates also arrive as agent_setup_progress.updated live events.", + request: { params: agentSetupProgressId }, + responses: { 200: r.ok(agentSetupProgressDoc), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + +registry.registerPath({ + method: "put", path: "/api/agent-setup-progress/{id}/checklist", tags: ["agent-setup-progress"], + summary: "Set the agent's setup checklist", + description: "Called by the person's own agent with Authorization: Bearer ; no Paperclip sign-in. Replaces the checklist (1 to 20 items, keys of lowercase letters, numbers, - and _).", + request: { params: agentSetupProgressId, body: { content: { "application/json": { schema: setAgentSetupChecklistSchema } } } }, + responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors }, +}); + +registry.registerPath({ + method: "post", path: "/api/agent-setup-progress/{id}/items/{key}", tags: ["agent-setup-progress"], + summary: "Update one step of the agent's setup checklist", + description: "Called by the person's own agent with Authorization: Bearer . Sets the item's status (pending, in_progress, done or failed) and an optional one-line detail.", + request: { params: agentSetupProgressId.extend({ key: z.string() }), body: { content: { "application/json": { schema: updateAgentSetupItemSchema } } } }, + responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors }, +}); + +registry.registerPath({ + method: "post", path: "/api/agent-setup-progress/{id}/finish", tags: ["agent-setup-progress"], + summary: "Finish the agent's setup", + description: "Called by the person's own agent with Authorization: Bearer . done ticks off any open items; failed keeps them. An optional summary is shown on the setup page.", + request: { params: agentSetupProgressId, body: { content: { "application/json": { schema: finishAgentSetupSchema } } } }, + responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors }, +}); + registry.registerPath({ method: "get", path: "/api/companies/{companyId}/workload-identity", tags: ["workload-identity"], summary: "Company workload identity issuer and key states", diff --git a/server/src/services/agent-setup-progress.ts b/server/src/services/agent-setup-progress.ts new file mode 100644 index 00000000000..9874e204ebd --- /dev/null +++ b/server/src/services/agent-setup-progress.ts @@ -0,0 +1,220 @@ +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { and, eq, inArray, lt, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { agentSetupProgress, type AgentSetupProgressItemRecord } from "@paperclipai/db"; +import { + AGENT_SETUP_PROGRESS_LIMITS, + type AgentSetupProgress, + type AgentSetupProgressHandoff, + type AgentSetupProgressPurpose, + type AgentSetupProgressStatus, + type FinishAgentSetup, + type SetAgentSetupChecklist, + type UpdateAgentSetupItem, +} from "@paperclipai/shared"; +import { HttpError, conflict, notFound, unprocessable } from "../errors.js"; +import { logActivity } from "./activity-log.js"; +import { publishLiveEvent } from "./live-events.js"; + +/** + * Checklists that a person's own agent fills in while it sets something up for + * them (see `@paperclipai/shared` agent-setup-progress). The board creates one + * and gets a token for the agent; the agent's writes are checked against the + * token's hash and pushed to the page as a live event. + */ + +type Row = typeof agentSetupProgress.$inferSelect; + +const hashToken = (token: string) => createHash("sha256").update(token).digest("hex"); + +function toProgress(row: Row): AgentSetupProgress { + return { + id: row.id, + companyId: row.companyId, + purpose: row.purpose as AgentSetupProgressPurpose, + subjectId: row.subjectId, + status: row.status, + items: row.items, + summary: row.summary, + expiresAt: row.expiresAt.toISOString(), + createdAt: row.createdAt.toISOString(), + updatedAt: row.updatedAt.toISOString(), + }; +} + +/** The agent's URLs: the item URL keeps `{key}` for the agent to fill in. */ +export function agentSetupProgressUrls(origin: string, id: string): AgentSetupProgressHandoff["urls"] { + const base = `${origin.replace(/\/+$/, "")}/api/agent-setup-progress/${id}`; + return { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` }; +} + +/** + * Until the agent finishes, a checklist with steps is in progress, even with every step ticked off: + * only the finish carries the summary (such as the role ARN), and the page keeps refreshing until then. + */ +function statusFor(items: AgentSetupProgressItemRecord[]): AgentSetupProgressStatus { + return items.length === 0 ? "waiting" : "in_progress"; +} + +export function agentSetupProgressService(db: Db, options: { now?: () => Date } = {}) { + const now = options.now ?? (() => new Date()); + + function publish(row: Row) { + publishLiveEvent({ companyId: row.companyId, type: "agent_setup_progress.updated", payload: { progressId: row.id } }); + } + + /** The row the agent's token opens, still open for writes. Any mismatch reads as not found. */ + async function openForAgent(id: string, authorization: string | undefined): Promise { + const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1]; + const [row] = token ? await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, id)) : []; + const expected = row ? Buffer.from(row.tokenHash, "hex") : null; + const given = token ? Buffer.from(hashToken(token), "hex") : null; + if (!row || !expected || !given || expected.length !== given.length || !timingSafeEqual(expected, given)) { + throw new HttpError(401, "This setup progress link is not valid. Copy the setup prompt from Paperclip again.", { code: "agent_setup_progress_unauthorized" }); + } + if (row.expiresAt.getTime() <= now().getTime()) { + throw new HttpError(410, "This setup progress link expired. Copy the setup prompt from Paperclip again.", { code: "agent_setup_progress_expired" }); + } + if (row.status === "done" || row.status === "failed") { + // Finished is final: a late or retried update must not make the page show work in progress again. + throw conflict("This setup already finished.", { code: "agent_setup_progress_finished" }); + } + if (row.updateCount >= AGENT_SETUP_PROGRESS_LIMITS.maxUpdates) { + throw new HttpError(429, "This setup checklist has had too many updates.", { code: "agent_setup_progress_update_limit" }); + } + return row; + } + + /** Saves the agent's change; the update counter guards against two writes racing. */ + async function save( + row: Row, + change: { items: AgentSetupProgressItemRecord[]; status?: AgentSetupProgressStatus; summary?: string | null }, + activity: { action: string; details: Record }, + ) { + const [saved] = await db.update(agentSetupProgress).set({ + items: change.items, + status: change.status ?? statusFor(change.items), + ...(change.summary !== undefined ? { summary: change.summary } : {}), + updateCount: sql`${agentSetupProgress.updateCount} + 1`, + updatedAt: now(), + }).where(and(eq(agentSetupProgress.id, row.id), eq(agentSetupProgress.updateCount, row.updateCount))).returning(); + if (!saved) throw conflict("The checklist changed at the same time. Send the update again.", { code: "agent_setup_progress_conflict" }); + // Every change the agent makes is on the activity history; the token never is. + await logActivity(db, { + companyId: row.companyId, actorType: "system", actorId: "agent-setup", action: activity.action, + entityType: "agent_setup_progress", entityId: row.id, details: { purpose: row.purpose, ...activity.details }, + }); + publish(saved); + return toProgress(saved); + } + + return { + async create(input: { + companyId: string; + purpose: AgentSetupProgressPurpose; + subjectId?: string | null; + userId: string | null; + origin: string; + }): Promise { + // Expired checklists are only history: as a company makes a new one, drop its own that are a day + // past expiry, a few at a time. Another company's rows are never touched. + const stale = await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress) + .where(and( + eq(agentSetupProgress.companyId, input.companyId), + lt(agentSetupProgress.expiresAt, new Date(now().getTime() - 24 * 60 * 60 * 1000)), + )).limit(100); + if (stale.length > 0) { + await db.delete(agentSetupProgress).where(and( + eq(agentSetupProgress.companyId, input.companyId), + inArray(agentSetupProgress.id, stale.map((row) => row.id)), + )); + } + const token = `pcsp_${randomBytes(32).toString("base64url")}`; + const [row] = await db.insert(agentSetupProgress).values({ + companyId: input.companyId, + purpose: input.purpose, + subjectId: input.subjectId ?? null, + tokenHash: hashToken(token), + createdByUserId: input.userId, + expiresAt: new Date(now().getTime() + AGENT_SETUP_PROGRESS_LIMITS.lifetimeMs), + }).returning(); + await logActivity(db, { + companyId: input.companyId, + actorType: "user", + actorId: input.userId ?? "board", + action: "agent_setup_progress.created", + entityType: "agent_setup_progress", + entityId: row!.id, + details: { purpose: input.purpose, subjectId: input.subjectId ?? null }, + }); + return { progress: toProgress(row!), token, urls: agentSetupProgressUrls(input.origin, row!.id) }; + }, + + /** + * Removes checklists more than a day past expiry, across companies. Runs once at server start + * (reconstructing cleanup from the rows, never as a recurring scan), so companies that stopped + * using agent setup do not keep dead rows; creating a checklist also cleans its own company. + */ + async sweepExpired(options: { batchSize?: number; maxBatches?: number } = {}): Promise { + // Batches keep each delete small; the cap keeps a very large backlog from holding up startup + // (whatever is left goes at the next start, or as each company creates a checklist). + const batchSize = options.batchSize ?? 1000; + const maxBatches = options.maxBatches ?? 50; + const cutoff = new Date(now().getTime() - 24 * 60 * 60 * 1000); + let removed = 0; + for (let batch = 0; batch < maxBatches; batch += 1) { + const stale = await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress) + .where(lt(agentSetupProgress.expiresAt, cutoff)).limit(batchSize); + if (stale.length === 0) break; + await db.delete(agentSetupProgress).where(inArray(agentSetupProgress.id, stale.map((row) => row.id))); + removed += stale.length; + if (stale.length < batchSize) break; + } + return removed; + }, + + /** The checklist and who started it (for the read check; not part of the API response). */ + async get(id: string): Promise<(AgentSetupProgress & { createdByUserId: string | null }) | null> { + const [row] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, id)); + return row ? { ...toProgress(row), createdByUserId: row.createdByUserId } : null; + }, + + async setChecklist(id: string, authorization: string | undefined, input: SetAgentSetupChecklist) { + const row = await openForAgent(id, authorization); + const items = input.items.map((item) => ({ + key: item.key, title: item.title, status: item.status ?? "pending", detail: item.detail ?? null, + })); + return save(row, { items, summary: null }, { + action: row.items.length === 0 ? "agent_setup_progress.started" : "agent_setup_progress.checklist_replaced", + details: { itemCount: items.length }, + }); + }, + + async updateItem(id: string, key: string, authorization: string | undefined, input: UpdateAgentSetupItem) { + const row = await openForAgent(id, authorization); + if (!row.items.some((item) => item.key === key)) { + throw notFound(`The checklist has no item "${key}". Set the checklist first, then update its items by key.`); + } + const items = row.items.map((item) => item.key === key + // Omitted keeps the detail; null clears it. + ? { ...item, status: input.status, detail: input.detail === undefined ? item.detail : input.detail } + : item); + return save(row, { items }, { action: "agent_setup_progress.item_updated", details: { key, status: input.status } }); + }, + + async finish(id: string, authorization: string | undefined, input: FinishAgentSetup) { + const row = await openForAgent(id, authorization); + if (row.items.length === 0 && input.status === "done") { + throw unprocessable("Set the checklist before finishing.", { code: "agent_setup_progress_empty" }); + } + // The agent's finish is the verdict: done ticks off every step (it recovered from any that failed), + // so a finished setup never shows open or failed steps; failed keeps the steps as they were. + const items = input.status === "done" + ? row.items.map((item) => ({ ...item, status: "done" as const })) + : row.items; + return save(row, { items, status: input.status, summary: input.summary ?? null }, { + action: "agent_setup_progress.finished", details: { status: input.status }, + }); + }, + }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index b9ef0034f1c..a207f34e35b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -57,6 +57,7 @@ "packages/shared/src/agent-observability.ts": "52dc94e13624adeaf1aafa8996099a5dc158ef4b", "packages/shared/src/agent-runner.test.ts": "d02d0bba0cf57838011d4ec5f1304b65c15cff56", "packages/shared/src/agent-runner.ts": "8d60a246a8eb0d6304642a28926516066b459b4f", + "packages/shared/src/agent-setup-progress.ts": "44e3b42853c8c3c795d2b5701a371d95c69adf55", "packages/shared/src/agent-url-key.ts": "d0ec20b3ea1636a960bc5372a2c1e5a124bc5511", "packages/shared/src/aggregator-app-catalog.test.ts": "39ee377e55cc9565fce004b928bbe0998268e004", "packages/shared/src/aggregator-app-catalog.ts": "d6778b07a41356878c549d039ae316553ca9a22b", @@ -236,7 +237,7 @@ "packages/shared/src/connector-availability.ts": "82aec0dfb2e9b8cb04e21c4bcd9aab74b087c76a", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "8df4ffc512b32aead4ec375998125df6040466cc", + "packages/shared/src/constants.ts": "2cb07762a025c0d678cfd9aeeae6653fe9afb9d6", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", @@ -275,7 +276,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "773b1934c94beae32470695140b80171a4607e6b", + "packages/shared/src/index.ts": "583f640ffdcccf38972edd8e3e3b148111c7a00d", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", diff --git a/ui/src/api/agentSetupProgress.ts b/ui/src/api/agentSetupProgress.ts new file mode 100644 index 00000000000..b021a6166ea --- /dev/null +++ b/ui/src/api/agentSetupProgress.ts @@ -0,0 +1,9 @@ +import type { AgentSetupProgress, AgentSetupProgressHandoff, CreateAgentSetupProgress } from "@paperclipai/shared"; +import { api } from "./client"; + +/** Checklists a person's own agent fills in while it sets something up (see AgentSetupProgressPanel). */ +export const agentSetupProgressApi = { + create: (companyId: string, input: CreateAgentSetupProgress) => + api.post(`/companies/${companyId}/agent-setup-progress`, input), + get: (id: string) => api.get(`/agent-setup-progress/${id}`), +}; diff --git a/ui/src/api/companies-query.identity.test.tsx b/ui/src/api/companies-query.identity.test.tsx new file mode 100644 index 00000000000..9b3e810fc94 --- /dev/null +++ b/ui/src/api/companies-query.identity.test.tsx @@ -0,0 +1,43 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { describe, expect, it, vi } from "vitest"; +import { useAccountIdentity } from "./companies-query"; +import { queryKeys } from "../lib/queryKeys"; + +const mockAuthApi = vi.hoisted(() => ({ getSession: vi.fn() })); +vi.mock("./auth", () => ({ authApi: mockAuthApi })); +vi.mock("./companies", () => ({ companiesApi: {} })); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +describe("useAccountIdentity", () => { + // After an in-place sign-in the session is invalidated but still holds the previous user until + // the refetch lands. `settled` stays true then; `current` must not, so callers that read what this + // tab saved for an account never use the previous account's. + it("is not current while an invalidated session still names the previous account", async () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + mockAuthApi.getSession.mockResolvedValueOnce({ user: { id: "user-1" } }); + const seen: Array<{ userId: string | null; settled: boolean; current: boolean }> = []; + function Probe() { + const { userId, settled, current } = useAccountIdentity(); + seen.push({ userId, settled, current }); + return null; + } + const root = createRoot(document.createElement("div")); + await act(async () => { root.render(); }); + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ userId: "user-1", settled: true, current: true })); + + let landSecondSession!: (value: unknown) => void; + mockAuthApi.getSession.mockReturnValueOnce(new Promise((resolve) => { landSecondSession = resolve; })); + seen.length = 0; + await act(async () => { void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session }); }); + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ userId: "user-1", settled: true, current: false })); + expect(seen.some((entry) => entry.userId === "user-1" && entry.current)).toBe(false); + + await act(async () => { landSecondSession({ user: { id: "user-2" } }); }); + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ userId: "user-2", settled: true, current: true })); + await act(async () => root.unmount()); + }); +}); diff --git a/ui/src/api/companies-query.ts b/ui/src/api/companies-query.ts index a922da06c46..95210d22c78 100644 --- a/ui/src/api/companies-query.ts +++ b/ui/src/api/companies-query.ts @@ -1,4 +1,4 @@ -import { useQuery, type QueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"; import type { BoardBootstrap, Company } from "@paperclipai/shared"; import { authApi } from "./auth"; import { companiesApi } from "./companies"; @@ -80,14 +80,25 @@ export function useAccountSessionQuery() { export function useAccountIdentity(): { userId: string | null; settled: boolean; + /** + * Settled, and still this account's answer: false while an invalidated session + * (for example right after an in-place sign-in) still holds the previous user. + * Use it before reading anything this tab saved for the account, the same rule + * `resolveAccountUserId` applies. + */ + current: boolean; failed: boolean; bootstrap: BoardBootstrap | undefined; updatedAt: number; } { - const { data: session, isSuccess, isError, dataUpdatedAt } = useAccountSessionQuery(); + const queryClient = useQueryClient(); + const { data: session, isSuccess, isError, isFetching, dataUpdatedAt } = useAccountSessionQuery(); const userId = session?.user.id ?? null; + // Reading `isFetching` subscribes to it, so the invalidation's refetch re-renders and `current` is recomputed. + const invalidated = isFetching !== undefined && Boolean(queryClient.getQueryState(queryKeys.auth.session)?.isInvalidated); + const current = isSuccess && !invalidated && !hasUnverifiedSession(queryClient); return { - userId, settled: isSuccess, failed: isError, updatedAt: dataUpdatedAt, + userId, settled: isSuccess, current, failed: isError, updatedAt: dataUpdatedAt, bootstrap: isSuccess && session?.boardBootstrap?.userId === userId ? session.boardBootstrap : undefined, }; } diff --git a/ui/src/components/AgentSetupProgress.test.tsx b/ui/src/components/AgentSetupProgress.test.tsx new file mode 100644 index 00000000000..02ca7e10ab5 --- /dev/null +++ b/ui/src/components/AgentSetupProgress.test.tsx @@ -0,0 +1,309 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { AgentSetupProgress, AgentSetupProgressHandoff } from "@paperclipai/shared"; +import { + AgentSetupProgressPanel, + agentSetupProgressInstructions, + useAgentSetupProgress, + type AgentSetupProgressClient, +} from "./AgentSetupProgress"; +import { queryKeys } from "@/lib/queryKeys"; + +vi.mock("@/api/agentSetupProgress", () => ({ agentSetupProgressApi: {} })); +const account = vi.hoisted(() => ({ userId: "user-1" as string | null, settled: true, current: true, failed: false })); +vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: account.userId, settled: account.settled, current: account.settled && account.current, failed: account.failed }) })); + +const ID = "11111111-1111-4111-8111-111111111111"; +const BASE = `https://acme.paperclip.app/api/agent-setup-progress/${ID}`; +const WAITING: AgentSetupProgress = { + id: ID, companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", status: "waiting", items: [], summary: null, + expiresAt: new Date(Date.now() + 6 * 3600_000).toISOString(), createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z", +}; +const HANDOFF: AgentSetupProgressHandoff = { + progress: WAITING, token: "pcsp_token", urls: { checklist: `${BASE}/checklist`, item: `${BASE}/items/{key}`, finish: `${BASE}/finish` }, +}; + +describe("agent setup progress", () => { + let container: HTMLDivElement; + let root: Root; + let queryClient: QueryClient; + beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + window.sessionStorage.clear(); + account.userId = "user-1"; + account.settled = true; + account.current = true; + account.failed = false; + }); + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + }); + + it("tells the agent exactly how to set, update and finish its checklist", () => { + const text = agentSetupProgressInstructions(HANDOFF, [{ key: "check-account", title: "Check the AWS account" }]); + expect(text).toContain(`curl -sS -X PUT ${BASE}/checklist -H "Authorization: Bearer pcsp_token"`); + expect(text).toContain(`'{"items":[{"key":"check-account","title":"Check the AWS account"}]}'`); + expect(text).toContain(`${BASE}/items/check-account`); + expect(text).toContain(`${BASE}/finish`); + expect(text).toContain("If one fails, keep going with the setup."); + }); + + function Harness({ client }: { client: AgentSetupProgressClient }) { + const { progress, handoff } = useAgentSetupProgress({ companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", client }); + return handoff ? :

creating

; + } + + it("creates one checklist, waits for the agent, then shows each update live and the finish", async () => { + let current: AgentSetupProgress = WAITING; + const client: AgentSetupProgressClient = { create: vi.fn(async () => HANDOFF), get: vi.fn(async () => current) }; + await act(async () => { + root.render(); + }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + expect(client.create).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent is setting up AWS")); + await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent.")); + + current = { ...WAITING, status: "in_progress", updatedAt: new Date().toISOString(), items: [ + { key: "check-account", title: "Check the AWS account", status: "done", detail: "Account 123456789012" }, + { key: "deploy-stack", title: "Create the role", status: "in_progress", detail: null }, + { key: "report-role", title: "Report the role ARN", status: "pending", detail: null }, + ] }; + // What the live event does when the agent sends an update. + await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + const rows = [...container.querySelectorAll("li")].map((li) => [ + li.getAttribute("data-status"), [...li.querySelectorAll("p")].map((p) => p.textContent).join(" | "), li.lastElementChild?.textContent, + ].join(" · ")); + expect(rows).toEqual([ + "done · Check the AWS account | Account 123456789012 · Done", + "in_progress · Create the role · In progress", + "pending · Report the role ARN · Not started", + ]); + await vi.waitFor(() => expect(container.textContent).toContain("Last update")); + + current = { ...current, status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1", + items: current.items.map((item) => ({ ...item, status: "done" as const })) }; + await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent set up AWS")); + await vi.waitFor(() => expect(container.textContent).toContain("Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1")); + expect(client.create).toHaveBeenCalledOnce(); + }); + + it("keeps following the same checklist after leaving the step and coming back", async () => { + const client: AgentSetupProgressClient = { create: vi.fn(async () => HANDOFF), get: vi.fn(async () => WAITING) }; + const show = (visible: boolean) => root.render( + {visible ? :

other step

}
, + ); + await act(async () => { show(true); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + await act(async () => { show(false); }); + await act(async () => { show(true); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + // The copied prompt writes to the first checklist, so coming back must not make another. + expect(client.create).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent is setting up AWS")); + }); + + it("says when the prompt expired and starts again with a fresh checklist", async () => { + const expiredAt = new Date(Date.now() - 1000).toISOString(); + const stale: AgentSetupProgress = { ...WAITING, status: "in_progress", expiresAt: expiredAt, + items: [{ key: "check-account", title: "Check the AWS account", status: "in_progress", detail: null }] }; + const fresh: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_fresh", progress: { ...WAITING, id: "22222222-2222-4222-8222-222222222222" } }; + const create = vi.fn().mockResolvedValueOnce({ ...HANDOFF, progress: stale }).mockResolvedValueOnce(fresh); + const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === fresh.progress.id ? fresh.progress : stale) }; + function Renewing() { + const state = useAgentSetupProgress({ companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", client }); + return state.handoff ? ( + <> + {state.handoff.token} + + + ) : null; + } + await act(async () => { root.render(); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + await vi.waitFor(() => expect(container.textContent).toContain("This setup prompt expired")); + const startAgain = [...container.querySelectorAll("button")].find((b) => b.textContent === "Start again")!; + await act(async () => { startAgain.click(); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + expect(create).toHaveBeenCalledTimes(2); + expect(container.querySelector('[data-testid="token"]')?.textContent).toBe("pcsp_fresh"); + await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent.")); + }); + + it("keeps following the same checklist after the page reloads", async () => { + const client: AgentSetupProgressClient = { create: vi.fn(async () => HANDOFF), get: vi.fn(async () => WAITING) }; + await act(async () => { root.render(); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + await act(async () => root.unmount()); + // A reload starts with an empty query cache; this tab still has the handoff the copied prompt uses. + root = createRoot(container); + const reloaded = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await act(async () => { root.render(); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + expect(client.create).toHaveBeenCalledOnce(); + expect(client.get).toHaveBeenCalledWith(ID); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent is setting up AWS")); + }); + + function Full({ client }: { client: AgentSetupProgressClient }) { + const state = useAgentSetupProgress({ companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", client }); + return state.handoff ? ( + <> + {state.handoff.token} + + + ) : null; + } + const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + const token = () => container.querySelector('[data-testid="token"]')?.textContent; + + it("offers a fresh checklist after a failed attempt, and opening the step again later starts fresh", async () => { + const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission", + items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] }; + const second: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_second", progress: { ...WAITING, id: "33333333-3333-4333-8333-333333333333" } }; + const create = vi.fn().mockResolvedValueOnce(HANDOFF).mockResolvedValueOnce(second); + const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? failedAttempt : second.progress) }; + await act(async () => { root.render(); }); + await flush(); + await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await flush(); + // The failed attempt stays on screen while this page is open, with a way to try again. + await vi.waitFor(() => expect(container.textContent).toContain("Your agent couldn’t finish setting up AWS")); + expect(window.sessionStorage.length).toBe(0); + const startAgain = [...container.querySelectorAll("button")].find((b) => b.textContent === "Start again")!; + await act(async () => { startAgain.click(); }); + await flush(); + await vi.waitFor(() => expect(token()).toBe("pcsp_second")); + + // Opening the step again with a finished checklist in the cache (such as a reconnect) starts a fresh one. + const third: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_third", progress: { ...WAITING, id: "44444444-4444-4444-8444-444444444444" } }; + const reopenCreate = vi.fn().mockResolvedValueOnce(third); + const finishedCache = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + finishedCache.setQueryData(["agent-setup-progress-handoff", "user-1", "company-1", "aws_connection", "conn-1"], { handoff: HANDOFF, fromEarlierVisit: false }); + // Cached before this step opens, like a checklist from an earlier visit in this session. + await new Promise((resolve) => setTimeout(resolve, 2)); + const reopenClient: AgentSetupProgressClient = { create: reopenCreate, get: vi.fn(async (id: string) => id === ID ? { ...failedAttempt, status: "done" as const } : third.progress) }; + await act(async () => root.unmount()); + root = createRoot(container); + await act(async () => { root.render(); }); + await flush(); + await flush(); + expect(reopenCreate).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(token()).toBe("pcsp_third")); + }); + + it("keeps the last checklist when a refresh fails, says so, and retries", async () => { + const working: AgentSetupProgress = { ...WAITING, status: "in_progress", + items: [{ key: "deploy", title: "Create the role", status: "in_progress", detail: null }] }; + const get = vi.fn().mockResolvedValueOnce(working).mockRejectedValueOnce(new Error("offline")).mockResolvedValue(working); + const client: AgentSetupProgressClient = { create: vi.fn(async () => HANDOFF), get }; + await act(async () => { root.render(); }); + await flush(); + await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await flush(); + await vi.waitFor(() => expect(container.textContent).toContain("Create the role")); + await vi.waitFor(() => expect(container.textContent).toContain("Couldn’t refresh your agent’s progress")); + const retry = [...container.querySelectorAll("button")].find((b) => b.textContent === "Retry")!; + await act(async () => { retry.click(); }); + await flush(); + expect(container.textContent).not.toContain("Couldn’t refresh your agent’s progress"); + }); + + it("never hands one account's checklist to another account in the same tab", async () => { + const second: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_other_account", progress: { ...WAITING, id: "55555555-5555-4555-8555-555555555555" } }; + const create = vi.fn().mockResolvedValueOnce(HANDOFF).mockResolvedValueOnce(second); + const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? WAITING : second.progress) }; + await act(async () => { root.render(); }); + await flush(); + await vi.waitFor(() => expect(token()).toBe("pcsp_token")); + // Signed out in another tab (this tab's storage stays), then another account opens the same setup here. + await act(async () => root.unmount()); + account.userId = "user-2"; + root = createRoot(container); + const freshCache = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await act(async () => { root.render(); }); + await flush(); + expect(create).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(token()).toBe("pcsp_other_account")); + }); + + it("does not read the previous account's checklist while a sign-in's session refresh is in flight", async () => { + // The previous account left a checklist in this tab; the session still names it, but was just invalidated. + window.sessionStorage.setItem("paperclip:agent-setup-progress:user-1:company-1:aws_connection:conn-1", JSON.stringify(HANDOFF)); + const fresh: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_new_account", progress: { ...WAITING, id: "77777777-7777-4777-8777-777777777777" } }; + const create = vi.fn().mockResolvedValueOnce(fresh); + const client: AgentSetupProgressClient = { create, get: vi.fn(async () => fresh.progress) }; + account.current = false; + const tree = () => ; + await act(async () => { root.render(tree()); }); + await flush(); + expect(token()).not.toBe("pcsp_token"); + expect(client.get).not.toHaveBeenCalled(); + expect(create).not.toHaveBeenCalled(); + // The refresh lands with the new account: it gets its own checklist. + account.userId = "user-2"; + account.current = true; + await act(async () => { root.render(tree()); }); + await vi.waitFor(() => expect(token()).toBe("pcsp_new_account")); + expect(create).toHaveBeenCalledOnce(); + }); + + it("replaces a finished checklist from an earlier visit even when the session arrives late", async () => { + // A previous visit in this tab stored a checklist that has since finished. + window.sessionStorage.setItem("paperclip:agent-setup-progress:user-1:company-1:aws_connection:conn-1", JSON.stringify(HANDOFF)); + const fresh: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_fresh_visit", progress: { ...WAITING, id: "66666666-6666-4666-8666-666666666666" } }; + const create = vi.fn().mockResolvedValueOnce(fresh); + const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? { ...WAITING, status: "done" as const } : fresh.progress) }; + account.userId = null; + account.settled = false; + const tree = () => ; + await act(async () => { root.render(tree()); }); + await flush(); + expect(create).not.toHaveBeenCalled(); + account.userId = "user-1"; + account.settled = true; + await act(async () => { root.render(tree()); }); + await vi.waitFor(() => expect(token()).toBe("pcsp_fresh_visit")); + expect(create).toHaveBeenCalledOnce(); + }); + + it("keeps the agent's text out of session recordings", async () => { + const done: AgentSetupProgress = { ...WAITING, status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1", + items: [{ key: "check-account", title: "Check the AWS account", status: "done", detail: "Account 123456789012" }] }; + await act(async () => { root.render(); }); + const summary = [...container.querySelectorAll("p")].find((p) => p.textContent?.startsWith("Role ARN"))!; + expect(summary.closest(".ph-mask")).not.toBeNull(); + expect(container.querySelector("ol")?.classList.contains("ph-mask")).toBe(true); + }); + + it("says when the sign-in lookup failed instead of waiting forever, and retries it", async () => { + account.userId = null; + account.settled = false; + account.failed = true; + const client: AgentSetupProgressClient = { create: vi.fn(async () => HANDOFF), get: vi.fn(async () => WAITING) }; + const invalidate = vi.spyOn(queryClient, "invalidateQueries"); + let state: ReturnType | null = null; + function Probe() { + state = useAgentSetupProgress({ companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", client }); + return null; + } + await act(async () => { root.render(); }); + await flush(); + expect(client.create).not.toHaveBeenCalled(); + expect(state!.error).toBe("Paperclip couldn’t confirm who is signed in."); + await act(async () => { state!.renew(); }); + expect(invalidate).toHaveBeenCalledWith({ queryKey: ["auth", "session"] }); + }); +}); diff --git a/ui/src/components/AgentSetupProgress.tsx b/ui/src/components/AgentSetupProgress.tsx new file mode 100644 index 00000000000..d077052552d --- /dev/null +++ b/ui/src/components/AgentSetupProgress.tsx @@ -0,0 +1,278 @@ +import { useEffect, useId, useRef, useState } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { AGENT_SETUP_PROGRESS_LIMITS } from "@paperclipai/shared"; +import type { + AgentSetupProgress, + AgentSetupProgressHandoff, + AgentSetupProgressItemStatus, + CreateAgentSetupProgress, +} from "@paperclipai/shared"; +import { agentSetupProgressApi } from "@/api/agentSetupProgress"; +import { useAccountIdentity } from "@/api/companies-query"; +import { describeError } from "@/api/errors"; +import { Button } from "@/components/ui/button"; +import { StatusIcon } from "@/components/StatusIcon"; +import { timeAgo } from "@/lib/timeAgo"; +import { queryKeys } from "@/lib/queryKeys"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { agentSetupHandoffStorageKey, storeAgentSetupHandoff, storedAgentSetupHandoff } from "@/lib/agent-setup-handoff-storage"; + +/** + * Live setup progress from a person's own agent. A page that offers "Set it up + * with your agent" creates a checklist with `useAgentSetupProgress`, appends + * `agentSetupProgressInstructions` to its prompt, and shows + * `AgentSetupProgressPanel`. The agent sets the checklist and ticks it off + * with the URLs and token in the prompt; each update reaches the page live. + */ + +/** The calls the hook makes. Stories and tests pass in-memory fakes. */ +export interface AgentSetupProgressClient { + create(companyId: string, input: CreateAgentSetupProgress): Promise; + get(id: string): Promise; +} + +export const agentSetupProgressApiClient: AgentSetupProgressClient = agentSetupProgressApi; + +/** A suggested checklist step for the agent; it may add, rename or drop steps as it works. */ +export interface AgentSetupStep { + key: string; + title: string; +} + +/** While the agent is working, a slow check backs up the live updates in case the page missed one. */ +const SAFETY_REFETCH_MS = 20_000; + +/** + * Creates one checklist for this setup and follows it. The checklist is kept + * per company, purpose and subject, so leaving the step and coming back keeps + * following the checklist the copied prompt writes to. `renew` makes a fresh + * one, for an expired prompt or after a failed request. + */ +export function useAgentSetupProgress({ + companyId, + purpose, + subjectId, + enabled = true, + client = agentSetupProgressApiClient, + accountId: accountOverride, +}: CreateAgentSetupProgress & { + companyId: string | null | undefined; + enabled?: boolean; + client?: AgentSetupProgressClient; + /** The signed-in account; stories and tests pass it, the app reads the session. */ + accountId?: string; +}) { + const queryClient = useQueryClient(); + // The checklist belongs to the person setting up: keyed by account so another account never reuses it. + const account = useAccountIdentity(); + const accountId = accountOverride ?? account.userId ?? "anonymous"; + // Current, not merely settled: right after an in-place sign-in the cached session still names the + // previous account, and this tab may hold that account's checklist token. + const accountKnown = Boolean(accountOverride) || account.current; + const accountFailed = !accountOverride && account.failed; + const handoffKey = ["agent-setup-progress-handoff", accountId, companyId ?? null, purpose, subjectId ?? null] as const; + const storageKey = agentSetupHandoffStorageKey(accountId, companyId, purpose, subjectId); + const handoffQuery = useQuery({ + queryKey: handoffKey, + queryFn: async () => { + // A handoff found in this tab's storage came from an earlier visit; a created one is new. + const stored = storedAgentSetupHandoff(storageKey); + const handoff = stored ?? await client.create(companyId!, { purpose, ...(subjectId ? { subjectId } : {}) }); + storeAgentSetupHandoff(storageKey, handoff); + return { handoff, fromEarlierVisit: Boolean(stored) }; + }, + enabled: Boolean(companyId) && enabled && accountKnown, + // Created once per setup: never re-created on its own (renew does that). A failed create + // follows the app's retry defaults; at worst a retry leaves an unused checklist that expires. + staleTime: Infinity, + gcTime: AGENT_SETUP_PROGRESS_LIMITS.lifetimeMs, + refetchOnMount: false, + refetchOnWindowFocus: false, + refetchOnReconnect: false, + }); + const handoff = handoffQuery.data?.handoff ?? null; + + const progressId = handoff?.progress.id ?? null; + const query = useQuery({ + queryKey: queryKeys.agentSetupProgress(progressId), + queryFn: () => client.get(progressId!), + enabled: Boolean(progressId), + initialData: handoff?.progress, + refetchInterval: (current) => { + const data = current.state.data; + if (!data || data.status === "done" || data.status === "failed") return false; + return Date.parse(data.expiresAt) > Date.now() ? SAFETY_REFETCH_MS : false; + }, + }); + const progress = query.data ?? handoff?.progress ?? null; + const finished = progress?.status === "done" || progress?.status === "failed"; + const expired = Boolean(progress && !finished && Date.parse(progress.expiresAt) <= Date.now()); + const renew = () => { + // A failed sign-in lookup is retried first; the checklist follows once it answers. + if (accountFailed) { + void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session }); + return; + } + storeAgentSetupHandoff(storageKey, null); + void handoffQuery.refetch(); + }; + + // A finished checklist takes no more updates, so it is never handed to another attempt: a reload + // stops reusing it, and opening the step again later (such as a reconnect) starts a fresh one. + useEffect(() => { + if (finished) storeAgentSetupHandoff(storageKey, null); + }, [finished, storageKey]); + // Only a checklist from an earlier visit is replaced: one this page created that finishes while it is + // open stays on screen. "Earlier" means found in storage, or cached before this step opened. It is + // decided once per account-specific key, so a session that arrives late is judged on its own key. + const openedAt = useRef(Date.now()); + const checkedKey = useRef(null); + useEffect(() => { + if (!handoffQuery.data || !query.isFetched || checkedKey.current === storageKey) return; + checkedKey.current = storageKey; + const fromEarlier = handoffQuery.data.fromEarlierVisit || handoffQuery.dataUpdatedAt < openedAt.current; + if (fromEarlier && finished) renew(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [handoffQuery.data, handoffQuery.dataUpdatedAt, query.isFetched, storageKey, finished]); + + return { + handoff, + progress, + expired, + error: handoffQuery.error + ? describeError(handoffQuery.error).body + : accountFailed ? "Paperclip couldn’t confirm who is signed in." : null, + /** A refresh of the checklist failed; the last one stays on screen. */ + refreshError: query.error && progress ? describeError(query.error).body : null, + retryRefresh: () => { void query.refetch(); }, + renew, + }; +} + +/** + * The part of a setup prompt that tells the agent how to report progress. + * `steps` are suggestions; the agent sets its own checklist. + */ +export function agentSetupProgressInstructions(handoff: AgentSetupProgressHandoff, steps: AgentSetupStep[]): string { + const auth = `-H "Authorization: Bearer ${handoff.token}" -H "Content-Type: application/json"`; + const checklist = JSON.stringify({ items: steps.map((step) => ({ key: step.key, title: step.title })) }); + const firstKey = steps[0]?.key ?? "step-1"; + return [ + "Report your progress to Paperclip as you work, so I can follow along on the setup page. These requests only update this setup's checklist, and they stop working after a few hours. If one fails, keep going with the setup.", + "", + "1. Before you start, set your checklist (one item per step; keys use lowercase letters, numbers, - and _). Change the steps if your plan differs:", + ` curl -sS -X PUT ${handoff.urls.checklist} ${auth} -d '${checklist}'`, + "2. When you start and finish each step, update it. status is in_progress, done or failed; detail is one short, optional sentence:", + ` curl -sS -X POST ${handoff.urls.item.replace("{key}", firstKey)} ${auth} -d '{"status":"in_progress"}'`, + ` (Use each step's own key in place of ${firstKey}.)`, + "3. When everything is finished, say so, with a one-line summary (status done or failed):", + ` curl -sS -X POST ${handoff.urls.finish} ${auth} -d '{"status":"done","summary":"…"}'`, + ].join("\n"); +} + +const ITEM_GLYPH: Record = { + pending: "backlog", + in_progress: "in_progress", + done: "done", + failed: "blocked", +}; +const ITEM_LABEL: Record = { + pending: null, + in_progress: "In progress", + done: "Done", + failed: "Failed", +}; + +export interface AgentSetupProgressPanelProps { + progress: AgentSetupProgress | null; + /** The prompt's token stopped working before the agent finished. */ + expired?: boolean; + /** Makes a fresh checklist (and prompt), after it expired or a failed attempt. */ + onRenew?: () => void; + /** Why the latest refresh failed; the last checklist stays on screen. */ + refreshError?: string | null; + onRetryRefresh?: () => void; + /** What the agent is setting up, in a few words, such as "AWS". */ + subject: string; + className?: string; +} + +/** The live checklist. Before the agent reports anything, it says what to do and waits. */ +export function AgentSetupProgressPanel({ + progress, subject, expired = false, onRenew, refreshError = null, onRetryRefresh, className, +}: AgentSetupProgressPanelProps) { + const headingId = useId(); + const [, setTick] = useState(0); + // Keeps "Last update …" current while the panel is open. + useEffect(() => { + const timer = window.setInterval(() => setTick((value) => value + 1), 15_000); + return () => window.clearInterval(timer); + }, []); + + const items = progress?.items ?? []; + const status = progress?.status ?? "waiting"; + const heading = status === "done" + ? `Your agent set up ${subject}` + : status === "failed" + ? `Your agent couldn’t finish setting up ${subject}` + : `Your agent is setting up ${subject}`; + + return ( +
+
+

+ {expired ? "This setup prompt expired" : heading} +

+

+ {expired + ? "Its progress link stopped working before your agent finished. Start again for a new prompt, then give it to your agent." + : status === "waiting" + ? "Paste the prompt into your agent. Its steps appear here as it works." + : progress?.summary ?? (status === "done" ? "Every step is done." : "Keep your agent running; its steps update here.")} +

+
+ + {items.length > 0 ? ( + // Agent-written text (titles, details, the summary) can name accounts and roles: never in session recordings. +
    + {items.map((item) => ( +
  1. + +
    +

    {item.title}

    + {item.detail ?

    {item.detail}

    : null} +
    + {ITEM_LABEL[item.status] ? ( + {ITEM_LABEL[item.status]} + ) : Not started} +
  2. + ))} +
+ ) : null} + + {progress && status !== "waiting" ? ( +

Last update {timeAgo(progress.updatedAt)}

+ ) : null} + {refreshError ? ( +

+ Couldn’t refresh your agent’s progress: {refreshError} + {onRetryRefresh ? : null} +

+ ) : null} + {(expired || status === "failed") && onRenew ? ( +
+ {status === "failed" && !expired ? ( +

Fix what stopped it, then start again for a new prompt.

+ ) : null} + +
+ ) : null} +
+ ); +} diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 56465728f32..abfef4a92de 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -2199,6 +2199,13 @@ function handleLiveEvent( return; } + if (event.type === "agent_setup_progress.updated") { + // A person's own agent checked off a setup step; the open setup page shows it. + const progressId = readString(payload.progressId); + if (progressId) queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(progressId) }); + return; + } + if (event.type === "agent.runtime_state.updated") { // The server saved a new provider rate-limit snapshot for this agent. const agentId = readString(payload.agentId); diff --git a/ui/src/features/connections/AwsRoleSetup.test.tsx b/ui/src/features/connections/AwsRoleSetup.test.tsx index b36cb1f7c41..da18b886ae7 100644 --- a/ui/src/features/connections/AwsRoleSetup.test.tsx +++ b/ui/src/features/connections/AwsRoleSetup.test.tsx @@ -1,12 +1,15 @@ // @vitest-environment jsdom import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { AwsConnectionSetup } from "@paperclipai/shared"; +import type { AgentSetupProgress, AgentSetupProgressHandoff, AwsConnectionSetup } from "@paperclipai/shared"; +import type { AgentSetupProgressClient } from "@/components/AgentSetupProgress"; import { AwsRoleSetup, awsAgentSetupPrompt, awsCliCommands, awsSetupErrorMessage, type AwsRoleSetupClient } from "./AwsRoleSetup"; import { ApiError } from "@/api/client"; vi.mock("@/api/tools", () => ({ toolsApi: {} })); +vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: "user-1", settled: true, current: true }) })); const READY: AwsConnectionSetup = { available: true, @@ -35,6 +38,7 @@ describe("AwsRoleSetup", () => { let root: Root; beforeEach(() => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + window.sessionStorage.clear(); container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); @@ -49,7 +53,11 @@ describe("AwsRoleSetup", () => { const client: AwsRoleSetupClient = { setup: vi.fn(async () => setup) }; const onTest = vi.fn(); await act(async () => { - root.render(); + root.render( + + + , + ); }); await act(async () => { await Promise.resolve(); }); return { client, onTest }; @@ -152,8 +160,51 @@ describe("AwsRoleSetup", () => { expect(revokeObjectURL).toHaveBeenCalledWith("blob:template"); }); - it("points to the access-key method when AWS cannot reach this instance", async () => { - await render({ available: false, reason: "loopback" }); + it("adds live progress reporting to the prompt and shows the agent's checklist", async () => { + const progress: AgentSetupProgress = { + id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", + status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 6 * 3600_000).toISOString(), createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z", + }; + const base = `https://acme.paperclip.app/api/agent-setup-progress/${progress.id}`; + const handoff: AgentSetupProgressHandoff = { progress, token: "pcsp_test", urls: { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` } }; + // Live updates are covered in AgentSetupProgress.test.tsx; here the agent has not reported yet. + const progressClient: AgentSetupProgressClient = { create: vi.fn(async () => handoff), get: vi.fn(async () => progress) }; + await render(READY, { companyId: "company-1", progressClient }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + // Creating the checklist is asynchronous: wait for it rather than assume one tick is enough. + await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent. Its steps appear here as it works.")); + expect(progressClient.create).toHaveBeenCalledWith("company-1", { purpose: "aws_connection", subjectId: "conn-1" }); + const prompt = awsAgentSetupPrompt(READY as Ready, "PROGRESS"); + expect(prompt).toContain("Also put it in your finish summary"); + // Progress reporting comes first, so the agent sets its checklist before it starts. + expect(prompt.indexOf("PROGRESS")).toBeLessThan(prompt.indexOf("Steps:")); + }); + + it("says when live progress is unavailable, keeps the prompt, and tries again", async () => { + const create = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ + progress: { id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", + status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 3600_000).toISOString(), + createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z" }, + token: "pcsp_test", urls: { checklist: "https://x/checklist", item: "https://x/items/{key}", finish: "https://x/finish" }, + }); + const progressClient: AgentSetupProgressClient = { create, get: vi.fn(async () => { throw new Error("unused"); }) }; + await render(READY, { companyId: "company-1", progressClient }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + await vi.waitFor(() => expect(container.textContent).toContain("Live progress isn’t available")); + expect(container.querySelector('button[aria-label="Set it up with your agent"]')).not.toBeNull(); + await act(async () => { button("Try again")?.click(); }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + expect(create).toHaveBeenCalledTimes(2); + expect(container.textContent).not.toContain("Live progress isn’t available"); + await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent.")); + }); + + it("points to the access-key method when AWS cannot reach this instance, without starting a checklist", async () => { + const progressClient: AgentSetupProgressClient = { create: vi.fn(), get: vi.fn() }; + await render({ available: false, reason: "loopback" }, { companyId: "company-1", progressClient }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + // No prompt can carry a checklist here, so none is created. + expect(progressClient.create).not.toHaveBeenCalled(); expect(container.textContent).toContain("Use an access key instead"); expect(container.textContent).toContain("runs on this computer only"); expect(button("Test connection")?.disabled).toBe(true); diff --git a/ui/src/features/connections/AwsRoleSetup.tsx b/ui/src/features/connections/AwsRoleSetup.tsx index 1b8615f5f13..1a9c789af21 100644 --- a/ui/src/features/connections/AwsRoleSetup.tsx +++ b/ui/src/features/connections/AwsRoleSetup.tsx @@ -5,6 +5,13 @@ import { ApiError } from "@/api/client"; import { toolsApi } from "@/api/tools"; import { describeError } from "@/api/errors"; import { AgentSetupPrompt } from "@/components/AgentSetupPrompt"; +import { + AgentSetupProgressPanel, + agentSetupProgressInstructions, + useAgentSetupProgress, + type AgentSetupProgressClient, + type AgentSetupStep, +} from "@/components/AgentSetupProgress"; import { InlineBanner } from "@/components/InlineBanner"; import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; @@ -56,8 +63,21 @@ export interface AwsRoleSetupProps { onTest: (roleArn: string) => void; /** Shown above the footer, such as who gets access to the connection. */ beforeFooter?: React.ReactNode; + /** The company, for the agent's live progress checklist; without it the prompt has no progress reporting. */ + companyId?: string | null; + progressClient?: AgentSetupProgressClient; + /** The signed-in account for the checklist; stories and tests pass it, the app reads the session. */ + progressAccountId?: string; } +/** The steps the agent is asked to report; it may adjust them. */ +export const AWS_AGENT_SETUP_STEPS: AgentSetupStep[] = [ + { key: "check-account", title: "Check the AWS account" }, + { key: "check-provider", title: "Check the identity provider" }, + { key: "deploy-stack", title: "Create the role with CloudFormation" }, + { key: "report-role", title: "Report the role ARN" }, +]; + /** * The app definition's role ARN rule (a server test keeps it equal to the server's), so this * check matches what the server accepts. Without a definition the server alone decides. @@ -82,8 +102,20 @@ export function AwsRoleSetup({ onBack, onTest, beforeFooter, + companyId, + progressClient, + progressAccountId, }: AwsRoleSetupProps) { const [setup, setSetup] = useState(null); + const agentProgress = useAgentSetupProgress({ + companyId, purpose: "aws_connection", subjectId: connectionId, + // Only when the role method is available: otherwise there is no prompt to carry the checklist. + enabled: setup?.available === true, + ...(progressClient ? { client: progressClient } : {}), + ...(progressAccountId ? { accountId: progressAccountId } : {}), + }); + // The prompt waits for the checklist (or its failure), so a copied prompt always carries progress reporting when it can. + const promptReady = !companyId || Boolean(agentProgress.handoff) || Boolean(agentProgress.error); const [loadError, setLoadError] = useState(null); const [roleArn, setRoleArn] = useState(""); @@ -135,24 +167,43 @@ export function AwsRoleSetup({ {ready ? ( <> -
    -
  1. +
    +

    Give this prompt to an agent on a computer signed in to your AWS account.{" "} - {ready.savedRoleArn - ? "It updates the existing role with the AWS CLI and tells you the role ARN." - : "It creates the role with the AWS CLI and tells you the role ARN."} -

    - -
    -
  2. -
  3. - + {ready.savedRoleArn ? "It updates the existing role" : "It creates the role"} with the AWS CLI + {agentProgress.handoff ? ", shows its progress here," : ""} and tells you the role ARN to paste below. +

    + {agentProgress.error ? ( + + {agentProgress.error} The prompt still works; your agent just won’t show its steps here.{" "} + + + ) : null} + {promptReady ? ( + + ) : ( +

    + Preparing the prompt… +

    + )} + {agentProgress.handoff ? ( + + ) : null} +
    + Use the full role ARN, like arn:aws:iam::123456789012:role/{ready.roleName}.

    ) : null} -
  4. -
+ + @@ -282,10 +333,12 @@ export function awsCliCommands(setup: Extract): string { +export function awsAgentSetupPrompt(setup: Extract, progressInstructions: string | null = null): string { // One stack per connection, like the role, so two connections never share (and replace) a stack. const stack = setup.roleName; const policyStep = setup.accessLevel === "read_only" @@ -295,6 +348,7 @@ export function awsAgentSetupPrompt(setup: Extract --capabilities CAPABILITY_NAMED_IAM --parameter-overrides CreateIdentityProvider=${setup.accessLevel === "full" ? " AccessPolicyArn=" : ""}`, ` If it fails because the role ${setup.roleName} already exists outside this stack, do not delete it. Instead update its trust policy with \`aws iam update-assume-role-policy\` to the trust policy in the template (with this account's ID and the identity provider's ARN), make sure AWSMCPSignInOAuthAccessPolicy and the access policy are attached, and use that role's ARN in step 5.`, - `5. Give me the role's ARN (the stack's RoleArn output, or \`aws iam get-role --role-name ${setup.roleName} --query Role.Arn --output text\`), so I can paste it into Paperclip and press Test connection.`, + `5. Give me the role's ARN (the stack's RoleArn output, or \`aws iam get-role --role-name ${setup.roleName} --query Role.Arn --output text\`), so I can paste it into Paperclip and press Test connection.${progressInstructions ? " Also put it in your finish summary, as \"Role ARN: \"." : ""}`, "", "The role trusts only this one Paperclip connection, and no AWS keys are created or shared:", `- Identity provider: ${setup.issuer} (audience ${setup.audience})`, diff --git a/ui/src/features/connections/useAwsRoleSetupStep.tsx b/ui/src/features/connections/useAwsRoleSetupStep.tsx index f2cf146fea9..acb59dad57c 100644 --- a/ui/src/features/connections/useAwsRoleSetupStep.tsx +++ b/ui/src/features/connections/useAwsRoleSetupStep.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState, type ReactNode } from "react"; import type { ToolConnection } from "@paperclipai/shared"; +import { useCompany } from "@/context/CompanyContext"; import { AwsRoleSetup, awsSetupErrorMessage } from "./AwsRoleSetup"; /** @@ -17,6 +18,7 @@ export function useAwsRoleSetupStep({ appSlug, methodKey, reconnectConnectionId, /** The connection the flow was opened to resume, if any. */ resumeConnection: Pick | null; }) { + const { selectedCompanyId } = useCompany(); const [stage, setStage] = useState<{ connectionId: string; error: string | null } | null>(null); // The draft this setup saved (kept across Back, so Connect updates it) and whether the next connect is the test. const draft = useRef<{ id: string | null; testing: boolean; roleArn: string | null }>({ id: null, testing: false, roleArn: null }); @@ -89,6 +91,7 @@ export function useAwsRoleSetupStep({ appSlug, methodKey, reconnectConnectionId, return ( { cloudBaseUrl: "https://cloud.example.test", }, }); + window.sessionStorage.setItem("paperclip:agent-setup-progress:company-a:aws_connection:conn-1", "{}"); const root = renderHarness(onSignedOut); flushSync(() => captured?.mutate()); await vi.waitFor(() => expect(mockNavigateTopLevel).toHaveBeenCalledOnce()); expect(mockNavigateTopLevel).toHaveBeenCalledWith("/cloud/logout"); + expect(window.sessionStorage.getItem("paperclip:agent-setup-progress:company-a:aws_connection:conn-1")).toBeNull(); expect(onSignedOut).toHaveBeenCalledOnce(); expect(mockAuthApi.signOut).not.toHaveBeenCalled(); @@ -140,6 +142,9 @@ describe("useSignOut", () => { companyIds: ["company-a"], }); queryClient.setQueryData(queryKeys.issues.list("company-a"), [{ id: "issue-a" }]); + // An agent setup token from this account, plus something unrelated in the tab. + window.sessionStorage.setItem("paperclip:agent-setup-progress:company-a:aws_connection:conn-1", "{\"token\":\"pcsp_account_a\"}"); + window.sessionStorage.setItem("unrelated:key", "kept"); const onSignedOut = vi.fn(); const root = renderHarness(onSignedOut); @@ -163,6 +168,9 @@ describe("useSignOut", () => { expect(queryClient.getQueryData(queryKeys.companies.all)).toBeUndefined(); expect(queryClient.getQueryData(queryKeys.access.currentBoardAccess)).toBeUndefined(); expect(queryClient.getQueryData(queryKeys.issues.list("company-a"))).toBeUndefined(); + // The next account in this tab never inherits the previous account's agent setup token. + expect(window.sessionStorage.getItem("paperclip:agent-setup-progress:company-a:aws_connection:conn-1")).toBeNull(); + expect(window.sessionStorage.getItem("unrelated:key")).toBe("kept"); // Health describes the instance, not the account, and several observers // read it with `enabled: false`. It is refreshed in place. diff --git a/ui/src/hooks/useSignOut.ts b/ui/src/hooks/useSignOut.ts index 5435a5bfc2d..b169711e03f 100644 --- a/ui/src/hooks/useSignOut.ts +++ b/ui/src/hooks/useSignOut.ts @@ -4,6 +4,7 @@ import { navigateTopLevel } from "@/lib/browserNavigation"; import { queryKeys } from "@/lib/queryKeys"; import { invalidateAccountScope } from "@/lib/account-scope"; import { clearPersistedQueryCache } from "@/lib/persisted-query-cache"; +import { clearAgentSetupHandoffs } from "@/lib/agent-setup-handoff-storage"; import { resetProductAnalyticsIdentity } from "@/lib/analytics/product-analytics"; import { useCloudInstance } from "./useCloudInstance"; @@ -54,6 +55,7 @@ export function useSignOut({ onSignedOut }: UseSignOutOptions = {}) { resetProductAnalyticsIdentity(); if (cloud) { clearPersistedQueryCache(queryClient); + clearAgentSetupHandoffs(); invalidateAccountScope(queryClient); onSignedOut?.(); navigateTopLevel(CLOUD_SIGN_OUT_PATH); @@ -67,6 +69,8 @@ export function useSignOut({ onSignedOut }: UseSignOutOptions = {}) { if (target === "cloud") return; clearPersistedQueryCache(queryClient); + // A stored agent setup token is a write credential for one checklist: never leave it for the next account. + clearAgentSetupHandoffs(); invalidateAccountScope(queryClient); onSignedOut?.(); diff --git a/ui/src/lib/agent-setup-handoff-storage.ts b/ui/src/lib/agent-setup-handoff-storage.ts new file mode 100644 index 00000000000..8ec71f95156 --- /dev/null +++ b/ui/src/lib/agent-setup-handoff-storage.ts @@ -0,0 +1,52 @@ +import type { AgentSetupProgressHandoff } from "@paperclipai/shared"; + +/** + * The agent setup handoff (checklist id, token and URLs) for one setup, kept in + * this tab so a reload follows the checklist the copied prompt writes to. The + * token can do nothing but update that checklist until it expires. The key names + * the signed-in account, so another account in this tab (even after a sign-out + * in another tab) never finds it, and sign-out here clears every stored handoff. + */ +const PREFIX = "paperclip:agent-setup-progress:"; + +export function agentSetupHandoffStorageKey( + accountId: string, + companyId: string | null | undefined, + purpose: string, + subjectId: string | null | undefined, +) { + return `${PREFIX}${accountId}:${companyId ?? ""}:${purpose}:${subjectId ?? ""}`; +} + +export function storedAgentSetupHandoff(key: string): AgentSetupProgressHandoff | null { + try { + const value = window.sessionStorage.getItem(key); + const parsed = value ? JSON.parse(value) as AgentSetupProgressHandoff : null; + return parsed && Date.parse(parsed.progress.expiresAt) > Date.now() ? parsed : null; + } catch { + return null; + } +} + +export function storeAgentSetupHandoff(key: string, handoff: AgentSetupProgressHandoff | null) { + try { + if (handoff) window.sessionStorage.setItem(key, JSON.stringify(handoff)); + else window.sessionStorage.removeItem(key); + } catch { + // Storage can be unavailable (private windows); the checklist then lasts until the page reloads. + } +} + +/** Removes every stored handoff in this tab. Sign-out calls it. */ +export function clearAgentSetupHandoffs() { + try { + const keys: string[] = []; + for (let index = 0; index < window.sessionStorage.length; index += 1) { + const key = window.sessionStorage.key(index); + if (key?.startsWith(PREFIX)) keys.push(key); + } + for (const key of keys) window.sessionStorage.removeItem(key); + } catch { + // Nothing stored when storage is unavailable. + } +} diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index 66431d2be6e..31ef72c1a89 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -1,4 +1,5 @@ export const queryKeys = { + agentSetupProgress: (id: string | null) => ["agent-setup-progress", id] as const, linkPreview: (companyId: string, userId: string | null, url: string) => ["link-preview", companyId, userId, url] as const, workspacePreferences: { diff --git a/ui/storybook/stories/connection-setup/agent-setup-progress.stories.tsx b/ui/storybook/stories/connection-setup/agent-setup-progress.stories.tsx new file mode 100644 index 00000000000..5123a16eae9 --- /dev/null +++ b/ui/storybook/stories/connection-setup/agent-setup-progress.stories.tsx @@ -0,0 +1,47 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import type { AgentSetupProgress, AgentSetupProgressItem } from "@paperclipai/shared"; +import { AgentSetupProgressPanel } from "@/components/AgentSetupProgress"; + +const at = (status: AgentSetupProgress["status"], items: AgentSetupProgressItem[], summary: string | null = null): AgentSetupProgress => ({ + id: "7d1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", companyId: "company-storybook", purpose: "aws_connection", subjectId: null, + status, items, summary, expiresAt: new Date(Date.now() + 3600_000).toISOString(), + createdAt: new Date(Date.now() - 60_000).toISOString(), updatedAt: new Date(Date.now() - 5_000).toISOString(), +}); +const item = (key: string, title: string, status: AgentSetupProgressItem["status"], detail: string | null = null) => ({ key, title, status, detail }); + +const meta = { + id: "connection-setup-agent-setup-progress", + title: "Apps, channels, and extensions/Connection setup/Apps/Connections/Agent setup progress", + component: AgentSetupProgressPanel, + parameters: { layout: "padded", paperclip: { implementation: "production", boundary: "fixtures", + capabilities: ["connection-setup/credentials"], + notes: "Production live checklist a person's own agent fills in during Set it up with your agent, with synthetic progress. Reusable by any setup prompt." } }, + decorators: [(Story) =>
], + args: { subject: "AWS", progress: at("waiting", []) }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Waiting: Story = {}; +export const Working: Story = { + args: { progress: at("in_progress", [ + item("connect", "Connect agent", "done", "Signed in through the AWS CLI."), + item("analyze", "Check the AWS account", "done", "Account 123456789012."), + item("deploy", "Create the role", "in_progress", "Deploying the CloudFormation stack."), + item("report", "Report the role ARN", "pending"), + ]) }, +}; +export const Done: Story = { + args: { progress: at("done", [ + item("analyze", "Check the AWS account", "done"), + item("deploy", "Create the role", "done", "Stack created."), + item("report", "Report the role ARN", "done"), + ], "Role ARN: arn:aws:iam::123456789012:role/paperclip-7d1f2a3b") }, +}; +export const Failed: Story = { + args: { progress: at("failed", [ + item("analyze", "Check the AWS account", "done"), + item("deploy", "Create the role", "failed", "This identity cannot create IAM roles."), + ], "Stopped: sign in as an administrator and run the prompt again.") }, +}; diff --git a/ui/storybook/stories/connection-setup/aws-role-setup.stories.tsx b/ui/storybook/stories/connection-setup/aws-role-setup.stories.tsx index a574f1512b3..5cd5e4e7190 100644 --- a/ui/storybook/stories/connection-setup/aws-role-setup.stories.tsx +++ b/ui/storybook/stories/connection-setup/aws-role-setup.stories.tsx @@ -1,5 +1,6 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; -import type { AwsConnectionSetup } from "@paperclipai/shared"; +import type { AgentSetupProgress, AgentSetupProgressItem, AwsConnectionSetup } from "@paperclipai/shared"; +import type { AgentSetupProgressClient } from "@/components/AgentSetupProgress"; import { AwsRoleSetup, type AwsRoleSetupClient } from "@/features/connections/AwsRoleSetup"; type ReadySetup = Extract; @@ -41,6 +42,24 @@ const readOnly: ReadySetup = { const fixed = (setup: AwsConnectionSetup): AwsRoleSetupClient => ({ setup: async () => setup }); +const connectionId = readOnly.subject.replace("connection:", ""); +const progressId = "7d1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b"; +const recently = () => new Date(Date.now() - 20_000).toISOString(); +/** The agent's checklist at one moment; the setup step reads it as if the agent had just sent it. */ +function progressAt(status: AgentSetupProgress["status"], items: AgentSetupProgressItem[], summary: string | null = null): AgentSetupProgressClient { + const progress: AgentSetupProgress = { + id: progressId, companyId: "company-storybook", purpose: "aws_connection", subjectId: connectionId, status, items, summary, + expiresAt: new Date(Date.now() + 6 * 3600_000).toISOString(), createdAt: recently(), updatedAt: recently(), + }; + const base = `https://acme.paperclip.app/api/agent-setup-progress/${progressId}`; + return { + create: async () => ({ progress, token: "pcsp_storybook", urls: { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` } }), + get: async () => progress, + }; +} +const step = (key: string, title: string, status: AgentSetupProgressItem["status"], detail: string | null = null): AgentSetupProgressItem => ({ key, title, status, detail }); +const roleArn = `arn:aws:iam::123456789012:role/${readOnly.roleName}`; + const meta = { id: "connection-setup-aws-role", title: "Apps, channels, and extensions/Connection setup/Apps/Connections/AWS role", @@ -49,7 +68,7 @@ const meta = { capabilities: ["connection-setup/credentials", "connection-setup/failure"], notes: "Production AWS role setup step with a template generated by the server for a synthetic connection. No AWS call is made." } }, decorators: [(Story) =>
], - args: { connectionId: readOnly.subject.replace("connection:", ""), client: fixed(readOnly), onBack: () => {}, onTest: () => {} }, + args: { connectionId, client: fixed(readOnly), onBack: () => {}, onTest: () => {} }, } satisfies Meta; export default meta; @@ -61,3 +80,47 @@ export const TestFailed: Story = { args: { error: "AWS refused this connection's export const AddressChanged: Story = { args: { client: fixed({ available: false, reason: "address_changed" }) } }; export const RoleArnSaved: Story = { args: { client: fixed({ ...readOnly, savedRoleArn: "arn:aws:iam::123456789012:role/" + readOnly.roleName }) } }; export const NotReachable: Story = { args: { client: fixed({ available: false, reason: "loopback" }) } }; + +// Each live-progress story uses its own account, so the checklist one story saves in the session is never picked up by another. +/** With live progress: the agent has not reported yet. */ +export const AgentWaiting: Story = { args: { companyId: "company-storybook", progressAccountId: "storybook-waiting", progressClient: progressAt("waiting", []) } }; +/** The agent set its checklist and is part way through. */ +export const AgentWorking: Story = { + args: { + companyId: "company-storybook", + progressAccountId: "storybook-working", + progressClient: progressAt("in_progress", [ + step("check-account", "Check the AWS account", "done", "Signed in to account 123456789012 as an administrator."), + step("check-provider", "Check the identity provider", "done", "No provider for this Paperclip address yet, so the stack creates one."), + step("deploy-stack", "Create the role with CloudFormation", "in_progress", "Deploying the stack."), + step("report-role", "Report the role ARN", "pending"), + ]), + }, +}; +/** The agent finished and reported the role ARN in its summary. */ +export const AgentDone: Story = { + args: { + companyId: "company-storybook", + progressAccountId: "storybook-done", + progressClient: progressAt("done", [ + step("check-account", "Check the AWS account", "done", "Signed in to account 123456789012 as an administrator."), + step("check-provider", "Check the identity provider", "done", "No provider for this Paperclip address yet, so the stack creates one."), + step("deploy-stack", "Create the role with CloudFormation", "done", "Stack created."), + step("report-role", "Report the role ARN", "done"), + ], `Role ARN: ${roleArn}`), + }, +}; +/** The agent hit a problem it could not fix. */ +export const AgentFailed: Story = { + args: { + companyId: "company-storybook", + progressAccountId: "storybook-failed", + progressClient: progressAt("failed", [ + step("check-account", "Check the AWS account", "done", "Signed in to account 123456789012."), + step("check-provider", "Check the identity provider", "done"), + step("deploy-stack", "Create the role with CloudFormation", "failed", "The CLI's role is not allowed to create IAM roles (iam:CreateRole)."), + step("report-role", "Report the role ARN", "pending"), + ], "Stopped: this AWS identity cannot create IAM roles. Sign in as an administrator and run the prompt again."), + }, +}; +