mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
feat(ui): redesign Settings → Secrets around what people manage (#21225)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents need API keys and tokens. People manage them in Settings →
Secrets.
> - The page showed every credential in one table. Tokens that Paperclip
saved for connections, chat channels and model sign-ins sat beside the
few secrets a person added, many with record IDs as names.
> - Each row repeated an always-true status, a version and a key. New
secret opened on two stacked mode switches and two storage pickers.
> - A person could not see which agents use a secret without opening it,
and had to open it again after creation to give an agent access.
> - This pull request redesigns the page, the New secret dialog, the
details panel, the Vaults tab, the import dialog, the Proposals tab and
My secrets. It keeps the existing data and API calls.
> - The benefit is a list that shows what a person manages, a create
flow with two fields, and a secret that an agent can use as soon as it
is saved.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
The Settings → Secrets page, its New secret dialog, the secret details
panel, the Vaults tab, the import-from-vault dialog, the Proposals tab
and the My secrets tab.
**Subsystem affected**
UI: `ui/src/pages/Secrets.tsx` and `ui/src/pages/secrets/*`.
**Current behavior**
- One table lists all secrets. On a busy organization most rows are
credentials that Paperclip saved itself, and many have record IDs as
names.
- Each row shows Active, a version, a chip and the key. The row does not
show which agents use the secret.
- A three-line help banner is always visible.
- New secret starts with two mode switches (Organization / Each user,
Managed value / External reference), then a provider picker and a vault
picker. The Create button is disabled without a reason.
- The details panel has Details, Usage and Access events tabs.
- The Vaults tab has one section per provider, with empty placeholder
boxes and a status picker in the form.
**Proposed behavior**
- The list shows the secrets that the team added. Each row shows who
provides the value (Organization, or Each user with a count) and which
agents use it.
- Credentials that Paperclip saved collapse into "Managed by Paperclip".
They are grouped by origin and have readable names.
- One Filter menu covers provided-by, storage and status. Active filters
show as chips. Archived secrets stay hidden until a person asks for
them.
- New secret has a name, one explicit Organization / Each user choice, a
masked value, an optional list of agents, and "Stored in" only when more
than one storage place exists. Create stays enabled and says what is
missing. A `NAME=value` pasted into Name fills both fields.
- The details panel is one scrolling view: agents, other places the
secret is set, details, and recent activity.
- The Vaults tab is one flat list with health and secret counts. The
connect dialog has two required fields. Paperclip checks a new vault
immediately after it is saved.
**Reason and benefit**
A person can find their own secrets, see if a secret is used, and create
a secret that an agent can use in one step.
**Breaking changes**
None. The API gains one optional query parameter (`order` on the board
proposals list). The default order is unchanged. See Risks for the UI
behaviors that changed.
## What Changed
- **List.** Rewrote the Secrets tab in `Secrets.tsx`. Added
`secret-list-parts.tsx` for the Provided by and Used by cells, the help
popover and the managed groups. The Folders / Flat toggle is removed.
Folders are always on and search covers all folders.
- **Managed grouping.** Added `secret-origin.ts`. It infers the origin
of a secret from the name and key conventions of the server modules that
create secrets (`tool_app.*`, `tool_oauth.*`, `slack_manager.*`,
`chat.*`, `ai_*`, `routine-*`, `agent-observability.*`). It is used for
presentation only.
- **Agent usage.** Added `agent-secret-access.ts`. It holds the grant
and revoke logic that was inside the details panel, and builds one usage
index from the agents list for all rows.
- **New secret.** Rewrote the dialog. Added `buildCreateVaultOptions`
and `parseEnvAssignment`. Agents selected in the dialog get an
environment variable binding after the secret is saved. A failed grant
shows an error and keeps the secret.
- **Details.** Replaced the tabs with sections. "Also set in" lists the
bindings that are not agents. Activity shows agent names and the last
five entries, with "Show all activity".
- **Vaults.** Flat list with a built-in Paperclip row, a Default badge
that follows `getSelectableProviderConfig`, Check again, Enable, and an
Add vault menu. The dialog has Name and AWS region, with naming and tags
in a disclosure. The Status picker is removed.
- **Import, Proposals, My secrets.** Restyled to the same design.
Proposals adds a Recently decided list. The board list endpoint `GET
/api/companies/{companyId}/secret-proposals` takes a new optional
`order=resolved` to sort by decision time.
- **Copy.** "Provider vault" is "vault". "Local encrypted" is
"Paperclip" or "Paperclip-encrypted". Toasts and block reasons use plain
words.
- **Stories.** `secrets.stories.tsx` has new stories for the managed
section, a folder, New secret, the details panel and Vaults. The
Storybook usage fixture now returns the `target` field that the API
returns.
- **Tests.** Updated the page, import, proposals and My secrets tests.
Added `secret-origin.test.ts`. Updated the runner E2E vault-reference
journey and the Storybook visual render-state copy for the new labels.
- **Docs.** `Secrets → Provider vaults` is now `Secrets → Vaults` in
three documents.
`Secrets.tsx` was 4,855 lines and is 4,951 lines. The redesign edits the
page in place to keep its queries, mutations and deep links. Splitting
the file is a separate change.
## Verification
- `cd ui && node ../scripts/run-tsc.mjs -b`: no errors.
- `cd ui && pnpm vitest run src/pages/secrets src/pages/Secrets.test.ts
src/pages/Secrets.render.test.tsx
src/components/AgentSecretAccessEditor.test.tsx
src/components/AgentConfigForm src/components/IssueThreadInteractionCard
storybook/map-tooling.test.ts`: 14 files, 467 tests passed.
- `cd server && pnpm vitest run
src/__tests__/secret-proposals-routes.test.ts -t "decision time"`:
passed.
- `pnpm vitest run --config tests/runner-e2e/vitest.config.ts
chat-catalog-domains/external-vault-reference
chat-catalog-domains/external-personal-secret-menu
chat-catalog-domains/external-personal-secret-entry-dialog
chat-catalog-domains/external-personal-secret.test`: 32 passed, 2
skipped.
- `node scripts/check-token-gates.mjs`, `node scripts/check-maps.mjs`,
`node scripts/check-module-boundaries.mjs`, `node
scripts/storybook-catalog.mjs`: clean.
- `pnpm verify`: exit 2. It asks for broader coverage because a runner
E2E source file changed. Required CI supplies that coverage.
- All 22 Secrets stories render and their play functions pass in
headless Chromium against a local Storybook.
- End to end, on an isolated local instance (`paperclipai worktree init
--empty`, one company, two agents), with a headless Chromium script. 16
of 16 steps passed, with no page errors:
- Empty state. Create explains missing fields.
- Create an organization secret and give an agent access. The agent's
saved config has the `secret_ref` binding.
- Paste `NAME=value`. Create an each-user secret. Add a value in My
secrets. The list shows "1 of 1 added".
- Create a folder, create a secret in it, search across folders.
- In details: add an agent, replace the value, remove the agent. The
agent's saved config changes each time.
- Disable, archive, and the Archived filter.
- Managed secrets leave the team list and show under their groups.
- Add a Paperclip-encrypted vault and an AWS vault. New secret then
shows "Stored in".
- The import dialog explains a denied vault. The Proposals tab shows its
empty state. The list at 390 px width.
- Not run: the paid runner E2E journeys. I updated
`external-vault-reference.ts` for the new labels and could not execute
it. A live AWS import, and a proposal from a real agent run, were not
exercised.
## Risks
- **Origin grouping is a heuristic.** It reads naming conventions that
live in server modules. If a module changes its naming, its secrets show
in the team list again. Nothing is hidden or blocked by it. A recorded
origin on each secret is the durable fix.
- **Removed UI.** The Folders / Flat toggle, the "View references"
dialog, the vault Status picker, and creating draft GCP or HashiCorp
vault entries from the Add vault menu. Existing draft vaults still show
and can be edited. A disabled vault now has an Enable action.
- **Default status filter.** The list now shows active and disabled
secrets. Before, it showed active secrets only.
- **Built-in storage in "Stored in".** A provider's built-in storage is
not offered once that provider has a usable vault. The form already
replaced that choice with the vault before this change.
- **Agent access at creation.** Access is a second request for each
agent after the secret is saved. If one fails, the secret exists without
that access and an error says so.
- **Automation contracts.** Labels that agents and the runner E2E
journeys depend on are kept: the key in each My secrets row, "Set
value", "Set my value", "Update my value", "Save value", and the import
dialog test IDs. The import entry point moved into the "More secret
actions" menu and the journey is updated for it.
- **Value masking** uses `-webkit-text-security`. A browser without it
shows the value as typed.
## Model Used
- Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with tool
use, code execution and browser automation. Three delegated agents on
the same model restyled the import dialog, the Proposals tab and My
secrets.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
2de5d97958
commit
826d41e646
30 files changed
+6193
-3856
No files matched your search
+1
-1
@@ -895,7 +895,7 @@ bootstrap credentials in Paperclip secrets.
|
||||
|
||||
Per-company provider vaults (multiple vault instances per provider, default
|
||||
vault selection, coming-soon GCP/Vault) can be configured from the board UI under
|
||||
`Organization Settings → Secrets → Provider vaults` or through the provider-config CLI
|
||||
`Organization Settings → Secrets → Vaults` or through the provider-config CLI
|
||||
commands above. See the
|
||||
[secrets deploy guide](../docs/deploy/secrets.md#provider-vaults) and
|
||||
[API reference](../docs/api/secrets.md#provider-vaults) for the contract.
|
||||
|
||||
+1
-1
@@ -4271,7 +4271,7 @@ CLI configuration support:
|
||||
- Provider health is available at `GET /api/companies/:companyId/secret-providers/health` and reports local key permission warnings plus backup guidance.
|
||||
|
||||
Per-company provider vaults are configured in the board UI under
|
||||
`Company Settings → Secrets → Provider vaults`, backed by
|
||||
`Company Settings → Secrets → Vaults`, backed by
|
||||
`/api/companies/{companyId}/secret-provider-configs`. The CLI does not own
|
||||
vault lifecycle today. See `docs/deploy/secrets.md` (`Provider Vaults` section)
|
||||
for the operator model.
|
||||
|
||||
@@ -13,7 +13,7 @@ Operational contract for the hosted `aws_secrets_manager` secret provider used b
|
||||
copy plaintext into Paperclip.
|
||||
- Per-company AWS provider vaults (named instances of `aws_secrets_manager`
|
||||
with their own region, namespace, prefix, KMS key id, and tags) are managed
|
||||
in the board UI under `Company Settings → Secrets → Provider vaults`. See
|
||||
in the board UI under `Company Settings → Secrets → Vaults`. See
|
||||
[Provider Vaults](../docs/deploy/secrets.md#provider-vaults) for the operator
|
||||
model and [Provider Vaults API](../docs/api/secrets.md#provider-vaults) for
|
||||
the routes. The bootstrap trust model in this document still applies — vault
|
||||
|
||||
@@ -1301,6 +1301,58 @@ describeEmbeddedPostgres("secret proposal routes", () => {
|
||||
expect(lastBoardPage.headers["x-next-offset"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("lists decided proposals by decision time when asked, and rejects an unknown order", async () => {
|
||||
const fixture = await seedRun();
|
||||
const liveSecret = await secretService(db).create(fixture.companyId, {
|
||||
name: "dev/order/source",
|
||||
key: "ORDER_SOURCE",
|
||||
provider: "local_encrypted",
|
||||
value: "order-source-secret",
|
||||
});
|
||||
await secretService(db).createBinding({
|
||||
companyId: fixture.companyId,
|
||||
secretId: liveSecret.id,
|
||||
targetType: "agent",
|
||||
targetId: fixture.agentId,
|
||||
configPath: "access.order_source",
|
||||
});
|
||||
const agentApp = createAgentApp(fixture);
|
||||
const created: string[] = [];
|
||||
for (const index of [0, 1, 2]) {
|
||||
const response = await request(agentApp)
|
||||
.post("/api/agents/me/secret-proposals")
|
||||
.send({
|
||||
kind: "binding",
|
||||
sourceConfigPath: "access.order_source",
|
||||
configPath: `env.ORDER_${index}`,
|
||||
justification: "Exercise decision-time ordering",
|
||||
});
|
||||
expect(response.status).toBe(201);
|
||||
created.push(response.body.id);
|
||||
}
|
||||
// Decide them in the opposite order to their creation: the oldest request is decided last.
|
||||
const decidedAt = [3, 2, 1].map((minutes) => new Date(Date.UTC(2026, 0, 1, 12, minutes)));
|
||||
for (const [index, id] of created.entries()) {
|
||||
await db.update(companySecretProposals)
|
||||
.set({ status: "rejected", resolvedAt: decidedAt[index], createdAt: new Date(Date.UTC(2026, 0, 1, 10, index)) })
|
||||
.where(eq(companySecretProposals.id, id));
|
||||
}
|
||||
const boardApp = createBoardApp(fixture);
|
||||
const base = `/api/companies/${fixture.companyId}/secret-proposals?status=rejected`;
|
||||
|
||||
const byDecision = await request(boardApp).get(`${base}&order=resolved`);
|
||||
expect(byDecision.status).toBe(200);
|
||||
expect(byDecision.body.map((row: { id: string }) => row.id)).toEqual(created);
|
||||
|
||||
const byCreation = await request(boardApp).get(base);
|
||||
expect(byCreation.body.map((row: { id: string }) => row.id)).toEqual([...created].reverse());
|
||||
|
||||
const topDecision = await request(boardApp).get(`${base}&order=resolved&limit=1`);
|
||||
expect(topDecision.body.map((row: { id: string }) => row.id)).toEqual([created[0]]);
|
||||
|
||||
expect((await request(boardApp).get(`${base}&order=newest`)).status).toBe(422);
|
||||
});
|
||||
|
||||
it("bounds each expiry sweep batch", async () => {
|
||||
const fixture = await seedRun();
|
||||
const liveSecret = await secretService(db).create(fixture.companyId, {
|
||||
|
||||
@@ -5697,6 +5697,10 @@ registry.registerPath({
|
||||
status: z
|
||||
.enum(["pending", "approved", "rejected", "withdrawn", "expired"])
|
||||
.optional(),
|
||||
order: z
|
||||
.enum(["created", "resolved"])
|
||||
.optional()
|
||||
.describe("created (default) lists the newest proposals first; resolved lists the most recent decisions first."),
|
||||
}),
|
||||
},
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
|
||||
@@ -243,9 +243,13 @@ export function secretRoutes(db: Db, deps: SecretRoutesDeps = {}) {
|
||||
assertCompanyAccess(req, companyId);
|
||||
const status = typeof req.query.status === "string" ? req.query.status : null;
|
||||
const page = proposalListPage(req.query);
|
||||
if (req.query.order !== undefined && req.query.order !== "created" && req.query.order !== "resolved") {
|
||||
throw unprocessable("order must be created or resolved");
|
||||
}
|
||||
const rows = await proposals.listForBoard(companyId, status, {
|
||||
limit: page.limit + 1,
|
||||
offset: page.offset,
|
||||
order: req.query.order === "resolved" ? "resolved" : "created",
|
||||
});
|
||||
const hasMore = rows.length > page.limit;
|
||||
setProposalPaginationHeaders(res, page, hasMore);
|
||||
|
||||
@@ -549,12 +549,17 @@ export function createSecretProposalsService(db: Db) {
|
||||
async function listForBoard(
|
||||
companyId: string,
|
||||
status?: string | null,
|
||||
options: { limit?: number; offset?: number } = {},
|
||||
options: { limit?: number; offset?: number; order?: "created" | "resolved" } = {},
|
||||
) {
|
||||
const rows = await db.select().from(companySecretProposals).where(and(
|
||||
eq(companySecretProposals.companyId, companyId),
|
||||
status ? eq(companySecretProposals.status, status) : undefined,
|
||||
)).orderBy(desc(companySecretProposals.createdAt))
|
||||
)).orderBy(
|
||||
// "resolved" puts the most recent decisions first; undecided rows follow by age.
|
||||
...(options.order === "resolved"
|
||||
? [sql`${companySecretProposals.resolvedAt} desc nulls last`, desc(companySecretProposals.createdAt)]
|
||||
: [desc(companySecretProposals.createdAt)]),
|
||||
)
|
||||
.limit(options.limit ?? DEFAULT_PROPOSAL_LIST_LIMIT)
|
||||
.offset(options.offset ?? 0);
|
||||
return Promise.all(rows.map(enrich));
|
||||
|
||||
@@ -536,6 +536,9 @@ export const vaultReferenceExternalCases = [
|
||||
.locator(`[id^="comment-"] a[href=${JSON.stringify(href)}]`)
|
||||
.first()
|
||||
.click();
|
||||
await ctx.input.page
|
||||
.getByRole("button", { name: "More secret actions", exact: true })
|
||||
.click();
|
||||
await ctx.input.page.getByTestId("import-from-vault-button").click();
|
||||
const dialog = ctx.input.page.getByTestId("import-from-vault-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
@@ -553,7 +556,7 @@ export const vaultReferenceExternalCases = [
|
||||
response.request().postDataJSON()?.query === query,
|
||||
);
|
||||
await dialog
|
||||
.getByLabel("Search remote secrets", { exact: true })
|
||||
.getByLabel("Search the vault", { exact: true })
|
||||
.fill(query);
|
||||
const response = await previewResponse;
|
||||
state.operatorChannel = "public-vault-import-ui";
|
||||
@@ -589,14 +592,15 @@ export const vaultReferenceExternalCases = [
|
||||
"Setup blocker: designated AWS vault reference is not an eligible import candidate under the selected runtime; no other reference may substitute",
|
||||
);
|
||||
await dialog
|
||||
.getByLabel(`Select ${candidate.remoteName}`, { exact: true })
|
||||
.getByLabel(candidate.remoteName, { exact: true })
|
||||
.check();
|
||||
await dialog
|
||||
.getByRole("button", { name: "Continue → Review", exact: true })
|
||||
.getByRole("button", { name: "Continue with 1", exact: true })
|
||||
.click();
|
||||
await dialog
|
||||
.getByTestId(`review-name-${f.arn}`)
|
||||
.fill("Deployment API key");
|
||||
await dialog.getByTestId("review-details-toggle").click();
|
||||
await dialog
|
||||
.getByTestId(`review-key-${f.arn}`)
|
||||
.fill("deployment-api-key");
|
||||
@@ -607,7 +611,7 @@ export const vaultReferenceExternalCases = [
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await dialog
|
||||
.getByRole("button", { name: "Import 1", exact: true })
|
||||
.getByRole("button", { name: "Import 1 secret", exact: true })
|
||||
.click();
|
||||
const saved = await importedResponse;
|
||||
if (!saved.ok()) {
|
||||
@@ -622,7 +626,8 @@ export const vaultReferenceExternalCases = [
|
||||
f.vault.id,
|
||||
);
|
||||
await dialog
|
||||
.getByRole("button", { name: "Cancel", exact: true })
|
||||
.getByRole("button", { name: "Close", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await returnToSource(ctx, state, sourceURL);
|
||||
return;
|
||||
@@ -684,16 +689,20 @@ export const vaultReferenceExternalCases = [
|
||||
.click();
|
||||
await expect(
|
||||
ctx.input.page.getByRole("heading", {
|
||||
name: "Agent access",
|
||||
name: "Agents that can use it",
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
await ctx.input.page
|
||||
.getByTestId("secret-details")
|
||||
.getByRole("button", { name: "Add agent", exact: true })
|
||||
.click();
|
||||
await ctx.input.page.locator("#agent-access-agent").click();
|
||||
await ctx.input.page
|
||||
.getByRole("button", { name: "Select Morgan", exact: true })
|
||||
.click();
|
||||
await ctx.input.page
|
||||
.getByLabel("Env var", { exact: true })
|
||||
.getByLabel("Environment variable", { exact: true })
|
||||
.fill("DEPLOYMENT_API_KEY");
|
||||
const grant = ctx.input.page.waitForResponse(
|
||||
(response) =>
|
||||
@@ -702,14 +711,7 @@ export const vaultReferenceExternalCases = [
|
||||
response.ok(),
|
||||
);
|
||||
await ctx.input.page
|
||||
.locator("section")
|
||||
.filter({
|
||||
has: ctx.input.page.getByRole("heading", {
|
||||
name: "Agent access",
|
||||
exact: true,
|
||||
}),
|
||||
})
|
||||
.getByRole("button", { name: "Add", exact: true })
|
||||
.getByRole("button", { name: "Give access", exact: true })
|
||||
.click();
|
||||
await grant;
|
||||
state.agentAccessUiCompleted = true;
|
||||
|
||||
@@ -198,9 +198,9 @@ const states: Record<string, Record<string, State>> = {
|
||||
},
|
||||
"feature-secret-proposal-review": {
|
||||
pending: { text: "dev/github/token" },
|
||||
loading: { text: "Loading proposals…" },
|
||||
empty: { text: "No pending proposals" },
|
||||
failed: { text: "Couldn’t load proposals. Try again." },
|
||||
loading: { text: "Loading requests…" },
|
||||
empty: { text: "Nothing to review" },
|
||||
failed: { text: "Couldn’t load requests. Try again." },
|
||||
},
|
||||
"feature-skill-test-runs": {
|
||||
"completed-test": { text: "succeeded" },
|
||||
|
||||
@@ -238,9 +238,15 @@ export const secretsApi = {
|
||||
// --- Secret & binding proposals (PAP-14731) -----------------------------
|
||||
// Board-facing review surface. Agents propose credentials/bindings; humans
|
||||
// approve or reject them here. Values are never returned by these routes.
|
||||
listProposals: (companyId: string, status: SecretProposalStatus = "pending") =>
|
||||
listProposals: (
|
||||
companyId: string,
|
||||
status: SecretProposalStatus = "pending",
|
||||
options: { order?: "created" | "resolved"; limit?: number } = {},
|
||||
) =>
|
||||
api.get<SecretProposalView[]>(
|
||||
`/companies/${companyId}/secret-proposals?status=${encodeURIComponent(status)}`,
|
||||
`/companies/${companyId}/secret-proposals?status=${encodeURIComponent(status)}${
|
||||
options.order ? `&order=${options.order}` : ""
|
||||
}${options.limit ? `&limit=${options.limit}` : ""}`,
|
||||
),
|
||||
approveProposal: (companyId: string, proposalId: string, data: ApproveSecretProposalInput = {}) =>
|
||||
api.post<SecretProposalView>(
|
||||
|
||||
+6
-1
@@ -3285,7 +3285,7 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
|
||||
--gtc-40: minmax(0,1fr) 320px; /* Extracted from ui/src/pages/IssueChatLongThreadPerf.tsx (grid-cols-[minmax(0,1fr)_320px]). */
|
||||
--gtc-52: minmax(0,1.4fr) minmax(220px,0.8fr); /* Extracted from ui/src/pages/PluginSettings.tsx (grid-cols-[minmax(0,1.4fr)_minmax(220px,0.8fr)]). */
|
||||
--gtc-53: minmax(0,1.4fr) minmax(18rem,0.9fr); /* Extracted from ui/src/pages/ProjectWorkspaceDetail.tsx (grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.9fr)]). */
|
||||
--gtc-54: minmax(12rem,2.4fr) minmax(5.25rem,0.75fr) minmax(7rem,1fr) minmax(5rem,0.7fr) 2.75rem; /* Extracted from ui/src/pages/Secrets.tsx (grid-cols-[minmax(12rem,2.4fr)_minmax(5.25rem,0.75fr)_minmax(7rem,1fr)_minmax(5rem,0.7fr)_2.75rem]). */
|
||||
--gtc-54: minmax(12rem,2.2fr) minmax(9rem,1.1fr) minmax(7rem,1fr) minmax(4.5rem,0.6fr) 2.75rem; /* Secrets list: name, provided by, used by, updated, actions (ui/src/pages/Secrets.tsx). */
|
||||
--gtc-55: 8rem minmax(0,1fr); /* Extracted from ui/src/pages/Secrets.tsx (grid-cols-[8rem_minmax(0,1fr)]). */
|
||||
--gtc-56: minmax(0,1fr) minmax(14rem,18rem); /* Extracted from ui/src/pages/TeamCatalog.tsx (grid-cols-[minmax(0,1fr)_minmax(14rem,18rem)]). */
|
||||
--gtc-57: repeat(14,minmax(0,1fr)); /* Extracted from ui/src/pages/UserProfile.tsx (grid-cols-[repeat(14,minmax(0,1fr))]). */
|
||||
@@ -5748,3 +5748,8 @@ html:has(.design-proposal-theme) .agent-markdown-name-field [data-slot="input"],
|
||||
.agents-org-toolbar .design-toolbar-actions { width: 100%; justify-content: flex-end; gap: var(--spacing); }
|
||||
.agents-org-toolbar .org-chart-controls { gap: var(--spacing); }
|
||||
}
|
||||
|
||||
/* Secret values stay hidden while typed; a multi-line field cannot use type="password". */
|
||||
.secret-value-masked {
|
||||
-webkit-text-security: disc;
|
||||
}
|
||||
+1331
-779
File diff suppressed because it is too large.
Load diff
@@ -3,11 +3,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CompanySecretProviderConfig, SecretProviderDescriptor } from "@paperclipai/shared";
|
||||
import {
|
||||
buildCreateVaultOptions,
|
||||
findCreateProviderReplacement,
|
||||
getAwsManagedPathPreview,
|
||||
getCreateProviderBlockReason,
|
||||
getDefaultProviderConfigId,
|
||||
getProviderConfigBlockReason,
|
||||
parseEnvAssignment,
|
||||
} from "./Secrets";
|
||||
import type { SecretProviderHealthResponse } from "../api/secrets";
|
||||
|
||||
@@ -85,7 +87,7 @@ describe("Secrets page provider helpers", () => {
|
||||
null,
|
||||
),
|
||||
).toBe(
|
||||
"Deployment default AWS Secrets Manager is not configured. Select a ready provider vault or configure the deployment default.",
|
||||
"AWS Secrets Manager is not set up on this Paperclip server. Choose a vault that is ready, or ask your administrator to set it up.",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -108,7 +110,7 @@ describe("Secrets page provider helpers", () => {
|
||||
health,
|
||||
),
|
||||
).toBe(
|
||||
"Deployment default AWS Secrets Manager is not configured. Select a ready provider vault or configure the deployment default. AWS Secrets Manager provider is not ready: missing PAPERCLIP_SECRETS_AWS_DEPLOYMENT_ID.",
|
||||
"AWS Secrets Manager is not set up on this Paperclip server. Choose a vault that is ready, or ask your administrator to set it up. AWS Secrets Manager provider is not ready: missing PAPERCLIP_SECRETS_AWS_DEPLOYMENT_ID.",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -141,7 +143,7 @@ describe("Secrets page provider helpers", () => {
|
||||
status: "disabled",
|
||||
}),
|
||||
),
|
||||
).toBe("This provider vault is disabled.");
|
||||
).toBe("This vault is disabled.");
|
||||
});
|
||||
|
||||
it("blocks provider modes the backend does not support", () => {
|
||||
@@ -203,6 +205,110 @@ describe("Secrets page provider helpers", () => {
|
||||
provider: "vault",
|
||||
status: "coming_soon",
|
||||
} as never),
|
||||
).toBe("This provider vault is saved as draft metadata only.");
|
||||
).toBe("Paperclip can't store or read secrets in this vault yet.");
|
||||
});
|
||||
|
||||
it("falls back to a plain sentence when an unhealthy vault reports no message", () => {
|
||||
expect(
|
||||
getProviderConfigBlockReason(
|
||||
providerConfig({ id: "aws-down", provider: "aws_secrets_manager", healthStatus: "error" }),
|
||||
),
|
||||
).toBe("Paperclip couldn't reach this vault.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCreateVaultOptions", () => {
|
||||
const build = (
|
||||
overrides: Partial<Parameters<typeof buildCreateVaultOptions>[0]> = {},
|
||||
) =>
|
||||
buildCreateVaultOptions({
|
||||
providers: [localProvider, awsProvider],
|
||||
providerConfigs: [],
|
||||
mode: "managed",
|
||||
health: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("offers only Paperclip's own storage when nothing else is set up", () => {
|
||||
expect(build({ providers: [localProvider, { ...awsProvider, configured: false }] })).toEqual([
|
||||
{
|
||||
value: "local_encrypted:",
|
||||
provider: "local_encrypted",
|
||||
providerConfigId: "",
|
||||
label: "Paperclip (default)",
|
||||
blockReason: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers a provider's connected vaults in place of its built-in storage", () => {
|
||||
const options = build({
|
||||
providerConfigs: [
|
||||
providerConfig({ id: "team", provider: "local_encrypted", displayName: "Team vault" }),
|
||||
providerConfig({ id: "aws-prod", provider: "aws_secrets_manager", displayName: "prod-us-east", isDefault: true }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(options.map((option) => option.label)).toEqual([
|
||||
"Team vault · Paperclip-encrypted (default)",
|
||||
"prod-us-east · AWS Secrets Manager",
|
||||
]);
|
||||
expect(options.map((option) => option.value)).toEqual([
|
||||
"local_encrypted:team",
|
||||
"aws_secrets_manager:aws-prod",
|
||||
]);
|
||||
expect(options.every((option) => option.blockReason === null)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps an unhealthy vault in the list with its reason and drops disabled and coming-soon ones", () => {
|
||||
const options = build({
|
||||
providers: [localProvider, { ...awsProvider, configured: false }],
|
||||
providerConfigs: [
|
||||
providerConfig({
|
||||
id: "aws-down",
|
||||
provider: "aws_secrets_manager",
|
||||
displayName: "staging-eu",
|
||||
healthStatus: "error",
|
||||
healthMessage: "AWS denied access.",
|
||||
}),
|
||||
providerConfig({ id: "aws-off", provider: "aws_secrets_manager", status: "disabled" }),
|
||||
providerConfig({ id: "aws-draft", provider: "aws_secrets_manager", status: "coming_soon" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(options.map((option) => option.value)).toEqual(["local_encrypted:", "aws_secrets_manager:aws-down"]);
|
||||
expect(options[1].blockReason).toBe("AWS denied access.");
|
||||
});
|
||||
|
||||
it("marks Paperclip's own storage as blocked for linking instead of hiding it", () => {
|
||||
const options = build({ mode: "external" });
|
||||
|
||||
expect(options[0]).toMatchObject({
|
||||
value: "local_encrypted:",
|
||||
blockReason: "Local encrypted (default) does not support linked external references.",
|
||||
});
|
||||
expect(options[1]).toMatchObject({ value: "aws_secrets_manager:", blockReason: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEnvAssignment", () => {
|
||||
it("splits NAME=value, with or without export and quotes", () => {
|
||||
expect(parseEnvAssignment("GITHUB_TOKEN=ghp_abc")).toEqual({ name: "GITHUB_TOKEN", value: "ghp_abc" });
|
||||
expect(parseEnvAssignment(' export LINEAR_API_KEY="lin_api_1" ')).toEqual({
|
||||
name: "LINEAR_API_KEY",
|
||||
value: "lin_api_1",
|
||||
});
|
||||
expect(parseEnvAssignment("DATABASE_URL='postgres://u:p@host/db?sslmode=require'")).toEqual({
|
||||
name: "DATABASE_URL",
|
||||
value: "postgres://u:p@host/db?sslmode=require",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves anything that is not a single assignment alone", () => {
|
||||
expect(parseEnvAssignment("ghp_abc")).toBeNull();
|
||||
expect(parseEnvAssignment("A=1\nB=2")).toBeNull();
|
||||
expect(parseEnvAssignment("1BAD=value")).toBeNull();
|
||||
expect(parseEnvAssignment("EMPTY=")).toBeNull();
|
||||
expect(parseEnvAssignment('EMPTY=""')).toBeNull();
|
||||
});
|
||||
});
|
||||
+1949
-1835
File diff suppressed because it is too large.
Load diff
@@ -98,6 +98,20 @@ async function flushDebounce() {
|
||||
});
|
||||
}
|
||||
|
||||
function findButton(predicate: (text: string) => boolean) {
|
||||
return Array.from(document.querySelectorAll("button")).find((btn) =>
|
||||
predicate(btn.textContent ?? ""),
|
||||
) as HTMLButtonElement | undefined;
|
||||
}
|
||||
|
||||
async function click(element: Element | null | undefined) {
|
||||
expect(element).toBeTruthy();
|
||||
await act(async () => {
|
||||
(element as HTMLElement).click();
|
||||
});
|
||||
await flush();
|
||||
}
|
||||
|
||||
function makeWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
@@ -172,8 +186,12 @@ describe("ImportFromVaultDialog", () => {
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const tableBody = document.querySelector('[data-testid="vault-table-body"]');
|
||||
expect(tableBody).not.toBeNull();
|
||||
const list = document.querySelector('[data-testid="vault-list"]');
|
||||
expect(list).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("Import secrets from a vault");
|
||||
expect(document.body.textContent).toContain("Their values stay in your vault.");
|
||||
// One usable vault: no vault picker.
|
||||
expect(document.querySelector('[aria-label="Vault"]')).toBeNull();
|
||||
expect(document.body.textContent).toContain("prod/stripe");
|
||||
expect(document.body.textContent).toContain("prod/openai");
|
||||
|
||||
@@ -186,7 +204,7 @@ describe("ImportFromVaultDialog", () => {
|
||||
stripeRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
expect(document.body.textContent).toContain("1 selected");
|
||||
expect(findButton((text) => text === "Continue with 1")).toBeTruthy();
|
||||
|
||||
// Load more page
|
||||
const loadMore = document.querySelector('[data-testid="vault-load-more"]') as HTMLButtonElement | null;
|
||||
@@ -199,14 +217,14 @@ describe("ImportFromVaultDialog", () => {
|
||||
|
||||
expect(document.body.textContent).toContain("prod/sendgrid");
|
||||
// Selection persisted through pagination.
|
||||
expect(document.body.textContent).toContain("1 selected");
|
||||
expect(findButton((text) => text === "Continue with 1")).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("disables checkboxes for already-imported (duplicate) rows and shows a conflict badge for conflicts", async () => {
|
||||
it("shows secrets already in Paperclip as not selectable and explains conflicts", async () => {
|
||||
mockSecretsApi.remoteImportPreview.mockResolvedValueOnce(
|
||||
makePreview([
|
||||
makeCandidate({
|
||||
@@ -261,8 +279,23 @@ describe("ImportFromVaultDialog", () => {
|
||||
) as HTMLButtonElement | null;
|
||||
expect(duplicateCheckbox?.getAttribute("data-disabled")).not.toBeNull();
|
||||
|
||||
expect(document.body.textContent).toContain("Conflict");
|
||||
expect(document.body.textContent).toContain("Name already in use");
|
||||
expect(duplicateRow?.textContent).toContain("Already in Paperclip");
|
||||
|
||||
// Clicking the row does not select it either.
|
||||
await act(async () => {
|
||||
duplicateRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
expect(findButton((text) => text === "Continue")).toBeTruthy();
|
||||
|
||||
const conflictRow = document.querySelector(
|
||||
'[data-testid="vault-row-arn:aws:secretsmanager:us-east-1:1:secret:prod/openai-XYZ"]',
|
||||
);
|
||||
expect(conflictRow?.getAttribute("data-row-state")).toBe("conflict");
|
||||
expect(conflictRow?.textContent).toContain("Name already in use");
|
||||
expect(conflictRow?.textContent).not.toContain("Already in Paperclip");
|
||||
// Raw references are never shown.
|
||||
expect(document.body.textContent).not.toContain("arn:aws");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -336,7 +369,7 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
await flush();
|
||||
|
||||
// Click "Continue → Review" button.
|
||||
// Continue to the naming step.
|
||||
const continueBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(btn) => btn.textContent?.includes("Continue"),
|
||||
);
|
||||
@@ -346,14 +379,20 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
await flush();
|
||||
|
||||
// Review step: error message visible, Import button disabled.
|
||||
// Naming step: the error is shown under the row. The Import button stays
|
||||
// enabled, but pressing it explains what to fix instead of importing.
|
||||
expect(document.body.textContent).toContain("Name 1 secret");
|
||||
expect(document.body.textContent?.toLowerCase()).toContain("a paperclip secret already uses this");
|
||||
|
||||
const importBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(btn) => btn.textContent?.startsWith("Import "),
|
||||
) as HTMLButtonElement | undefined;
|
||||
const importBtn = findButton((text) => text.startsWith("Import "));
|
||||
expect(importBtn).toBeTruthy();
|
||||
expect(importBtn?.disabled).toBe(true);
|
||||
expect(importBtn?.disabled).toBe(false);
|
||||
expect(document.querySelector('[data-testid="import-blocked-message"]')).toBeNull();
|
||||
await click(importBtn);
|
||||
expect(mockSecretsApi.remoteImport).not.toHaveBeenCalled();
|
||||
expect(
|
||||
document.querySelector('[data-testid="import-blocked-message"]')?.textContent,
|
||||
).toContain("Fix the 1 secret marked above");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -407,6 +446,10 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
await flush();
|
||||
|
||||
// Keys sit behind a disclosure until they are needed.
|
||||
expect(document.querySelector(`[data-testid="review-key-${externalRef}"]`)).toBeNull();
|
||||
await click(document.querySelector('[data-testid="review-details-toggle"]'));
|
||||
|
||||
const keyInput = document.querySelector(
|
||||
`[data-testid="review-key-${externalRef}"]`,
|
||||
) as HTMLInputElement | null;
|
||||
@@ -421,10 +464,13 @@ describe("ImportFromVaultDialog", () => {
|
||||
await flush();
|
||||
|
||||
expect(document.body.textContent).toContain("lowercase letters");
|
||||
const importBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(btn) => btn.textContent?.startsWith("Import "),
|
||||
) as HTMLButtonElement | undefined;
|
||||
expect(importBtn?.disabled).toBe(true);
|
||||
// The key field stays visible while it has a problem, even with the disclosure closed.
|
||||
await click(document.querySelector('[data-testid="review-details-toggle"]'));
|
||||
expect(document.querySelector(`[data-testid="review-key-${externalRef}"]`)).not.toBeNull();
|
||||
|
||||
await click(findButton((text) => text.startsWith("Import ")));
|
||||
expect(mockSecretsApi.remoteImport).not.toHaveBeenCalled();
|
||||
expect(document.querySelector('[data-testid="import-blocked-message"]')).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -499,6 +545,7 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
await flush();
|
||||
|
||||
await click(document.querySelector('[data-testid="review-details-toggle"]'));
|
||||
const descriptionInput = document.querySelector(
|
||||
`[data-testid="review-description-${externalRef}"]`,
|
||||
) as HTMLInputElement | null;
|
||||
@@ -533,12 +580,19 @@ describe("ImportFromVaultDialog", () => {
|
||||
],
|
||||
});
|
||||
|
||||
// Everything imported: a short confirmation with one Done action.
|
||||
expect(document.body.textContent).toContain("1 secret imported");
|
||||
expect(
|
||||
document.querySelector(`[data-testid="result-row-${externalRef}"]`)?.getAttribute("data-row-status"),
|
||||
).toBe("imported");
|
||||
expect(findButton((text) => text === "Done")).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders mixed import results (created/skipped/failed) and shows error reason", async () => {
|
||||
it("keeps failed secrets listed with their reason after a mixed import and retries only those", async () => {
|
||||
mockSecretsApi.remoteImportPreview.mockResolvedValueOnce(
|
||||
makePreview([
|
||||
makeCandidate({
|
||||
@@ -622,8 +676,8 @@ describe("ImportFromVaultDialog", () => {
|
||||
|
||||
// Select all loaded
|
||||
const headerCheckbox = document.querySelector(
|
||||
'[data-testid="vault-table-body"]',
|
||||
)?.parentElement?.querySelector('thead button[role="checkbox"]') as HTMLButtonElement | null;
|
||||
'[data-testid="vault-select-all"]',
|
||||
) as HTMLButtonElement | null;
|
||||
expect(headerCheckbox).toBeTruthy();
|
||||
await act(async () => {
|
||||
headerCheckbox!.click();
|
||||
@@ -651,13 +705,67 @@ describe("ImportFromVaultDialog", () => {
|
||||
await flush();
|
||||
|
||||
expect(mockSecretsApi.remoteImport).toHaveBeenCalledTimes(1);
|
||||
expect(document.body.textContent).toContain("Import complete");
|
||||
expect(document.body.textContent).toContain("1 created");
|
||||
expect(document.body.textContent).toContain("1 skipped");
|
||||
expect(document.body.textContent).toContain("1 failed");
|
||||
expect(document.body.textContent).toContain("AWS Secrets Manager denied the request");
|
||||
const summary = document.querySelector('[data-testid="result-summary"]');
|
||||
expect(summary?.textContent).toContain("1 imported.");
|
||||
expect(summary?.textContent).toContain("1 already in Paperclip.");
|
||||
expect(summary?.textContent).toContain("1 could not be linked and is listed below.");
|
||||
|
||||
// Only the failure stays in the list, with its reason.
|
||||
const gammaRef = "arn:aws:secretsmanager:us-east-1:1:secret:c-CCC";
|
||||
expect(document.querySelectorAll('[data-testid^="review-row-"]').length).toBe(1);
|
||||
expect(
|
||||
document.querySelector(`[data-testid="review-failure-${gammaRef}"]`)?.textContent,
|
||||
).toContain("AWS Secrets Manager denied the request");
|
||||
expect(document.body.textContent).not.toContain("AccessDeniedException");
|
||||
expect(document.body.textContent).not.toContain("123456789012");
|
||||
expect(document.body.textContent).not.toContain("arn:aws");
|
||||
|
||||
// The finished rows are one click away, each with its own outcome.
|
||||
await click(document.querySelector('[data-testid="result-done-toggle"]'));
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-testid="result-row-arn:aws:secretsmanager:us-east-1:1:secret:a-AAA"]')
|
||||
?.getAttribute("data-row-status"),
|
||||
).toBe("imported");
|
||||
const skippedRow = document.querySelector(
|
||||
'[data-testid="result-row-arn:aws:secretsmanager:us-east-1:1:secret:b-BBB"]',
|
||||
);
|
||||
expect(skippedRow?.getAttribute("data-row-status")).toBe("skipped");
|
||||
expect(skippedRow?.textContent).toContain("exact reference already imported");
|
||||
|
||||
// Footer: Close on the left, Try again on the right; closing needs no discard prompt.
|
||||
expect(findButton((text) => text === "Close")).toBeTruthy();
|
||||
expect(findButton((text) => text === "Back")).toBeUndefined();
|
||||
|
||||
mockSecretsApi.remoteImport.mockResolvedValueOnce({
|
||||
providerConfigId: awsVault.id,
|
||||
provider: "aws_secrets_manager",
|
||||
importedCount: 1,
|
||||
skippedCount: 0,
|
||||
errorCount: 0,
|
||||
results: [
|
||||
{
|
||||
externalRef: gammaRef,
|
||||
name: "gamma",
|
||||
key: "gamma",
|
||||
status: "imported",
|
||||
reason: null,
|
||||
secretId: "secret-gamma",
|
||||
conflicts: [],
|
||||
},
|
||||
],
|
||||
} satisfies RemoteSecretImportResult);
|
||||
await click(findButton((text) => text === "Try again"));
|
||||
await flush();
|
||||
|
||||
expect(mockSecretsApi.remoteImport).toHaveBeenCalledTimes(2);
|
||||
const retryInput = mockSecretsApi.remoteImport.mock.calls[1]?.[1];
|
||||
expect(retryInput.secrets.map((secret: { externalRef: string }) => secret.externalRef)).toEqual([
|
||||
gammaRef,
|
||||
]);
|
||||
expect(document.body.textContent).toContain("2 secrets imported");
|
||||
expect(document.querySelectorAll('[data-testid^="result-row-"]').length).toBe(3);
|
||||
expect(findButton((text) => text === "Done")).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -683,7 +791,10 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(document.querySelector('[data-testid="select-empty-vaults"]')).not.toBeNull();
|
||||
const empty = document.querySelector('[data-testid="select-empty-vaults"]');
|
||||
expect(empty?.textContent).toContain("No vault is connected yet.");
|
||||
expect(findButton((text) => text === "Connect one in Vaults")).toBeTruthy();
|
||||
expect(findButton((text) => text.startsWith("Continue"))).toBeUndefined();
|
||||
expect(mockSecretsApi.remoteImportPreview).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
@@ -719,7 +830,8 @@ describe("ImportFromVaultDialog", () => {
|
||||
|
||||
const banner = document.querySelector('[data-testid="preview-error-banner"]');
|
||||
expect(banner).not.toBeNull();
|
||||
expect(banner?.textContent).toContain("Could not load remote secrets");
|
||||
expect(banner?.textContent).toContain("Paperclip couldn't load the secrets in this vault.");
|
||||
expect(findButton((text) => text === "Try again")).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -727,6 +839,7 @@ describe("ImportFromVaultDialog", () => {
|
||||
});
|
||||
|
||||
it("renders sanitized preview provider errors without raw AWS exception text", async () => {
|
||||
const onManageVaults = vi.fn();
|
||||
const rawProviderMessage =
|
||||
"AccessDeniedException: User: arn:aws:sts::123456789012:assumed-role/prod/Paperclip is not authorized";
|
||||
mockSecretsApi.remoteImportPreview.mockRejectedValueOnce(
|
||||
@@ -748,6 +861,7 @@ describe("ImportFromVaultDialog", () => {
|
||||
companyId="company-1"
|
||||
providerConfigs={[awsVault]}
|
||||
existingSecrets={[]}
|
||||
onManageVaults={onManageVaults}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
@@ -757,8 +871,12 @@ describe("ImportFromVaultDialog", () => {
|
||||
|
||||
const banner = document.querySelector('[data-testid="preview-error-banner"]');
|
||||
expect(banner).not.toBeNull();
|
||||
expect(banner?.textContent).toContain("AWS denied list access");
|
||||
expect(banner?.textContent).toContain("missing secretsmanager:ListSecrets");
|
||||
expect(banner?.textContent).toContain("AWS denied access. Paperclip's role can't list the secrets in this vault.");
|
||||
expect(banner?.textContent).toContain("secretsmanager:ListSecrets");
|
||||
await click(findButton((text) => text === "Fix it in Vaults"));
|
||||
expect(onManageVaults).toHaveBeenCalledTimes(1);
|
||||
// Nothing to continue with while the vault cannot be listed.
|
||||
expect(findButton((text) => text.startsWith("Continue"))).toBeUndefined();
|
||||
expect(banner?.textContent).not.toContain(rawProviderMessage);
|
||||
expect(banner?.textContent).not.toContain("arn:aws");
|
||||
expect(banner?.textContent).not.toContain("123456789012");
|
||||
@@ -820,4 +938,87 @@ describe("ImportFromVaultDialog", () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("explains why Continue does nothing when no secret is selected", async () => {
|
||||
mockSecretsApi.remoteImportPreview.mockResolvedValueOnce(makePreview([makeCandidate()]));
|
||||
|
||||
const { queryClient } = makeWrapper();
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ImportFromVaultDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
companyId="company-1"
|
||||
providerConfigs={[awsVault]}
|
||||
existingSecrets={[]}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const continueBtn = findButton((text) => text === "Continue");
|
||||
expect(continueBtn?.disabled).toBe(false);
|
||||
await click(continueBtn);
|
||||
expect(
|
||||
document.querySelector('[data-testid="import-blocked-message"]')?.textContent,
|
||||
).toBe("Select at least one secret to import.");
|
||||
expect(document.querySelector('[data-testid="vault-list"]')).not.toBeNull();
|
||||
|
||||
// Picking a secret clears the message.
|
||||
await click(document.querySelector('[data-testid="vault-select-all"]'));
|
||||
expect(document.querySelector('[data-testid="import-blocked-message"]')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("offers a vault picker only when more than one vault is usable, and asks before discarding picks", async () => {
|
||||
mockSecretsApi.remoteImportPreview.mockResolvedValue(makePreview([makeCandidate()]));
|
||||
const secondVault: CompanySecretProviderConfig = {
|
||||
...awsVault,
|
||||
id: "vault-aws-2",
|
||||
displayName: "AWS staging",
|
||||
isDefault: false,
|
||||
};
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
const { queryClient } = makeWrapper();
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ImportFromVaultDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
companyId="company-1"
|
||||
providerConfigs={[awsVault, secondVault]}
|
||||
existingSecrets={[]}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(document.querySelector('[aria-label="Vault"]')).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("Secret in AWS production");
|
||||
|
||||
await click(document.querySelector('[data-testid="vault-select-all"]'));
|
||||
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValueOnce(false).mockReturnValueOnce(true);
|
||||
await click(findButton((text) => text === "Cancel"));
|
||||
expect(confirmSpy).toHaveBeenCalledWith("Discard 1 pending import?");
|
||||
expect(onOpenChange).not.toHaveBeenCalled();
|
||||
await click(findButton((text) => text === "Cancel"));
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
confirmSpy.mockRestore();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,8 @@
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { UserSecretDefinition } from "@paperclipai/shared";
|
||||
import type { ReactNode } from "react";
|
||||
import type { CompanySecret, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MyUserSecretsTab } from "./MyUserSecretsTab";
|
||||
import { ApiError } from "../../api/client";
|
||||
@@ -23,6 +24,26 @@ vi.mock("../../context/ToastContext", () => ({
|
||||
useToastActions: () => ({ pushToast: mockPushToast }),
|
||||
}));
|
||||
|
||||
// The overflow menu is a Radix portal; render it inline so its items are reachable in jsdom.
|
||||
vi.mock("@/components/ui/dropdown-menu", () => ({
|
||||
DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
DropdownMenuContent: ({ children }: { children: ReactNode }) => <div role="menu">{children}</div>,
|
||||
DropdownMenuItem: ({
|
||||
children,
|
||||
onSelect,
|
||||
disabled,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
onSelect?: () => void;
|
||||
disabled?: boolean;
|
||||
}) => (
|
||||
<button type="button" role="menuitem" disabled={disabled} onClick={() => onSelect?.()}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
@@ -50,6 +71,34 @@ function definition(overrides: Partial<UserSecretDefinition> = {}): UserSecretDe
|
||||
};
|
||||
}
|
||||
|
||||
function mySecret(overrides: Partial<CompanySecret> = {}): CompanySecret {
|
||||
return {
|
||||
id: "secret-1",
|
||||
status: "active",
|
||||
latestVersion: 1,
|
||||
lastRotatedAt: null,
|
||||
createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
|
||||
updatedAt: new Date(),
|
||||
...overrides,
|
||||
} as CompanySecret;
|
||||
}
|
||||
|
||||
function rows() {
|
||||
return Array.from(container.querySelectorAll<HTMLElement>('[data-testid^="my-secret-"]'));
|
||||
}
|
||||
|
||||
function buttonIn(scope: ParentNode, label: string) {
|
||||
return Array.from(scope.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === label,
|
||||
) as HTMLButtonElement | undefined;
|
||||
}
|
||||
|
||||
function setTextareaValue(textarea: HTMLTextAreaElement, value: string) {
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;
|
||||
setter.call(textarea, value);
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
const transientError = () =>
|
||||
new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" });
|
||||
|
||||
@@ -139,7 +188,7 @@ describe("MyUserSecretsTab", () => {
|
||||
const errorState = container.querySelector('[data-query-view="error"]');
|
||||
expect(errorState?.textContent).toContain("Couldn't load your secrets");
|
||||
expect(errorState?.textContent).toContain("Boom");
|
||||
expect(container.textContent).not.toContain("No user secrets are defined");
|
||||
expect(container.textContent).not.toContain("Nothing is asked of you yet");
|
||||
const retryButton = Array.from(errorState?.querySelectorAll("button") ?? []).find((button) =>
|
||||
button.textContent?.includes("Retry"),
|
||||
);
|
||||
@@ -151,4 +200,189 @@ describe("MyUserSecretsTab", () => {
|
||||
expect(mockSecretsApi.listMyUserSecrets).toHaveBeenCalledTimes(2);
|
||||
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("says in plain words that nothing is asked yet when no secrets are defined", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
|
||||
expect(container.textContent).toContain("Values only you provide. Agents use them when they work for you.");
|
||||
expect(container.textContent).toContain(
|
||||
"Nothing is asked of you yet. An admin decides which secrets each member provides.",
|
||||
);
|
||||
expect(container.textContent).not.toContain("your value.");
|
||||
expect(rows()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("sorts secrets that still need a value first and counts them in the lead", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([
|
||||
{ definition: definition({ id: "def-added", name: "Added token" }), secret: mySecret() },
|
||||
{ definition: definition({ id: "def-off", name: "Retired token", status: "disabled" }), secret: null },
|
||||
{ definition: definition({ id: "def-missing-1", name: "Missing token" }), secret: null },
|
||||
{ definition: definition({ id: "def-missing-2", name: "Another missing token" }), secret: null },
|
||||
] satisfies MyUserSecretEntry[]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
|
||||
expect(rows().map((row) => row.dataset.testid)).toEqual([
|
||||
"my-secret-def-missing-1",
|
||||
"my-secret-def-missing-2",
|
||||
"my-secret-def-added",
|
||||
"my-secret-def-off",
|
||||
]);
|
||||
expect(container.textContent).toContain("2 still need your value.");
|
||||
});
|
||||
|
||||
it("uses the singular lead when one secret needs a value", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: definition(), secret: null }]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
|
||||
expect(container.textContent).toContain("1 still needs your value.");
|
||||
});
|
||||
|
||||
it("shows the name, the key agents refer to and guidance, but no always-true status", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([
|
||||
{
|
||||
definition: definition({ usageGuidance: "Create it under Settings → Developer settings." }),
|
||||
secret: mySecret(),
|
||||
},
|
||||
]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
|
||||
const [row] = rows();
|
||||
expect(row.textContent).toContain("Personal GitHub token");
|
||||
expect(row.textContent).toContain("Used for private repo access");
|
||||
expect(row.textContent).toContain("Create it under Settings → Developer settings.");
|
||||
expect(row.textContent).toContain("Added 3d ago");
|
||||
expect(row.querySelector("code")?.textContent).toBe("PERSONAL_GH_TOKEN");
|
||||
expect(row.textContent).not.toMatch(/Active|Value set|local_encrypted/);
|
||||
expect(buttonIn(row, "Replace")).toBeDefined();
|
||||
expect(buttonIn(row, "Set value")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("explains a turned-off secret and offers no way to add a value", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([
|
||||
{ definition: definition({ id: "def-off", status: "disabled" }), secret: null },
|
||||
{ definition: definition({ id: "def-off-with-value", status: "disabled" }), secret: mySecret() },
|
||||
]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
|
||||
const [withoutValue, withValue] = rows();
|
||||
expect(withoutValue.textContent).toContain("Agents won't ask for it.");
|
||||
expect(withoutValue.querySelectorAll("button")).toHaveLength(0);
|
||||
expect(buttonIn(withValue, "Replace")).toBeUndefined();
|
||||
expect(buttonIn(withValue, "Remove your value")).toBeDefined();
|
||||
expect(container.textContent).not.toContain("your value.");
|
||||
});
|
||||
|
||||
it("adds a value through the dialog for a secret that needs one", async () => {
|
||||
const def = definition();
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: def, secret: null }]);
|
||||
mockSecretsApi.createMyUserSecret.mockResolvedValue(mySecret());
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
await act(() => buttonIn(rows()[0], "Set value")!.click());
|
||||
await flushReact();
|
||||
|
||||
const dialog = document.body.querySelector('[role="dialog"]') as HTMLElement;
|
||||
expect(dialog.textContent).toContain("Set your value for Personal GitHub token");
|
||||
expect(dialog.textContent).toContain("Encrypted when saved. After that it can be replaced, never viewed.");
|
||||
const save = buttonIn(dialog, "Save value")!;
|
||||
expect(save.disabled).toBe(true);
|
||||
|
||||
await act(() => setTextareaValue(dialog.querySelector("textarea")!, " ghp_example "));
|
||||
await flushReact();
|
||||
expect(save.disabled).toBe(false);
|
||||
await act(() => save.click());
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.createMyUserSecret).toHaveBeenCalledWith("c1", {
|
||||
definitionId: "def-1",
|
||||
definitionKey: "PERSONAL_GH_TOKEN",
|
||||
value: "ghp_example",
|
||||
});
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Your value was saved", tone: "success" }),
|
||||
);
|
||||
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("replaces an existing value in place", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: definition(), secret: mySecret() }]);
|
||||
mockSecretsApi.rotateMyUserSecret.mockResolvedValue(mySecret({ latestVersion: 2 }));
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
await act(() => buttonIn(rows()[0], "Replace")!.click());
|
||||
await flushReact();
|
||||
|
||||
const dialog = document.body.querySelector('[role="dialog"]') as HTMLElement;
|
||||
expect(dialog.textContent).toContain("Replace your value for Personal GitHub token");
|
||||
await act(() => setTextareaValue(dialog.querySelector("textarea")!, "ghp_new"));
|
||||
await flushReact();
|
||||
await act(() => buttonIn(dialog, "Replace value")!.click());
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.rotateMyUserSecret).toHaveBeenCalledWith("c1", "secret-1", { value: "ghp_new" });
|
||||
expect(mockSecretsApi.createMyUserSecret).not.toHaveBeenCalled();
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Your value was replaced", tone: "success" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("hides the typed value until Show value is pressed", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: definition(), secret: null }]);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
await act(() => buttonIn(rows()[0], "Set value")!.click());
|
||||
await flushReact();
|
||||
|
||||
const dialog = document.body.querySelector('[role="dialog"]') as HTMLElement;
|
||||
const toggle = dialog.querySelector('button[aria-label="Show value"]') as HTMLButtonElement;
|
||||
expect(toggle.getAttribute("aria-pressed")).toBe("false");
|
||||
await act(() => toggle.click());
|
||||
expect(dialog.querySelector('button[aria-label="Hide value"]')?.getAttribute("aria-pressed")).toBe("true");
|
||||
});
|
||||
|
||||
it("removes a value from the row's overflow menu and refreshes the list", async () => {
|
||||
const def = definition();
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: def, secret: mySecret() }]);
|
||||
mockSecretsApi.removeMyUserSecret.mockResolvedValue(undefined);
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
expect(rows()[0].querySelector('button[aria-label="More actions for Personal GitHub token"]')).not.toBeNull();
|
||||
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: def, secret: null }]);
|
||||
await act(() => buttonIn(rows()[0], "Remove your value")!.click());
|
||||
await waitForReact(() => buttonIn(container, "Set value") !== undefined);
|
||||
|
||||
expect(mockSecretsApi.removeMyUserSecret).toHaveBeenCalledWith("c1", "secret-1");
|
||||
expect(mockPushToast).toHaveBeenCalledWith({ title: "Your value was removed", tone: "info" });
|
||||
});
|
||||
|
||||
it("says what went wrong when a value cannot be removed", async () => {
|
||||
mockSecretsApi.listMyUserSecrets.mockResolvedValue([{ definition: definition(), secret: mySecret() }]);
|
||||
mockSecretsApi.removeMyUserSecret.mockRejectedValue(new ApiError("Boom", 500, { error: "Boom" }));
|
||||
|
||||
await render();
|
||||
await flushReact();
|
||||
await act(() => buttonIn(rows()[0], "Remove your value")!.click());
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Couldn't remove your value", tone: "error" }),
|
||||
);
|
||||
expect(buttonIn(rows()[0], "Replace")).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +1,29 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { CompanySecret } from "@paperclipai/shared";
|
||||
import { KeyRound, Trash2, UserRound } from "lucide-react";
|
||||
import { Check, KeyRound, MoreHorizontal } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { secretsApi, type MyUserSecretEntry } from "../../api/secrets";
|
||||
import { queryKeys } from "../../lib/queryKeys";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { relativeTime } from "../../lib/utils";
|
||||
import { useToastActions } from "../../context/ToastContext";
|
||||
import { SetMyUserSecretDialog } from "./SetMyUserSecretDialog";
|
||||
import { SecretPathName } from "./SecretPathName";
|
||||
import {
|
||||
myValueLabel,
|
||||
myValueState,
|
||||
myValueTone,
|
||||
} from "./my-value-state";
|
||||
import { myValueState } from "./my-value-state";
|
||||
import { describeError } from "@/api/errors";
|
||||
|
||||
/**
|
||||
* Secrets → My secrets tab. Lists every company user-secret definition paired
|
||||
* with the current user's own value state, and lets the user set / update /
|
||||
* clear their value. This is the owner-facing counterpart to the admin
|
||||
* "User secret definitions" tab.
|
||||
* Secrets → My secrets tab. Lists every secret the organization asks each
|
||||
* member to provide, with whether the signed-in person has added their value,
|
||||
* and lets them add, replace or remove it.
|
||||
*/
|
||||
export function MyUserSecretsTab({ companyId }: { companyId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
@@ -41,66 +41,61 @@ export function MyUserSecretsTab({ companyId }: { companyId: string }) {
|
||||
mutationFn: (secret: CompanySecret) => secretsApi.removeMyUserSecret(companyId, secret.id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.secrets.myUserSecrets(companyId) });
|
||||
pushToast({ title: "Value cleared", tone: "info" });
|
||||
pushToast({ title: "Your value was removed", tone: "info" });
|
||||
},
|
||||
onError: (err) =>
|
||||
pushToast({
|
||||
title: "Could not clear value",
|
||||
title: "Couldn't remove your value",
|
||||
body: describeError(err).body,
|
||||
tone: "error",
|
||||
}),
|
||||
});
|
||||
|
||||
const missingCount = entries.filter(
|
||||
(entry) => entry.definition.status === "active" && !entry.secret,
|
||||
).length;
|
||||
const needsValue = (entry: MyUserSecretEntry) =>
|
||||
entry.definition.status === "active" && !entry.secret;
|
||||
const missingCount = entries.filter(needsValue).length;
|
||||
// Secrets still waiting on this person come first; the rest keep the server's order.
|
||||
const sortedEntries = [...entries].sort(
|
||||
(a, b) => Number(needsValue(b)) - Number(needsValue(a)),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start gap-2 rounded-md border border-violet-500/30 bg-violet-500/5 px-4 py-3 text-xs text-violet-800 dark:text-violet-200">
|
||||
<UserRound className="h-4 w-4 mt-0.5 shrink-0" />
|
||||
<p>
|
||||
These are credentials only you provide. Each value is yours alone — used when you are the
|
||||
user responsible for a run — and is never shown back to anyone, including admins.
|
||||
{missingCount > 0 ? (
|
||||
<span className="font-medium">
|
||||
{" "}
|
||||
{missingCount} required secret{missingCount === 1 ? " still needs" : "s still need"} your
|
||||
value.
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
<section aria-label="My secrets" className="flex flex-col gap-4">
|
||||
<p className="max-w-xl text-sm text-muted-foreground">
|
||||
Values only you provide. Agents use them when they work for you.
|
||||
{missingCount > 0 ? (
|
||||
<span className="text-foreground">
|
||||
{" "}
|
||||
{missingCount} still {missingCount === 1 ? "needs" : "need"} your value.
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
<div>
|
||||
{mySecretsView.kind === "error" ? (
|
||||
<div className="py-4">
|
||||
<QueryErrorState
|
||||
error={mySecretsQuery.error}
|
||||
action="load your secrets"
|
||||
onRetry={mySecretsView.retry}
|
||||
retrying={mySecretsView.isFetching}
|
||||
{mySecretsView.kind === "error" ? (
|
||||
<QueryErrorState
|
||||
error={mySecretsQuery.error}
|
||||
action="load your secrets"
|
||||
onRetry={mySecretsView.retry}
|
||||
retrying={mySecretsView.isFetching}
|
||||
/>
|
||||
) : entries.length === 0 && !mySecretsQuery.isPending && mySecretsView.kind !== "reconnecting" ? (
|
||||
<EmptyState
|
||||
icon={KeyRound}
|
||||
message="Nothing is asked of you yet. An admin decides which secrets each member provides."
|
||||
/>
|
||||
) : (
|
||||
<ul className="divide-y divide-border border-y border-border">
|
||||
{sortedEntries.map((entry) => (
|
||||
<MyUserSecretRow
|
||||
key={entry.definition.id}
|
||||
entry={entry}
|
||||
onSet={() => setDialogFor(entry)}
|
||||
onClear={() => entry.secret && clear.mutate(entry.secret)}
|
||||
clearing={clear.isPending}
|
||||
/>
|
||||
</div>
|
||||
) : entries.length === 0 && !mySecretsQuery.isPending && mySecretsView.kind !== "reconnecting" ? (
|
||||
<EmptyState
|
||||
icon={KeyRound}
|
||||
message="No user secrets are defined for this organization yet. An admin defines which credentials each member supplies."
|
||||
/>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{entries.map((entry) => (
|
||||
<MyUserSecretRow
|
||||
key={entry.definition.id}
|
||||
entry={entry}
|
||||
onSet={() => setDialogFor(entry)}
|
||||
onClear={() => entry.secret && clear.mutate(entry.secret)}
|
||||
clearing={clear.isPending}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<SetMyUserSecretDialog
|
||||
companyId={companyId}
|
||||
@@ -111,7 +106,7 @@ export function MyUserSecretsTab({ companyId }: { companyId: string }) {
|
||||
if (!open) setDialogFor(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -129,58 +124,74 @@ function MyUserSecretRow({
|
||||
const { definition, secret } = entry;
|
||||
const state = myValueState(definition, secret);
|
||||
const disabledDefinition = definition.status !== "active";
|
||||
const replaced = secret ? secret.latestVersion > 1 && secret.lastRotatedAt : null;
|
||||
|
||||
return (
|
||||
<li
|
||||
className={cn(
|
||||
"flex items-start gap-3 rounded-md border p-3",
|
||||
state === "not_set" && !disabledDefinition
|
||||
? "border-amber-500/40 bg-amber-500/5"
|
||||
: "border-border",
|
||||
)}
|
||||
className="flex flex-wrap items-center gap-x-4 gap-y-2 px-3 py-3"
|
||||
data-testid={`my-secret-${definition.id}`}
|
||||
data-needs-value={!secret && !disabledDefinition ? "true" : undefined}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<SecretPathName name={definition.name} />
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 text-(length:--text-micro) text-muted-foreground">
|
||||
{definition.key}
|
||||
</code>
|
||||
{disabledDefinition ? (
|
||||
<Badge variant="outline" className="text-(length:--text-nano)">
|
||||
{definition.status}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 basis-64 flex-col gap-0.5">
|
||||
<span className="flex min-w-0 flex-wrap items-baseline gap-x-2">
|
||||
<SecretPathName name={definition.name} className="text-sm" />
|
||||
{/* Agents point people at a secret by this key, so it stays visible. */}
|
||||
<code className="font-mono text-xs text-muted-foreground">{definition.key}</code>
|
||||
</span>
|
||||
{definition.description ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground">{definition.description}</p>
|
||||
<span className="text-xs text-muted-foreground">{definition.description}</span>
|
||||
) : null}
|
||||
{definition.usageGuidance ? (
|
||||
<p className="mt-1 text-(length:--text-micro) text-muted-foreground/80">{definition.usageGuidance}</p>
|
||||
<span className="text-xs text-muted-foreground">{definition.usageGuidance}</span>
|
||||
) : null}
|
||||
{disabledDefinition ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Turned off by an admin. Agents won't ask for it.
|
||||
</span>
|
||||
) : state === "inactive" ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Your value is turned off. Replace it to use it again.
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<Badge variant="outline" className={cn("text-(length:--text-micro)", myValueTone(state))}>
|
||||
{myValueLabel(state)}
|
||||
</Badge>
|
||||
{!disabledDefinition ? (
|
||||
<Button size="sm" variant={secret ? "outline" : "default"} onClick={onSet}>
|
||||
{secret ? "Update" : "Set value"}
|
||||
</Button>
|
||||
) : null}
|
||||
{secret ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
onClick={onClear}
|
||||
disabled={clearing}
|
||||
title="Clear my value"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{secret ? (
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="mr-2 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Check className="size-3.5" aria-hidden />
|
||||
{replaced
|
||||
? `Replaced ${relativeTime(replaced)}`
|
||||
: `Added ${relativeTime(secret.createdAt)}`}
|
||||
</span>
|
||||
{!disabledDefinition ? (
|
||||
<Button variant="ghost" size="sm" onClick={onSet}>
|
||||
Replace
|
||||
</Button>
|
||||
) : null}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="text-muted-foreground"
|
||||
aria-label={`More actions for ${definition.name}`}
|
||||
disabled={clearing}
|
||||
>
|
||||
<MoreHorizontal aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem variant="destructive" disabled={clearing} onSelect={onClear}>
|
||||
Remove your value
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</span>
|
||||
) : !disabledDefinition ? (
|
||||
<Button size="sm" onClick={onSet}>
|
||||
Set value
|
||||
</Button>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -132,6 +132,20 @@ function findButton(label: string): HTMLButtonElement | undefined {
|
||||
) as HTMLButtonElement | undefined;
|
||||
}
|
||||
|
||||
function fieldByLabel<T extends HTMLElement = HTMLInputElement>(label: string): T | null {
|
||||
const host = [...document.querySelectorAll("label")].find((node) =>
|
||||
node.textContent?.trim().startsWith(label),
|
||||
);
|
||||
return (host?.querySelector("input, select") as T | null) ?? null;
|
||||
}
|
||||
|
||||
/** Serve each status its own rows, the way the API does. */
|
||||
function mockProposals(rows: SecretProposalView[]) {
|
||||
mockSecretsApi.listProposals.mockImplementation(async (_companyId: string, status = "pending") =>
|
||||
rows.filter((row) => row.status === status),
|
||||
);
|
||||
}
|
||||
|
||||
let activeRoot: ReturnType<typeof createRoot> | null = null;
|
||||
let activeContainer: HTMLDivElement | null = null;
|
||||
|
||||
@@ -163,8 +177,6 @@ async function renderTab(
|
||||
|
||||
describe("ProposalsTab", () => {
|
||||
afterEach(async () => {
|
||||
// Unmount the React root first so Radix dialog portals clean themselves up
|
||||
// before the DOM is wiped (else jsdom throws NotFoundError on teardown).
|
||||
if (activeRoot) await act(async () => activeRoot!.unmount());
|
||||
activeContainer?.remove();
|
||||
activeRoot = null;
|
||||
@@ -179,57 +191,92 @@ describe("ProposalsTab", () => {
|
||||
});
|
||||
|
||||
it("shows a fingerprint and provenance but never the value", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([makeSecretProposal()]);
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => document.body.textContent?.includes("dev/github/token") ?? false);
|
||||
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("token"); // folder-styled leaf
|
||||
expect(text).toContain("Nothing changes until you approve.");
|
||||
expect(text).toContain("ClaudeCoder wants to save a new secret, dev/github/token");
|
||||
expect(text).toContain("sha256:abcdef0123"); // fingerprint
|
||||
expect(text).toContain("40 bytes"); // length
|
||||
expect(text).toContain("ClaudeCoder"); // proposer
|
||||
expect(text).toContain("PAP-14743"); // origin issue
|
||||
// Provenance: the task is named by its title and linked, not shown as a raw key.
|
||||
expect(text).toContain("While working on “UI review surface”");
|
||||
expect(text).not.toContain("PAP-14743");
|
||||
expect(document.querySelector('a[href="/issues/PAP-14743"]')).not.toBeNull();
|
||||
expect(text).toContain("Expires in");
|
||||
// Justification is framed as an untrusted, agent-authored claim (Q0 concern).
|
||||
expect(text).toContain("Reason given by the agent");
|
||||
expect(text).toContain("“Need the GitHub token to open the PR.”");
|
||||
// Never renders a raw secret value.
|
||||
expect(text).not.toContain("ghp_");
|
||||
});
|
||||
|
||||
it("disables Approve with the authz explanation when the viewer can't approve", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([
|
||||
it("copies the full fingerprint for comparison", async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true });
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
const chip = [...document.querySelectorAll("button")].find((button) =>
|
||||
button.textContent?.includes("sha256:abcdef0123"),
|
||||
);
|
||||
await act(async () => chip?.click());
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
|
||||
expect(writeText).toHaveBeenCalledWith("sha256:abcdef0123456789abcdef");
|
||||
expect(mockPushToast).toHaveBeenCalledWith({ title: "Fingerprint copied", tone: "success" });
|
||||
});
|
||||
|
||||
it("replaces the actions with a plain sentence when the viewer can't decide", async () => {
|
||||
mockProposals([
|
||||
makeSecretProposal({
|
||||
viewerCanApprove: false,
|
||||
approveBlockReason: "You need secrets write to approve this.",
|
||||
approveBlockReason: "Company admin access required",
|
||||
}),
|
||||
makeBindingProposal({
|
||||
viewerCanApprove: false,
|
||||
approveBlockReason: "agent_config:update denied",
|
||||
secretProposalId: null,
|
||||
secretProposalName: null,
|
||||
secretId: "secret-1",
|
||||
secretName: "dev/github/token",
|
||||
}),
|
||||
]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve")));
|
||||
await waitForReact(() => document.body.textContent?.includes("dev/github/token") ?? false);
|
||||
|
||||
const approve = findButton("Approve");
|
||||
expect(approve?.disabled).toBe(true);
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Only organization admins can approve or reject this.");
|
||||
expect(text).toContain(
|
||||
"Only people who can change DeployBot’s settings can approve or reject this.",
|
||||
);
|
||||
// The server's internal block reason is never shown.
|
||||
expect(text).not.toContain("agent_config:update");
|
||||
expect(findButton("Approve and save secret")).toBeUndefined();
|
||||
expect(findButton("Approve access")).toBeUndefined();
|
||||
expect(findButton("Reject")).toBeUndefined();
|
||||
expect(fieldByLabel("Name")?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("opens the secret confirm dialog with re-folder/rename and approves with overrides", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([makeSecretProposal()]);
|
||||
it("approves a new secret with an edited name and the default vault", async () => {
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve")));
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
await act(async () => findButton("Approve")?.click());
|
||||
await flushReact();
|
||||
|
||||
const nameInput = document.getElementById("approve-name") as HTMLInputElement | null;
|
||||
const folderInput = document.getElementById("approve-folder") as HTMLInputElement | null;
|
||||
expect(nameInput?.value).toBe("token");
|
||||
expect(folderInput?.value).toBe("dev/github");
|
||||
// Dialog restates the fingerprint, never a value.
|
||||
expect(document.body.textContent).toContain("sha256:abcdef0123");
|
||||
const nameInput = fieldByLabel("Name");
|
||||
expect(nameInput?.value).toBe("dev/github/token");
|
||||
// One usable vault: nothing to choose, so no picker.
|
||||
expect(fieldByLabel("Stored in")).toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
if (nameInput) setInputValue(nameInput, "client-secret");
|
||||
if (nameInput) setInputValue(nameInput, " dev/github/client-secret/ ");
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
await act(async () => findButton("Approve & create")?.click());
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal).toHaveBeenCalledWith("company-1", "prop-secret-1", {
|
||||
@@ -239,19 +286,113 @@ describe("ProposalsTab", () => {
|
||||
providerConfigId: "vault-local",
|
||||
},
|
||||
});
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Secret approved", tone: "success" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("won't approve a new secret without a name", async () => {
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
await act(async () => {
|
||||
const nameInput = fieldByLabel("Name");
|
||||
if (nameInput) setInputValue(nameInput, " ");
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(findButton("Approve and save secret")?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("lets the approver pick a vault and add a description", async () => {
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab("company-1", [
|
||||
providerConfigs[0],
|
||||
{ ...providerConfigs[0], id: "vault-team", displayName: "Team vault", isDefault: false },
|
||||
] as CompanySecretProviderConfig[]);
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
const vault = fieldByLabel<HTMLSelectElement>("Stored in");
|
||||
expect(vault?.value).toBe("vault-local");
|
||||
expect([...(vault?.options ?? [])].map((option) => option.textContent)).toEqual([
|
||||
"Local default",
|
||||
"Team vault",
|
||||
]);
|
||||
await act(async () => {
|
||||
if (vault) {
|
||||
vault.value = "vault-team";
|
||||
vault.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
|
||||
// Description stays out of the way until asked for.
|
||||
expect(fieldByLabel("Description")).toBeNull();
|
||||
await act(async () => findButton("Add a description")?.click());
|
||||
await flushReact();
|
||||
await act(async () => {
|
||||
const description = fieldByLabel("Description");
|
||||
if (description) setInputValue(description, "Token for the release bot");
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal).toHaveBeenCalledWith("company-1", "prop-secret-1", {
|
||||
overrides: {
|
||||
name: "dev/github/token",
|
||||
description: "Token for the release bot",
|
||||
providerConfigId: "vault-team",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("offers the only vault as a choice when it is not the default, so it can be picked", async () => {
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab("company-1", [
|
||||
{ ...providerConfigs[0], id: "vault-team", displayName: "Team vault", isDefault: false },
|
||||
] as CompanySecretProviderConfig[]);
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
const vault = fieldByLabel<HTMLSelectElement>("Stored in");
|
||||
expect([...(vault?.options ?? [])].map((option) => [option.value, option.textContent])).toEqual([
|
||||
["", "Paperclip"],
|
||||
["vault-team", "Team vault"],
|
||||
]);
|
||||
await act(async () => {
|
||||
if (vault) {
|
||||
vault.value = "vault-team";
|
||||
vault.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal.mock.calls[0][2].overrides.providerConfigId).toBe("vault-team");
|
||||
});
|
||||
|
||||
it("shows the agent's proposed description for review", async () => {
|
||||
mockProposals([makeSecretProposal({ proposedDescription: "CI token" })]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
expect(fieldByLabel("Description")?.value).toBe("CI token");
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
expect(mockSecretsApi.approveProposal.mock.calls[0][2].overrides.description).toBe("CI token");
|
||||
});
|
||||
|
||||
it("does not preselect a non-local default vault for secret approval", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([makeSecretProposal()]);
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab("company-1", [
|
||||
{ ...providerConfigs[0], id: "vault-aws", provider: "aws_secrets_manager" },
|
||||
{ ...providerConfigs[0], isDefault: false },
|
||||
] as CompanySecretProviderConfig[]);
|
||||
await waitForReact(() => Boolean(findButton("Approve")));
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
await act(async () => findButton("Approve")?.click());
|
||||
await flushReact();
|
||||
await act(async () => findButton("Approve & create")?.click());
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal).toHaveBeenCalledWith("company-1", "prop-secret-1", {
|
||||
@@ -263,22 +404,25 @@ describe("ProposalsTab", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces the cascade pairing and approves the binding with cascade", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([makeBindingProposal()]);
|
||||
it("approves access together with the new secret it depends on", async () => {
|
||||
mockProposals([makeBindingProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve")));
|
||||
await waitForReact(() => Boolean(findButton("Approve access and save secret")));
|
||||
|
||||
// Row shows target, delivery + env key, and the pending-secret pill.
|
||||
// Row says who gets what, how it is delivered, and that the secret is still new.
|
||||
const rowText = document.body.textContent ?? "";
|
||||
expect(rowText).toContain("DeployBot");
|
||||
expect(rowText).toContain("GITHUB_TOKEN");
|
||||
expect(rowText).toContain("Env var");
|
||||
expect(rowText).toContain("Proposed");
|
||||
expect(rowText).toContain("ClaudeCoder wants DeployBot to use dev/github/token");
|
||||
expect(rowText).toContain("DeployBot’s runs as the environment variable GITHUB_TOKEN");
|
||||
expect(rowText).toContain("hasn’t been saved yet");
|
||||
expect(rowText).not.toContain("env.GITHUB_TOKEN");
|
||||
|
||||
await act(async () => findButton("Approve")?.click());
|
||||
await flushReact();
|
||||
// Cascade is pre-checked because the secret is still a pending proposal.
|
||||
await act(async () => findButton("Approve secret & bind")?.click());
|
||||
// Saving the secret is pre-checked because access can't be approved without it.
|
||||
const checkbox = document.querySelector(
|
||||
'[aria-label="Also save the new secret"]',
|
||||
) as HTMLButtonElement | null;
|
||||
expect(checkbox?.getAttribute("aria-checked")).toBe("true");
|
||||
|
||||
await act(async () => findButton("Approve access and save secret")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal).toHaveBeenCalledWith("company-1", "prop-binding-1", {
|
||||
@@ -286,37 +430,178 @@ describe("ProposalsTab", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("requires a reason to reject", async () => {
|
||||
mockSecretsApi.listProposals.mockResolvedValue([makeSecretProposal()]);
|
||||
it("approves access to an existing secret without a cascade", async () => {
|
||||
mockSecretsApi.approveProposal.mockResolvedValue(makeBindingProposal({ status: "approved" }));
|
||||
mockProposals([
|
||||
makeBindingProposal({
|
||||
secretProposalId: null,
|
||||
secretProposalName: null,
|
||||
secretId: "secret-1",
|
||||
secretName: "dev/stripe/key",
|
||||
target: { id: "agent-coder", name: "ClaudeCoder", icon: "code" },
|
||||
configPath: "access.STRIPE",
|
||||
}),
|
||||
]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve access")));
|
||||
|
||||
const rowText = document.body.textContent ?? "";
|
||||
expect(rowText).toContain("ClaudeCoder wants to use dev/stripe/key");
|
||||
expect(rowText).toContain("could ask for it during a run as STRIPE");
|
||||
expect(document.querySelector('[aria-label="Also save the new secret"]')).toBeNull();
|
||||
|
||||
await act(async () => findButton("Approve access")?.click());
|
||||
await waitForReact(() => mockSecretsApi.approveProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.approveProposal.mock.calls[0]).toEqual([
|
||||
"company-1",
|
||||
"prop-binding-1",
|
||||
{ cascade: undefined },
|
||||
]);
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Access approved" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("tells the approver which environment variable a new secret will be read as", async () => {
|
||||
mockProposals([makeSecretProposal(), makeBindingProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
expect(document.body.textContent).toContain("Agents given access will read it as GITHUB_TOKEN.");
|
||||
// New secrets are listed before the access requests that depend on them.
|
||||
const rows = [...document.querySelectorAll('[data-testid^="proposal-"]')].map((row) =>
|
||||
row.getAttribute("data-testid"),
|
||||
);
|
||||
expect(rows).toEqual(["proposal-prop-secret-1", "proposal-prop-binding-1"]);
|
||||
});
|
||||
|
||||
it("requires a reason to reject, inline", async () => {
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Reject")));
|
||||
|
||||
await act(async () => findButton("Reject")?.click());
|
||||
await flushReact();
|
||||
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
expect(dialog).not.toBeNull();
|
||||
const dialogReject = () =>
|
||||
[...(dialog?.querySelectorAll("button") ?? [])].find(
|
||||
(b) => b.textContent?.trim() === "Reject",
|
||||
) as HTMLButtonElement | undefined;
|
||||
// Rejecting happens in the row, not in a dialog.
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
const reason = () =>
|
||||
document.querySelector('[aria-label="Reason for rejecting"]') as HTMLInputElement | null;
|
||||
expect(reason()).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("A reason is required. It is sent to ClaudeCoder.");
|
||||
expect(findButton("Approve and save secret")).toBeUndefined();
|
||||
|
||||
// The dialog's confirm button is disabled until a reason is typed.
|
||||
const reason = dialog?.querySelector("#reject-reason") as HTMLTextAreaElement | null;
|
||||
expect(reason).not.toBeNull();
|
||||
expect(dialogReject()?.disabled).toBe(true);
|
||||
// The confirm button is disabled until a reason is typed.
|
||||
expect(findButton("Reject")?.disabled).toBe(true);
|
||||
|
||||
// Cancel returns to the approve/reject footer without calling the API.
|
||||
await act(async () => findButton("Cancel")?.click());
|
||||
await flushReact();
|
||||
expect(reason()).toBeNull();
|
||||
expect(findButton("Approve and save secret")).toBeDefined();
|
||||
await act(async () => findButton("Reject")?.click());
|
||||
await flushReact();
|
||||
|
||||
await act(async () => {
|
||||
if (reason) setInputValue(reason, "Not needed for this task.");
|
||||
const input = reason();
|
||||
if (input) setInputValue(input, " Not needed for this task. ");
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(dialogReject()?.disabled).toBe(false);
|
||||
await act(async () => dialogReject()?.click());
|
||||
expect(findButton("Reject")?.disabled).toBe(false);
|
||||
await act(async () => findButton("Reject")?.click());
|
||||
await waitForReact(() => mockSecretsApi.rejectProposal.mock.calls.length > 0);
|
||||
|
||||
expect(mockSecretsApi.rejectProposal).toHaveBeenCalledWith("company-1", "prop-secret-1", {
|
||||
reason: "Not needed for this task.",
|
||||
});
|
||||
await waitForReact(() => mockPushToast.mock.calls.length > 0);
|
||||
expect(mockPushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Proposal rejected", tone: "info" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows a failed decision in the row and keeps the request open", async () => {
|
||||
mockSecretsApi.approveProposal.mockRejectedValue(new Error("A secret with this name already exists."));
|
||||
mockProposals([makeSecretProposal()]);
|
||||
await renderTab();
|
||||
await waitForReact(() => Boolean(findButton("Approve and save secret")));
|
||||
|
||||
await act(async () => findButton("Approve and save secret")?.click());
|
||||
await waitForReact(() => Boolean(document.querySelector('[role="alert"]')));
|
||||
|
||||
expect(document.querySelector('[role="alert"]')?.textContent).toBeTruthy();
|
||||
expect(findButton("Approve and save secret")?.disabled).toBe(false);
|
||||
expect(mockPushToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the empty state when nothing is waiting or decided", async () => {
|
||||
mockProposals([]);
|
||||
await renderTab();
|
||||
await waitForReact(() => document.body.textContent?.includes("Nothing to review") ?? false);
|
||||
|
||||
expect(document.body.textContent).toContain(
|
||||
"When an agent asks to save a secret or to use one, the request appears here.",
|
||||
);
|
||||
});
|
||||
|
||||
it("lists recent decisions under the pending requests, newest first", async () => {
|
||||
mockProposals([
|
||||
makeSecretProposal({
|
||||
id: "done-approved",
|
||||
status: "approved",
|
||||
proposedName: "dev/slack/token",
|
||||
viewerCanApprove: false,
|
||||
resolvedByUserId: "user-raw-id-123",
|
||||
resolvedAt: new Date(Date.now() - 2 * 3600_000).toISOString(),
|
||||
}),
|
||||
makeBindingProposal({
|
||||
id: "done-rejected",
|
||||
status: "rejected",
|
||||
viewerCanApprove: false,
|
||||
resolvedByUserId: "user-raw-id-123",
|
||||
resolvedAt: new Date(Date.now() - 3600_000).toISOString(),
|
||||
resolutionReason: "Use the shared connection.",
|
||||
}),
|
||||
makeSecretProposal({
|
||||
id: "done-expired",
|
||||
status: "expired",
|
||||
proposedName: "dev/old/key",
|
||||
viewerCanApprove: false,
|
||||
resolvedAt: new Date(Date.now() - 3 * 24 * 3600_000).toISOString(),
|
||||
}),
|
||||
]);
|
||||
await renderTab();
|
||||
await waitForReact(() => document.body.textContent?.includes("Recently decided") ?? false);
|
||||
|
||||
expect(mockSecretsApi.listProposals.mock.calls.map((call) => call[1]).sort()).toEqual([
|
||||
"approved",
|
||||
"expired",
|
||||
"pending",
|
||||
"rejected",
|
||||
]);
|
||||
// Decided lists are asked for by decision time, so a fresh decision on an old request is in the page.
|
||||
expect(
|
||||
mockSecretsApi.listProposals.mock.calls.filter((call) => call[1] !== "pending").map((call) => call[2]),
|
||||
).toEqual([
|
||||
{ order: "resolved", limit: 10 },
|
||||
{ order: "resolved", limit: 10 },
|
||||
{ order: "resolved", limit: 10 },
|
||||
]);
|
||||
expect(document.body.textContent).toContain("You’re caught up. No requests are waiting.");
|
||||
const decided = [
|
||||
...document.querySelectorAll('section[aria-label="Recently decided"] li'),
|
||||
].map((row) => row.textContent);
|
||||
expect(decided).toHaveLength(3);
|
||||
expect(decided[0]).toContain("ClaudeCoder wants DeployBot to use dev/github/token");
|
||||
expect(decided[0]).toContain("Rejected · 1h ago");
|
||||
expect(decided[1]).toContain("ClaudeCoder wants to save a new secret, dev/slack/token");
|
||||
expect(decided[1]).toContain("Approved · 2h ago");
|
||||
expect(decided[2]).toContain("Expired · 3d ago");
|
||||
// Decided rows are read-only and never show a raw user id.
|
||||
expect(document.body.textContent).not.toContain("user-raw-id-123");
|
||||
expect(findButton("Reject")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,142 +1,385 @@
|
||||
import { useMemo } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useId, useMemo, useState } from "react";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
ArrowRight,
|
||||
ExternalLink,
|
||||
Inbox,
|
||||
KeyRound,
|
||||
Link2,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import type { CompanySecretProviderConfig, SecretProposalView } from "@paperclipai/shared";
|
||||
import { Inbox, Loader2 } from "lucide-react";
|
||||
import type {
|
||||
CompanySecretProviderConfig,
|
||||
SecretProposalStatus,
|
||||
SecretProposalView,
|
||||
} from "@paperclipai/shared";
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NativeSelect } from "@/components/ui/select";
|
||||
import { secretsApi } from "../../api/secrets";
|
||||
import { queryKeys } from "../../lib/queryKeys";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { deliveryModeForConfigPath } from "../../lib/secret-delivery";
|
||||
import { cn, relativeTime } from "../../lib/utils";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { SecretPathName } from "./SecretPathName";
|
||||
import {
|
||||
AgentRefChip,
|
||||
DeliveryBadge,
|
||||
FingerprintChip,
|
||||
ProposalActions,
|
||||
ProposalJustification,
|
||||
ProposedBadge,
|
||||
bindingEnvKey,
|
||||
bindingSecretLabel,
|
||||
useProposalReview,
|
||||
useProposalDecision,
|
||||
} from "./proposal-review";
|
||||
|
||||
/** ISO expiry → "expires in 12d" / "expires in 5h" / "expired". */
|
||||
function expiryLabel(expiresAt: string): { text: string; urgent: boolean } {
|
||||
const DECIDED_STATUSES = ["approved", "rejected", "expired"] as const satisfies readonly SecretProposalStatus[];
|
||||
const DECIDED_LIMIT = 10;
|
||||
|
||||
/** ISO expiry → "Expires in 12d" / "Expires in 5h" / "Expired". */
|
||||
function expiryLabel(expiresAt: string): { text: string; urgent: boolean } | null {
|
||||
const ms = new Date(expiresAt).getTime() - Date.now();
|
||||
if (Number.isNaN(ms)) return { text: "no expiry", urgent: false };
|
||||
if (ms <= 0) return { text: "expired", urgent: true };
|
||||
if (Number.isNaN(ms)) return null;
|
||||
if (ms <= 0) return { text: "Expired", urgent: true };
|
||||
const hours = Math.floor(ms / 3_600_000);
|
||||
if (hours < 24) return { text: `expires in ${hours}h`, urgent: true };
|
||||
if (hours < 24) return { text: `Expires in ${hours}h`, urgent: true };
|
||||
const days = Math.floor(hours / 24);
|
||||
return { text: `expires in ${days}d`, urgent: days <= 2 };
|
||||
return { text: `Expires in ${days}d`, urgent: days <= 2 };
|
||||
}
|
||||
|
||||
function ProposalRow({
|
||||
/** Trim a typed secret name and drop stray leading/trailing slashes. */
|
||||
function normalizeSecretName(value: string): string {
|
||||
return value.trim().replace(/^\/+|\/+$/g, "");
|
||||
}
|
||||
|
||||
/** "<Agent> wants to save a new secret, <Name>" and its access equivalents. */
|
||||
function RequestSentence({ proposal }: { proposal: SecretProposalView }) {
|
||||
const proposer = <span className="font-medium">{proposal.proposedBy.name}</span>;
|
||||
if (proposal.kind === "secret") {
|
||||
return (
|
||||
<>
|
||||
{proposer} wants to save a new secret,{" "}
|
||||
<span className="break-all font-medium">{proposal.proposedName ?? "unnamed"}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const secret = <span className="break-all font-medium">{bindingSecretLabel(proposal).name}</span>;
|
||||
if (proposal.target && proposal.target.id !== proposal.proposedBy.id) {
|
||||
return (
|
||||
<>
|
||||
{proposer} wants <span className="font-medium">{proposal.target.name}</span> to use {secret}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{proposer} wants to use {secret}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** One line saying how an approved secret would reach the agent. */
|
||||
function DeliveryLine({ proposal }: { proposal: SecretProposalView }) {
|
||||
const mode = deliveryModeForConfigPath(proposal.configPath);
|
||||
const alias = bindingEnvKey(proposal);
|
||||
const code = <code className="font-mono text-foreground">{alias}</code>;
|
||||
const agent = proposal.target?.name ?? "the agent";
|
||||
return (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{mode === "env" ? (
|
||||
<>It would be available in {agent}’s runs as the environment variable {code}.</>
|
||||
) : mode === "api" ? (
|
||||
<>{agent} could ask for it during a run as {code}. It is never written to the environment.</>
|
||||
) : (
|
||||
<>It would be provided through {agent}’s settings.</>
|
||||
)}{" "}
|
||||
Access is granted with your permissions.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingProposal({
|
||||
proposal,
|
||||
onApprove,
|
||||
onReject,
|
||||
disabled,
|
||||
companyId,
|
||||
vaults,
|
||||
readAs,
|
||||
}: {
|
||||
proposal: SecretProposalView;
|
||||
onApprove: (p: SecretProposalView) => void;
|
||||
onReject: (p: SecretProposalView) => void;
|
||||
disabled: boolean;
|
||||
companyId: string;
|
||||
/** Vaults a new secret can be stored in. */
|
||||
vaults: CompanySecretProviderConfig[];
|
||||
/** Environment variable names that pending access requests would expose this new secret as. */
|
||||
readAs: string[];
|
||||
}) {
|
||||
const fieldId = useId();
|
||||
const isSecret = proposal.kind === "secret";
|
||||
const canDecide = proposal.viewerCanApprove;
|
||||
const defaultVaultId = vaults.find((vault) => vault.isDefault)?.id ?? "";
|
||||
|
||||
const [name, setName] = useState(proposal.proposedName ?? "");
|
||||
const [description, setDescription] = useState(proposal.proposedDescription ?? "");
|
||||
const [editingDescription, setEditingDescription] = useState(Boolean(proposal.proposedDescription));
|
||||
// "" stores the secret in the default vault.
|
||||
const [vaultId, setVaultId] = useState(defaultVaultId);
|
||||
// Access to a secret that is itself still waiting can only be approved together with it.
|
||||
const needsSecret = Boolean(proposal.secretProposalId);
|
||||
const [alsoSaveSecret, setAlsoSaveSecret] = useState(needsSecret);
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
const [reason, setReason] = useState("");
|
||||
|
||||
const decision = useProposalDecision(companyId);
|
||||
const expiry = expiryLabel(proposal.expiresAt);
|
||||
const secret = bindingSecretLabel(proposal);
|
||||
const envKey = bindingEnvKey(proposal);
|
||||
const secretName = normalizeSecretName(name);
|
||||
const secretLabel = bindingSecretLabel(proposal).name;
|
||||
|
||||
const approve = () => {
|
||||
decision.clearError();
|
||||
if (isSecret) {
|
||||
decision.approve(proposal, {
|
||||
overrides: {
|
||||
name: secretName,
|
||||
description: description.trim() || null,
|
||||
providerConfigId: vaultId || null,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
decision.approve(proposal, { cascade: alsoSaveSecret || undefined });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-border bg-card p-3 sm:flex-row sm:items-start sm:gap-3">
|
||||
<span
|
||||
className="mt-0.5 inline-flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-muted/40 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{isSecret ? <KeyRound className="size-3.5" /> : <Link2 className="size-3.5" />}
|
||||
</span>
|
||||
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
{/* Headline */}
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
|
||||
{isSecret ? (
|
||||
<SecretPathName name={proposal.proposedName ?? "—"} className="text-sm" />
|
||||
) : (
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-1.5 text-sm">
|
||||
{proposal.target ? (
|
||||
<AgentRefChip agent={proposal.target} className="font-medium" />
|
||||
) : (
|
||||
<span className="text-muted-foreground">agent</span>
|
||||
)}
|
||||
<DeliveryBadge configPath={proposal.configPath} />
|
||||
<code className="font-mono text-xs">{envKey || proposal.configPath}</code>
|
||||
<ArrowRight className="size-3 text-muted-foreground" />
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<KeyRound className="size-3 text-muted-foreground" />
|
||||
<span className="font-medium">{secret.name}</span>
|
||||
{secret.pending ? <ProposedBadge /> : null}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<li className="flex flex-col gap-3 px-3 py-4" data-testid={`proposal-${proposal.id}`}>
|
||||
<div className="flex items-start gap-3">
|
||||
<AgentAvatar agent={proposal.proposedBy} size={32} />
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<p className="text-sm">
|
||||
<RequestSentence proposal={proposal} />
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{proposal.originIssue ? (
|
||||
<>
|
||||
While working on{" "}
|
||||
<Link
|
||||
to={`/issues/${proposal.originIssue.key}`}
|
||||
className="hover:text-foreground hover:underline"
|
||||
>
|
||||
“{proposal.originIssue.title}”
|
||||
</Link>
|
||||
{" · "}
|
||||
</>
|
||||
) : null}
|
||||
{relativeTime(proposal.createdAt)}
|
||||
{expiry ? (
|
||||
<>
|
||||
{" · "}
|
||||
<span className={cn(expiry.urgent && "font-medium text-foreground")}>{expiry.text}</span>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Provenance meta */}
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
by <AgentRefChip agent={proposal.proposedBy} className="font-medium text-foreground" />
|
||||
</span>
|
||||
{proposal.originIssue ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<Link
|
||||
to={`/issues/${proposal.originIssue.key}`}
|
||||
className="inline-flex items-center gap-1 font-mono hover:text-foreground hover:underline"
|
||||
title={proposal.originIssue.title}
|
||||
>
|
||||
{proposal.originIssue.key}
|
||||
<ExternalLink className="size-3" />
|
||||
</Link>
|
||||
</>
|
||||
) : null}
|
||||
{isSecret ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<FingerprintChip
|
||||
fingerprint={proposal.valueFingerprintSha256}
|
||||
length={proposal.valueLength}
|
||||
<ProposalJustification variant="quote" justification={proposal.justification} />
|
||||
|
||||
{isSecret ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<label
|
||||
htmlFor={`${fieldId}-name`}
|
||||
className="flex min-w-48 flex-1 flex-col gap-1.5 text-sm font-medium"
|
||||
>
|
||||
Name
|
||||
<Input
|
||||
id={`${fieldId}-name`}
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
disabled={!canDecide || decision.isBusy}
|
||||
aria-invalid={!secretName}
|
||||
className="font-mono"
|
||||
/>
|
||||
</>
|
||||
</label>
|
||||
{vaults.length + (defaultVaultId ? 0 : 1) > 1 ? (
|
||||
<label
|
||||
htmlFor={`${fieldId}-vault`}
|
||||
className="flex flex-col gap-1.5 text-sm font-medium"
|
||||
>
|
||||
Stored in
|
||||
<NativeSelect
|
||||
id={`${fieldId}-vault`}
|
||||
value={vaultId}
|
||||
onChange={(event) => setVaultId(event.target.value)}
|
||||
disabled={!canDecide || decision.isBusy}
|
||||
className="font-normal"
|
||||
>
|
||||
{defaultVaultId ? null : <option value="">Paperclip</option>}
|
||||
{vaults.map((vault) => (
|
||||
<option key={vault.id} value={vault.id}>
|
||||
{vault.displayName}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{editingDescription ? (
|
||||
<label
|
||||
htmlFor={`${fieldId}-description`}
|
||||
className="flex flex-col gap-1.5 text-sm font-medium"
|
||||
>
|
||||
Description
|
||||
<Input
|
||||
id={`${fieldId}-description`}
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
disabled={!canDecide || decision.isBusy}
|
||||
placeholder="Optional"
|
||||
className="font-normal"
|
||||
/>
|
||||
</label>
|
||||
) : canDecide ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
className="h-auto self-start p-0 text-xs text-muted-foreground"
|
||||
onClick={() => setEditingDescription(true)}
|
||||
>
|
||||
Add a description
|
||||
</Button>
|
||||
) : null}
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className={cn(expiry.urgent && "text-amber-600 dark:text-amber-400")}>
|
||||
{expiry.text}
|
||||
</span>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{readAs.length > 0 ? (
|
||||
<>
|
||||
Agents given access will read it as{" "}
|
||||
{readAs.map((key, index) => (
|
||||
<span key={key}>
|
||||
{index > 0 ? ", " : null}
|
||||
<code className="font-mono text-foreground">{key}</code>
|
||||
</span>
|
||||
))}
|
||||
.{" "}
|
||||
</>
|
||||
) : null}
|
||||
The value stays hidden and is saved exactly as the agent recorded it. Its fingerprint
|
||||
lets you confirm it with the agent:{" "}
|
||||
<FingerprintChip
|
||||
fingerprint={proposal.valueFingerprintSha256}
|
||||
length={proposal.valueLength}
|
||||
className="align-middle text-foreground"
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<DeliveryLine proposal={proposal} />
|
||||
{needsSecret ? (
|
||||
<label className="flex items-start gap-2 text-xs text-muted-foreground">
|
||||
<Checkbox
|
||||
checked={alsoSaveSecret}
|
||||
onCheckedChange={(checked) => setAlsoSaveSecret(checked === true)}
|
||||
disabled={!canDecide || decision.isBusy}
|
||||
aria-label="Also save the new secret"
|
||||
/>
|
||||
<span>
|
||||
<span className="font-medium text-foreground">{secretLabel}</span> is a new secret
|
||||
that hasn’t been saved yet. Save it as part of this approval. Access can’t be
|
||||
approved without it.
|
||||
</span>
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Justification (agent-authored — framed as an untrusted claim). */}
|
||||
<ProposalJustification justification={proposal.justification} />
|
||||
</div>
|
||||
{decision.error ? (
|
||||
<p className="text-xs text-destructive" role="alert">
|
||||
{decision.error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="shrink-0 sm:pt-0.5">
|
||||
<ProposalActions
|
||||
proposal={proposal}
|
||||
onApprove={onApprove}
|
||||
onReject={onReject}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!canDecide ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isSecret
|
||||
? "Only organization admins can approve or reject this."
|
||||
: `Only people who can change ${proposal.target?.name ?? "this agent"}’s settings can approve or reject this.`}
|
||||
</p>
|
||||
) : rejecting ? (
|
||||
<form
|
||||
className="flex flex-col gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!reason.trim()) return;
|
||||
decision.clearError();
|
||||
decision.reject(proposal, reason);
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
aria-label="Reason for rejecting"
|
||||
autoFocus
|
||||
required
|
||||
className="min-w-48 flex-1"
|
||||
placeholder="Tell the agent why"
|
||||
value={reason}
|
||||
onChange={(event) => setReason(event.target.value)}
|
||||
disabled={decision.isBusy}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={decision.isBusy}
|
||||
onClick={() => {
|
||||
setRejecting(false);
|
||||
setReason("");
|
||||
decision.clearError();
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={decision.isBusy || !reason.trim()}
|
||||
>
|
||||
{decision.rejecting ? "Rejecting…" : "Reject"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A reason is required. It is sent to {proposal.proposedBy.name}.
|
||||
{isSecret ? " Requests to use this secret are rejected too." : null}
|
||||
</p>
|
||||
</form>
|
||||
) : (
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={decision.isBusy}
|
||||
onClick={() => {
|
||||
decision.clearError();
|
||||
setRejecting(true);
|
||||
}}
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
<Button size="sm" disabled={decision.isBusy || (isSecret && !secretName)} onClick={approve}>
|
||||
{decision.approving
|
||||
? "Approving…"
|
||||
: isSecret
|
||||
? "Approve and save secret"
|
||||
: alsoSaveSecret
|
||||
? "Approve access and save secret"
|
||||
: "Approve access"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function decidedLabel(proposal: SecretProposalView): string {
|
||||
const outcome =
|
||||
proposal.status === "approved" ? "Approved" : proposal.status === "rejected" ? "Rejected" : "Expired";
|
||||
const at = proposal.resolvedAt ?? proposal.createdAt;
|
||||
return `${outcome} · ${relativeTime(at)}`;
|
||||
}
|
||||
|
||||
export function ProposalsTab({
|
||||
companyId,
|
||||
providerConfigs,
|
||||
@@ -149,14 +392,22 @@ export function ProposalsTab({
|
||||
queryFn: () => secretsApi.listProposals(companyId, "pending"),
|
||||
enabled: Boolean(companyId),
|
||||
});
|
||||
const decidedQueries = useQueries({
|
||||
queries: DECIDED_STATUSES.map((status) => ({
|
||||
queryKey: [...queryKeys.secrets.proposals(companyId, status), "recent"] as const,
|
||||
// Ordered by decision time on the server, so the newest decisions are
|
||||
// in the page even when the request itself is old.
|
||||
queryFn: () => secretsApi.listProposals(companyId, status, { order: "resolved", limit: DECIDED_LIMIT }),
|
||||
enabled: Boolean(companyId),
|
||||
})),
|
||||
});
|
||||
|
||||
const proposalsView = useQueryView(proposalsQuery);
|
||||
const review = useProposalReview(companyId, providerConfigs);
|
||||
const proposals = proposalsQuery.data ?? EMPTY_PROPOSALS;
|
||||
|
||||
// Secret proposals first, then bindings — an approver usually lands the
|
||||
// secret before (or alongside) the bindings that depend on it.
|
||||
const sorted = useMemo(
|
||||
// New secrets first, then access — an approver usually saves the secret
|
||||
// before (or alongside) the access requests that depend on it.
|
||||
const pending = useMemo(
|
||||
() =>
|
||||
[...proposals].sort((a, b) => {
|
||||
if (a.kind !== b.kind) return a.kind === "secret" ? -1 : 1;
|
||||
@@ -165,12 +416,30 @@ export function ProposalsTab({
|
||||
[proposals],
|
||||
);
|
||||
|
||||
const decidedLoading = decidedQueries.some((query) => query.isPending);
|
||||
const decidedFailed = decidedQueries.some((query) => query.isError);
|
||||
const decided = decidedQueries
|
||||
.flatMap((query, index) =>
|
||||
(query.data ?? []).filter((row) => row.status === DECIDED_STATUSES[index]),
|
||||
)
|
||||
.sort((a, b) => (b.resolvedAt ?? b.createdAt).localeCompare(a.resolvedAt ?? a.createdAt))
|
||||
.slice(0, DECIDED_LIMIT);
|
||||
|
||||
// A new secret can only be stored in an encrypted vault Paperclip manages.
|
||||
const vaults = useMemo(
|
||||
() =>
|
||||
providerConfigs.filter(
|
||||
(config) => config.provider === "local_encrypted" && config.status !== "disabled",
|
||||
),
|
||||
[providerConfigs],
|
||||
);
|
||||
|
||||
if (proposalsView.kind === "error") {
|
||||
return (
|
||||
<div className="py-4">
|
||||
<QueryErrorState
|
||||
error={proposalsQuery.error}
|
||||
action="load proposals"
|
||||
action="load requests"
|
||||
onRetry={proposalsView.retry}
|
||||
retrying={proposalsView.isFetching}
|
||||
/>
|
||||
@@ -178,42 +447,99 @@ export function ProposalsTab({
|
||||
);
|
||||
}
|
||||
|
||||
if (proposalsQuery.isPending || proposalsView.kind === "reconnecting") {
|
||||
if (
|
||||
proposalsQuery.isPending ||
|
||||
proposalsView.kind === "reconnecting" ||
|
||||
(pending.length === 0 && decidedLoading)
|
||||
) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading proposals…
|
||||
<Loader2 className="size-4 animate-spin" /> Loading requests…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (sorted.length === 0) {
|
||||
if (pending.length === 0 && decided.length === 0 && !decidedFailed) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={Inbox}
|
||||
title="No pending proposals"
|
||||
message="When an agent proposes a secret or an access binding, it shows up here for review."
|
||||
title="Nothing to review"
|
||||
message="When an agent asks to save a secret or to use one, the request appears here."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Agents propose credentials and access bindings; you approve or reject them here. Proposed
|
||||
values are never shown — only a fingerprint and length.
|
||||
</p>
|
||||
{sorted.map((proposal) => (
|
||||
<ProposalRow
|
||||
key={proposal.id}
|
||||
proposal={proposal}
|
||||
onApprove={review.requestApprove}
|
||||
onReject={review.requestReject}
|
||||
disabled={review.isBusy}
|
||||
/>
|
||||
))}
|
||||
{review.dialogs}
|
||||
<div className="flex flex-col gap-6">
|
||||
<section aria-label="Waiting for a decision" className="flex flex-col gap-2">
|
||||
<p className="max-w-xl text-sm text-muted-foreground">
|
||||
Agents ask here before they save a secret or use one they don’t have. Nothing changes
|
||||
until you approve.
|
||||
</p>
|
||||
{pending.length > 0 ? (
|
||||
<ul className="divide-y divide-border border-y border-border">
|
||||
{pending.map((proposal) => (
|
||||
<PendingProposal
|
||||
key={proposal.id}
|
||||
proposal={proposal}
|
||||
companyId={companyId}
|
||||
vaults={vaults}
|
||||
readAs={
|
||||
proposal.kind === "secret"
|
||||
? [
|
||||
...new Set(
|
||||
pending
|
||||
.filter(
|
||||
(other) =>
|
||||
other.secretProposalId === proposal.id &&
|
||||
deliveryModeForConfigPath(other.configPath) === "env",
|
||||
)
|
||||
.map(bindingEnvKey)
|
||||
.filter(Boolean),
|
||||
),
|
||||
]
|
||||
: EMPTY_KEYS
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="border-y border-border px-3 py-4 text-sm text-muted-foreground">
|
||||
You’re caught up. No requests are waiting.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{decided.length > 0 || decidedFailed ? (
|
||||
<section aria-label="Recently decided" className="flex flex-col gap-2">
|
||||
<h2 className="text-xs font-medium text-muted-foreground">Recently decided</h2>
|
||||
{decided.length > 0 ? (
|
||||
<ul className="divide-y divide-border border-y border-border">
|
||||
{decided.map((proposal) => (
|
||||
<li
|
||||
key={proposal.id}
|
||||
className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 px-3 py-2.5 text-sm"
|
||||
>
|
||||
<span className="min-w-0 text-muted-foreground">
|
||||
<RequestSentence proposal={proposal} />
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{decidedLabel(proposal)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{decidedFailed ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Some earlier decisions couldn’t be loaded. Reload the page to try again.
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const EMPTY_PROPOSALS: SecretProposalView[] = [];
|
||||
const EMPTY_KEYS: string[] = [];
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { CompanySecret, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -15,14 +16,14 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { secretsApi } from "../../api/secrets";
|
||||
import { queryKeys } from "../../lib/queryKeys";
|
||||
import { useToastActions } from "../../context/ToastContext";
|
||||
import { UserSecretChip } from "./user-secret-presentation";
|
||||
import { describeError } from "@/api/errors";
|
||||
|
||||
// Hides the pasted value like a password field while keeping a multi-line box.
|
||||
|
||||
/**
|
||||
* Shared "set my value" dialog for a user-secret definition. Used both from the
|
||||
* Secrets → My secrets tab and from the missing-required-secret warning surfaces
|
||||
* (task run / issue failure), so a user can satisfy a required secret from either
|
||||
* place with identical behavior.
|
||||
* Shared dialog where a person adds or replaces their own value for a secret.
|
||||
* Used both from the Secrets → My secrets tab and from the missing-secret
|
||||
* warning surfaces (task run / task failure), so both behave identically.
|
||||
*/
|
||||
export function SetMyUserSecretDialog({
|
||||
companyId,
|
||||
@@ -44,6 +45,8 @@ export function SetMyUserSecretDialog({
|
||||
const [value, setValue] = useState("");
|
||||
const [externalRef, setExternalRef] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showValue, setShowValue] = useState(false);
|
||||
const fieldId = useId();
|
||||
|
||||
const isExternal = definition?.managedMode === "external_reference";
|
||||
|
||||
@@ -52,6 +55,7 @@ export function SetMyUserSecretDialog({
|
||||
setValue("");
|
||||
setExternalRef("");
|
||||
setError(null);
|
||||
setShowValue(false);
|
||||
}
|
||||
}, [open, definition?.id]);
|
||||
|
||||
@@ -75,7 +79,7 @@ export function SetMyUserSecretDialog({
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.secrets.myUserSecrets(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.secrets.userDefinitions(companyId) });
|
||||
pushToast({
|
||||
title: existingSecret ? "Value updated" : "Value saved",
|
||||
title: existingSecret ? "Your value was replaced" : "Your value was saved",
|
||||
body: definition?.name,
|
||||
tone: "success",
|
||||
});
|
||||
@@ -95,73 +99,92 @@ export function SetMyUserSecretDialog({
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{existingSecret ? "Update your value" : "Set your value"}
|
||||
<UserSecretChip />
|
||||
<DialogTitle>
|
||||
{existingSecret ? "Replace your value" : "Set your value"}
|
||||
{definition ? ` for ${definition.name}` : ""}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{definition ? (
|
||||
<>
|
||||
This value is yours only. It is used when you are the user responsible for a run that
|
||||
needs <span className="font-mono">{definition.key}</span>.
|
||||
</>
|
||||
) : null}
|
||||
Only you provide this value. Agents use it when they work for you.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{definition ? (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-md border border-border bg-muted/20 p-3 text-xs">
|
||||
<div className="font-medium text-foreground">{definition.name}</div>
|
||||
{definition.description ? (
|
||||
<p className="mt-1 text-muted-foreground">{definition.description}</p>
|
||||
) : null}
|
||||
{definition.usageGuidance ? (
|
||||
<p className="mt-1 text-muted-foreground">{definition.usageGuidance}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
{definition.description || definition.usageGuidance ? (
|
||||
<div className="flex flex-col gap-1 text-xs text-muted-foreground">
|
||||
{definition.description ? <p>{definition.description}</p> : null}
|
||||
{definition.usageGuidance ? <p>{definition.usageGuidance}</p> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isExternal ? (
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-foreground">External reference</label>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs font-medium text-foreground" htmlFor={fieldId}>
|
||||
Where your value is stored
|
||||
</label>
|
||||
<Input
|
||||
id={fieldId}
|
||||
value={externalRef}
|
||||
onChange={(event) => setExternalRef(event.target.value)}
|
||||
placeholder="provider reference or ARN"
|
||||
placeholder="Reference or ARN"
|
||||
className="font-mono text-sm"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
autoFocus
|
||||
/>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground">
|
||||
Points at your own credential in the configured provider. Paperclip stores the
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Points to your own secret in your organization's vault. Paperclip saves the
|
||||
reference, not the value.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-foreground">Your value</label>
|
||||
<Textarea
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
placeholder="Paste your token or credential"
|
||||
className="font-mono text-sm min-h-(--sz-80px)"
|
||||
autoFocus
|
||||
/>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground">
|
||||
Stored encrypted. Never shown back to anyone, including admins.
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs font-medium text-foreground" htmlFor={fieldId}>
|
||||
Your value
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Textarea
|
||||
id={fieldId}
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
placeholder="Paste your token or key"
|
||||
className={`min-h-(--sz-80px) pr-11 font-mono text-sm${showValue ? "" : " secret-value-masked"}`}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-2 top-2"
|
||||
aria-label={showValue ? "Hide value" : "Show value"}
|
||||
aria-pressed={showValue}
|
||||
onClick={() => setShowValue((current) => !current)}
|
||||
>
|
||||
{showValue ? <EyeOff aria-hidden /> : <Eye aria-hidden />}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Encrypted when saved. After that it can be replaced, never viewed.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error ? <p className="text-xs text-destructive">{error}</p> : null}
|
||||
{error ? (
|
||||
<p className="text-xs text-destructive" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogFooter className="flex-row items-center justify-between sm:justify-between">
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={save.isPending}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => save.mutate()} disabled={!canSave || save.isPending}>
|
||||
{save.isPending ? "Saving…" : existingSecret ? "Update value" : "Save value"}
|
||||
{save.isPending ? "Saving…" : existingSecret ? "Replace value" : "Save value"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSecretAgentUsage } from "./agent-secret-access";
|
||||
|
||||
function agent(id: string, adapterConfig: Record<string, unknown>, status = "active"): Agent {
|
||||
return { id, name: id, status, adapterConfig } as unknown as Agent;
|
||||
}
|
||||
|
||||
describe("buildSecretAgentUsage", () => {
|
||||
it("indexes agents by the secrets and user secrets they hold", () => {
|
||||
const builder = agent("builder", {
|
||||
env: {
|
||||
GITHUB_TOKEN: { type: "secret_ref", secretId: "secret-github" },
|
||||
PLAIN: { type: "plain", value: "x" },
|
||||
PERSONAL: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN" },
|
||||
},
|
||||
"access.deploy": { type: "secret_ref", secretId: "secret-deploy" },
|
||||
});
|
||||
const reviewer = agent("reviewer", { env: { GH: { type: "secret_ref", secretId: "secret-github" } } });
|
||||
const gone = agent("gone", { env: { GH: { type: "secret_ref", secretId: "secret-github" } } }, "terminated");
|
||||
|
||||
const usage = buildSecretAgentUsage([builder, reviewer, gone]);
|
||||
|
||||
expect(usage.bySecretId.get("secret-github")?.map((entry) => entry.id)).toEqual(["builder", "reviewer"]);
|
||||
expect(usage.bySecretId.get("secret-deploy")?.map((entry) => entry.id)).toEqual(["builder"]);
|
||||
expect(usage.byUserSecretKey.get("PERSONAL_GH_TOKEN")?.map((entry) => entry.id)).toEqual(["builder"]);
|
||||
});
|
||||
|
||||
it("lists an agent once per secret even when it binds it under two names", () => {
|
||||
const usage = buildSecretAgentUsage([
|
||||
agent("builder", {
|
||||
env: { A: { type: "secret_ref", secretId: "secret-1" }, B: { type: "secret_ref", secretId: "secret-1" } },
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(usage.bySecretId.get("secret-1")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reads each binding a fixed number of times on a large organization", () => {
|
||||
const AGENTS = 1000;
|
||||
const BINDINGS_PER_AGENT = 30;
|
||||
const SECRETS = 400;
|
||||
const totalBindings = AGENTS * BINDINGS_PER_AGENT;
|
||||
// The index may look at a binding's type more than once, but never once per other agent or secret.
|
||||
const limit = totalBindings * 4;
|
||||
let reads = 0;
|
||||
const countedBinding = (secretId: string) => ({
|
||||
get type() {
|
||||
reads += 1;
|
||||
if (reads > limit) throw new Error(`read binding types ${reads} times; the limit is ${limit}`);
|
||||
return "secret_ref";
|
||||
},
|
||||
secretId,
|
||||
});
|
||||
const agents = Array.from({ length: AGENTS }, (_, agentIndex) =>
|
||||
agent(`agent-${agentIndex}`, {
|
||||
env: Object.fromEntries(
|
||||
Array.from({ length: BINDINGS_PER_AGENT }, (_, bindingIndex) => [
|
||||
`VAR_${bindingIndex}`,
|
||||
countedBinding(`secret-${(agentIndex * BINDINGS_PER_AGENT + bindingIndex) % SECRETS}`),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const usage = buildSecretAgentUsage(agents);
|
||||
|
||||
expect(usage.bySecretId.size).toBe(SECRETS);
|
||||
expect([...usage.bySecretId.values()].reduce((sum, list) => sum + list.length, 0)).toBe(totalBindings);
|
||||
expect(reads).toBeGreaterThanOrEqual(totalBindings);
|
||||
expect(reads).toBeLessThanOrEqual(limit);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Agent, CompanySecret, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { agentsApi } from "../../api/agents";
|
||||
import { AGENT_ACCESS_CONFIG_PATH_PREFIX } from "../../lib/secret-delivery";
|
||||
|
||||
export type AgentAccessReference =
|
||||
| { kind: "company"; secret: CompanySecret }
|
||||
| { kind: "user"; definition: UserSecretDefinition };
|
||||
|
||||
export const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
|
||||
type BindingRecord = Record<string, unknown>;
|
||||
|
||||
function isBinding(value: unknown): value is BindingRecord {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function bindingMatches(binding: BindingRecord, reference: AgentAccessReference): boolean {
|
||||
return reference.kind === "company"
|
||||
? binding.type === "secret_ref" && binding.secretId === reference.secret.id
|
||||
: binding.type === "user_secret_ref" && binding.key === reference.definition.key;
|
||||
}
|
||||
|
||||
/** Env keys in an agent's env config that resolve to this secret/definition. */
|
||||
export function envKeysReferencingSecret(env: unknown, reference: AgentAccessReference): string[] {
|
||||
if (!isBinding(env)) return [];
|
||||
return Object.entries(env)
|
||||
.filter(([, binding]) => isBinding(binding) && bindingMatches(binding, reference))
|
||||
.map(([key]) => key)
|
||||
.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level `access.<ALIAS>` keys in an agent's adapter config that resolve to
|
||||
* this secret (API-access delivery). Only company secrets support API access;
|
||||
* user secrets remain env-only.
|
||||
*/
|
||||
export function apiAliasesReferencingSecret(adapterConfig: unknown, reference: AgentAccessReference): string[] {
|
||||
if (reference.kind !== "company" || !isBinding(adapterConfig)) return [];
|
||||
return Object.entries(adapterConfig)
|
||||
.filter(([key, binding]) => key.startsWith(AGENT_ACCESS_CONFIG_PATH_PREFIX) && isBinding(binding) && bindingMatches(binding, reference))
|
||||
.map(([key]) => key.slice(AGENT_ACCESS_CONFIG_PATH_PREFIX.length))
|
||||
.sort();
|
||||
}
|
||||
|
||||
export interface SecretAgentUsage {
|
||||
/** Agents holding a binding to a company secret, keyed by secret id. */
|
||||
bySecretId: Map<string, Agent[]>;
|
||||
/** Agents holding a binding to a user-provided secret, keyed by its key. */
|
||||
byUserSecretKey: Map<string, Agent[]>;
|
||||
}
|
||||
|
||||
function push(map: Map<string, Agent[]>, key: string, agent: Agent) {
|
||||
const list = map.get(key);
|
||||
if (!list) map.set(key, [agent]);
|
||||
else if (list[list.length - 1] !== agent) list.push(agent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which agents can use which secret, read once from the agents' own configs.
|
||||
* One pass over the agents instead of one scan per row.
|
||||
*/
|
||||
export function buildSecretAgentUsage(agents: readonly Agent[]): SecretAgentUsage {
|
||||
const usage: SecretAgentUsage = { bySecretId: new Map(), byUserSecretKey: new Map() };
|
||||
for (const agent of agents) {
|
||||
if (agent.status === "terminated") continue;
|
||||
const adapterConfig = agent.adapterConfig as unknown;
|
||||
if (!isBinding(adapterConfig)) continue;
|
||||
const bindings: unknown[] = [
|
||||
...(isBinding(adapterConfig.env) ? Object.values(adapterConfig.env) : []),
|
||||
...Object.entries(adapterConfig).filter(([key]) => key.startsWith(AGENT_ACCESS_CONFIG_PATH_PREFIX)).map(([, binding]) => binding),
|
||||
];
|
||||
for (const binding of bindings) {
|
||||
if (!isBinding(binding)) continue;
|
||||
if (binding.type === "secret_ref" && typeof binding.secretId === "string") push(usage.bySecretId, binding.secretId, agent);
|
||||
else if (binding.type === "user_secret_ref" && typeof binding.key === "string") push(usage.byUserSecretKey, binding.key, agent);
|
||||
}
|
||||
}
|
||||
return usage;
|
||||
}
|
||||
|
||||
/** Give one agent the secret as an environment variable, merged into its freshest config. */
|
||||
export async function grantAgentSecretAccess(input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
envKey: string;
|
||||
reference: AgentAccessReference;
|
||||
}): Promise<Agent> {
|
||||
const detail = await agentsApi.get(input.agentId, input.companyId);
|
||||
const adapterConfig = { ...((detail.adapterConfig ?? {}) as Record<string, unknown>) };
|
||||
const env = { ...((adapterConfig.env ?? {}) as Record<string, unknown>) };
|
||||
if (env[input.envKey] !== undefined) {
|
||||
throw new Error(`${detail.name} already has an env var named ${input.envKey}.`);
|
||||
}
|
||||
env[input.envKey] =
|
||||
input.reference.kind === "company"
|
||||
? { type: "secret_ref", secretId: input.reference.secret.id }
|
||||
: { type: "user_secret_ref", key: input.reference.definition.key };
|
||||
return agentsApi.update(input.agentId, { adapterConfig: { ...adapterConfig, env }, replaceAdapterConfig: true }, input.companyId);
|
||||
}
|
||||
|
||||
/** Remove every env var and API alias of one agent that points at the secret. */
|
||||
export async function revokeAgentSecretAccess(input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
reference: AgentAccessReference;
|
||||
}): Promise<Agent> {
|
||||
const detail = await agentsApi.get(input.agentId, input.companyId);
|
||||
const adapterConfig = { ...((detail.adapterConfig ?? {}) as Record<string, unknown>) };
|
||||
const env = { ...((adapterConfig.env ?? {}) as Record<string, unknown>) };
|
||||
const keys = envKeysReferencingSecret(env, input.reference);
|
||||
const aliases = apiAliasesReferencingSecret(adapterConfig, input.reference);
|
||||
if (keys.length === 0 && aliases.length === 0) return detail;
|
||||
for (const key of keys) delete env[key];
|
||||
for (const alias of aliases) delete adapterConfig[`${AGENT_ACCESS_CONFIG_PATH_PREFIX}${alias}`];
|
||||
return agentsApi.update(input.agentId, { adapterConfig: { ...adapterConfig, env }, replaceAdapterConfig: true }, input.companyId);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Copy, Fingerprint, KeyRound, Link2, ShieldAlert, Variable, ServerCog } from "lucide-react";
|
||||
import type {
|
||||
ApproveSecretProposalInput,
|
||||
CompanySecretProviderConfig,
|
||||
SecretProposalAgentRef,
|
||||
SecretProposalView,
|
||||
@@ -102,10 +103,29 @@ export function FingerprintChip({
|
||||
export function ProposalJustification({
|
||||
justification,
|
||||
className,
|
||||
variant = "captioned",
|
||||
}: {
|
||||
justification: string;
|
||||
className?: string;
|
||||
/**
|
||||
* `captioned` (default) shows the "Reason given by the agent" caption above
|
||||
* the quote. `quote` is one quiet quoted line with the caption kept for
|
||||
* screen readers, for surfaces whose heading already names the agent.
|
||||
*/
|
||||
variant?: "captioned" | "quote";
|
||||
}) {
|
||||
if (variant === "quote") {
|
||||
return (
|
||||
<p
|
||||
className={cn(
|
||||
"whitespace-pre-wrap break-words border-l-2 border-border pl-3 text-sm text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="sr-only">Reason given by the agent: </span>“{justification}”
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cn("space-y-0.5", className)}>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground">Reason given by the agent</p>
|
||||
@@ -215,22 +235,33 @@ export interface UseProposalReview {
|
||||
dialogs: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface UseProposalDecision {
|
||||
/** Approve a proposal, optionally with edits (secret) or a cascade (access). */
|
||||
approve: (proposal: SecretProposalView, input?: ApproveSecretProposalInput) => void;
|
||||
/** Reject a proposal. The API requires a non-empty reason. */
|
||||
reject: (proposal: SecretProposalView, reason: string) => void;
|
||||
approving: boolean;
|
||||
rejecting: boolean;
|
||||
/** True while an approve/reject request is in flight. */
|
||||
isBusy: boolean;
|
||||
/** Readable message from the last failed request, if any. */
|
||||
error: string | null;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared approve/reject workflow for secret & binding proposals. Both the
|
||||
* board Proposals tab and the agent-settings "Proposed" rows use this so the
|
||||
* confirm/reject affordances behave identically everywhere.
|
||||
* Approve/reject requests for one review surface: API calls, toasts, cache
|
||||
* invalidation and the last error. Surfaces own their presentation — dialogs
|
||||
* (`useProposalReview`) or inline rows (the Secrets page Proposals tab).
|
||||
*/
|
||||
export function useProposalReview(
|
||||
export function useProposalDecision(
|
||||
companyId: string | null,
|
||||
providerConfigs: CompanySecretProviderConfig[] = [],
|
||||
): UseProposalReview {
|
||||
callbacks: { onApproved?: () => void; onRejected?: () => void } = {},
|
||||
): UseProposalDecision {
|
||||
const queryClient = useQueryClient();
|
||||
const { pushToast } = useToastActions();
|
||||
|
||||
const [approveDraft, setApproveDraft] = useState<ApproveDraft | null>(null);
|
||||
const [rejectTarget, setRejectTarget] = useState<SecretProposalView | null>(null);
|
||||
const [rejectReason, setRejectReason] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { onApproved, onRejected } = callbacks;
|
||||
|
||||
const invalidate = useCallback(() => {
|
||||
if (!companyId) return;
|
||||
@@ -239,35 +270,19 @@ export function useProposalReview(
|
||||
}, [companyId, queryClient]);
|
||||
|
||||
const approveMutation = useMutation({
|
||||
mutationFn: (draft: ApproveDraft) => {
|
||||
const { proposal } = draft;
|
||||
if (proposal.kind === "secret") {
|
||||
const name = draft.folder.trim()
|
||||
? `${draft.folder.trim().replace(/\/+$/, "")}/${draft.leaf.trim()}`
|
||||
: draft.leaf.trim();
|
||||
return secretsApi.approveProposal(companyId!, proposal.id, {
|
||||
overrides: {
|
||||
name,
|
||||
description: draft.description.trim() || null,
|
||||
providerConfigId: draft.providerConfigId || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return secretsApi.approveProposal(companyId!, proposal.id, {
|
||||
cascade: draft.cascade || undefined,
|
||||
});
|
||||
},
|
||||
mutationFn: ({ proposal, input }: { proposal: SecretProposalView; input: ApproveSecretProposalInput }) =>
|
||||
secretsApi.approveProposal(companyId!, proposal.id, input),
|
||||
onSuccess: (result) => {
|
||||
pushToast({
|
||||
title: result.kind === "secret" ? "Secret approved" : "Binding approved",
|
||||
title: result.kind === "secret" ? "Secret approved" : "Access approved",
|
||||
body:
|
||||
result.kind === "secret"
|
||||
? (result.proposedName ?? "Secret created")
|
||||
: `${result.target?.name ?? "Agent"} · ${bindingEnvKey(result) || "binding"}`,
|
||||
: `${result.target?.name ?? "Agent"} · ${bindingEnvKey(result) || "access"}`,
|
||||
tone: "success",
|
||||
});
|
||||
setApproveDraft(null);
|
||||
setError(null);
|
||||
onApproved?.();
|
||||
invalidate();
|
||||
},
|
||||
onError: (err) => setError(readableError(err)),
|
||||
@@ -282,17 +297,77 @@ export function useProposalReview(
|
||||
body: result.kind === "secret" ? (result.proposedName ?? undefined) : undefined,
|
||||
tone: "info",
|
||||
});
|
||||
setRejectTarget(null);
|
||||
setRejectReason("");
|
||||
setError(null);
|
||||
onRejected?.();
|
||||
invalidate();
|
||||
},
|
||||
onError: (err) => setError(readableError(err)),
|
||||
});
|
||||
|
||||
const { mutate: mutateApprove } = approveMutation;
|
||||
const { mutate: mutateReject } = rejectMutation;
|
||||
const approve = useCallback(
|
||||
(proposal: SecretProposalView, input: ApproveSecretProposalInput = {}) =>
|
||||
mutateApprove({ proposal, input }),
|
||||
[mutateApprove],
|
||||
);
|
||||
const reject = useCallback(
|
||||
(proposal: SecretProposalView, reason: string) => mutateReject({ proposal, reason }),
|
||||
[mutateReject],
|
||||
);
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
return {
|
||||
approve,
|
||||
reject,
|
||||
approving: approveMutation.isPending,
|
||||
rejecting: rejectMutation.isPending,
|
||||
isBusy: approveMutation.isPending || rejectMutation.isPending,
|
||||
error,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
|
||||
function approveInputFromDraft(draft: ApproveDraft): ApproveSecretProposalInput {
|
||||
if (draft.proposal.kind === "secret") {
|
||||
const name = draft.folder.trim()
|
||||
? `${draft.folder.trim().replace(/\/+$/, "")}/${draft.leaf.trim()}`
|
||||
: draft.leaf.trim();
|
||||
return {
|
||||
overrides: {
|
||||
name,
|
||||
description: draft.description.trim() || null,
|
||||
providerConfigId: draft.providerConfigId || null,
|
||||
},
|
||||
};
|
||||
}
|
||||
return { cascade: draft.cascade || undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared approve/reject dialogs for secret & access proposals, used where a
|
||||
* proposal is reviewed among other rows (the agent-settings "Proposed" rows).
|
||||
*/
|
||||
export function useProposalReview(
|
||||
companyId: string | null,
|
||||
providerConfigs: CompanySecretProviderConfig[] = [],
|
||||
): UseProposalReview {
|
||||
const [approveDraft, setApproveDraft] = useState<ApproveDraft | null>(null);
|
||||
const [rejectTarget, setRejectTarget] = useState<SecretProposalView | null>(null);
|
||||
const [rejectReason, setRejectReason] = useState("");
|
||||
|
||||
const decision = useProposalDecision(companyId, {
|
||||
onApproved: () => setApproveDraft(null),
|
||||
onRejected: () => {
|
||||
setRejectTarget(null);
|
||||
setRejectReason("");
|
||||
},
|
||||
});
|
||||
const { error, clearError } = decision;
|
||||
|
||||
const requestApprove = useCallback(
|
||||
(proposal: SecretProposalView) => {
|
||||
setError(null);
|
||||
clearError();
|
||||
const segments = (proposal.proposedName ?? "").split("/");
|
||||
const leaf = segments.pop() ?? "";
|
||||
setApproveDraft({
|
||||
@@ -309,42 +384,42 @@ export function useProposalReview(
|
||||
cascade: Boolean(proposal.secretProposalId),
|
||||
});
|
||||
},
|
||||
[providerConfigs],
|
||||
[providerConfigs, clearError],
|
||||
);
|
||||
|
||||
const requestReject = useCallback((proposal: SecretProposalView) => {
|
||||
setError(null);
|
||||
clearError();
|
||||
setRejectReason("");
|
||||
setRejectTarget(proposal);
|
||||
}, []);
|
||||
}, [clearError]);
|
||||
|
||||
const dialogs = (
|
||||
<>
|
||||
<ApproveDialog
|
||||
draft={approveDraft}
|
||||
error={error}
|
||||
pending={approveMutation.isPending}
|
||||
pending={decision.approving}
|
||||
providerConfigs={providerConfigs}
|
||||
onChange={setApproveDraft}
|
||||
onCancel={() => {
|
||||
setApproveDraft(null);
|
||||
setError(null);
|
||||
clearError();
|
||||
}}
|
||||
onConfirm={() => approveDraft && approveMutation.mutate(approveDraft)}
|
||||
onConfirm={() => approveDraft && decision.approve(approveDraft.proposal, approveInputFromDraft(approveDraft))}
|
||||
/>
|
||||
<RejectDialog
|
||||
proposal={rejectTarget}
|
||||
reason={rejectReason}
|
||||
error={error}
|
||||
pending={rejectMutation.isPending}
|
||||
pending={decision.rejecting}
|
||||
onReasonChange={setRejectReason}
|
||||
onCancel={() => {
|
||||
setRejectTarget(null);
|
||||
setRejectReason("");
|
||||
setError(null);
|
||||
clearError();
|
||||
}}
|
||||
onConfirm={() =>
|
||||
rejectTarget && rejectMutation.mutate({ proposal: rejectTarget, reason: rejectReason })
|
||||
rejectTarget && decision.reject(rejectTarget, rejectReason)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
@@ -353,7 +428,7 @@ export function useProposalReview(
|
||||
return {
|
||||
requestApprove,
|
||||
requestReject,
|
||||
isBusy: approveMutation.isPending || rejectMutation.isPending,
|
||||
isBusy: decision.isBusy,
|
||||
dialogs,
|
||||
};
|
||||
}
|
||||
@@ -395,12 +470,12 @@ function ApproveDialog({
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isSecret ? "Approve & create secret" : "Approve binding"}
|
||||
{isSecret ? "Approve and save secret" : "Approve access"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isSecret
|
||||
? "The value is created as the proposing agent recorded it. Re-folder or rename it before it lands."
|
||||
: "Grant the target agent access to this secret. This runs with your permissions."}
|
||||
? "The value is saved exactly as the agent recorded it. You can rename it or move it to another folder first."
|
||||
: "Give the agent access to this secret. Access is granted with your permissions."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -440,7 +515,7 @@ function ApproveDialog({
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground">
|
||||
Lands as{" "}
|
||||
Saved as{" "}
|
||||
{previewName ? (
|
||||
<SecretPathName name={previewName} className="font-mono" />
|
||||
) : (
|
||||
@@ -460,7 +535,7 @@ function ApproveDialog({
|
||||
|
||||
{localConfigs.length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="approve-provider-config">Provider vault</Label>
|
||||
<Label htmlFor="approve-provider-config">Stored in</Label>
|
||||
<select
|
||||
id="approve-provider-config"
|
||||
value={draft.providerConfigId}
|
||||
@@ -469,7 +544,7 @@ function ApproveDialog({
|
||||
}
|
||||
className="h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
>
|
||||
<option value="">Deployment default</option>
|
||||
<option value="">Default vault</option>
|
||||
{localConfigs.map((config) => (
|
||||
<option key={config.id} value={config.id}>
|
||||
{config.displayName}
|
||||
@@ -504,10 +579,10 @@ function ApproveDialog({
|
||||
{pending
|
||||
? "Approving…"
|
||||
: isSecret
|
||||
? "Approve & create"
|
||||
? "Approve and save secret"
|
||||
: draft.cascade
|
||||
? "Approve secret & bind"
|
||||
: "Approve binding"}
|
||||
? "Approve access and save secret"
|
||||
: "Approve access"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
@@ -531,7 +606,7 @@ function BindingApproveBody({
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="space-y-2 rounded-md border border-border p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-muted-foreground">Target agent</span>
|
||||
<span className="text-xs text-muted-foreground">Agent</span>
|
||||
{proposal.target ? (
|
||||
<AgentRefChip agent={proposal.target} className="text-sm font-medium" />
|
||||
) : (
|
||||
@@ -566,8 +641,8 @@ function BindingApproveBody({
|
||||
/>
|
||||
<span className="text-foreground/90">
|
||||
Also approve the proposed secret{" "}
|
||||
<span className="font-medium">{secret.name}</span> and create it in the same step. The
|
||||
binding can’t land without it.
|
||||
<span className="font-medium">{secret.name}</span> and save it in the same step. Access
|
||||
can’t be approved without it.
|
||||
</span>
|
||||
</label>
|
||||
) : null}
|
||||
@@ -606,8 +681,8 @@ function RejectDialog({
|
||||
<DialogTitle>Reject proposal</DialogTitle>
|
||||
<DialogDescription>
|
||||
The reason is sent back to{" "}
|
||||
<AgentRefChip agent={proposal.proposedBy} className="text-foreground" />. Dependent
|
||||
bindings are rejected too.
|
||||
<AgentRefChip agent={proposal.proposedBy} className="text-foreground" />. Requests to
|
||||
use this secret are rejected too.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { Building2, ChevronRight, CircleHelp, Users } from "lucide-react";
|
||||
import { AgentAvatar } from "../../components/AgentAvatar";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { cn } from "../../lib/utils";
|
||||
import type { SecretOriginGroup } from "./secret-origin";
|
||||
|
||||
/** Which agents hold the secret; falls back to other places it is set, then to "Not used yet". */
|
||||
export function SecretUsedBy({ agents, otherUseCount = 0 }: { agents: readonly Agent[]; otherUseCount?: number }) {
|
||||
if (agents.length === 0) {
|
||||
return (
|
||||
<span className="truncate text-sm text-muted-foreground">
|
||||
{otherUseCount > 0 ? `Set in ${otherUseCount} ${otherUseCount === 1 ? "place" : "places"}` : "Not used yet"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-sm">
|
||||
<span className="flex shrink-0 -space-x-1.5">
|
||||
{agents.slice(0, 3).map((agent) => (
|
||||
<AgentAvatar key={agent.id} agent={agent} size={24} className="ring-2 ring-background" />
|
||||
))}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground">
|
||||
{agents.length === 1 ? agents[0].name : `${agents.length} agents`}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Who supplies the value: the organization, or each user (with how many have). */
|
||||
export function SecretProvidedBy({ perUser, coverage }: { perUser: boolean; coverage?: ReactNode }) {
|
||||
const Icon = perUser ? Users : Building2;
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
<span className="truncate">
|
||||
{perUser ? "Each user" : "Organization"}
|
||||
{perUser && coverage ? <> · {coverage}</> : null}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function HowSecretsWork() {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button type="button" className="inline-flex items-center gap-1 underline underline-offset-4 hover:text-foreground">
|
||||
<CircleHelp className="h-3.5 w-3.5" aria-hidden />
|
||||
How secrets work
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-80 text-sm">
|
||||
<ol className="flex list-decimal flex-col gap-2 pl-4 text-muted-foreground">
|
||||
<li>Add a secret once. The organization provides one shared value, or each user adds their own.</li>
|
||||
<li>Choose which agents can use it, here or in an agent's settings. A project can set it for every task in that project.</li>
|
||||
<li>
|
||||
When a run starts, the agent finds it as an environment variable, such as{" "}
|
||||
<code className="font-mono text-foreground">GITHUB_TOKEN</code>. The value is never shown again.
|
||||
</li>
|
||||
</ol>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/** One collapsible origin ("Connections", "Model sign-ins", …) inside Managed by Paperclip. */
|
||||
export function ManagedSecretGroup({
|
||||
group,
|
||||
count,
|
||||
open,
|
||||
onToggle,
|
||||
children,
|
||||
}: {
|
||||
group: SecretOriginGroup;
|
||||
count: number;
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const Icon = group.icon;
|
||||
return (
|
||||
<div data-testid={`managed-secret-group-${group.id}`}>
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2.5 border-b border-border/60 px-3 py-2.5 text-left hover:bg-accent/40"
|
||||
aria-expanded={open}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", open && "rotate-90")}
|
||||
aria-hidden
|
||||
/>
|
||||
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
|
||||
<span className="shrink-0 text-sm font-medium">{group.label}</span>
|
||||
<span className="hidden min-w-0 flex-1 truncate text-xs text-muted-foreground @min-[40rem]:inline">{group.detail}</span>
|
||||
<span className="ml-auto shrink-0 text-sm tabular-nums text-muted-foreground">
|
||||
{count} {count === 1 ? "secret" : "secrets"}
|
||||
</span>
|
||||
</button>
|
||||
{open ? children : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { classifySecretOrigin, managedSecretLabel } from "./secret-origin";
|
||||
|
||||
const origin = (key: string, name: string) => classifySecretOrigin({ key, name });
|
||||
const label = (key: string, name: string) => managedSecretLabel({ key, name }, origin(key, name));
|
||||
|
||||
describe("classifySecretOrigin", () => {
|
||||
it("keeps secrets a person named with the team", () => {
|
||||
expect(origin("github-token", "GITHUB_TOKEN")).toBe("team");
|
||||
expect(origin("ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY for onboarding")).toBe("team");
|
||||
expect(origin("x_write_api_key", "x_write_api_key")).toBe("team");
|
||||
expect(origin("airtable-key", "ai-tools/airtable")).toBe("team");
|
||||
expect(origin("chatbot-token", "Chatbot token")).toBe("team");
|
||||
});
|
||||
|
||||
it("groups credentials saved by connections", () => {
|
||||
expect(origin("tool_app.500df1ea-4b23-4c24-93a4-c9802c893448.oauth_access_token", "Neon for the organization OAuth access token 80255b18")).toBe("connections");
|
||||
expect(origin("tool_oauth.9ad19afd-323d-47c7-8b95-3d58fda94dcf.oauth_access_token", "GitHub (2) GitHub access token")).toBe("connections");
|
||||
expect(origin("slack_manager.b4a7ba86-4b88-41e6-82cf-f5b385752541.access_token", "Slack workspace management access_token aae516bc")).toBe("connections");
|
||||
});
|
||||
|
||||
it("groups model sign-ins by generated key or name", () => {
|
||||
expect(origin("ai_141d4c34_84d2_4f19_a158_0c64e8985f04", "Riley's OpenAI API key")).toBe("models");
|
||||
expect(origin("ai-01d0de1a-ac24-461a-b229-989d2937a4e1", "ai-01d0de1a-ac24-461a-b229-989d2937a4e1")).toBe("models");
|
||||
});
|
||||
|
||||
it("groups chat channels, routine webhooks and observability headers", () => {
|
||||
expect(origin("chat_slack_5c860bfd_2399_45d8_8ca8_267c05dff5eb_bottoken_565d9081", "chat.slack.5c860bfd.botToken.565d9081")).toBe("chat");
|
||||
expect(origin("routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29", "routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29")).toBe("routines");
|
||||
expect(origin("agent_observability_headers_8b0f048a_74cd_49c3_a77d_b004b22921b3", "agent-observability.8b0f048a-74cd-49c3-a77d-b004b22921b3")).toBe("observability");
|
||||
});
|
||||
});
|
||||
|
||||
describe("managedSecretLabel", () => {
|
||||
it("replaces record IDs with what the secret is for", () => {
|
||||
expect(label("chat_slack_x", "chat.slack.5c860bfd.botToken.565d9081")).toBe("Slack bot token");
|
||||
expect(label("chat_github_x", "chat.github.bc7e8222.webhookSecret.c1155293")).toBe("GitHub webhook secret");
|
||||
expect(label("routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29", "routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29")).toBe("Routine webhook secret");
|
||||
expect(label("ai-01d0de1a-ac24-461a-b229-989d2937a4e1", "ai-01d0de1a-ac24-461a-b229-989d2937a4e1")).toBe("Model provider key");
|
||||
expect(label("agent_observability_headers_x", "agent-observability.8b0f048a-74cd-49c3-a77d-b004b22921b3")).toBe("Trace exporter headers");
|
||||
});
|
||||
|
||||
it("drops the trailing record suffix from connection names and keeps readable names", () => {
|
||||
expect(label("tool_app.500df1ea-4b23-4c24-93a4-c9802c893448.oauth_access_token", "Neon for the organization OAuth access token 80255b18")).toBe("Neon for the organization OAuth access token");
|
||||
expect(label("ai_141d4c34_84d2_4f19_a158_0c64e8985f04", "Riley's OpenAI API key")).toBe("Riley's OpenAI API key");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { Activity, Bot, MessageSquare, Plug, Repeat } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Where a secret came from, inferred from the naming conventions of the
|
||||
* server modules that create secrets on a person's behalf:
|
||||
* connection credentials (`tool_app.*`, `tool_oauth.*`, `slack_manager.*`),
|
||||
* chat channels (`chat.<platform>.*`), model sign-ins (`ai_*` / `ai-*`),
|
||||
* routine webhooks (`routine-<id>-*`) and the observability exporter
|
||||
* (`agent-observability.*`). Secrets do not record their origin yet, so this
|
||||
* is a presentation-only grouping: it never gates an action.
|
||||
*/
|
||||
export type SecretOrigin = "team" | "connections" | "chat" | "models" | "routines" | "observability";
|
||||
|
||||
export interface SecretOriginGroup {
|
||||
id: Exclude<SecretOrigin, "team">;
|
||||
label: string;
|
||||
detail: string;
|
||||
icon: LucideIcon;
|
||||
}
|
||||
|
||||
export const SECRET_ORIGIN_GROUPS: SecretOriginGroup[] = [
|
||||
{ id: "models", label: "Model sign-ins", detail: "Accounts and keys for the models your agents run on", icon: Bot },
|
||||
{ id: "connections", label: "Connections", detail: "Tokens for the apps you connected", icon: Plug },
|
||||
{ id: "chat", label: "Chat channels", detail: "Credentials for chat apps your agents answer in", icon: MessageSquare },
|
||||
{ id: "routines", label: "Routine webhooks", detail: "Signing secrets for routine triggers", icon: Repeat },
|
||||
{ id: "observability", label: "Agent observability", detail: "Headers for your trace exporter", icon: Activity },
|
||||
];
|
||||
|
||||
const UUID = "[0-9a-f]{8}[-_][0-9a-f]{4}[-_][0-9a-f]{4}[-_][0-9a-f]{4}[-_][0-9a-f]{12}";
|
||||
const MODEL_KEY = new RegExp(`^ai[-_]${UUID}$`, "i");
|
||||
const ROUTINE_NAME = new RegExp(`^routine-${UUID}-[0-9a-f]+$`, "i");
|
||||
|
||||
export function classifySecretOrigin(input: { key: string; name: string }): SecretOrigin {
|
||||
const key = input.key.toLowerCase();
|
||||
const name = input.name.toLowerCase();
|
||||
if (key.startsWith("tool_app.") || key.startsWith("tool_oauth.") || key.startsWith("slack_manager.")) return "connections";
|
||||
if (MODEL_KEY.test(key) || MODEL_KEY.test(name)) return "models";
|
||||
if (name.startsWith("chat.") || key.startsWith("chat_") || key.startsWith("chat.")) return "chat";
|
||||
if (ROUTINE_NAME.test(name)) return "routines";
|
||||
if (name.startsWith("agent-observability.") || key.startsWith("agent_observability_headers_")) return "observability";
|
||||
return "team";
|
||||
}
|
||||
|
||||
function words(value: string): string {
|
||||
return value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
const PLATFORM_NAMES: Record<string, string> = { github: "GitHub" };
|
||||
|
||||
function platformName(value: string): string {
|
||||
return PLATFORM_NAMES[value.toLowerCase()] ?? (value ? value.charAt(0).toUpperCase() + value.slice(1) : value);
|
||||
}
|
||||
|
||||
/**
|
||||
* A readable name for a secret Paperclip created itself. Their stored names
|
||||
* carry record IDs; people should see what the secret is for instead.
|
||||
*/
|
||||
export function managedSecretLabel(input: { key: string; name: string }, origin: SecretOrigin): string {
|
||||
const name = input.name.trim();
|
||||
if (origin === "chat") {
|
||||
const [, platform, , field] = name.split(".");
|
||||
if (platform && field) return `${platformName(platform)} ${words(field)}`;
|
||||
}
|
||||
if (origin === "routines") return "Routine webhook secret";
|
||||
if (origin === "observability") return "Trace exporter headers";
|
||||
if (origin === "models" && MODEL_KEY.test(name)) return "Model provider key";
|
||||
if (origin === "connections") return name.replace(/\s+[0-9a-f]{8}$/i, "");
|
||||
return name;
|
||||
}
|
||||
@@ -633,9 +633,19 @@ function installStorybookApiFixtures() {
|
||||
const [, secretId] = secretUsageMatch;
|
||||
return Response.json({
|
||||
secretId,
|
||||
bindings: storybookSecretBindings.filter(
|
||||
(binding) => binding.secretId === secretId,
|
||||
),
|
||||
// The usage endpoint resolves each binding's target; mirror that shape.
|
||||
bindings: storybookSecretBindings
|
||||
.filter((binding) => binding.secretId === secretId)
|
||||
.map((binding) => ({
|
||||
...binding,
|
||||
target: {
|
||||
type: binding.targetType,
|
||||
id: binding.targetId,
|
||||
label: binding.label ?? binding.targetId,
|
||||
href: null,
|
||||
status: null,
|
||||
},
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,8 @@ const meta = {
|
||||
[
|
||||
{
|
||||
path: "/api/companies/company-storybook/secret-proposals",
|
||||
read: () => rows,
|
||||
// Only the pending list has rows here; the decided lists stay empty.
|
||||
read: ({ url }) => ((url.searchParams.get("status") ?? "pending") === "pending" ? rows : []),
|
||||
},
|
||||
{
|
||||
path: /^\/api\/companies\/company-storybook\/secret-proposals\/proposal-gap\/(approve|reject)$/,
|
||||
@@ -111,43 +112,37 @@ export const Failed: Story = { parameters: { fixtureState: "failure" } };
|
||||
export const PermissionBlocked: Story = {
|
||||
parameters: { blocked: true },
|
||||
play: async ({ canvasElement }) => {
|
||||
await expect(
|
||||
await within(canvasElement).findByRole("button", { name: "Approve" }),
|
||||
).toBeDisabled();
|
||||
const c = within(canvasElement);
|
||||
await c.findByText("Only organization admins can approve or reject this.");
|
||||
await expect(c.queryByRole("button", { name: /Approve/ })).not.toBeInTheDocument();
|
||||
await expect(c.queryByRole("button", { name: "Reject" })).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
export const RejectProposal: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const c = within(canvasElement);
|
||||
await userEvent.click(await c.findByRole("button", { name: "Reject" }));
|
||||
const body = within(document.body);
|
||||
await userEvent.type(
|
||||
await body.findByRole("textbox"),
|
||||
await c.findByRole("textbox", { name: /reason/i }),
|
||||
"The task can use the existing managed connection.",
|
||||
{ delay: 15 },
|
||||
);
|
||||
await userEvent.click(
|
||||
within(body.getByRole("dialog")).getByRole("button", { name: "Reject" }),
|
||||
);
|
||||
await userEvent.click(c.getByRole("button", { name: "Reject" }));
|
||||
await waitFor(() => expect(rows).toHaveLength(0));
|
||||
await body.findByText("Proposal rejected");
|
||||
await within(document.body).findByText("Proposal rejected");
|
||||
},
|
||||
};
|
||||
export const RejectFailed: Story = {
|
||||
parameters: { fixtureState: "mutation-failure" },
|
||||
play: async ({ canvasElement }) => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole("button", { name: "Reject" }),
|
||||
);
|
||||
const body = within(document.body);
|
||||
const c = within(canvasElement);
|
||||
await userEvent.click(await c.findByRole("button", { name: "Reject" }));
|
||||
await userEvent.type(
|
||||
await body.findByRole("textbox"),
|
||||
await c.findByRole("textbox", { name: /reason/i }),
|
||||
"Use the existing connection.",
|
||||
{ delay: 15 },
|
||||
);
|
||||
await userEvent.click(
|
||||
within(body.getByRole("dialog")).getByRole("button", { name: "Reject" }),
|
||||
);
|
||||
await body.findByText("The request failed. Please try again.");
|
||||
await userEvent.click(c.getByRole("button", { name: "Reject" }));
|
||||
await c.findByText("The request failed. Please try again.");
|
||||
},
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertCircle, KeyRound } from "lucide-react";
|
||||
import type {
|
||||
@@ -15,7 +16,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { storybookCompanies, storybookSecrets } from "../../fixtures/paperclipData";
|
||||
import { storybookAgents, storybookCompanies, storybookSecrets } from "../../fixtures/paperclipData";
|
||||
|
||||
const COMPANY_ID = "company-storybook";
|
||||
|
||||
@@ -77,6 +78,28 @@ const storybookUserSecretCoverage: Record<string, UserSecretCoverageSummary> = {
|
||||
},
|
||||
};
|
||||
|
||||
const baseSecret = storybookSecrets[0]!;
|
||||
|
||||
// Secrets Paperclip saved on someone's behalf, plus team secrets inside a folder.
|
||||
const storybookSecretInventory: CompanySecret[] = [
|
||||
...storybookSecrets,
|
||||
{ ...baseSecret, id: "secret-staging-db", key: "staging-database-url", name: "staging/DATABASE_URL", description: null, referenceCount: 0 },
|
||||
{ ...baseSecret, id: "secret-staging-stripe", key: "staging-stripe-key", name: "staging/STRIPE_TEST_KEY", description: null, referenceCount: 2 },
|
||||
{ ...baseSecret, id: "secret-neon-access", key: "tool_app.500df1ea-4b23-4c24-93a4-c9802c893448.oauth_access_token", name: "Neon for the organization OAuth access token 80255b18", description: null, referenceCount: 1 },
|
||||
{ ...baseSecret, id: "secret-neon-refresh", key: "tool_app.afbdf0fb-70df-490b-9364-e919dedcbafa.oauth_refresh_token", name: "Neon for the organization OAuth refresh token cfdb9070", description: null, referenceCount: 1 },
|
||||
{ ...baseSecret, id: "secret-slack-bot", key: "chat_slack_5c860bfd_bottoken_565d9081", name: "chat.slack.5c860bfd.botToken.565d9081", description: null, referenceCount: 1 },
|
||||
{ ...baseSecret, id: "secret-slack-signing", key: "chat_slack_5c860bfd_signingsecret_2ab031a0", name: "chat.slack.5c860bfd.signingSecret.2ab031a0", description: null, referenceCount: 1 },
|
||||
{ ...baseSecret, id: "secret-model-key", key: "ai-01d0de1a-ac24-461a-b229-989d2937a4e1", name: "ai-01d0de1a-ac24-461a-b229-989d2937a4e1", description: null, referenceCount: 1 },
|
||||
{ ...baseSecret, id: "secret-routine", key: "routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29", name: "routine-604ffeed-2bba-4ade-b87d-3db79f481370-99f65874bf29", description: null, referenceCount: 1 },
|
||||
];
|
||||
|
||||
// Two agents hold the first secret, so the list and details show who uses it.
|
||||
const storybookSecretAgents = storybookAgents.map((agent, index) =>
|
||||
index < 2
|
||||
? { ...agent, adapterConfig: { ...agent.adapterConfig, env: { OPENAI_API_KEY: { type: "secret_ref", secretId: baseSecret.id, version: "latest" } } } }
|
||||
: agent,
|
||||
);
|
||||
|
||||
// Seed localStorage before CompanyContext mounts so its `useState` initializer reads the right id.
|
||||
if (typeof window !== "undefined") {
|
||||
window.localStorage.setItem("paperclip.selectedCompanyId", COMPANY_ID);
|
||||
@@ -85,7 +108,8 @@ if (typeof window !== "undefined") {
|
||||
function StorybookSecretsFixtures({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
// Seed query caches synchronously so children hydrate from cache on first render.
|
||||
queryClient.setQueryData(queryKeys.secrets.list(COMPANY_ID), storybookSecrets);
|
||||
queryClient.setQueryData(queryKeys.secrets.list(COMPANY_ID), storybookSecretInventory);
|
||||
queryClient.setQueryData(queryKeys.agents.list(COMPANY_ID), storybookSecretAgents);
|
||||
queryClient.setQueryData(
|
||||
queryKeys.secrets.userDefinitions(COMPANY_ID),
|
||||
storybookUserSecretDefinitions,
|
||||
@@ -131,7 +155,8 @@ const meta: Meta = {
|
||||
"secrets/vault-import"
|
||||
],
|
||||
"implementation": "production",
|
||||
"boundary": "fixtures"
|
||||
"boundary": "fixtures",
|
||||
"notes": "The shipped Secrets page on fixture data: team secrets with who provides and who uses them, folders, the collapsed Managed by Paperclip section, the New secret dialog, the details panel and the Vaults tab. Nothing is stored, encrypted or delivered; agent access, vault health and import are covered by tests and need a live instance to prove."
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -162,6 +187,80 @@ export const SecretsInventory: Story = {
|
||||
),
|
||||
};
|
||||
|
||||
function SecretsPage() {
|
||||
return (
|
||||
<StorybookSecretsFixtures>
|
||||
<div className="h-screen w-full bg-background p-6">
|
||||
<Secrets />
|
||||
</div>
|
||||
</StorybookSecretsFixtures>
|
||||
);
|
||||
}
|
||||
|
||||
export const ManagedByPaperclip: Story = {
|
||||
render: () => <SecretsPage />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const section = within(await canvas.findByTestId("managed-secrets"));
|
||||
await expect(canvas.queryByText("Slack bot token")).not.toBeInTheDocument();
|
||||
await userEvent.click(section.getByRole("button", { name: /Managed by Paperclip/ }));
|
||||
await userEvent.click(section.getByRole("button", { name: /Chat channels/ }));
|
||||
await expect((await section.findAllByText("Slack bot token")).length).toBeGreaterThan(0);
|
||||
},
|
||||
};
|
||||
|
||||
export const InsideFolder: Story = {
|
||||
parameters: { initialEntries: ["/PAP/company/settings/secrets?path=staging"] },
|
||||
render: () => <SecretsPage />,
|
||||
};
|
||||
|
||||
export const NewSecret: Story = {
|
||||
render: () => <SecretsPage />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement), body = within(canvasElement.ownerDocument.body);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: "New secret" }));
|
||||
const dialog = within(await body.findByRole("dialog"));
|
||||
await userEvent.click(dialog.getByRole("button", { name: "Create secret" }));
|
||||
await expect(await dialog.findByText("Give the secret a name.")).toBeVisible();
|
||||
await expect(dialog.getByRole("radio", { name: /Organization/ })).toHaveAttribute("aria-checked", "true");
|
||||
},
|
||||
};
|
||||
|
||||
export const NewSecretEachUser: Story = {
|
||||
render: () => <SecretsPage />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement), body = within(canvasElement.ownerDocument.body);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: "New secret" }));
|
||||
const dialog = within(await body.findByRole("dialog"));
|
||||
await userEvent.click(dialog.getByRole("radio", { name: /Each user/ }));
|
||||
await expect(dialog.queryByRole("textbox", { name: "Value" })).not.toBeInTheDocument();
|
||||
await expect(dialog.getByLabelText(/Instructions for members/)).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const SecretDetails: Story = {
|
||||
parameters: { initialEntries: ["/PAP/company/settings/secrets?secret=secret-openai"] },
|
||||
render: () => <SecretsPage />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const panel = within(await within(canvasElement.ownerDocument.body).findByTestId("secret-details"));
|
||||
await expect(await panel.findByRole("button", { name: `Remove access for ${storybookSecretAgents[0]!.name}` })).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const EachUserSecretDetails: Story = {
|
||||
parameters: { initialEntries: ["/PAP/company/settings/secrets?definition=def-storybook-github"] },
|
||||
render: () => <SecretsPage />,
|
||||
};
|
||||
|
||||
export const Vaults: Story = {
|
||||
render: () => <SecretsPage />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(await canvas.findByRole("tab", { name: "Vaults" }));
|
||||
await expect(await canvas.findByTestId("provider-vault-built-in")).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
function BindingPickerSurface({
|
||||
initial,
|
||||
label,
|
||||
|
||||
Reference in new issue
Block a user