Skip to content

The open-source app everyone uses to manage agents at work

feat: implement multi-user access and invite flows (#3784)

Dottab9a80dcf226c
diff --git a/.gitignore b/.gitignore
index f685aca695..cdeb446edc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,7 @@
+node_modules
node_modules/
+**/node_modules
+**/node_modules/
dist/
.env
*.tsbuildinfo
diff --git a/cli/README.md b/cli/README.md
index db92a53983..be390d19a0 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -12,7 +12,7 @@
<p align="center">
<a href="https://github.com/paperclipai/paperclip/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT License" /></a>
<a href="https://github.com/paperclipai/paperclip/stargazers"><img src="https://img.shields.io/github/stars/paperclipai/paperclip?style=flat" alt="Stars" /></a>
- <a href="https://discord.gg/m4HZY7xNG3"><img src="https://img.shields.io/badge/discord-join%20chat-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
+ <a href="https://discord.gg/m4HZY7xNG3"><img src="https://img.shields.io/discord/000000000?label=discord" alt="Discord" /></a>
</p>
<br/>
diff --git a/cli/src/__tests__/worktree.test.ts b/cli/src/__tests__/worktree.test.ts
index b552bd283e..ce0f85ad53 100644
--- a/cli/src/__tests__/worktree.test.ts
+++ b/cli/src/__tests__/worktree.test.ts
@@ -6,6 +6,7 @@ import { randomUUID } from "node:crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
agents,
+ authUsers,
companies,
createDb,
projects,
@@ -47,6 +48,7 @@ import {
const ORIGINAL_CWD = process.cwd();
const ORIGINAL_ENV = { ...process.env };
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const itEmbeddedPostgres = embeddedPostgresSupport.supported ? it : it.skip;
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
@@ -373,6 +375,97 @@ describe("worktree helpers", () => {
}
});
+ itEmbeddedPostgres(
+ "seeds authenticated users into minimally cloned worktree instances",
+ async () => {
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-auth-seed-"));
+ const worktreeRoot = path.join(tempRoot, "PAP-999-auth-seed");
+ const sourceHome = path.join(tempRoot, "source-home");
+ const sourceConfigDir = path.join(sourceHome, "instances", "source");
+ const sourceConfigPath = path.join(sourceConfigDir, "config.json");
+ const sourceEnvPath = path.join(sourceConfigDir, ".env");
+ const sourceKeyPath = path.join(sourceConfigDir, "secrets", "master.key");
+ const worktreeHome = path.join(tempRoot, ".paperclip-worktrees");
+ const originalCwd = process.cwd();
+ const sourceDb = await startEmbeddedPostgresTestDatabase("paperclip-worktree-auth-source-");
+
+ try {
+ const sourceDbClient = createDb(sourceDb.connectionString);
+ await sourceDbClient.insert(authUsers).values({
+ id: "user-existing",
+ email: "[email protected]",
+ name: "Existing User",
+ emailVerified: true,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+
+ fs.mkdirSync(path.dirname(sourceKeyPath), { recursive: true });
+ fs.mkdirSync(worktreeRoot, { recursive: true });
+
+ const sourceConfig = buildSourceConfig();
+ sourceConfig.database = {
+ mode: "postgres",
+ embeddedPostgresDataDir: path.join(sourceConfigDir, "db"),
+ embeddedPostgresPort: 54329,
+ backup: {
+ enabled: true,
+ intervalMinutes: 60,
+ retentionDays: 30,
+ dir: path.join(sourceConfigDir, "backups"),
+ },
+ connectionString: sourceDb.connectionString,
+ };
+ sourceConfig.logging.logDir = path.join(sourceConfigDir, "logs");
+ sourceConfig.storage.localDisk.baseDir = path.join(sourceConfigDir, "storage");
+ sourceConfig.secrets.localEncrypted.keyFilePath = sourceKeyPath;
+
+ fs.writeFileSync(sourceConfigPath, JSON.stringify(sourceConfig, null, 2) + "\n", "utf8");
+ fs.writeFileSync(sourceEnvPath, "", "utf8");
+ fs.writeFileSync(sourceKeyPath, "source-master-key", "utf8");
+
+ process.chdir(worktreeRoot);
+ await worktreeInitCommand({
+ name: "PAP-999-auth-seed",
+ home: worktreeHome,
+ fromConfig: sourceConfigPath,
+ force: true,
+ });
+
+ const targetConfig = JSON.parse(
+ fs.readFileSync(path.join(worktreeRoot, ".paperclip", "config.json"), "utf8"),
+ ) as PaperclipConfig;
+ const { default: EmbeddedPostgres } = await import("embedded-postgres");
+ const targetPg = new EmbeddedPostgres({
+ databaseDir: targetConfig.database.embeddedPostgresDataDir,
+ user: "paperclip",
+ password: "paperclip",
+ port: targetConfig.database.embeddedPostgresPort,
+ persistent: true,
+ initdbFlags: ["--encoding=UTF8", "--locale=C", "--lc-messages=C"],
+ onLog: () => {},
+ onError: () => {},
+ });
+
+ await targetPg.start();
+ try {
+ const targetDb = createDb(
+ `postgres://paperclip:[email protected]:${targetConfig.database.embeddedPostgresPort}/paperclip`,
+ );
+ const seededUsers = await targetDb.select().from(authUsers);
+ expect(seededUsers.some((row) => row.email === "[email protected]")).toBe(true);
+ } finally {
+ await targetPg.stop();
+ }
+ } finally {
+ process.chdir(originalCwd);
+ await sourceDb.cleanup();
+ fs.rmSync(tempRoot, { recursive: true, force: true });
+ }
+ },
+ 20000,
+ );
+
it("avoids ports already claimed by sibling worktree instance configs", async () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-claimed-ports-"));
const repoRoot = path.join(tempRoot, "repo");
diff --git a/doc/DEPLOYMENT-MODES.md b/doc/DEPLOYMENT-MODES.md
index a7b8d7fb0a..bf8dbdd4c7 100644
--- a/doc/DEPLOYMENT-MODES.md
+++ b/doc/DEPLOYMENT-MODES.md
@@ -142,3 +142,4 @@ This prevents lockout when a user migrates from long-running local trusted usage
- implementation plan: `doc/plans/deployment-auth-mode-consolidation.md`
- V1 contract: `doc/SPEC-implementation.md`
- operator workflows: `doc/DEVELOPING.md` and `doc/CLI.md`
+- invite/join state map: `doc/spec/invite-flow.md`
diff --git a/doc/PUBLISHING.md b/doc/PUBLISHING.md
index db56540dca..83a6c4a7be 100644
--- a/doc/PUBLISHING.md
+++ b/doc/PUBLISHING.md
@@ -115,38 +115,6 @@ If the first real publish returns npm `E404`, check npm-side prerequisites befor
- The initial publish must include `--access public` for a public scoped package.
- npm also requires either account 2FA for publishing or a granular token that is allowed to bypass 2FA.
-### Manual first publish for `@paperclipai/mcp-server`
-
-If you need to publish only the MCP server package once by hand, use:
-
-- `@paperclipai/mcp-server`
-
-Recommended flow from the repo root:
-
-```bash
-# optional sanity check: this 404s until the first publish exists
-npm view @paperclipai/mcp-server version
-
-# make sure the build output is fresh
-pnpm --filter @paperclipai/mcp-server build
-
-# confirm your local npm auth before the real publish
-npm whoami
-
-# safe preview of the exact publish payload
-cd packages/mcp-server
-pnpm publish --dry-run --no-git-checks --access public
-
-# real publish
-pnpm publish --no-git-checks --access public
-```
-
-Notes:
-
-- Publish from `packages/mcp-server/`, not the repo root.
-- If `npm view @paperclipai/mcp-server version` already returns the same version that is in [`packages/mcp-server/package.json`](../packages/mcp-server/package.json), do not republish. Bump the version or use the normal repo-wide release flow in [`scripts/release.sh`](../scripts/release.sh).
-- The same npm-side prerequisites apply as above: valid npm auth, permission to publish to the `@paperclipai` scope, `--access public`, and the required publish auth/2FA policy.
-
## Version formats
Paperclip uses calendar versions:
diff --git a/doc/spec/invite-flow.md b/doc/spec/invite-flow.md
new file mode 100644
index 0000000000..504744b038
--- /dev/null
+++ b/doc/spec/invite-flow.md
@@ -0,0 +1,299 @@
+# Invite Flow State Map
+
+Status: Current implementation map
+Date: 2026-04-13
+
+This document maps the current invite creation and acceptance states implemented in:
+
+- `ui/src/pages/CompanyInvites.tsx`
+- `ui/src/pages/CompanySettings.tsx`
+- `ui/src/pages/InviteLanding.tsx`
+- `server/src/routes/access.ts`
+- `server/src/lib/join-request-dedupe.ts`
+
+## State Legend
+
+- Invite state: `active`, `revoked`, `accepted`, `expired`
+- Join request status: `pending_approval`, `approved`, `rejected`
+- Claim secret state for agent joins: `available`, `consumed`, `expired`
+- Invite type: `company_join` or `bootstrap_ceo`
+- Join type: `human`, `agent`, or `both`
+
+## Entity Lifecycle
+
+```mermaid
+flowchart TD
+ Board[Board user on invite screen]
+ HumanInvite[Create human company invite]
+ OpenClawInvite[Generate OpenClaw invite prompt]
+ Active[Invite state: active]
+ Revoked[Invite state: revoked]
+ Expired[Invite state: expired]
+ Accepted[Invite state: accepted]
+ BootstrapDone[Bootstrap accepted<br/>no join request]
+ HumanReuse{Matching human join request<br/>already exists for same user/email?}
+ HumanPending[Join request<br/>pending_approval]
+ HumanApproved[Join request<br/>approved]
+ HumanRejected[Join request<br/>rejected]
+ AgentPending[Agent join request<br/>pending_approval<br/>+ optional claim secret]
+ AgentApproved[Agent join request<br/>approved]
+ AgentRejected[Agent join request<br/>rejected]
+ ClaimAvailable[Claim secret available]
+ ClaimConsumed[Claim secret consumed]
+ ClaimExpired[Claim secret expired]
+ OpenClawReplay[Special replay path:<br/>accepted invite can be POSTed again<br/>for openclaw_gateway only]
+
+ Board --> HumanInvite --> Active
+ Board --> OpenClawInvite --> Active
+ Active --> Revoked: revoke
+ Active --> Expired: expiresAt passes
+
+ Active --> BootstrapDone: bootstrap_ceo accept
+ BootstrapDone --> Accepted
+
+ Active --> HumanReuse: human accept
+ HumanReuse --> HumanPending: reuse existing pending request
+ HumanReuse --> HumanApproved: reuse existing approved request
+ HumanReuse --> HumanPending: no reusable request<br/>create new request
+ HumanPending --> HumanApproved: board approves
+ HumanPending --> HumanRejected: board rejects
+ HumanPending --> Accepted
+ HumanApproved --> Accepted
+
+ Active --> AgentPending: agent accept
+ AgentPending --> Accepted
+ AgentPending --> AgentApproved: board approves
+ AgentPending --> AgentRejected: board rejects
+ AgentApproved --> ClaimAvailable: createdAgentId + claimSecretHash
+ ClaimAvailable --> ClaimConsumed: POST claim-api-key succeeds
+ ClaimAvailable --> ClaimExpired: secret expires
+
+ Accepted --> OpenClawReplay
+ OpenClawReplay --> AgentPending
+ OpenClawReplay --> AgentApproved
+```
+
+## Board-Side Screen States
+
+```mermaid
+stateDiagram-v2
+ [*] --> CompanySelection
+
+ CompanySelection --> NoCompany: no company selected
+ CompanySelection --> LoadingHistory: selectedCompanyId present
+ LoadingHistory --> HistoryError: listInvites failed
+ LoadingHistory --> Ready: listInvites succeeded
+
+ state Ready {
+ [*] --> EmptyHistory
+ EmptyHistory --> PopulatedHistory: invites exist
+ PopulatedHistory --> LoadingMore: View more
+ LoadingMore --> PopulatedHistory: next page loaded
+
+ PopulatedHistory --> RevokePending: Revoke active invite
+ RevokePending --> PopulatedHistory: revoke succeeded
+ RevokePending --> PopulatedHistory: revoke failed
+
+ EmptyHistory --> CreatePending: Create invite
+ PopulatedHistory --> CreatePending: Create invite
+ CreatePending --> LatestInviteVisible: create succeeded
+ CreatePending --> Ready: create failed
+ LatestInviteVisible --> CopiedToast: clipboard copy succeeded
+ LatestInviteVisible --> Ready: navigate away or refresh
+ }
+
+ CompanySelection --> OpenClawPromptReady: Company settings prompt generator
+ OpenClawPromptReady --> OpenClawPromptPending: Generate OpenClaw Invite Prompt
+ OpenClawPromptPending --> OpenClawSnippetVisible: prompt generated
+ OpenClawPromptPending --> OpenClawPromptReady: generation failed
+```
+
+## Invite Landing Screen States
+
+```mermaid
+stateDiagram-v2
+ [*] --> TokenGate
+
+ TokenGate --> InvalidToken: token missing
+ TokenGate --> Loading: token present
+ Loading --> InviteUnavailable: invite fetch failed or invite not returned
+ Loading --> CheckingAccess: signed-in session and invite.companyId
+ Loading --> InviteResolved: invite loaded without membership check
+ Loading --> AcceptedInviteSummary: invite already consumed<br/>but linked join request still exists
+
+ CheckingAccess --> RedirectToBoard: current user already belongs to company
+ CheckingAccess --> InviteResolved: membership check finished and no join-request summary state is active
+ CheckingAccess --> AcceptedInviteSummary: membership check finished and invite has joinRequestStatus
+
+ state InviteResolved {
+ [*] --> Branch
+ Branch --> AgentForm: company_join + allowedJoinTypes=agent
+ Branch --> InlineAuth: authenticated mode + no session + join is not agent-only
+ Branch --> AcceptReady: bootstrap invite or human-ready session/local_trusted
+
+ InlineAuth --> InlineAuth: toggle sign-up/sign-in
+ InlineAuth --> InlineAuth: auth validation or auth error message
+ InlineAuth --> RedirectToBoard: auth succeeded and company membership already exists
+ InlineAuth --> AcceptPending: auth succeeded and invite still needs acceptance
+
+ AgentForm --> AcceptPending: submit request
+ AgentForm --> AgentForm: validation or accept error
+
+ AcceptReady --> AcceptPending: Accept invite
+ AcceptReady --> AcceptReady: accept error
+ }
+
+ AcceptPending --> BootstrapComplete: bootstrapAccepted=true
+ AcceptPending --> RedirectToBoard: join status=approved
+ AcceptPending --> PendingApprovalResult: join status=pending_approval
+ AcceptPending --> RejectedResult: join status=rejected
+
+ state AcceptedInviteSummary {
+ [*] --> SummaryBranch
+ SummaryBranch --> PendingApprovalReload: joinRequestStatus=pending_approval
+ SummaryBranch --> OpeningCompany: joinRequestStatus=approved<br/>and human invite user is now a member
+ SummaryBranch --> RejectedReload: joinRequestStatus=rejected
+ SummaryBranch --> ConsumedReload: approved agent invite or other consumed state
+ }
+
+ PendingApprovalResult --> PendingApprovalReload: reload after submit
+ RejectedResult --> RejectedReload: reload after board rejects
+ RedirectToBoard --> OpeningCompany: brief pre-navigation render when approved membership is detected
+ OpeningCompany --> RedirectToBoard: navigate to board
+```
+
+## Sequence Diagrams
+
+### Human Invite Creation And First Acceptance
+
+```mermaid
+sequenceDiagram
+ autonumber
+ actor Board as Board user
+ participant Settings as Company Invites UI
+ participant API as Access routes
+ participant Invites as invites table
+ actor Invitee as Invite recipient
+ participant Landing as Invite landing UI
+ participant Auth as Auth session
+ participant Join as join_requests table
+
+ Board->>Settings: Choose role and click Create invite
+ Settings->>API: POST /api/companies/:companyId/invites
+ API->>Invites: Insert active invite
+ API-->>Settings: inviteUrl + metadata
+
+ Invitee->>Landing: Open invite URL
+ Landing->>API: GET /api/invites/:token
+ API->>Invites: Load active invite
+ API-->>Landing: Invite summary
+
+ alt Authenticated mode and no session
+ Landing->>Auth: Sign up or sign in
+ Auth-->>Landing: Session established
+ end
+
+ Landing->>API: POST /api/invites/:token/accept (requestType=human)
+ API->>Join: Look for reusable human join request
+ alt Reusable pending or approved request exists
+ API->>Invites: Mark invite accepted
+ API-->>Landing: Existing join request status
+ else No reusable request exists
+ API->>Invites: Mark invite accepted
+ API->>Join: Insert pending_approval join request
+ API-->>Landing: New pending_approval join request
+ end
+```
+
+### Human Approval And Reload Path
+
+```mermaid
+sequenceDiagram
+ autonumber
+ actor Invitee as Invite recipient
+ participant Landing as Invite landing UI
+ participant API as Access routes
+ participant Join as join_requests table
+ actor Approver as Company admin
+ participant Queue as Access queue UI
+ participant Membership as company_memberships + grants
+
+ Invitee->>Landing: Reload consumed invite URL
+ Landing->>API: GET /api/invites/:token
+ API->>Join: Load join request by inviteId
+ API-->>Landing: joinRequestStatus + joinRequestType
+
+ alt joinRequestStatus = pending_approval
+ Landing-->>Invitee: Show waiting-for-approval panel
+ Approver->>Queue: Review request in Company Settings -> Access
+ Queue->>API: POST /companies/:companyId/join-requests/:requestId/approve
+ API->>Membership: Ensure membership and grants
+ API->>Join: Mark join request approved
+ Invitee->>Landing: Refresh after approval
+ Landing->>API: GET /api/invites/:token
+ API->>Join: Reload approved join request
+ API-->>Landing: approved status
+ Landing-->>Invitee: Opening company and redirect
+ else joinRequestStatus = rejected
+ Landing-->>Invitee: Show rejected error panel
+ else joinRequestStatus = approved but membership missing
+ Landing-->>Invitee: Fall through to consumed/unavailable state
+ end
+```
+
+### Agent Invite Approval, Claim, And Replay
+
+```mermaid
+sequenceDiagram
+ autonumber
+ actor Board as Board user
+ participant Settings as Company Settings UI
+ participant API as Access routes
+ participant Invites as invites table
+ actor Gateway as OpenClaw gateway agent
+ participant Join as join_requests table
+ actor Approver as Company admin
+ participant Agents as agents table
+ participant Keys as agent_api_keys table
+
+ Board->>Settings: Generate OpenClaw invite prompt
+ Settings->>API: POST /api/companies/:companyId/openclaw-invite-prompt
+ API->>Invites: Insert active agent invite
+ API-->>Settings: Prompt text + invite token
+
+ Gateway->>API: POST /api/invites/:token/accept (agent, openclaw_gateway)
+ API->>Invites: Mark invite accepted
+ API->>Join: Insert pending_approval join request + claimSecretHash
+ API-->>Gateway: requestId + claimSecret + claimApiKeyPath
+
+ Approver->>API: POST /companies/:companyId/join-requests/:requestId/approve
+ API->>Agents: Create agent + membership + grants
+ API->>Join: Mark request approved and store createdAgentId
+
+ Gateway->>API: POST /api/join-requests/:requestId/claim-api-key (claimSecret)
+ API->>Keys: Create initial API key
+ API->>Join: Mark claim secret consumed
+ API-->>Gateway: Plaintext Paperclip API key
+
+ opt Replay accepted invite for updated gateway defaults
+ Gateway->>API: POST /api/invites/:token/accept again
+ API->>Join: Reuse existing approved or pending request
+ API->>Agents: Update approved agent adapter config when applicable
+ API-->>Gateway: Updated join request payload
+ end
+```
+
+## Notes
+
+- `GET /api/invites/:token` treats `revoked` and `expired` invites as unavailable. Accepted invites remain resolvable when they already have a linked join request, and the summary now includes `joinRequestStatus` plus `joinRequestType`.
+- Human acceptance consumes the invite immediately and then either creates a new join request or reuses an existing `pending_approval` or `approved` human join request for the same user/email.
+- The landing page has two layers of post-accept UI:
+ - immediate mutation-result UI from `POST /api/invites/:token/accept`
+ - reload-time summary UI from `GET /api/invites/:token` once the invite has already been consumed
+- Reload behavior for accepted company invites is now status-sensitive:
+ - `pending_approval` re-renders the waiting-for-approval panel
+ - `rejected` renders the "This join request was not approved." error panel
+ - `approved` only becomes a success path for human invites after membership is visible to the current session; otherwise the page falls through to the generic consumed/unavailable state
+- `GET /api/invites/:token/logo` still rejects accepted invites, so accepted-invite reload states may fall back to the generated company icon even though the summary payload still carries `companyLogoUrl`.
+- The only accepted-invite replay path in the current implementation is `POST /api/invites/:token/accept` for `agent` requests with `adapterType=openclaw_gateway`, and only when the existing join request is still `pending_approval` or already `approved`.
+- `bootstrap_ceo` invites are one-time and do not create join requests.
diff --git a/docs/docs.json b/docs/docs.json
index be48cc8e9e..54dfb003eb 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -48,6 +48,8 @@
"guides/board-operator/managing-tasks",
"guides/board-operator/execution-workspaces-and-runtime-services",
"guides/board-operator/delegation",
+ "guides/board-operator/execution-workspaces-and-runtime-services",
+ "guides/board-operator/delegation",
"guides/board-operator/approvals",
"guides/board-operator/costs-and-budgets",
"guides/board-operator/activity-log",
diff --git a/package.json b/package.json
index ea356f0b49..ce666bfaf3 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"smoke:openclaw-sse-standalone": "./scripts/smoke/openclaw-sse-standalone.sh",
"test:e2e": "npx playwright test --config tests/e2e/playwright.config.ts",
"test:e2e:headed": "npx playwright test --config tests/e2e/playwright.config.ts --headed",
+ "test:e2e:multiuser-authenticated": "npx playwright test --config tests/e2e/playwright-multiuser-authenticated.config.ts",
"evals:smoke": "cd evals/promptfoo && npx [email protected] eval",
"test:release-smoke": "npx playwright test --config tests/release-smoke/playwright.config.ts",
"test:release-smoke:headed": "npx playwright test --config tests/release-smoke/playwright.config.ts --headed",
diff --git a/packages/db/scripts/create-auth-bootstrap-invite.ts b/packages/db/scripts/create-auth-bootstrap-invite.ts
new file mode 100644
index 0000000000..7af8a7d34f
--- /dev/null
+++ b/packages/db/scripts/create-auth-bootstrap-invite.ts
@@ -0,0 +1,84 @@
+import { createHash, randomBytes } from "node:crypto";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { and, eq, gt, isNull } from "drizzle-orm";
+import { createDb } from "../src/client.js";
+import { invites } from "../src/schema/index.js";
+
+function hashToken(token: string) {
+ return createHash("sha256").update(token).digest("hex");
+}
+
+function createInviteToken() {
+ return `pcp_bootstrap_${randomBytes(24).toString("hex")}`;
+}
+
+function readArg(flag: string) {
+ const index = process.argv.indexOf(flag);
+ if (index === -1) return null;
+ return process.argv[index + 1] ?? null;
+}
+
+async function main() {
+ const configPath = readArg("--config");
+ const baseUrl = readArg("--base-url");
+
+ if (!configPath || !baseUrl) {
+ throw new Error("Usage: tsx create-auth-bootstrap-invite.ts --config <path> --base-url <url>");
+ }
+
+ const config = JSON.parse(readFileSync(path.resolve(configPath), "utf8")) as {
+ database?: {
+ mode?: string;
+ embeddedPostgresPort?: number;
+ connectionString?: string;
+ };
+ };
+ const dbUrl =
+ config.database?.mode === "postgres"
+ ? config.database.connectionString
+ : `postgres://paperclip:[email protected]:${config.database?.embeddedPostgresPort ?? 54329}/paperclip`;
+ if (!dbUrl) {
+ throw new Error(`Could not resolve database connection from ${configPath}`);
+ }
+
+ const db = createDb(dbUrl);
+ const closableDb = db as typeof db & {
+ $client?: {
+ end?: (options?: { timeout?: number }) => Promise<void>;
+ };
+ };
+
+ try {
+ const now = new Date();
+ await db
+ .update(invites)
+ .set({ revokedAt: now, updatedAt: now })
+ .where(
+ and(
+ eq(invites.inviteType, "bootstrap_ceo"),
+ isNull(invites.revokedAt),
+ isNull(invites.acceptedAt),
+ gt(invites.expiresAt, now)
+ )
+ );
+
+ const token = createInviteToken();
+ await db.insert(invites).values({
+ inviteType: "bootstrap_ceo",
+ tokenHash: hashToken(token),
+ allowedJoinTypes: "human",
+ expiresAt: new Date(Date.now() + 72 * 60 * 60 * 1000),
+ invitedByUserId: "system",
+ });
+
+ process.stdout.write(`${baseUrl.replace(/\/+$/, "")}/invite/${token}\n`);
+ } finally {
+ await closableDb.$client?.end?.({ timeout: 5 }).catch(() => undefined);
+ }
+}
+
+main().catch((error) => {
+ process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
+ process.exit(1);
+});
diff --git a/packages/db/src/migrations/0057_tidy_join_requests.sql b/packages/db/src/migrations/0057_tidy_join_requests.sql
new file mode 100644
index 0000000000..8ab27b410b
--- /dev/null
+++ b/packages/db/src/migrations/0057_tidy_join_requests.sql
@@ -0,0 +1,57 @@
+WITH ranked_user_requests AS (
+ SELECT
+ id,
+ row_number() OVER (
+ PARTITION BY company_id, requesting_user_id
+ ORDER BY created_at ASC, id ASC
+ ) AS rank
+ FROM join_requests
+ WHERE request_type = 'human'
+ AND status = 'pending_approval'
+ AND requesting_user_id IS NOT NULL
+)
+UPDATE join_requests
+SET
+ status = 'rejected',
+ rejected_at = COALESCE(rejected_at, now()),
+ updated_at = now()
+WHERE id IN (
+ SELECT id
+ FROM ranked_user_requests
+ WHERE rank > 1
+);
+--> statement-breakpoint
+WITH ranked_email_requests AS (
+ SELECT
+ id,
+ row_number() OVER (
+ PARTITION BY company_id, lower(request_email_snapshot)
+ ORDER BY created_at ASC, id ASC
+ ) AS rank
+ FROM join_requests
+ WHERE request_type = 'human'
+ AND status = 'pending_approval'
+ AND request_email_snapshot IS NOT NULL
+)
+UPDATE join_requests
+SET
+ status = 'rejected',
+ rejected_at = COALESCE(rejected_at, now()),
+ updated_at = now()
+WHERE id IN (
+ SELECT id
+ FROM ranked_email_requests
+ WHERE rank > 1
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "join_requests_pending_human_user_uq"
+ON "join_requests" USING btree ("company_id", "requesting_user_id")
+WHERE "request_type" = 'human'
+ AND "status" = 'pending_approval'
+ AND "requesting_user_id" IS NOT NULL;
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "join_requests_pending_human_email_uq"
+ON "join_requests" USING btree ("company_id", lower("request_email_snapshot"))
+WHERE "request_type" = 'human'
+ AND "status" = 'pending_approval'
+ AND "request_email_snapshot" IS NOT NULL;
diff --git a/packages/db/src/migrations/meta/0057_snapshot.json b/packages/db/src/migrations/meta/0057_snapshot.json
new file mode 100644
index 0000000000..f57e05e33d
--- /dev/null
+++ b/packages/db/src/migrations/meta/0057_snapshot.json
@@ -0,0 +1,13432 @@
+{
+ "id": "c13b1dd5-1860-4d0b-aeb2-5bb197766983",
+ "prevId": "5b9211ec-73c0-4825-bdf7-08ba60b6915c",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.activity_log": {
+ "name": "activity_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_type": {
+ "name": "actor_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'system'"
+ },
+ "actor_id": {
+ "name": "actor_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity_type": {
+ "name": "entity_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity_id": {
+ "name": "entity_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "details": {
+ "name": "details",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "activity_log_company_created_idx": {
+ "name": "activity_log_company_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "activity_log_run_id_idx": {
+ "name": "activity_log_run_id_idx",
+ "columns": [
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "activity_log_entity_type_id_idx": {
+ "name": "activity_log_entity_type_id_idx",
+ "columns": [
+ {
+ "expression": "entity_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "entity_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "activity_log_company_id_companies_id_fk": {
+ "name": "activity_log_company_id_companies_id_fk",
+ "tableFrom": "activity_log",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "activity_log_agent_id_agents_id_fk": {
+ "name": "activity_log_agent_id_agents_id_fk",
+ "tableFrom": "activity_log",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "activity_log_run_id_heartbeat_runs_id_fk": {
+ "name": "activity_log_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "activity_log",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_api_keys": {
+ "name": "agent_api_keys",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key_hash": {
+ "name": "key_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_api_keys_key_hash_idx": {
+ "name": "agent_api_keys_key_hash_idx",
+ "columns": [
+ {
+ "expression": "key_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_api_keys_company_agent_idx": {
+ "name": "agent_api_keys_company_agent_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_api_keys_agent_id_agents_id_fk": {
+ "name": "agent_api_keys_agent_id_agents_id_fk",
+ "tableFrom": "agent_api_keys",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_api_keys_company_id_companies_id_fk": {
+ "name": "agent_api_keys_company_id_companies_id_fk",
+ "tableFrom": "agent_api_keys",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_config_revisions": {
+ "name": "agent_config_revisions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'patch'"
+ },
+ "rolled_back_from_revision_id": {
+ "name": "rolled_back_from_revision_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changed_keys": {
+ "name": "changed_keys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "before_config": {
+ "name": "before_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "after_config": {
+ "name": "after_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_config_revisions_company_agent_created_idx": {
+ "name": "agent_config_revisions_company_agent_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_config_revisions_agent_created_idx": {
+ "name": "agent_config_revisions_agent_created_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_config_revisions_company_id_companies_id_fk": {
+ "name": "agent_config_revisions_company_id_companies_id_fk",
+ "tableFrom": "agent_config_revisions",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_config_revisions_agent_id_agents_id_fk": {
+ "name": "agent_config_revisions_agent_id_agents_id_fk",
+ "tableFrom": "agent_config_revisions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_config_revisions_created_by_agent_id_agents_id_fk": {
+ "name": "agent_config_revisions_created_by_agent_id_agents_id_fk",
+ "tableFrom": "agent_config_revisions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_runtime_state": {
+ "name": "agent_runtime_state",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "adapter_type": {
+ "name": "adapter_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "state_json": {
+ "name": "state_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_run_id": {
+ "name": "last_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_run_status": {
+ "name": "last_run_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_input_tokens": {
+ "name": "total_input_tokens",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "total_output_tokens": {
+ "name": "total_output_tokens",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "total_cached_input_tokens": {
+ "name": "total_cached_input_tokens",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "total_cost_cents": {
+ "name": "total_cost_cents",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_runtime_state_company_agent_idx": {
+ "name": "agent_runtime_state_company_agent_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_runtime_state_company_updated_idx": {
+ "name": "agent_runtime_state_company_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_runtime_state_agent_id_agents_id_fk": {
+ "name": "agent_runtime_state_agent_id_agents_id_fk",
+ "tableFrom": "agent_runtime_state",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_runtime_state_company_id_companies_id_fk": {
+ "name": "agent_runtime_state_company_id_companies_id_fk",
+ "tableFrom": "agent_runtime_state",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_task_sessions": {
+ "name": "agent_task_sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "adapter_type": {
+ "name": "adapter_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_key": {
+ "name": "task_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_params_json": {
+ "name": "session_params_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_display_id": {
+ "name": "session_display_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_run_id": {
+ "name": "last_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_task_sessions_company_agent_adapter_task_uniq": {
+ "name": "agent_task_sessions_company_agent_adapter_task_uniq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "adapter_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "task_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_task_sessions_company_agent_updated_idx": {
+ "name": "agent_task_sessions_company_agent_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_task_sessions_company_task_updated_idx": {
+ "name": "agent_task_sessions_company_task_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "task_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_task_sessions_company_id_companies_id_fk": {
+ "name": "agent_task_sessions_company_id_companies_id_fk",
+ "tableFrom": "agent_task_sessions",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_task_sessions_agent_id_agents_id_fk": {
+ "name": "agent_task_sessions_agent_id_agents_id_fk",
+ "tableFrom": "agent_task_sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_task_sessions_last_run_id_heartbeat_runs_id_fk": {
+ "name": "agent_task_sessions_last_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "agent_task_sessions",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "last_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_wakeup_requests": {
+ "name": "agent_wakeup_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger_detail": {
+ "name": "trigger_detail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "coalesced_count": {
+ "name": "coalesced_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "requested_by_actor_type": {
+ "name": "requested_by_actor_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_by_actor_id": {
+ "name": "requested_by_actor_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idempotency_key": {
+ "name": "idempotency_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_at": {
+ "name": "requested_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "claimed_at": {
+ "name": "claimed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_wakeup_requests_company_agent_status_idx": {
+ "name": "agent_wakeup_requests_company_agent_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_wakeup_requests_company_requested_idx": {
+ "name": "agent_wakeup_requests_company_requested_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "requested_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_wakeup_requests_agent_requested_idx": {
+ "name": "agent_wakeup_requests_agent_requested_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "requested_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_wakeup_requests_company_id_companies_id_fk": {
+ "name": "agent_wakeup_requests_company_id_companies_id_fk",
+ "tableFrom": "agent_wakeup_requests",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_wakeup_requests_agent_id_agents_id_fk": {
+ "name": "agent_wakeup_requests_agent_id_agents_id_fk",
+ "tableFrom": "agent_wakeup_requests",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agents": {
+ "name": "agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'general'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'idle'"
+ },
+ "reports_to": {
+ "name": "reports_to",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "adapter_type": {
+ "name": "adapter_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'process'"
+ },
+ "adapter_config": {
+ "name": "adapter_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "runtime_config": {
+ "name": "runtime_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "budget_monthly_cents": {
+ "name": "budget_monthly_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "spent_monthly_cents": {
+ "name": "spent_monthly_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "pause_reason": {
+ "name": "pause_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "paused_at": {
+ "name": "paused_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_heartbeat_at": {
+ "name": "last_heartbeat_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agents_company_status_idx": {
+ "name": "agents_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_company_reports_to_idx": {
+ "name": "agents_company_reports_to_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "reports_to",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agents_company_id_companies_id_fk": {
+ "name": "agents_company_id_companies_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agents_reports_to_agents_id_fk": {
+ "name": "agents_reports_to_agents_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "reports_to"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.approval_comments": {
+ "name": "approval_comments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approval_id": {
+ "name": "approval_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "author_agent_id": {
+ "name": "author_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "approval_comments_company_idx": {
+ "name": "approval_comments_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "approval_comments_approval_idx": {
+ "name": "approval_comments_approval_idx",
+ "columns": [
+ {
+ "expression": "approval_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "approval_comments_approval_created_idx": {
+ "name": "approval_comments_approval_created_idx",
+ "columns": [
+ {
+ "expression": "approval_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "approval_comments_company_id_companies_id_fk": {
+ "name": "approval_comments_company_id_companies_id_fk",
+ "tableFrom": "approval_comments",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "approval_comments_approval_id_approvals_id_fk": {
+ "name": "approval_comments_approval_id_approvals_id_fk",
+ "tableFrom": "approval_comments",
+ "tableTo": "approvals",
+ "columnsFrom": [
+ "approval_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "approval_comments_author_agent_id_agents_id_fk": {
+ "name": "approval_comments_author_agent_id_agents_id_fk",
+ "tableFrom": "approval_comments",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "author_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.approvals": {
+ "name": "approvals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "requested_by_agent_id": {
+ "name": "requested_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_by_user_id": {
+ "name": "requested_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision_note": {
+ "name": "decision_note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_by_user_id": {
+ "name": "decided_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_at": {
+ "name": "decided_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "approvals_company_status_type_idx": {
+ "name": "approvals_company_status_type_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "approvals_company_id_companies_id_fk": {
+ "name": "approvals_company_id_companies_id_fk",
+ "tableFrom": "approvals",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "approvals_requested_by_agent_id_agents_id_fk": {
+ "name": "approvals_requested_by_agent_id_agents_id_fk",
+ "tableFrom": "approvals",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "requested_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.assets": {
+ "name": "assets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "object_key": {
+ "name": "object_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content_type": {
+ "name": "content_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "byte_size": {
+ "name": "byte_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sha256": {
+ "name": "sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "original_filename": {
+ "name": "original_filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "assets_company_created_idx": {
+ "name": "assets_company_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "assets_company_provider_idx": {
+ "name": "assets_company_provider_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "assets_company_object_key_uq": {
+ "name": "assets_company_object_key_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "object_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "assets_company_id_companies_id_fk": {
+ "name": "assets_company_id_companies_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "assets_created_by_agent_id_agents_id_fk": {
+ "name": "assets_created_by_agent_id_agents_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.board_api_keys": {
+ "name": "board_api_keys",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key_hash": {
+ "name": "key_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "board_api_keys_key_hash_idx": {
+ "name": "board_api_keys_key_hash_idx",
+ "columns": [
+ {
+ "expression": "key_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "board_api_keys_user_idx": {
+ "name": "board_api_keys_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "board_api_keys_user_id_user_id_fk": {
+ "name": "board_api_keys_user_id_user_id_fk",
+ "tableFrom": "board_api_keys",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.budget_incidents": {
+ "name": "budget_incidents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "policy_id": {
+ "name": "policy_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_type": {
+ "name": "scope_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_id": {
+ "name": "scope_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metric": {
+ "name": "metric",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_kind": {
+ "name": "window_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_start": {
+ "name": "window_start",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_end": {
+ "name": "window_end",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "threshold_type": {
+ "name": "threshold_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount_limit": {
+ "name": "amount_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount_observed": {
+ "name": "amount_observed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "approval_id": {
+ "name": "approval_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "budget_incidents_company_status_idx": {
+ "name": "budget_incidents_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "budget_incidents_company_scope_idx": {
+ "name": "budget_incidents_company_scope_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "budget_incidents_policy_window_threshold_idx": {
+ "name": "budget_incidents_policy_window_threshold_idx",
+ "columns": [
+ {
+ "expression": "policy_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "window_start",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "threshold_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"budget_incidents\".\"status\" <> 'dismissed'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "budget_incidents_company_id_companies_id_fk": {
+ "name": "budget_incidents_company_id_companies_id_fk",
+ "tableFrom": "budget_incidents",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "budget_incidents_policy_id_budget_policies_id_fk": {
+ "name": "budget_incidents_policy_id_budget_policies_id_fk",
+ "tableFrom": "budget_incidents",
+ "tableTo": "budget_policies",
+ "columnsFrom": [
+ "policy_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "budget_incidents_approval_id_approvals_id_fk": {
+ "name": "budget_incidents_approval_id_approvals_id_fk",
+ "tableFrom": "budget_incidents",
+ "tableTo": "approvals",
+ "columnsFrom": [
+ "approval_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.budget_policies": {
+ "name": "budget_policies",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_type": {
+ "name": "scope_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_id": {
+ "name": "scope_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metric": {
+ "name": "metric",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'billed_cents'"
+ },
+ "window_kind": {
+ "name": "window_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "warn_percent": {
+ "name": "warn_percent",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 80
+ },
+ "hard_stop_enabled": {
+ "name": "hard_stop_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "notify_enabled": {
+ "name": "notify_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_user_id": {
+ "name": "updated_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "budget_policies_company_scope_active_idx": {
+ "name": "budget_policies_company_scope_active_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "is_active",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "budget_policies_company_window_idx": {
+ "name": "budget_policies_company_window_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "window_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "metric",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "budget_policies_company_scope_metric_unique_idx": {
+ "name": "budget_policies_company_scope_metric_unique_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "metric",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "window_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "budget_policies_company_id_companies_id_fk": {
+ "name": "budget_policies_company_id_companies_id_fk",
+ "tableFrom": "budget_policies",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cli_auth_challenges": {
+ "name": "cli_auth_challenges",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "secret_hash": {
+ "name": "secret_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_name": {
+ "name": "client_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_access": {
+ "name": "requested_access",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'board'"
+ },
+ "requested_company_id": {
+ "name": "requested_company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pending_key_hash": {
+ "name": "pending_key_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pending_key_name": {
+ "name": "pending_key_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approved_by_user_id": {
+ "name": "approved_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "board_api_key_id": {
+ "name": "board_api_key_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approved_at": {
+ "name": "approved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancelled_at": {
+ "name": "cancelled_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "cli_auth_challenges_secret_hash_idx": {
+ "name": "cli_auth_challenges_secret_hash_idx",
+ "columns": [
+ {
+ "expression": "secret_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cli_auth_challenges_approved_by_idx": {
+ "name": "cli_auth_challenges_approved_by_idx",
+ "columns": [
+ {
+ "expression": "approved_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cli_auth_challenges_requested_company_idx": {
+ "name": "cli_auth_challenges_requested_company_idx",
+ "columns": [
+ {
+ "expression": "requested_company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "cli_auth_challenges_requested_company_id_companies_id_fk": {
+ "name": "cli_auth_challenges_requested_company_id_companies_id_fk",
+ "tableFrom": "cli_auth_challenges",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "requested_company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "cli_auth_challenges_approved_by_user_id_user_id_fk": {
+ "name": "cli_auth_challenges_approved_by_user_id_user_id_fk",
+ "tableFrom": "cli_auth_challenges",
+ "tableTo": "user",
+ "columnsFrom": [
+ "approved_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "cli_auth_challenges_board_api_key_id_board_api_keys_id_fk": {
+ "name": "cli_auth_challenges_board_api_key_id_board_api_keys_id_fk",
+ "tableFrom": "cli_auth_challenges",
+ "tableTo": "board_api_keys",
+ "columnsFrom": [
+ "board_api_key_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.companies": {
+ "name": "companies",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "pause_reason": {
+ "name": "pause_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "paused_at": {
+ "name": "paused_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_prefix": {
+ "name": "issue_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'PAP'"
+ },
+ "issue_counter": {
+ "name": "issue_counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "budget_monthly_cents": {
+ "name": "budget_monthly_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "spent_monthly_cents": {
+ "name": "spent_monthly_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "require_board_approval_for_new_agents": {
+ "name": "require_board_approval_for_new_agents",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "feedback_data_sharing_enabled": {
+ "name": "feedback_data_sharing_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "feedback_data_sharing_consent_at": {
+ "name": "feedback_data_sharing_consent_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_data_sharing_consent_by_user_id": {
+ "name": "feedback_data_sharing_consent_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_data_sharing_terms_version": {
+ "name": "feedback_data_sharing_terms_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "brand_color": {
+ "name": "brand_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "companies_issue_prefix_idx": {
+ "name": "companies_issue_prefix_idx",
+ "columns": [
+ {
+ "expression": "issue_prefix",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_logos": {
+ "name": "company_logos",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "asset_id": {
+ "name": "asset_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "company_logos_company_uq": {
+ "name": "company_logos_company_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_logos_asset_uq": {
+ "name": "company_logos_asset_uq",
+ "columns": [
+ {
+ "expression": "asset_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_logos_company_id_companies_id_fk": {
+ "name": "company_logos_company_id_companies_id_fk",
+ "tableFrom": "company_logos",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "company_logos_asset_id_assets_id_fk": {
+ "name": "company_logos_asset_id_assets_id_fk",
+ "tableFrom": "company_logos",
+ "tableTo": "assets",
+ "columnsFrom": [
+ "asset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_memberships": {
+ "name": "company_memberships",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal_type": {
+ "name": "principal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal_id": {
+ "name": "principal_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "membership_role": {
+ "name": "membership_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "company_memberships_company_principal_unique_idx": {
+ "name": "company_memberships_company_principal_unique_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_memberships_principal_status_idx": {
+ "name": "company_memberships_principal_status_idx",
+ "columns": [
+ {
+ "expression": "principal_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_memberships_company_status_idx": {
+ "name": "company_memberships_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_memberships_company_id_companies_id_fk": {
+ "name": "company_memberships_company_id_companies_id_fk",
+ "tableFrom": "company_memberships",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_secret_versions": {
+ "name": "company_secret_versions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "secret_id": {
+ "name": "secret_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "material": {
+ "name": "material",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value_sha256": {
+ "name": "value_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "company_secret_versions_secret_idx": {
+ "name": "company_secret_versions_secret_idx",
+ "columns": [
+ {
+ "expression": "secret_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_secret_versions_value_sha256_idx": {
+ "name": "company_secret_versions_value_sha256_idx",
+ "columns": [
+ {
+ "expression": "value_sha256",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_secret_versions_secret_version_uq": {
+ "name": "company_secret_versions_secret_version_uq",
+ "columns": [
+ {
+ "expression": "secret_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "version",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_secret_versions_secret_id_company_secrets_id_fk": {
+ "name": "company_secret_versions_secret_id_company_secrets_id_fk",
+ "tableFrom": "company_secret_versions",
+ "tableTo": "company_secrets",
+ "columnsFrom": [
+ "secret_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "company_secret_versions_created_by_agent_id_agents_id_fk": {
+ "name": "company_secret_versions_created_by_agent_id_agents_id_fk",
+ "tableFrom": "company_secret_versions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_secrets": {
+ "name": "company_secrets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local_encrypted'"
+ },
+ "external_ref": {
+ "name": "external_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latest_version": {
+ "name": "latest_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "company_secrets_company_idx": {
+ "name": "company_secrets_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_secrets_company_provider_idx": {
+ "name": "company_secrets_company_provider_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_secrets_company_name_uq": {
+ "name": "company_secrets_company_name_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_secrets_company_id_companies_id_fk": {
+ "name": "company_secrets_company_id_companies_id_fk",
+ "tableFrom": "company_secrets",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "company_secrets_created_by_agent_id_agents_id_fk": {
+ "name": "company_secrets_created_by_agent_id_agents_id_fk",
+ "tableFrom": "company_secrets",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_skills": {
+ "name": "company_skills",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "markdown": {
+ "name": "markdown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_type": {
+ "name": "source_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local_path'"
+ },
+ "source_locator": {
+ "name": "source_locator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_ref": {
+ "name": "source_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trust_level": {
+ "name": "trust_level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'markdown_only'"
+ },
+ "compatibility": {
+ "name": "compatibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'compatible'"
+ },
+ "file_inventory": {
+ "name": "file_inventory",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "company_skills_company_key_idx": {
+ "name": "company_skills_company_key_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_skills_company_name_idx": {
+ "name": "company_skills_company_name_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_skills_company_id_companies_id_fk": {
+ "name": "company_skills_company_id_companies_id_fk",
+ "tableFrom": "company_skills",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.company_user_sidebar_preferences": {
+ "name": "company_user_sidebar_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_order": {
+ "name": "project_order",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "company_user_sidebar_preferences_company_idx": {
+ "name": "company_user_sidebar_preferences_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_user_sidebar_preferences_user_idx": {
+ "name": "company_user_sidebar_preferences_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "company_user_sidebar_preferences_company_user_uq": {
+ "name": "company_user_sidebar_preferences_company_user_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "company_user_sidebar_preferences_company_id_companies_id_fk": {
+ "name": "company_user_sidebar_preferences_company_id_companies_id_fk",
+ "tableFrom": "company_user_sidebar_preferences",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cost_events": {
+ "name": "cost_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "heartbeat_run_id": {
+ "name": "heartbeat_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "billing_code": {
+ "name": "billing_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "biller": {
+ "name": "biller",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unknown'"
+ },
+ "billing_type": {
+ "name": "billing_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unknown'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "cached_input_tokens": {
+ "name": "cached_input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "cost_cents": {
+ "name": "cost_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "occurred_at": {
+ "name": "occurred_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "cost_events_company_occurred_idx": {
+ "name": "cost_events_company_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cost_events_company_agent_occurred_idx": {
+ "name": "cost_events_company_agent_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cost_events_company_provider_occurred_idx": {
+ "name": "cost_events_company_provider_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cost_events_company_biller_occurred_idx": {
+ "name": "cost_events_company_biller_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "biller",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "cost_events_company_heartbeat_run_idx": {
+ "name": "cost_events_company_heartbeat_run_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "heartbeat_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "cost_events_company_id_companies_id_fk": {
+ "name": "cost_events_company_id_companies_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "cost_events_agent_id_agents_id_fk": {
+ "name": "cost_events_agent_id_agents_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "cost_events_issue_id_issues_id_fk": {
+ "name": "cost_events_issue_id_issues_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "cost_events_project_id_projects_id_fk": {
+ "name": "cost_events_project_id_projects_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "cost_events_goal_id_goals_id_fk": {
+ "name": "cost_events_goal_id_goals_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "cost_events_heartbeat_run_id_heartbeat_runs_id_fk": {
+ "name": "cost_events_heartbeat_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "cost_events",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "heartbeat_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_revisions": {
+ "name": "document_revisions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revision_number": {
+ "name": "revision_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "format": {
+ "name": "format",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'markdown'"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "change_summary": {
+ "name": "change_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_run_id": {
+ "name": "created_by_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_revisions_document_revision_uq": {
+ "name": "document_revisions_document_revision_uq",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "revision_number",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_revisions_company_document_created_idx": {
+ "name": "document_revisions_company_document_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_revisions_company_id_companies_id_fk": {
+ "name": "document_revisions_company_id_companies_id_fk",
+ "tableFrom": "document_revisions",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "document_revisions_document_id_documents_id_fk": {
+ "name": "document_revisions_document_id_documents_id_fk",
+ "tableFrom": "document_revisions",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_revisions_created_by_agent_id_agents_id_fk": {
+ "name": "document_revisions_created_by_agent_id_agents_id_fk",
+ "tableFrom": "document_revisions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "document_revisions_created_by_run_id_heartbeat_runs_id_fk": {
+ "name": "document_revisions_created_by_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "document_revisions",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "created_by_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "format": {
+ "name": "format",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'markdown'"
+ },
+ "latest_body": {
+ "name": "latest_body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "latest_revision_id": {
+ "name": "latest_revision_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latest_revision_number": {
+ "name": "latest_revision_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_agent_id": {
+ "name": "updated_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_user_id": {
+ "name": "updated_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_company_updated_idx": {
+ "name": "documents_company_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_company_created_idx": {
+ "name": "documents_company_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_company_id_companies_id_fk": {
+ "name": "documents_company_id_companies_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "documents_created_by_agent_id_agents_id_fk": {
+ "name": "documents_created_by_agent_id_agents_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "documents_updated_by_agent_id_agents_id_fk": {
+ "name": "documents_updated_by_agent_id_agents_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "updated_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.execution_workspaces": {
+ "name": "execution_workspaces",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_workspace_id": {
+ "name": "project_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_issue_id": {
+ "name": "source_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "strategy_type": {
+ "name": "strategy_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "cwd": {
+ "name": "cwd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "repo_url": {
+ "name": "repo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "base_ref": {
+ "name": "base_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "branch_name": {
+ "name": "branch_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_type": {
+ "name": "provider_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local_fs'"
+ },
+ "provider_ref": {
+ "name": "provider_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "derived_from_execution_workspace_id": {
+ "name": "derived_from_execution_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "opened_at": {
+ "name": "opened_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cleanup_eligible_at": {
+ "name": "cleanup_eligible_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cleanup_reason": {
+ "name": "cleanup_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "execution_workspaces_company_project_status_idx": {
+ "name": "execution_workspaces_company_project_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "execution_workspaces_company_project_workspace_status_idx": {
+ "name": "execution_workspaces_company_project_workspace_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "execution_workspaces_company_source_issue_idx": {
+ "name": "execution_workspaces_company_source_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "execution_workspaces_company_last_used_idx": {
+ "name": "execution_workspaces_company_last_used_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "last_used_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "execution_workspaces_company_branch_idx": {
+ "name": "execution_workspaces_company_branch_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "branch_name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "execution_workspaces_company_id_companies_id_fk": {
+ "name": "execution_workspaces_company_id_companies_id_fk",
+ "tableFrom": "execution_workspaces",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "execution_workspaces_project_id_projects_id_fk": {
+ "name": "execution_workspaces_project_id_projects_id_fk",
+ "tableFrom": "execution_workspaces",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "execution_workspaces_project_workspace_id_project_workspaces_id_fk": {
+ "name": "execution_workspaces_project_workspace_id_project_workspaces_id_fk",
+ "tableFrom": "execution_workspaces",
+ "tableTo": "project_workspaces",
+ "columnsFrom": [
+ "project_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "execution_workspaces_source_issue_id_issues_id_fk": {
+ "name": "execution_workspaces_source_issue_id_issues_id_fk",
+ "tableFrom": "execution_workspaces",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "source_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "execution_workspaces_derived_from_execution_workspace_id_execution_workspaces_id_fk": {
+ "name": "execution_workspaces_derived_from_execution_workspace_id_execution_workspaces_id_fk",
+ "tableFrom": "execution_workspaces",
+ "tableTo": "execution_workspaces",
+ "columnsFrom": [
+ "derived_from_execution_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feedback_exports": {
+ "name": "feedback_exports",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feedback_vote_id": {
+ "name": "feedback_vote_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "vote": {
+ "name": "vote",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local_only'"
+ },
+ "destination": {
+ "name": "destination",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "export_id": {
+ "name": "export_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consent_version": {
+ "name": "consent_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "schema_version": {
+ "name": "schema_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'paperclip-feedback-envelope-v2'"
+ },
+ "bundle_version": {
+ "name": "bundle_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'paperclip-feedback-bundle-v2'"
+ },
+ "payload_version": {
+ "name": "payload_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'paperclip-feedback-v1'"
+ },
+ "payload_digest": {
+ "name": "payload_digest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload_snapshot": {
+ "name": "payload_snapshot",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_summary": {
+ "name": "target_summary",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redaction_summary": {
+ "name": "redaction_summary",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempt_count": {
+ "name": "attempt_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_attempted_at": {
+ "name": "last_attempted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "exported_at": {
+ "name": "exported_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failure_reason": {
+ "name": "failure_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_exports_feedback_vote_idx": {
+ "name": "feedback_exports_feedback_vote_idx",
+ "columns": [
+ {
+ "expression": "feedback_vote_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_exports_company_created_idx": {
+ "name": "feedback_exports_company_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_exports_company_status_idx": {
+ "name": "feedback_exports_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_exports_company_issue_idx": {
+ "name": "feedback_exports_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_exports_company_project_idx": {
+ "name": "feedback_exports_company_project_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_exports_company_author_idx": {
+ "name": "feedback_exports_company_author_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feedback_exports_company_id_companies_id_fk": {
+ "name": "feedback_exports_company_id_companies_id_fk",
+ "tableFrom": "feedback_exports",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "feedback_exports_feedback_vote_id_feedback_votes_id_fk": {
+ "name": "feedback_exports_feedback_vote_id_feedback_votes_id_fk",
+ "tableFrom": "feedback_exports",
+ "tableTo": "feedback_votes",
+ "columnsFrom": [
+ "feedback_vote_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "feedback_exports_issue_id_issues_id_fk": {
+ "name": "feedback_exports_issue_id_issues_id_fk",
+ "tableFrom": "feedback_exports",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "feedback_exports_project_id_projects_id_fk": {
+ "name": "feedback_exports_project_id_projects_id_fk",
+ "tableFrom": "feedback_exports",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feedback_votes": {
+ "name": "feedback_votes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "vote": {
+ "name": "vote",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "shared_with_labs": {
+ "name": "shared_with_labs",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "shared_at": {
+ "name": "shared_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consent_version": {
+ "name": "consent_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redaction_summary": {
+ "name": "redaction_summary",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_votes_company_issue_idx": {
+ "name": "feedback_votes_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_votes_issue_target_idx": {
+ "name": "feedback_votes_issue_target_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_votes_author_idx": {
+ "name": "feedback_votes_author_idx",
+ "columns": [
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_votes_company_target_author_idx": {
+ "name": "feedback_votes_company_target_author_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feedback_votes_company_id_companies_id_fk": {
+ "name": "feedback_votes_company_id_companies_id_fk",
+ "tableFrom": "feedback_votes",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "feedback_votes_issue_id_issues_id_fk": {
+ "name": "feedback_votes_issue_id_issues_id_fk",
+ "tableFrom": "feedback_votes",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.finance_events": {
+ "name": "finance_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "heartbeat_run_id": {
+ "name": "heartbeat_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_event_id": {
+ "name": "cost_event_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "billing_code": {
+ "name": "billing_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "event_kind": {
+ "name": "event_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "direction": {
+ "name": "direction",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'debit'"
+ },
+ "biller": {
+ "name": "biller",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_adapter_type": {
+ "name": "execution_adapter_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pricing_tier": {
+ "name": "pricing_tier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quantity": {
+ "name": "quantity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "unit": {
+ "name": "unit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "amount_cents": {
+ "name": "amount_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'USD'"
+ },
+ "estimated": {
+ "name": "estimated",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "external_invoice_id": {
+ "name": "external_invoice_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata_json": {
+ "name": "metadata_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "occurred_at": {
+ "name": "occurred_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "finance_events_company_occurred_idx": {
+ "name": "finance_events_company_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "finance_events_company_biller_occurred_idx": {
+ "name": "finance_events_company_biller_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "biller",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "finance_events_company_kind_occurred_idx": {
+ "name": "finance_events_company_kind_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "event_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "finance_events_company_direction_occurred_idx": {
+ "name": "finance_events_company_direction_occurred_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "direction",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "finance_events_company_heartbeat_run_idx": {
+ "name": "finance_events_company_heartbeat_run_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "heartbeat_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "finance_events_company_cost_event_idx": {
+ "name": "finance_events_company_cost_event_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "cost_event_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "finance_events_company_id_companies_id_fk": {
+ "name": "finance_events_company_id_companies_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_agent_id_agents_id_fk": {
+ "name": "finance_events_agent_id_agents_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_issue_id_issues_id_fk": {
+ "name": "finance_events_issue_id_issues_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_project_id_projects_id_fk": {
+ "name": "finance_events_project_id_projects_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_goal_id_goals_id_fk": {
+ "name": "finance_events_goal_id_goals_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_heartbeat_run_id_heartbeat_runs_id_fk": {
+ "name": "finance_events_heartbeat_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "heartbeat_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "finance_events_cost_event_id_cost_events_id_fk": {
+ "name": "finance_events_cost_event_id_cost_events_id_fk",
+ "tableFrom": "finance_events",
+ "tableTo": "cost_events",
+ "columnsFrom": [
+ "cost_event_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'task'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'planned'"
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "owner_agent_id": {
+ "name": "owner_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goals_company_idx": {
+ "name": "goals_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goals_company_id_companies_id_fk": {
+ "name": "goals_company_id_companies_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "goals_parent_id_goals_id_fk": {
+ "name": "goals_parent_id_goals_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "parent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "goals_owner_agent_id_agents_id_fk": {
+ "name": "goals_owner_agent_id_agents_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "owner_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.heartbeat_run_events": {
+ "name": "heartbeat_run_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "heartbeat_run_events_run_seq_idx": {
+ "name": "heartbeat_run_events_run_seq_idx",
+ "columns": [
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "heartbeat_run_events_company_run_idx": {
+ "name": "heartbeat_run_events_company_run_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "heartbeat_run_events_company_created_idx": {
+ "name": "heartbeat_run_events_company_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "heartbeat_run_events_company_id_companies_id_fk": {
+ "name": "heartbeat_run_events_company_id_companies_id_fk",
+ "tableFrom": "heartbeat_run_events",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "heartbeat_run_events_run_id_heartbeat_runs_id_fk": {
+ "name": "heartbeat_run_events_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "heartbeat_run_events",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "heartbeat_run_events_agent_id_agents_id_fk": {
+ "name": "heartbeat_run_events_agent_id_agents_id_fk",
+ "tableFrom": "heartbeat_run_events",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.heartbeat_runs": {
+ "name": "heartbeat_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invocation_source": {
+ "name": "invocation_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'on_demand'"
+ },
+ "trigger_detail": {
+ "name": "trigger_detail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "wakeup_request_id": {
+ "name": "wakeup_request_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signal": {
+ "name": "signal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "usage_json": {
+ "name": "usage_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "result_json": {
+ "name": "result_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id_before": {
+ "name": "session_id_before",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id_after": {
+ "name": "session_id_after",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_store": {
+ "name": "log_store",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_ref": {
+ "name": "log_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_bytes": {
+ "name": "log_bytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_sha256": {
+ "name": "log_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_compressed": {
+ "name": "log_compressed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "stdout_excerpt": {
+ "name": "stdout_excerpt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stderr_excerpt": {
+ "name": "stderr_excerpt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "external_run_id": {
+ "name": "external_run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "process_pid": {
+ "name": "process_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "process_group_id": {
+ "name": "process_group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "process_started_at": {
+ "name": "process_started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retry_of_run_id": {
+ "name": "retry_of_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "process_loss_retry_count": {
+ "name": "process_loss_retry_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "issue_comment_status": {
+ "name": "issue_comment_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'not_applicable'"
+ },
+ "issue_comment_satisfied_by_comment_id": {
+ "name": "issue_comment_satisfied_by_comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_comment_retry_queued_at": {
+ "name": "issue_comment_retry_queued_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context_snapshot": {
+ "name": "context_snapshot",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "heartbeat_runs_company_agent_started_idx": {
+ "name": "heartbeat_runs_company_agent_started_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "heartbeat_runs_company_id_companies_id_fk": {
+ "name": "heartbeat_runs_company_id_companies_id_fk",
+ "tableFrom": "heartbeat_runs",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "heartbeat_runs_agent_id_agents_id_fk": {
+ "name": "heartbeat_runs_agent_id_agents_id_fk",
+ "tableFrom": "heartbeat_runs",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk": {
+ "name": "heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk",
+ "tableFrom": "heartbeat_runs",
+ "tableTo": "agent_wakeup_requests",
+ "columnsFrom": [
+ "wakeup_request_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "heartbeat_runs_retry_of_run_id_heartbeat_runs_id_fk": {
+ "name": "heartbeat_runs_retry_of_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "heartbeat_runs",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "retry_of_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.inbox_dismissals": {
+ "name": "inbox_dismissals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "item_key": {
+ "name": "item_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dismissed_at": {
+ "name": "dismissed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "inbox_dismissals_company_user_idx": {
+ "name": "inbox_dismissals_company_user_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "inbox_dismissals_company_item_idx": {
+ "name": "inbox_dismissals_company_item_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "item_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "inbox_dismissals_company_user_item_idx": {
+ "name": "inbox_dismissals_company_user_item_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "item_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "inbox_dismissals_company_id_companies_id_fk": {
+ "name": "inbox_dismissals_company_id_companies_id_fk",
+ "tableFrom": "inbox_dismissals",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.instance_settings": {
+ "name": "instance_settings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "singleton_key": {
+ "name": "singleton_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "general": {
+ "name": "general",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "experimental": {
+ "name": "experimental",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "instance_settings_singleton_key_idx": {
+ "name": "instance_settings_singleton_key_idx",
+ "columns": [
+ {
+ "expression": "singleton_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.instance_user_roles": {
+ "name": "instance_user_roles",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'instance_admin'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "instance_user_roles_user_role_unique_idx": {
+ "name": "instance_user_roles_user_role_unique_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "role",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "instance_user_roles_role_idx": {
+ "name": "instance_user_roles_role_idx",
+ "columns": [
+ {
+ "expression": "role",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invites": {
+ "name": "invites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "invite_type": {
+ "name": "invite_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'company_join'"
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "allowed_join_types": {
+ "name": "allowed_join_types",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'both'"
+ },
+ "defaults_payload": {
+ "name": "defaults_payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by_user_id": {
+ "name": "invited_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "invites_token_hash_unique_idx": {
+ "name": "invites_token_hash_unique_idx",
+ "columns": [
+ {
+ "expression": "token_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "invites_company_invite_state_idx": {
+ "name": "invites_company_invite_state_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "invite_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "revoked_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "invites_company_id_companies_id_fk": {
+ "name": "invites_company_id_companies_id_fk",
+ "tableFrom": "invites",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_approvals": {
+ "name": "issue_approvals",
+ "schema": "",
+ "columns": {
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approval_id": {
+ "name": "approval_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "linked_by_agent_id": {
+ "name": "linked_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linked_by_user_id": {
+ "name": "linked_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_approvals_issue_idx": {
+ "name": "issue_approvals_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_approvals_approval_idx": {
+ "name": "issue_approvals_approval_idx",
+ "columns": [
+ {
+ "expression": "approval_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_approvals_company_idx": {
+ "name": "issue_approvals_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_approvals_company_id_companies_id_fk": {
+ "name": "issue_approvals_company_id_companies_id_fk",
+ "tableFrom": "issue_approvals",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_approvals_issue_id_issues_id_fk": {
+ "name": "issue_approvals_issue_id_issues_id_fk",
+ "tableFrom": "issue_approvals",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_approvals_approval_id_approvals_id_fk": {
+ "name": "issue_approvals_approval_id_approvals_id_fk",
+ "tableFrom": "issue_approvals",
+ "tableTo": "approvals",
+ "columnsFrom": [
+ "approval_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_approvals_linked_by_agent_id_agents_id_fk": {
+ "name": "issue_approvals_linked_by_agent_id_agents_id_fk",
+ "tableFrom": "issue_approvals",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "linked_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_approvals_pk": {
+ "name": "issue_approvals_pk",
+ "columns": [
+ "issue_id",
+ "approval_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_attachments": {
+ "name": "issue_attachments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "asset_id": {
+ "name": "asset_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_comment_id": {
+ "name": "issue_comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_attachments_company_issue_idx": {
+ "name": "issue_attachments_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_attachments_issue_comment_idx": {
+ "name": "issue_attachments_issue_comment_idx",
+ "columns": [
+ {
+ "expression": "issue_comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_attachments_asset_uq": {
+ "name": "issue_attachments_asset_uq",
+ "columns": [
+ {
+ "expression": "asset_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_attachments_company_id_companies_id_fk": {
+ "name": "issue_attachments_company_id_companies_id_fk",
+ "tableFrom": "issue_attachments",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_attachments_issue_id_issues_id_fk": {
+ "name": "issue_attachments_issue_id_issues_id_fk",
+ "tableFrom": "issue_attachments",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_attachments_asset_id_assets_id_fk": {
+ "name": "issue_attachments_asset_id_assets_id_fk",
+ "tableFrom": "issue_attachments",
+ "tableTo": "assets",
+ "columnsFrom": [
+ "asset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_attachments_issue_comment_id_issue_comments_id_fk": {
+ "name": "issue_attachments_issue_comment_id_issue_comments_id_fk",
+ "tableFrom": "issue_attachments",
+ "tableTo": "issue_comments",
+ "columnsFrom": [
+ "issue_comment_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_comments": {
+ "name": "issue_comments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "author_agent_id": {
+ "name": "author_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_run_id": {
+ "name": "created_by_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_comments_issue_idx": {
+ "name": "issue_comments_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_comments_company_idx": {
+ "name": "issue_comments_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_comments_company_issue_created_at_idx": {
+ "name": "issue_comments_company_issue_created_at_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_comments_company_author_issue_created_at_idx": {
+ "name": "issue_comments_company_author_issue_created_at_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_comments_body_search_idx": {
+ "name": "issue_comments_body_search_idx",
+ "columns": [
+ {
+ "expression": "body",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "gin_trgm_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_comments_company_id_companies_id_fk": {
+ "name": "issue_comments_company_id_companies_id_fk",
+ "tableFrom": "issue_comments",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_comments_issue_id_issues_id_fk": {
+ "name": "issue_comments_issue_id_issues_id_fk",
+ "tableFrom": "issue_comments",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_comments_author_agent_id_agents_id_fk": {
+ "name": "issue_comments_author_agent_id_agents_id_fk",
+ "tableFrom": "issue_comments",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "author_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_comments_created_by_run_id_heartbeat_runs_id_fk": {
+ "name": "issue_comments_created_by_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "issue_comments",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "created_by_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_documents": {
+ "name": "issue_documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_documents_company_issue_key_uq": {
+ "name": "issue_documents_company_issue_key_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_documents_document_uq": {
+ "name": "issue_documents_document_uq",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_documents_company_issue_updated_idx": {
+ "name": "issue_documents_company_issue_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_documents_company_id_companies_id_fk": {
+ "name": "issue_documents_company_id_companies_id_fk",
+ "tableFrom": "issue_documents",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_documents_issue_id_issues_id_fk": {
+ "name": "issue_documents_issue_id_issues_id_fk",
+ "tableFrom": "issue_documents",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_documents_document_id_documents_id_fk": {
+ "name": "issue_documents_document_id_documents_id_fk",
+ "tableFrom": "issue_documents",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_execution_decisions": {
+ "name": "issue_execution_decisions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stage_id": {
+ "name": "stage_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stage_type": {
+ "name": "stage_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_agent_id": {
+ "name": "actor_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_run_id": {
+ "name": "created_by_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_execution_decisions_company_issue_idx": {
+ "name": "issue_execution_decisions_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_execution_decisions_stage_idx": {
+ "name": "issue_execution_decisions_stage_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "stage_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_execution_decisions_company_id_companies_id_fk": {
+ "name": "issue_execution_decisions_company_id_companies_id_fk",
+ "tableFrom": "issue_execution_decisions",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_execution_decisions_issue_id_issues_id_fk": {
+ "name": "issue_execution_decisions_issue_id_issues_id_fk",
+ "tableFrom": "issue_execution_decisions",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_execution_decisions_actor_agent_id_agents_id_fk": {
+ "name": "issue_execution_decisions_actor_agent_id_agents_id_fk",
+ "tableFrom": "issue_execution_decisions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "actor_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_execution_decisions_created_by_run_id_heartbeat_runs_id_fk": {
+ "name": "issue_execution_decisions_created_by_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "issue_execution_decisions",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "created_by_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_inbox_archives": {
+ "name": "issue_inbox_archives",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_inbox_archives_company_issue_idx": {
+ "name": "issue_inbox_archives_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_inbox_archives_company_user_idx": {
+ "name": "issue_inbox_archives_company_user_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_inbox_archives_company_issue_user_idx": {
+ "name": "issue_inbox_archives_company_issue_user_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_inbox_archives_company_id_companies_id_fk": {
+ "name": "issue_inbox_archives_company_id_companies_id_fk",
+ "tableFrom": "issue_inbox_archives",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_inbox_archives_issue_id_issues_id_fk": {
+ "name": "issue_inbox_archives_issue_id_issues_id_fk",
+ "tableFrom": "issue_inbox_archives",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_labels": {
+ "name": "issue_labels",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_labels_issue_idx": {
+ "name": "issue_labels_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_labels_label_idx": {
+ "name": "issue_labels_label_idx",
+ "columns": [
+ {
+ "expression": "label_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_labels_company_idx": {
+ "name": "issue_labels_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_labels_issue_id_issues_id_fk": {
+ "name": "issue_labels_issue_id_issues_id_fk",
+ "tableFrom": "issue_labels",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_labels_label_id_labels_id_fk": {
+ "name": "issue_labels_label_id_labels_id_fk",
+ "tableFrom": "issue_labels",
+ "tableTo": "labels",
+ "columnsFrom": [
+ "label_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_labels_company_id_companies_id_fk": {
+ "name": "issue_labels_company_id_companies_id_fk",
+ "tableFrom": "issue_labels",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_labels_pk": {
+ "name": "issue_labels_pk",
+ "columns": [
+ "issue_id",
+ "label_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_read_states": {
+ "name": "issue_read_states",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_read_at": {
+ "name": "last_read_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_read_states_company_issue_idx": {
+ "name": "issue_read_states_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_read_states_company_user_idx": {
+ "name": "issue_read_states_company_user_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_read_states_company_issue_user_idx": {
+ "name": "issue_read_states_company_issue_user_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_read_states_company_id_companies_id_fk": {
+ "name": "issue_read_states_company_id_companies_id_fk",
+ "tableFrom": "issue_read_states",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_read_states_issue_id_issues_id_fk": {
+ "name": "issue_read_states_issue_id_issues_id_fk",
+ "tableFrom": "issue_read_states",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_relations": {
+ "name": "issue_relations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "related_issue_id": {
+ "name": "related_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_relations_company_issue_idx": {
+ "name": "issue_relations_company_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_relations_company_related_issue_idx": {
+ "name": "issue_relations_company_related_issue_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "related_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_relations_company_type_idx": {
+ "name": "issue_relations_company_type_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_relations_company_edge_uq": {
+ "name": "issue_relations_company_edge_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "related_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_relations_company_id_companies_id_fk": {
+ "name": "issue_relations_company_id_companies_id_fk",
+ "tableFrom": "issue_relations",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_relations_issue_id_issues_id_fk": {
+ "name": "issue_relations_issue_id_issues_id_fk",
+ "tableFrom": "issue_relations",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_relations_related_issue_id_issues_id_fk": {
+ "name": "issue_relations_related_issue_id_issues_id_fk",
+ "tableFrom": "issue_relations",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "related_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_relations_created_by_agent_id_agents_id_fk": {
+ "name": "issue_relations_created_by_agent_id_agents_id_fk",
+ "tableFrom": "issue_relations",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_work_products": {
+ "name": "issue_work_products",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "execution_workspace_id": {
+ "name": "execution_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runtime_service_id": {
+ "name": "runtime_service_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "review_state": {
+ "name": "review_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'none'"
+ },
+ "is_primary": {
+ "name": "is_primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "health_status": {
+ "name": "health_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unknown'"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_run_id": {
+ "name": "created_by_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_work_products_company_issue_type_idx": {
+ "name": "issue_work_products_company_issue_type_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_work_products_company_execution_workspace_type_idx": {
+ "name": "issue_work_products_company_execution_workspace_type_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "execution_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_work_products_company_provider_external_id_idx": {
+ "name": "issue_work_products_company_provider_external_id_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "external_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_work_products_company_updated_idx": {
+ "name": "issue_work_products_company_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_work_products_company_id_companies_id_fk": {
+ "name": "issue_work_products_company_id_companies_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_work_products_project_id_projects_id_fk": {
+ "name": "issue_work_products_project_id_projects_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_work_products_issue_id_issues_id_fk": {
+ "name": "issue_work_products_issue_id_issues_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_work_products_execution_workspace_id_execution_workspaces_id_fk": {
+ "name": "issue_work_products_execution_workspace_id_execution_workspaces_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "execution_workspaces",
+ "columnsFrom": [
+ "execution_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_work_products_runtime_service_id_workspace_runtime_services_id_fk": {
+ "name": "issue_work_products_runtime_service_id_workspace_runtime_services_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "workspace_runtime_services",
+ "columnsFrom": [
+ "runtime_service_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_work_products_created_by_run_id_heartbeat_runs_id_fk": {
+ "name": "issue_work_products_created_by_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "issue_work_products",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "created_by_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issues": {
+ "name": "issues",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_workspace_id": {
+ "name": "project_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'medium'"
+ },
+ "assignee_agent_id": {
+ "name": "assignee_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_user_id": {
+ "name": "assignee_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "checkout_run_id": {
+ "name": "checkout_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_run_id": {
+ "name": "execution_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_agent_name_key": {
+ "name": "execution_agent_name_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_locked_at": {
+ "name": "execution_locked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_number": {
+ "name": "issue_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'manual'"
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_run_id": {
+ "name": "origin_run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_depth": {
+ "name": "request_depth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "billing_code": {
+ "name": "billing_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_adapter_overrides": {
+ "name": "assignee_adapter_overrides",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_policy": {
+ "name": "execution_policy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_state": {
+ "name": "execution_state",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_workspace_id": {
+ "name": "execution_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_workspace_preference": {
+ "name": "execution_workspace_preference",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_workspace_settings": {
+ "name": "execution_workspace_settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancelled_at": {
+ "name": "cancelled_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issues_company_status_idx": {
+ "name": "issues_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_assignee_status_idx": {
+ "name": "issues_company_assignee_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "assignee_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_assignee_user_status_idx": {
+ "name": "issues_company_assignee_user_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "assignee_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_parent_idx": {
+ "name": "issues_company_parent_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_project_idx": {
+ "name": "issues_company_project_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_origin_idx": {
+ "name": "issues_company_origin_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "origin_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "origin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_project_workspace_idx": {
+ "name": "issues_company_project_workspace_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_company_execution_workspace_idx": {
+ "name": "issues_company_execution_workspace_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "execution_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_identifier_idx": {
+ "name": "issues_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issues_title_search_idx": {
+ "name": "issues_title_search_idx",
+ "columns": [
+ {
+ "expression": "title",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "gin_trgm_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "issues_identifier_search_idx": {
+ "name": "issues_identifier_search_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "gin_trgm_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "issues_description_search_idx": {
+ "name": "issues_description_search_idx",
+ "columns": [
+ {
+ "expression": "description",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "gin_trgm_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "issues_open_routine_execution_uq": {
+ "name": "issues_open_routine_execution_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "origin_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "origin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"issues\".\"origin_kind\" = 'routine_execution'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"execution_run_id\" is not null\n and \"issues\".\"status\" in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issues_company_id_companies_id_fk": {
+ "name": "issues_company_id_companies_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_project_id_projects_id_fk": {
+ "name": "issues_project_id_projects_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_project_workspace_id_project_workspaces_id_fk": {
+ "name": "issues_project_workspace_id_project_workspaces_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "project_workspaces",
+ "columnsFrom": [
+ "project_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issues_goal_id_goals_id_fk": {
+ "name": "issues_goal_id_goals_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_parent_id_issues_id_fk": {
+ "name": "issues_parent_id_issues_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "parent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_assignee_agent_id_agents_id_fk": {
+ "name": "issues_assignee_agent_id_agents_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "assignee_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_checkout_run_id_heartbeat_runs_id_fk": {
+ "name": "issues_checkout_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "checkout_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issues_execution_run_id_heartbeat_runs_id_fk": {
+ "name": "issues_execution_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "execution_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issues_created_by_agent_id_agents_id_fk": {
+ "name": "issues_created_by_agent_id_agents_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issues_execution_workspace_id_execution_workspaces_id_fk": {
+ "name": "issues_execution_workspace_id_execution_workspaces_id_fk",
+ "tableFrom": "issues",
+ "tableTo": "execution_workspaces",
+ "columnsFrom": [
+ "execution_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.join_requests": {
+ "name": "join_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "invite_id": {
+ "name": "invite_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request_type": {
+ "name": "request_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending_approval'"
+ },
+ "request_ip": {
+ "name": "request_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "requesting_user_id": {
+ "name": "requesting_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_email_snapshot": {
+ "name": "request_email_snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_name": {
+ "name": "agent_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "adapter_type": {
+ "name": "adapter_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_defaults_payload": {
+ "name": "agent_defaults_payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_secret_hash": {
+ "name": "claim_secret_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_secret_expires_at": {
+ "name": "claim_secret_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_secret_consumed_at": {
+ "name": "claim_secret_consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_agent_id": {
+ "name": "created_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approved_by_user_id": {
+ "name": "approved_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approved_at": {
+ "name": "approved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rejected_by_user_id": {
+ "name": "rejected_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rejected_at": {
+ "name": "rejected_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "join_requests_invite_unique_idx": {
+ "name": "join_requests_invite_unique_idx",
+ "columns": [
+ {
+ "expression": "invite_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "join_requests_company_status_type_created_idx": {
+ "name": "join_requests_company_status_type_created_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "request_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "join_requests_pending_human_user_uq": {
+ "name": "join_requests_pending_human_user_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "requesting_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"requesting_user_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "join_requests_pending_human_email_uq": {
+ "name": "join_requests_pending_human_email_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lower(\"request_email_snapshot\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"request_email_snapshot\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "join_requests_invite_id_invites_id_fk": {
+ "name": "join_requests_invite_id_invites_id_fk",
+ "tableFrom": "join_requests",
+ "tableTo": "invites",
+ "columnsFrom": [
+ "invite_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "join_requests_company_id_companies_id_fk": {
+ "name": "join_requests_company_id_companies_id_fk",
+ "tableFrom": "join_requests",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "join_requests_created_agent_id_agents_id_fk": {
+ "name": "join_requests_created_agent_id_agents_id_fk",
+ "tableFrom": "join_requests",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.labels": {
+ "name": "labels",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "labels_company_idx": {
+ "name": "labels_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "labels_company_name_idx": {
+ "name": "labels_company_name_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "labels_company_id_companies_id_fk": {
+ "name": "labels_company_id_companies_id_fk",
+ "tableFrom": "labels",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_company_settings": {
+ "name": "plugin_company_settings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "settings_json": {
+ "name": "settings_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_company_settings_company_idx": {
+ "name": "plugin_company_settings_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_company_settings_plugin_idx": {
+ "name": "plugin_company_settings_plugin_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_company_settings_company_plugin_uq": {
+ "name": "plugin_company_settings_company_plugin_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_company_settings_company_id_companies_id_fk": {
+ "name": "plugin_company_settings_company_id_companies_id_fk",
+ "tableFrom": "plugin_company_settings",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "plugin_company_settings_plugin_id_plugins_id_fk": {
+ "name": "plugin_company_settings_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_company_settings",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_config": {
+ "name": "plugin_config",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config_json": {
+ "name": "config_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_config_plugin_id_idx": {
+ "name": "plugin_config_plugin_id_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_config_plugin_id_plugins_id_fk": {
+ "name": "plugin_config_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_config",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_entities": {
+ "name": "plugin_entities",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity_type": {
+ "name": "entity_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_kind": {
+ "name": "scope_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_id": {
+ "name": "scope_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_entities_plugin_idx": {
+ "name": "plugin_entities_plugin_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_entities_type_idx": {
+ "name": "plugin_entities_type_idx",
+ "columns": [
+ {
+ "expression": "entity_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_entities_scope_idx": {
+ "name": "plugin_entities_scope_idx",
+ "columns": [
+ {
+ "expression": "scope_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_entities_external_idx": {
+ "name": "plugin_entities_external_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "entity_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "external_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_entities_plugin_id_plugins_id_fk": {
+ "name": "plugin_entities_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_entities",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_job_runs": {
+ "name": "plugin_job_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "logs": {
+ "name": "logs",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_job_runs_job_idx": {
+ "name": "plugin_job_runs_job_idx",
+ "columns": [
+ {
+ "expression": "job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_job_runs_plugin_idx": {
+ "name": "plugin_job_runs_plugin_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_job_runs_status_idx": {
+ "name": "plugin_job_runs_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_job_runs_job_id_plugin_jobs_id_fk": {
+ "name": "plugin_job_runs_job_id_plugin_jobs_id_fk",
+ "tableFrom": "plugin_job_runs",
+ "tableTo": "plugin_jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "plugin_job_runs_plugin_id_plugins_id_fk": {
+ "name": "plugin_job_runs_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_job_runs",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_jobs": {
+ "name": "plugin_jobs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "job_key": {
+ "name": "job_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "schedule": {
+ "name": "schedule",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_jobs_plugin_idx": {
+ "name": "plugin_jobs_plugin_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_jobs_next_run_idx": {
+ "name": "plugin_jobs_next_run_idx",
+ "columns": [
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_jobs_unique_idx": {
+ "name": "plugin_jobs_unique_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "job_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_jobs_plugin_id_plugins_id_fk": {
+ "name": "plugin_jobs_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_jobs",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_logs": {
+ "name": "plugin_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'info'"
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "meta": {
+ "name": "meta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_logs_plugin_time_idx": {
+ "name": "plugin_logs_plugin_time_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_logs_level_idx": {
+ "name": "plugin_logs_level_idx",
+ "columns": [
+ {
+ "expression": "level",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_logs_plugin_id_plugins_id_fk": {
+ "name": "plugin_logs_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_logs",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_state": {
+ "name": "plugin_state",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_kind": {
+ "name": "scope_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_id": {
+ "name": "scope_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "namespace": {
+ "name": "namespace",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "state_key": {
+ "name": "state_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value_json": {
+ "name": "value_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_state_plugin_scope_idx": {
+ "name": "plugin_state_plugin_scope_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_state_plugin_id_plugins_id_fk": {
+ "name": "plugin_state_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_state",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "plugin_state_unique_entry_idx": {
+ "name": "plugin_state_unique_entry_idx",
+ "nullsNotDistinct": true,
+ "columns": [
+ "plugin_id",
+ "scope_kind",
+ "scope_id",
+ "namespace",
+ "state_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_webhook_deliveries": {
+ "name": "plugin_webhook_deliveries",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "webhook_key": {
+ "name": "webhook_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "headers": {
+ "name": "headers",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_webhook_deliveries_plugin_idx": {
+ "name": "plugin_webhook_deliveries_plugin_idx",
+ "columns": [
+ {
+ "expression": "plugin_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_webhook_deliveries_status_idx": {
+ "name": "plugin_webhook_deliveries_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugin_webhook_deliveries_key_idx": {
+ "name": "plugin_webhook_deliveries_key_idx",
+ "columns": [
+ {
+ "expression": "webhook_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_webhook_deliveries_plugin_id_plugins_id_fk": {
+ "name": "plugin_webhook_deliveries_plugin_id_plugins_id_fk",
+ "tableFrom": "plugin_webhook_deliveries",
+ "tableTo": "plugins",
+ "columnsFrom": [
+ "plugin_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugins": {
+ "name": "plugins",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "plugin_key": {
+ "name": "plugin_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "package_name": {
+ "name": "package_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "api_version": {
+ "name": "api_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "categories": {
+ "name": "categories",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "manifest_json": {
+ "name": "manifest_json",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'installed'"
+ },
+ "install_order": {
+ "name": "install_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "package_path": {
+ "name": "package_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "installed_at": {
+ "name": "installed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugins_plugin_key_idx": {
+ "name": "plugins_plugin_key_idx",
+ "columns": [
+ {
+ "expression": "plugin_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "plugins_status_idx": {
+ "name": "plugins_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.principal_permission_grants": {
+ "name": "principal_permission_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal_type": {
+ "name": "principal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal_id": {
+ "name": "principal_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permission_key": {
+ "name": "permission_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "granted_by_user_id": {
+ "name": "granted_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "principal_permission_grants_unique_idx": {
+ "name": "principal_permission_grants_unique_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "permission_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "principal_permission_grants_company_permission_idx": {
+ "name": "principal_permission_grants_company_permission_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "permission_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "principal_permission_grants_company_id_companies_id_fk": {
+ "name": "principal_permission_grants_company_id_companies_id_fk",
+ "tableFrom": "principal_permission_grants",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_goals": {
+ "name": "project_goals",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_goals_project_idx": {
+ "name": "project_goals_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_goals_goal_idx": {
+ "name": "project_goals_goal_idx",
+ "columns": [
+ {
+ "expression": "goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_goals_company_idx": {
+ "name": "project_goals_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_goals_project_id_projects_id_fk": {
+ "name": "project_goals_project_id_projects_id_fk",
+ "tableFrom": "project_goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_goals_goal_id_goals_id_fk": {
+ "name": "project_goals_goal_id_goals_id_fk",
+ "tableFrom": "project_goals",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_goals_company_id_companies_id_fk": {
+ "name": "project_goals_company_id_companies_id_fk",
+ "tableFrom": "project_goals",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_goals_project_id_goal_id_pk": {
+ "name": "project_goals_project_id_goal_id_pk",
+ "columns": [
+ "project_id",
+ "goal_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_workspaces": {
+ "name": "project_workspaces",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_type": {
+ "name": "source_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local_path'"
+ },
+ "cwd": {
+ "name": "cwd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "repo_url": {
+ "name": "repo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "repo_ref": {
+ "name": "repo_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "default_ref": {
+ "name": "default_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "setup_command": {
+ "name": "setup_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cleanup_command": {
+ "name": "cleanup_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remote_provider": {
+ "name": "remote_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remote_workspace_ref": {
+ "name": "remote_workspace_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "shared_workspace_key": {
+ "name": "shared_workspace_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_primary": {
+ "name": "is_primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_workspaces_company_project_idx": {
+ "name": "project_workspaces_company_project_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_workspaces_project_primary_idx": {
+ "name": "project_workspaces_project_primary_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "is_primary",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_workspaces_project_source_type_idx": {
+ "name": "project_workspaces_project_source_type_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_workspaces_company_shared_key_idx": {
+ "name": "project_workspaces_company_shared_key_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "shared_workspace_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_workspaces_project_remote_ref_idx": {
+ "name": "project_workspaces_project_remote_ref_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "remote_provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "remote_workspace_ref",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_workspaces_company_id_companies_id_fk": {
+ "name": "project_workspaces_company_id_companies_id_fk",
+ "tableFrom": "project_workspaces",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "project_workspaces_project_id_projects_id_fk": {
+ "name": "project_workspaces_project_id_projects_id_fk",
+ "tableFrom": "project_workspaces",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.projects": {
+ "name": "projects",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "lead_agent_id": {
+ "name": "lead_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_date": {
+ "name": "target_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "env": {
+ "name": "env",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pause_reason": {
+ "name": "pause_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "paused_at": {
+ "name": "paused_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_workspace_policy": {
+ "name": "execution_workspace_policy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "projects_company_idx": {
+ "name": "projects_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "projects_company_id_companies_id_fk": {
+ "name": "projects_company_id_companies_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "projects_goal_id_goals_id_fk": {
+ "name": "projects_goal_id_goals_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "projects_lead_agent_id_agents_id_fk": {
+ "name": "projects_lead_agent_id_agents_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "lead_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.routine_runs": {
+ "name": "routine_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "routine_id": {
+ "name": "routine_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger_id": {
+ "name": "trigger_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'received'"
+ },
+ "triggered_at": {
+ "name": "triggered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "idempotency_key": {
+ "name": "idempotency_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger_payload": {
+ "name": "trigger_payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linked_issue_id": {
+ "name": "linked_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "coalesced_into_run_id": {
+ "name": "coalesced_into_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failure_reason": {
+ "name": "failure_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "routine_runs_company_routine_idx": {
+ "name": "routine_runs_company_routine_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "routine_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_runs_trigger_idx": {
+ "name": "routine_runs_trigger_idx",
+ "columns": [
+ {
+ "expression": "trigger_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_runs_linked_issue_idx": {
+ "name": "routine_runs_linked_issue_idx",
+ "columns": [
+ {
+ "expression": "linked_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_runs_trigger_idempotency_idx": {
+ "name": "routine_runs_trigger_idempotency_idx",
+ "columns": [
+ {
+ "expression": "trigger_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "routine_runs_company_id_companies_id_fk": {
+ "name": "routine_runs_company_id_companies_id_fk",
+ "tableFrom": "routine_runs",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routine_runs_routine_id_routines_id_fk": {
+ "name": "routine_runs_routine_id_routines_id_fk",
+ "tableFrom": "routine_runs",
+ "tableTo": "routines",
+ "columnsFrom": [
+ "routine_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routine_runs_trigger_id_routine_triggers_id_fk": {
+ "name": "routine_runs_trigger_id_routine_triggers_id_fk",
+ "tableFrom": "routine_runs",
+ "tableTo": "routine_triggers",
+ "columnsFrom": [
+ "trigger_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routine_runs_linked_issue_id_issues_id_fk": {
+ "name": "routine_runs_linked_issue_id_issues_id_fk",
+ "tableFrom": "routine_runs",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "linked_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.routine_triggers": {
+ "name": "routine_triggers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "routine_id": {
+ "name": "routine_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "cron_expression": {
+ "name": "cron_expression",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public_id": {
+ "name": "public_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "secret_id": {
+ "name": "secret_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signing_mode": {
+ "name": "signing_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "replay_window_sec": {
+ "name": "replay_window_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_rotated_at": {
+ "name": "last_rotated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_result": {
+ "name": "last_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_agent_id": {
+ "name": "updated_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_user_id": {
+ "name": "updated_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "routine_triggers_company_routine_idx": {
+ "name": "routine_triggers_company_routine_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "routine_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_triggers_company_kind_idx": {
+ "name": "routine_triggers_company_kind_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_triggers_next_run_idx": {
+ "name": "routine_triggers_next_run_idx",
+ "columns": [
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_triggers_public_id_idx": {
+ "name": "routine_triggers_public_id_idx",
+ "columns": [
+ {
+ "expression": "public_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routine_triggers_public_id_uq": {
+ "name": "routine_triggers_public_id_uq",
+ "columns": [
+ {
+ "expression": "public_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "routine_triggers_company_id_companies_id_fk": {
+ "name": "routine_triggers_company_id_companies_id_fk",
+ "tableFrom": "routine_triggers",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routine_triggers_routine_id_routines_id_fk": {
+ "name": "routine_triggers_routine_id_routines_id_fk",
+ "tableFrom": "routine_triggers",
+ "tableTo": "routines",
+ "columnsFrom": [
+ "routine_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routine_triggers_secret_id_company_secrets_id_fk": {
+ "name": "routine_triggers_secret_id_company_secrets_id_fk",
+ "tableFrom": "routine_triggers",
+ "tableTo": "company_secrets",
+ "columnsFrom": [
+ "secret_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routine_triggers_created_by_agent_id_agents_id_fk": {
+ "name": "routine_triggers_created_by_agent_id_agents_id_fk",
+ "tableFrom": "routine_triggers",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routine_triggers_updated_by_agent_id_agents_id_fk": {
+ "name": "routine_triggers_updated_by_agent_id_agents_id_fk",
+ "tableFrom": "routine_triggers",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "updated_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.routines": {
+ "name": "routines",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_issue_id": {
+ "name": "parent_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_agent_id": {
+ "name": "assignee_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'medium'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "concurrency_policy": {
+ "name": "concurrency_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'coalesce_if_active'"
+ },
+ "catch_up_policy": {
+ "name": "catch_up_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'skip_missed'"
+ },
+ "variables": {
+ "name": "variables",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_agent_id": {
+ "name": "updated_by_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by_user_id": {
+ "name": "updated_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_triggered_at": {
+ "name": "last_triggered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_enqueued_at": {
+ "name": "last_enqueued_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "routines_company_status_idx": {
+ "name": "routines_company_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routines_company_assignee_idx": {
+ "name": "routines_company_assignee_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "assignee_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "routines_company_project_idx": {
+ "name": "routines_company_project_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "routines_company_id_companies_id_fk": {
+ "name": "routines_company_id_companies_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routines_project_id_projects_id_fk": {
+ "name": "routines_project_id_projects_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "routines_goal_id_goals_id_fk": {
+ "name": "routines_goal_id_goals_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routines_parent_issue_id_issues_id_fk": {
+ "name": "routines_parent_issue_id_issues_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "parent_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routines_assignee_agent_id_agents_id_fk": {
+ "name": "routines_assignee_agent_id_agents_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "assignee_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "routines_created_by_agent_id_agents_id_fk": {
+ "name": "routines_created_by_agent_id_agents_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "created_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "routines_updated_by_agent_id_agents_id_fk": {
+ "name": "routines_updated_by_agent_id_agents_id_fk",
+ "tableFrom": "routines",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "updated_by_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_sidebar_preferences": {
+ "name": "user_sidebar_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "company_order": {
+ "name": "company_order",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_sidebar_preferences_user_uq": {
+ "name": "user_sidebar_preferences_user_uq",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_operations": {
+ "name": "workspace_operations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "execution_workspace_id": {
+ "name": "execution_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "heartbeat_run_id": {
+ "name": "heartbeat_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cwd": {
+ "name": "cwd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'running'"
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_store": {
+ "name": "log_store",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_ref": {
+ "name": "log_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_bytes": {
+ "name": "log_bytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_sha256": {
+ "name": "log_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_compressed": {
+ "name": "log_compressed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "stdout_excerpt": {
+ "name": "stdout_excerpt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stderr_excerpt": {
+ "name": "stderr_excerpt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspace_operations_company_run_started_idx": {
+ "name": "workspace_operations_company_run_started_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "heartbeat_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_operations_company_workspace_started_idx": {
+ "name": "workspace_operations_company_workspace_started_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "execution_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_operations_company_id_companies_id_fk": {
+ "name": "workspace_operations_company_id_companies_id_fk",
+ "tableFrom": "workspace_operations",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "workspace_operations_execution_workspace_id_execution_workspaces_id_fk": {
+ "name": "workspace_operations_execution_workspace_id_execution_workspaces_id_fk",
+ "tableFrom": "workspace_operations",
+ "tableTo": "execution_workspaces",
+ "columnsFrom": [
+ "execution_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk": {
+ "name": "workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "workspace_operations",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "heartbeat_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_runtime_services": {
+ "name": "workspace_runtime_services",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_workspace_id": {
+ "name": "project_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_workspace_id": {
+ "name": "execution_workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope_type": {
+ "name": "scope_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_id": {
+ "name": "scope_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "service_name": {
+ "name": "service_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lifecycle": {
+ "name": "lifecycle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reuse_key": {
+ "name": "reuse_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cwd": {
+ "name": "cwd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "port": {
+ "name": "port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_ref": {
+ "name": "provider_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "owner_agent_id": {
+ "name": "owner_agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_by_run_id": {
+ "name": "started_by_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "stopped_at": {
+ "name": "stopped_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stop_policy": {
+ "name": "stop_policy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "health_status": {
+ "name": "health_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unknown'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspace_runtime_services_company_workspace_status_idx": {
+ "name": "workspace_runtime_services_company_workspace_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_runtime_services_company_execution_workspace_status_idx": {
+ "name": "workspace_runtime_services_company_execution_workspace_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "execution_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_runtime_services_company_project_status_idx": {
+ "name": "workspace_runtime_services_company_project_status_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_runtime_services_run_idx": {
+ "name": "workspace_runtime_services_run_idx",
+ "columns": [
+ {
+ "expression": "started_by_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_runtime_services_company_updated_idx": {
+ "name": "workspace_runtime_services_company_updated_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_runtime_services_company_id_companies_id_fk": {
+ "name": "workspace_runtime_services_company_id_companies_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_project_id_projects_id_fk": {
+ "name": "workspace_runtime_services_project_id_projects_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_project_workspace_id_project_workspaces_id_fk": {
+ "name": "workspace_runtime_services_project_workspace_id_project_workspaces_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "project_workspaces",
+ "columnsFrom": [
+ "project_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_execution_workspace_id_execution_workspaces_id_fk": {
+ "name": "workspace_runtime_services_execution_workspace_id_execution_workspaces_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "execution_workspaces",
+ "columnsFrom": [
+ "execution_workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_issue_id_issues_id_fk": {
+ "name": "workspace_runtime_services_issue_id_issues_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_owner_agent_id_agents_id_fk": {
+ "name": "workspace_runtime_services_owner_agent_id_agents_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "owner_agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workspace_runtime_services_started_by_run_id_heartbeat_runs_id_fk": {
+ "name": "workspace_runtime_services_started_by_run_id_heartbeat_runs_id_fk",
+ "tableFrom": "workspace_runtime_services",
+ "tableTo": "heartbeat_runs",
+ "columnsFrom": [
+ "started_by_run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index bce93f11a8..757b7c9a14 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -400,6 +400,13 @@
"when": 1776084034244,
"tag": "0056_spooky_ultragirl",
"breakpoints": true
+ },
+ {
+ "idx": 57,
+ "version": "7",
+ "when": 1776309613598,
+ "tag": "0057_tidy_join_requests",
+ "breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/packages/db/src/schema/join_requests.ts b/packages/db/src/schema/join_requests.ts
index 458e45d080..3813c27db7 100644
--- a/packages/db/src/schema/join_requests.ts
+++ b/packages/db/src/schema/join_requests.ts
@@ -1,3 +1,4 @@
+import { sql } from "drizzle-orm";
import { pgTable, uuid, text, timestamp, jsonb, index, uniqueIndex } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { invites } from "./invites.js";
@@ -37,5 +38,11 @@ export const joinRequests = pgTable(
table.requestType,
table.createdAt,
),
+ pendingHumanUserUniqueIdx: uniqueIndex("join_requests_pending_human_user_uq")
+ .on(table.companyId, table.requestingUserId)
+ .where(sql`${table.requestType} = 'human' AND ${table.status} = 'pending_approval' AND ${table.requestingUserId} IS NOT NULL`),
+ pendingHumanEmailUniqueIdx: uniqueIndex("join_requests_pending_human_email_uq")
+ .on(table.companyId, sql`lower(${table.requestEmailSnapshot})`)
+ .where(sql`${table.requestType} = 'human' AND ${table.status} = 'pending_approval' AND ${table.requestEmailSnapshot} IS NOT NULL`),
}),
);
diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts
index f62d2777a0..a9f5de3d43 100644
--- a/packages/shared/src/constants.ts
+++ b/packages/shared/src/constants.ts
@@ -362,6 +362,30 @@ export type PrincipalType = (typeof PRINCIPAL_TYPES)[number];
export const MEMBERSHIP_STATUSES = ["pending", "active", "suspended"] as const;
export type MembershipStatus = (typeof MEMBERSHIP_STATUSES)[number];
+export const COMPANY_MEMBERSHIP_ROLES = [
+ "owner",
+ "admin",
+ "operator",
+ "viewer",
+ "member",
+] as const;
+export type CompanyMembershipRole = (typeof COMPANY_MEMBERSHIP_ROLES)[number];
+
+export const HUMAN_COMPANY_MEMBERSHIP_ROLES = [
+ "owner",
+ "admin",
+ "operator",
+ "viewer",
+] as const;
+export type HumanCompanyMembershipRole = (typeof HUMAN_COMPANY_MEMBERSHIP_ROLES)[number];
+
+export const HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS: Record<HumanCompanyMembershipRole, string> = {
+ owner: "Owner",
+ admin: "Admin",
+ operator: "Operator",
+ viewer: "Viewer",
+};
+
export const INSTANCE_USER_ROLES = ["instance_admin"] as const;
export type InstanceUserRole = (typeof INSTANCE_USER_ROLES)[number];
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index fab8c1ed7a..d1569b67ab 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -54,6 +54,9 @@ export {
LIVE_EVENT_TYPES,
PRINCIPAL_TYPES,
MEMBERSHIP_STATUSES,
+ COMPANY_MEMBERSHIP_ROLES,
+ HUMAN_COMPANY_MEMBERSHIP_ROLES,
+ HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS,
INSTANCE_USER_ROLES,
INVITE_TYPES,
INVITE_JOIN_TYPES,
@@ -127,6 +130,8 @@ export {
type LiveEventType,
type PrincipalType,
type MembershipStatus,
+ type CompanyMembershipRole,
+ type HumanCompanyMembershipRole,
type InstanceUserRole,
type InviteType,
type InviteJoinType,
@@ -308,11 +313,21 @@ export type {
SidebarBadges,
SidebarOrderPreference,
InboxDismissal,
+ AccessUserProfile,
+ CompanyMemberRecord,
+ CompanyMembersResponse,
CompanyMembership,
+ CompanyInviteListResponse,
+ CompanyInviteRecord,
PrincipalPermissionGrant,
Invite,
JoinRequest,
+ JoinRequestInviteSummary,
+ JoinRequestRecord,
InstanceUserRoleGrant,
+ AdminUserDirectoryEntry,
+ UserCompanyAccessEntry,
+ UserCompanyAccessResponse,
CompanyPortabilityInclude,
CompanyPortabilityEnvInput,
CompanyPortabilityFileEntry,
@@ -566,12 +581,19 @@ export {
createCompanyInviteSchema,
createOpenClawInvitePromptSchema,
acceptInviteSchema,
+ listCompanyInvitesQuerySchema,
listJoinRequestsQuerySchema,
claimJoinRequestApiKeySchema,
boardCliAuthAccessLevelSchema,
createCliAuthChallengeSchema,
resolveCliAuthChallengeSchema,
+ currentUserProfileSchema,
+ authSessionSchema,
+ updateCurrentUserProfileSchema,
+ updateCompanyMemberSchema,
+ updateCompanyMemberWithPermissionsSchema,
updateMemberPermissionsSchema,
+ searchAdminUsersQuerySchema,
updateUserCompanyAccessSchema,
type CreateCostEvent,
type CreateFinanceEvent,
@@ -580,12 +602,19 @@ export {
type CreateCompanyInvite,
type CreateOpenClawInvitePrompt,
type AcceptInvite,
+ type ListCompanyInvitesQuery,
type ListJoinRequestsQuery,
type ClaimJoinRequestApiKey,
type BoardCliAuthAccessLevel,
type CreateCliAuthChallenge,
type ResolveCliAuthChallenge,
+ type CurrentUserProfile,
+ type AuthSession,
+ type UpdateCurrentUserProfile,
+ type UpdateCompanyMember,
+ type UpdateCompanyMemberWithPermissions,
type UpdateMemberPermissions,
+ type SearchAdminUsersQuery,
type UpdateUserCompanyAccess,
companySkillSourceTypeSchema,
companySkillTrustLevelSchema,
@@ -663,18 +692,23 @@ export {
AGENT_MENTION_SCHEME,
PROJECT_MENTION_SCHEME,
SKILL_MENTION_SCHEME,
+ USER_MENTION_SCHEME,
buildAgentMentionHref,
buildProjectMentionHref,
buildSkillMentionHref,
+ buildUserMentionHref,
extractAgentMentionIds,
+ extractProjectMentionIds,
extractSkillMentionIds,
+ extractUserMentionIds,
parseAgentMentionHref,
parseProjectMentionHref,
parseSkillMentionHref,
- extractProjectMentionIds,
+ parseUserMentionHref,
type ParsedAgentMention,
type ParsedProjectMention,
type ParsedSkillMention,
+ type ParsedUserMention,
} from "./project-mentions.js";
export {
diff --git a/packages/shared/src/project-mentions.test.ts b/packages/shared/src/project-mentions.test.ts
index 5a156959a9..709fd27d6e 100644
--- a/packages/shared/src/project-mentions.test.ts
+++ b/packages/shared/src/project-mentions.test.ts
@@ -3,12 +3,15 @@ import {
buildAgentMentionHref,
buildProjectMentionHref,
buildSkillMentionHref,
+ buildUserMentionHref,
extractAgentMentionIds,
extractProjectMentionIds,
extractSkillMentionIds,
+ extractUserMentionIds,
parseAgentMentionHref,
parseProjectMentionHref,
parseSkillMentionHref,
+ parseUserMentionHref,
} from "./project-mentions.js";
describe("project-mentions", () => {
@@ -30,6 +33,14 @@ describe("project-mentions", () => {
expect(extractAgentMentionIds(`[@CodexCoder](${href})`)).toEqual(["agent-123"]);
});
+ it("round-trips user mentions", () => {
+ const href = buildUserMentionHref("user-123");
+ expect(parseUserMentionHref(href)).toEqual({
+ userId: "user-123",
+ });
+ expect(extractUserMentionIds(`[@Taylor](${href})`)).toEqual(["user-123"]);
+ });
+
it("round-trips skill mentions with slug metadata", () => {
const href = buildSkillMentionHref("skill-123", "release-changelog");
expect(parseSkillMentionHref(href)).toEqual({
diff --git a/packages/shared/src/project-mentions.ts b/packages/shared/src/project-mentions.ts
index 117fad3947..b2d3ee9316 100644
--- a/packages/shared/src/project-mentions.ts
+++ b/packages/shared/src/project-mentions.ts
@@ -1,5 +1,6 @@
export const PROJECT_MENTION_SCHEME = "project://";
export const AGENT_MENTION_SCHEME = "agent://";
+export const USER_MENTION_SCHEME = "user://";
export const SKILL_MENTION_SCHEME = "skill://";
const HEX_COLOR_RE = /^[0-9a-f]{6}$/i;
@@ -8,6 +9,7 @@ const HEX_COLOR_WITH_HASH_RE = /^#[0-9a-f]{6}$/i;
const HEX_COLOR_SHORT_WITH_HASH_RE = /^#[0-9a-f]{3}$/i;
const PROJECT_MENTION_LINK_RE = /\[[^\]]*]\((project:\/\/[^)\s]+)\)/gi;
const AGENT_MENTION_LINK_RE = /\[[^\]]*]\((agent:\/\/[^)\s]+)\)/gi;
+const USER_MENTION_LINK_RE = /\[[^\]]*]\((user:\/\/[^)\s]+)\)/gi;
const SKILL_MENTION_LINK_RE = /\[[^\]]*]\((skill:\/\/[^)\s]+)\)/gi;
const AGENT_ICON_NAME_RE = /^[a-z0-9-]+$/i;
const SKILL_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/i;
@@ -22,6 +24,10 @@ export interface ParsedAgentMention {
icon: string | null;
}
+export interface ParsedUserMention {
+ userId: string;
+}
+
export interface ParsedSkillMention {
skillId: string;
slug: string | null;
@@ -111,6 +117,28 @@ export function parseAgentMentionHref(href: string): ParsedAgentMention | null {
};
}
+export function buildUserMentionHref(userId: string): string {
+ return `${USER_MENTION_SCHEME}${userId.trim()}`;
+}
+
+export function parseUserMentionHref(href: string): ParsedUserMention | null {
+ if (!href.startsWith(USER_MENTION_SCHEME)) return null;
+
+ let url: URL;
+ try {
+ url = new URL(href);
+ } catch {
+ return null;
+ }
+
+ if (url.protocol !== "user:") return null;
+
+ const userId = `${url.hostname}${url.pathname}`.replace(/^\/+/, "").trim();
+ if (!userId) return null;
+
+ return { userId };
+}
+
export function buildSkillMentionHref(skillId: string, slug?: string | null): string {
const trimmedSkillId = skillId.trim();
const normalizedSlug = normalizeSkillSlug(slug ?? null);
@@ -165,6 +193,18 @@ export function extractAgentMentionIds(markdown: string): string[] {
return [...ids];
}
+export function extractUserMentionIds(markdown: string): string[] {
+ if (!markdown) return [];
+ const ids = new Set<string>();
+ const re = new RegExp(USER_MENTION_LINK_RE);
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(markdown)) !== null) {
+ const parsed = parseUserMentionHref(match[1]);
+ if (parsed) ids.add(parsed.userId);
+ }
+ return [...ids];
+}
+
export function extractSkillMentionIds(markdown: string): string[] {
if (!markdown) return [];
const ids = new Set<string>();
diff --git a/packages/shared/src/types/access.ts b/packages/shared/src/types/access.ts
index db6554eea2..25f605ba51 100644
--- a/packages/shared/src/types/access.ts
+++ b/packages/shared/src/types/access.ts
@@ -1,5 +1,7 @@
import type {
AgentAdapterType,
+ CompanyStatus,
+ HumanCompanyMembershipRole,
InstanceUserRole,
InviteJoinType,
InviteType,
@@ -33,6 +35,30 @@ export interface PrincipalPermissionGrant {
updatedAt: Date;
}
+export interface AccessUserProfile {
+ id: string;
+ email: string | null;
+ name: string | null;
+ image: string | null;
+}
+
+export interface CompanyMemberRecord extends CompanyMembership {
+ principalType: "user";
+ membershipRole: HumanCompanyMembershipRole | null;
+ user: AccessUserProfile | null;
+ grants: PrincipalPermissionGrant[];
+}
+
+export interface CompanyMembersResponse {
+ members: CompanyMemberRecord[];
+ access: {
+ currentUserRole: HumanCompanyMembershipRole | null;
+ canManageMembers: boolean;
+ canInviteUsers: boolean;
+ canApproveJoinRequests: boolean;
+ };
+}
+
export interface Invite {
id: string;
companyId: string | null;
@@ -48,6 +74,22 @@ export interface Invite {
updatedAt: Date;
}
+export type InviteState = "active" | "revoked" | "accepted" | "expired";
+
+export interface CompanyInviteRecord extends Invite {
+ companyName: string | null;
+ humanRole: HumanCompanyMembershipRole | null;
+ inviteMessage: string | null;
+ state: InviteState;
+ invitedByUser: AccessUserProfile | null;
+ relatedJoinRequestId: string | null;
+}
+
+export interface CompanyInviteListResponse {
+ invites: CompanyInviteRecord[];
+ nextOffset: number | null;
+}
+
export interface JoinRequest {
id: string;
inviteId: string;
@@ -72,6 +114,26 @@ export interface JoinRequest {
updatedAt: Date;
}
+export interface JoinRequestInviteSummary {
+ id: string;
+ inviteType: InviteType;
+ allowedJoinTypes: InviteJoinType;
+ humanRole: HumanCompanyMembershipRole | null;
+ inviteMessage: string | null;
+ createdAt: Date;
+ expiresAt: Date;
+ revokedAt: Date | null;
+ acceptedAt: Date | null;
+ invitedByUser: AccessUserProfile | null;
+}
+
+export interface JoinRequestRecord extends JoinRequest {
+ requesterUser: AccessUserProfile | null;
+ approvedByUser: AccessUserProfile | null;
+ rejectedByUser: AccessUserProfile | null;
+ invite: JoinRequestInviteSummary | null;
+}
+
export interface InstanceUserRoleGrant {
id: string;
userId: string;
@@ -79,3 +141,21 @@ export interface InstanceUserRoleGrant {
createdAt: Date;
updatedAt: Date;
}
+
+export interface AdminUserDirectoryEntry extends AccessUserProfile {
+ isInstanceAdmin: boolean;
+ activeCompanyMembershipCount: number;
+}
+
+export interface UserCompanyAccessEntry extends CompanyMembership {
+ principalType: "user";
+ companyName: string | null;
+ companyStatus: CompanyStatus | null;
+}
+
+export interface UserCompanyAccessResponse {
+ user: (AccessUserProfile & {
+ isInstanceAdmin: boolean;
+ }) | null;
+ companyAccess: UserCompanyAccessEntry[];
+}
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index 62ca4dde0a..0089c92d01 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -173,11 +173,21 @@ export type { SidebarBadges } from "./sidebar-badges.js";
export type { SidebarOrderPreference } from "./sidebar-preferences.js";
export type { InboxDismissal } from "./inbox-dismissal.js";
export type {
+ AccessUserProfile,
+ CompanyMemberRecord,
+ CompanyMembersResponse,
CompanyMembership,
+ CompanyInviteListResponse,
+ CompanyInviteRecord,
PrincipalPermissionGrant,
Invite,
JoinRequest,
+ JoinRequestInviteSummary,
+ JoinRequestRecord,
InstanceUserRoleGrant,
+ AdminUserDirectoryEntry,
+ UserCompanyAccessEntry,
+ UserCompanyAccessResponse,
} from "./access.js";
export type { QuotaWindow, ProviderQuotaResult } from "./quota.js";
export type {
diff --git a/packages/shared/src/types/project.ts b/packages/shared/src/types/project.ts
index 6bd7da1b0e..2aa5036155 100644
--- a/packages/shared/src/types/project.ts
+++ b/packages/shared/src/types/project.ts
@@ -1,10 +1,10 @@
import type { PauseReason, ProjectStatus } from "../constants.js";
-import type { AgentEnvConfig } from "./secrets.js";
import type {
ProjectExecutionWorkspacePolicy,
ProjectWorkspaceRuntimeConfig,
WorkspaceRuntimeService,
} from "./workspace-runtime.js";
+import type { AgentEnvConfig } from "./secrets.js";
export type ProjectWorkspaceSourceType = "local_path" | "git_repo" | "remote_managed" | "non_git_path";
export type ProjectWorkspaceVisibility = "default" | "advanced";
diff --git a/packages/shared/src/validators/access.ts b/packages/shared/src/validators/access.ts
index 6da95c126e..8cd8f5c3a0 100644
--- a/packages/shared/src/validators/access.ts
+++ b/packages/shared/src/validators/access.ts
@@ -1,14 +1,18 @@
import { z } from "zod";
import {
+ AGENT_ADAPTER_TYPES,
+ HUMAN_COMPANY_MEMBERSHIP_ROLES,
INVITE_JOIN_TYPES,
JOIN_REQUEST_STATUSES,
JOIN_REQUEST_TYPES,
+ MEMBERSHIP_STATUSES,
PERMISSION_KEYS,
} from "../constants.js";
import { optionalAgentAdapterTypeSchema } from "../adapter-type.js";
export const createCompanyInviteSchema = z.object({
allowedJoinTypes: z.enum(INVITE_JOIN_TYPES).default("both"),
+ humanRole: z.enum(HUMAN_COMPANY_MEMBERSHIP_ROLES).optional().nullable(),
defaultsPayload: z.record(z.string(), z.unknown()).optional().nullable(),
agentMessage: z.string().max(4000).optional().nullable(),
});
@@ -46,6 +50,14 @@ export const listJoinRequestsQuerySchema = z.object({
export type ListJoinRequestsQuery = z.infer<typeof listJoinRequestsQuerySchema>;
+export const listCompanyInvitesQuerySchema = z.object({
+ state: z.enum(["active", "revoked", "accepted", "expired"]).optional(),
+ limit: z.coerce.number().int().min(1).max(100).optional().default(20),
+ offset: z.coerce.number().int().min(0).optional().default(0),
+});
+
+export type ListCompanyInvitesQuery = z.infer<typeof listCompanyInvitesQuerySchema>;
+
export const claimJoinRequestApiKeySchema = z.object({
claimSecret: z.string().min(16).max(256),
});
@@ -85,8 +97,82 @@ export const updateMemberPermissionsSchema = z.object({
export type UpdateMemberPermissions = z.infer<typeof updateMemberPermissionsSchema>;
+export const updateCompanyMemberSchema = z.object({
+ membershipRole: z.enum(HUMAN_COMPANY_MEMBERSHIP_ROLES).optional().nullable(),
+ status: z.enum(MEMBERSHIP_STATUSES).optional(),
+}).refine((value) => value.membershipRole !== undefined || value.status !== undefined, {
+ message: "membershipRole or status is required",
+});
+
+export type UpdateCompanyMember = z.infer<typeof updateCompanyMemberSchema>;
+
+export const updateCompanyMemberWithPermissionsSchema = z.object({
+ membershipRole: z.enum(HUMAN_COMPANY_MEMBERSHIP_ROLES).optional().nullable(),
+ status: z.enum(MEMBERSHIP_STATUSES).optional(),
+ grants: updateMemberPermissionsSchema.shape.grants.default([]),
+}).refine((value) => value.membershipRole !== undefined || value.status !== undefined, {
+ message: "membershipRole or status is required",
+});
+
+export type UpdateCompanyMemberWithPermissions = z.infer<typeof updateCompanyMemberWithPermissionsSchema>;
+
export const updateUserCompanyAccessSchema = z.object({
companyIds: z.array(z.string().uuid()).default([]),
});
export type UpdateUserCompanyAccess = z.infer<typeof updateUserCompanyAccessSchema>;
+
+export const searchAdminUsersQuerySchema = z.object({
+ query: z.string().trim().max(120).optional().default(""),
+});
+
+export type SearchAdminUsersQuery = z.infer<typeof searchAdminUsersQuerySchema>;
+
+const profileImageAssetPathPattern = /^\/api\/assets\/[^/?#]+\/content(?:\?[^#]*)?(?:#.*)?$/;
+
+function isValidProfileImage(value: string): boolean {
+ if (profileImageAssetPathPattern.test(value)) return true;
+
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" || url.protocol === "http:";
+ } catch {
+ return false;
+ }
+}
+
+const profileImageSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(4000)
+ .refine(isValidProfileImage, { message: "Invalid profile image URL" });
+
+export const currentUserProfileSchema = z.object({
+ id: z.string().min(1),
+ email: z.string().email().nullable(),
+ name: z.string().min(1).max(120).nullable(),
+ image: profileImageSchema.nullable(),
+});
+
+export type CurrentUserProfile = z.infer<typeof currentUserProfileSchema>;
+
+export const authSessionSchema = z.object({
+ session: z.object({
+ id: z.string().min(1),
+ userId: z.string().min(1),
+ }),
+ user: currentUserProfileSchema,
+});
+
+export type AuthSession = z.infer<typeof authSessionSchema>;
+
+export const updateCurrentUserProfileSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ image: z
+ .union([profileImageSchema, z.literal(""), z.null()])
+ .optional()
+ .transform((value) => value === "" ? null : value),
+});
+
+export type UpdateCurrentUserProfile = z.infer<typeof updateCurrentUserProfileSchema>;
diff --git a/packages/shared/src/validators/execution-workspace.ts b/packages/shared/src/validators/execution-workspace.ts
index fad6382380..db5507e099 100644
--- a/packages/shared/src/validators/execution-workspace.ts
+++ b/packages/shared/src/validators/execution-workspace.ts
@@ -99,7 +99,6 @@ export const workspaceRuntimeServiceSchema = z.object({
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
}).strict();
-
export const executionWorkspaceCloseReadinessSchema = z.object({
workspaceId: z.string().uuid(),
state: executionWorkspaceCloseReadinessStateSchema,
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 4f8e659bbc..8e1662f428 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -253,22 +253,36 @@ export {
createCompanyInviteSchema,
createOpenClawInvitePromptSchema,
acceptInviteSchema,
+ listCompanyInvitesQuerySchema,
listJoinRequestsQuerySchema,
claimJoinRequestApiKeySchema,
boardCliAuthAccessLevelSchema,
createCliAuthChallengeSchema,
resolveCliAuthChallengeSchema,
+ currentUserProfileSchema,
+ authSessionSchema,
+ updateCurrentUserProfileSchema,
+ updateCompanyMemberSchema,
+ updateCompanyMemberWithPermissionsSchema,
updateMemberPermissionsSchema,
+ searchAdminUsersQuerySchema,
updateUserCompanyAccessSchema,
type CreateCompanyInvite,
type CreateOpenClawInvitePrompt,
type AcceptInvite,
+ type ListCompanyInvitesQuery,
type ListJoinRequestsQuery,
type ClaimJoinRequestApiKey,
type BoardCliAuthAccessLevel,
type CreateCliAuthChallenge,
type ResolveCliAuthChallenge,
+ type CurrentUserProfile,
+ type AuthSession,
+ type UpdateCurrentUserProfile,
+ type UpdateCompanyMember,
+ type UpdateCompanyMemberWithPermissions,
type UpdateMemberPermissions,
+ type SearchAdminUsersQuery,
type UpdateUserCompanyAccess,
} from "./access.js";
diff --git a/releases/v2026.414.0.md b/releases/v2026.414.0.md
new file mode 100644
index 0000000000..d1c2863520
--- /dev/null
+++ b/releases/v2026.414.0.md
@@ -0,0 +1,107 @@
+# v2026.414.0
+
+> Released: 2026-04-14
+
+## Security
+
+- **Authorization hardening (GHSA-68qg-g8mg-6pr7)** — Scoped import, approval, activity, and heartbeat API routes to enforce proper authorization checks. Previously, certain administrative endpoints were accessible without adequate permission verification. All users are strongly encouraged to upgrade. ([#3315](https://github.com/paperclipai/paperclip/pull/3315), [#3009](https://github.com/paperclipai/paperclip/pull/3009), @KhairulA)
+- **Removed hardcoded JWT secret fallback** — The `createBetterAuthInstance` function no longer falls back to a hardcoded JWT secret, closing a credential-hygiene gap. ([#3124](https://github.com/paperclipai/paperclip/pull/3124), @cleanunicorn)
+- **Redact Bearer tokens in logs** — Server log output now redacts Bearer tokens to prevent accidental credential exposure.
+- **Dependency bumps** — Updated `multer` to 2.1.1 (HIGH CVEs) and `rollup` to 4.59.0 (path-traversal CVE). ([#2909](https://github.com/paperclipai/paperclip/pull/2909), @marysomething99-prog)
+
+## Highlights
+
+- **Multi-user access and invites** — Full multi-user authentication, company roles, and invite management. Board users can create invite links, approve join requests, and manage member roles. Invite flows support auto-accept for signed-in users, paginated history, and human-readable requester identities in approval views.
+- **Human user identities everywhere** — Human users now appear with real names and avatars across activity feeds, issue tables, assignee pickers, and @-mention menus. A lightweight user directory endpoint powers consistent identity resolution across the UI.
+- **Issue chat thread** — Replaced the classic comment timeline with a full chat-style thread powered by assistant-ui. Agent run transcripts, chain-of-thought, and user messages render inline as a continuous conversation with polished avatars, action bars, and relative timestamps. ([#3079](https://github.com/paperclipai/paperclip/pull/3079))
+- **External adapter plugin system** — Third-party adapters can now be installed as npm packages or loaded from local directories. Plugins declare a config schema and an optional UI transcript parser; built-in adapters can be overridden by external ones. Includes Hermes local session management and provider/model display in run details. ([#2649](https://github.com/paperclipai/paperclip/pull/2649), [#2650](https://github.com/paperclipai/paperclip/pull/2650), [#2651](https://github.com/paperclipai/paperclip/pull/2651), [#2654](https://github.com/paperclipai/paperclip/pull/2654), [#2655](https://github.com/paperclipai/paperclip/pull/2655), [#2659](https://github.com/paperclipai/paperclip/pull/2659), @plind-dm)
+- **Execution policies** — Issues can carry a review/approval execution policy with multi-stage signoff workflows. Reviewers and approvers are selected per-stage, and Paperclip routes the issue through each stage automatically. ([#3222](https://github.com/paperclipai/paperclip/pull/3222))
+- **Blocker dependencies** — First-class issue blocker relations with automatic wake-on-dependency-resolved. Set `blockedByIssueIds` on any issue and Paperclip wakes the assignee when all blockers reach `done`. ([#2797](https://github.com/paperclipai/paperclip/pull/2797))
+- **Standalone MCP server** — New `@paperclipai/mcp-server` package exposing the Paperclip API as an MCP tool server, including approval creation. ([#2435](https://github.com/paperclipai/paperclip/pull/2435))
+
+## Improvements
+
+- **Invite UX polish** — Auto-submit for signed-in invites, inline auth flow, paginated invite history, requester identity in join approvals, and prevention of duplicate join requests and member re-invites.
+- **Board approvals** — Generic issue-linked board approvals with card styling and visibility improvements in the issue detail sidebar. ([#3220](https://github.com/paperclipai/paperclip/pull/3220))
+- **Inbox parent-child nesting** — Parent issues group their children in the inbox Mine view with a toggle button, j/k keyboard traversal across nested items, and collapsible groups. ([#2218](https://github.com/paperclipai/paperclip/pull/2218), @HenkDz)
+- **Inbox workspace grouping** — Issues can now be grouped by workspace in the inbox with collapsible mobile groups and shared column controls across inbox and issues lists. ([#3356](https://github.com/paperclipai/paperclip/pull/3356))
+- **Issue search** — Trigram-indexed full-text search across titles, identifiers, descriptions, and comments with debounced input. Comment matches now surface in search results. ([#2999](https://github.com/paperclipai/paperclip/pull/2999))
+- **Sub-issues inline** — Sub-issues moved from a separate tab to inline display on the issue detail, with parent-inherited workspace defaults and assignee propagation. ([#3355](https://github.com/paperclipai/paperclip/pull/3355))
+- **Issue-to-issue navigation** — Faster navigation between issues with scroll reset, prefetch, and detail-view optimizations. ([#3542](https://github.com/paperclipai/paperclip/pull/3542))
+- **Auto-checkout for scoped wakes** — Agent harness now automatically checks out the scoped issue on comment-driven wakes, reducing latency for agent heartbeats. ([#3538](https://github.com/paperclipai/paperclip/pull/3538))
+- **Document revision diff viewer** — Side-by-side diff viewer for issue document revisions with improved modal layout. ([#2792](https://github.com/paperclipai/paperclip/pull/2792))
+- **Keyboard shortcuts cheatsheet** — Press `?` to open a keyboard shortcut reference dialog; new `g i` (go to inbox), `g c` (comment composer), and inbox archive undo shortcuts. ([#2772](https://github.com/paperclipai/paperclip/pull/2772))
+- **Bedrock model selection** — Claude local adapter now supports AWS Bedrock authentication and model selection. ([#3033](https://github.com/paperclipai/paperclip/pull/3033), [#2793](https://github.com/paperclipai/paperclip/pull/2793), @kimnamu)
+- **Codex fast mode** — Added fast mode support for the Codex local adapter with env probe safeguards. ([#3383](https://github.com/paperclipai/paperclip/pull/3383))
+- **Backup improvements** — Gzip-compressed backups with tiered daily/weekly/monthly retention and UI controls in Instance Settings. ([#3015](https://github.com/paperclipai/paperclip/pull/3015), @aronprins)
+- **GitHub webhook signing modes** — Added `github_hmac` and `none` webhook signing modes with timing-safe HMAC comparison. ([#1961](https://github.com/paperclipai/paperclip/pull/1961), @antonio-mello-ai)
+- **Sidebar order persistence** — Sidebar project and company ordering preferences now persist per-user.
+- **Workspace runtime controls** — Start/stop controls, runtime state reconciliation, runtime service improvements, and workspace branch/folder display in the issue properties sidebar. ([#3354](https://github.com/paperclipai/paperclip/pull/3354))
+- **Attachment improvements** — Arbitrary file attachments (not just images), drag-and-drop non-image files onto markdown editor, and square-cropped image gallery grid. ([#2749](https://github.com/paperclipai/paperclip/pull/2749))
+- **Image gallery in chat** — Clicking images in chat messages now opens a full gallery viewer.
+- **Mobile UX** — Gmail-inspired mobile top bar for inbox issue views, responsive execution workspace pages, mobile mention menu placement, and mobile comment copy button feedback.
+- **Routine improvements** — Draft routine defaults, run-time overrides, routine title variables, and relaxed project/agent requirements for routines. ([#3220](https://github.com/paperclipai/paperclip/pull/3220))
+- **Project environment variables** — Projects can now define environment variables that are inherited by workspace runs.
+- **Skill auto-enable** — Mentioned skills are automatically enabled for heartbeat runs.
+- **Comment wake batching** — Multiple comment wakes are batched into a single inline payload for more efficient agent heartbeats.
+- **Server-side adapter pause/resume** — Builtin adapter types can now be paused/resumed from the server with `overridePaused`. ([#2542](https://github.com/paperclipai/paperclip/pull/2542), @plind-dm)
+- **Skill slash-command autocomplete** — Skill names now autocomplete in the editor.
+- **Worktree reseed command** — New CLI command to reseed worktrees from latest repo state. ([#3353](https://github.com/paperclipai/paperclip/pull/3353))
+
+## Fixes
+
+- **Assignee name overflow** — Fixed long assignee names overflowing in the issues list grid with proper truncation.
+- **Company alerts isolation** — Company-level alerts no longer appear in personal inbox.
+- **Invite state management** — Fixed reused invite refresh pending state, paginated invite history cache isolation, and invite flow state mapping across reloads.
+- **Issue detail stability** — Fixed visible refreshes during agent updates, comment post resets, ref update loops, split regressions, and main-pane focus on navigation. ([#3355](https://github.com/paperclipai/paperclip/pull/3355))
+- **Inbox badge count** — Badge now correctly counts only unread Mine issues. ([#2512](https://github.com/paperclipai/paperclip/pull/2512), @AllenHyang)
+- **Inbox keyboard navigation** — Fixed j/k traversal across groups and nesting column alignment. ([#2218](https://github.com/paperclipai/paperclip/pull/2218), @HenkDz)
+- **Execution workspaces** — Fixed linked worktree reuse, dev runner isolation, workspace import regressions, and workspace preflight through server toolchain.
+- **Stale execution locks** — Fixed stale execution lock lifecycle with proper `executionAgentNameKey` clearing. ([#2643](https://github.com/paperclipai/paperclip/pull/2643), @chrisschwer)
+- **Agent env bindings** — Fixed cleared agent env bindings not persisting on save. ([#3232](https://github.com/paperclipai/paperclip/pull/3232), @officialasishkumar)
+- **Capabilities field** — Fixed blank screen when clearing the Capabilities field. ([#2442](https://github.com/paperclipai/paperclip/pull/2442), @sparkeros)
+- **Skill deletion** — Company skills can now be deleted with an agent usage check. ([#2441](https://github.com/paperclipai/paperclip/pull/2441), @DanielSousa)
+- **Claude session resume** — Fixed `--append-system-prompt-file` being sent on resumed Claude sessions and preserved instructions on resume fallback. ([#2949](https://github.com/paperclipai/paperclip/pull/2949), [#2936](https://github.com/paperclipai/paperclip/pull/2936), [#2937](https://github.com/paperclipai/paperclip/pull/2937), @Lempkey)
+- **Agent auth JWT** — Fixed agent auth to fall back to `BETTER_AUTH_SECRET` when `PAPERCLIP_AGENT_JWT_SECRET` is absent. ([#2866](https://github.com/paperclipai/paperclip/pull/2866), @ergonaworks)
+- **Typing lag** — Fixed typing lag in long comment threads. ([#3163](https://github.com/paperclipai/paperclip/pull/3163))
+- **Shimmer animation** — Fixed shimmer text using invalid `hsl()` wrapper on `oklch` colors, loop jitter, and added pause between repeats.
+- **Mention selection** — Restored touch mention selection and fixed spaced mention queries.
+- **Inbox archive** — Fixed archive flashing back after fade-out.
+- **Goal description** — Made goal description area scrollable in create dialog. ([#2148](https://github.com/paperclipai/paperclip/pull/2148), @shoaib050326)
+- **Worktree provisioning** — Fixed symlink relinking, fallback seeding, dependency hydration, and validated linked worktrees before reuse. ([#3354](https://github.com/paperclipai/paperclip/pull/3354))
+- **Node keepAliveTimeout** — Increased timeout behind reverse proxies to prevent 502 errors.
+- **Codex tool-use transcripts** — Fixed Codex tool-use transcript completion parsing.
+- **Codex resume error** — Recognize missing-rollout Codex resume error as stale session.
+- **Pi quota exhaustion** — Treat Pi quota exhaustion as a failed run. ([#2305](https://github.com/paperclipai/paperclip/pull/2305))
+- **Issue identifier collisions** — Prevented identifier collisions during concurrent issue creation.
+- **OpenClaw CEO paths** — Fixed `$AGENT_HOME` references in CEO onboarding instructions to use relative paths. ([#3299](https://github.com/paperclipai/paperclip/pull/3299), @aronprins)
+- **Windows adapter** — Uses `cmd.exe` for `.cmd`/`.bat` wrappers on Windows. ([#2662](https://github.com/paperclipai/paperclip/pull/2662), @wbelt)
+- **Markdown autoformat** — Fixed autoformat of pasted markdown in inline editor. ([#2733](https://github.com/paperclipai/paperclip/pull/2733), @davison)
+- **Paused agent dimming** — Correctly dim paused agents in list and org chart views; skip dimming on Paused filter tab. ([#2397](https://github.com/paperclipai/paperclip/pull/2397), @HearthCore)
+- **Import role fallback** — Import now reads agent role from frontmatter before defaulting to "agent". ([#2594](https://github.com/paperclipai/paperclip/pull/2594), @plind-dm)
+- **Backup cleanup** — Clean up orphaned `.sql` files on compression failure and fix stale startup log.
+
+## Upgrade Guide
+
+Nine new database migrations (`0049`–`0056`) will run automatically on startup. These add:
+
+- Issue blocker relations table (`0049`)
+- Project environment variables (`0050`)
+- Trigram search indexes on issues and comments (`0051` — requires `pg_trgm` extension)
+- Execution policy decision tracking (`0052`)
+- Non-issue inbox dismissals (`0053`)
+- Relaxed routine constraints (`0054`)
+- Heartbeat run process group tracking (`0055`)
+- User sidebar preferences (`0056`)
+
+All migrations are additive — no existing data is modified or removed.
+
+**`pg_trgm` extension**: Migration `0051` creates the `pg_trgm` PostgreSQL extension for full-text search. If your database user does not have `CREATE EXTENSION` privileges, ask your DBA to run `CREATE EXTENSION IF NOT EXISTS pg_trgm;` before upgrading.
+
+If you use external adapter plugins, note that built-in adapters can now be overridden by external ones. The `overriddenBuiltin` flag in the adapter API indicates when this is happening.
+
+## Contributors
+
+Thank you to everyone who contributed to this release!
+
+@AllenHyang, @antonio-mello-ai, @aronprins, @chrisschwer, @cleanunicorn, @cryppadotta, @DanielSousa, @davison, @ergonaworks, @HearthCore, @HenkDz, @KhairulA, @kimnamu, @Lempkey, @marysomething99-prog, @mvanhorn, @officialasishkumar, @plind-dm, @shoaib050326, @sparkeros, @wbelt
diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts
index a26ef6380e..a30096882a 100644
--- a/scripts/dev-runner.ts
+++ b/scripts/dev-runner.ts
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } f
import path from "node:path";
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
-import { createCapturedOutputBuffer, parseJsonResponseWithLimit } from "./dev-runner-output.mjs";
+import { createCapturedOutputBuffer, parseJsonResponseWithLimit } from "./dev-runner-output.ts";
import { shouldTrackDevServerPath } from "./dev-runner-paths.mjs";
import { createDevServiceIdentity, repoRoot } from "./dev-service-profile.ts";
import { bootstrapDevRunnerWorktreeEnv } from "../server/src/dev-runner-worktree.ts";
@@ -557,7 +557,7 @@ async function getDevHealthPayload() {
if (!response.ok) {
throw new Error(`Health request failed (${response.status})`);
}
- return await parseJsonResponseWithLimit<{ devServer?: { enabled?: boolean; autoRestartEnabled?: boolean; activeRunCount?: number } }>(response);
+ return await parseJsonResponseWithLimit(response);
}
async function waitForChildExit() {
diff --git a/scripts/paperclip-commit-metrics.ts b/scripts/paperclip-commit-metrics.ts
index 8a648afac1..5f989ca1db 100644
--- a/scripts/paperclip-commit-metrics.ts
+++ b/scripts/paperclip-commit-metrics.ts
@@ -436,9 +436,6 @@ async function searchWindow(
for (let page = 2; page <= pageCount; page += 1) {
const response = await searchPage(client, options, start, end, page, 100);
- if (response.incomplete_results) {
- throw new Error(`GitHub returned incomplete search results for window ${windowKey} on page ${page}`);
- }
ingestSearchItems(cache, response.items, shas);
}
@@ -512,7 +509,7 @@ function sortFilteredShas(cache: CacheFile, shas: string[]): string[] {
}
function formatQueryDate(value: Date): string {
- return new Date(Math.floor(value.getTime() / 1000) * 1000).toISOString().replace(".000Z", "Z");
+ return value.toISOString().replace(".000Z", "Z");
}
function ingestSearchItems(cache: CacheFile, items: SearchCommitItem[], shas: Set<string>) {
@@ -850,14 +847,6 @@ class GitHubClient {
return (await response.json()) as T;
}
- const retryAfter = response.headers.get("retry-after");
- if ((response.status === 403 || response.status === 429) && retryAfter) {
- const waitMs = Math.max(Number.parseInt(retryAfter, 10) * 1000, 1_000);
- console.error(`GitHub secondary rate limit hit for ${pathname}; waiting ${Math.ceil(waitMs / 1000)}s...`);
- await sleep(waitMs);
- continue;
- }
-
const remaining = response.headers.get("x-ratelimit-remaining");
const resetAt = response.headers.get("x-ratelimit-reset");
if ((response.status === 403 || response.status === 429) && remaining === "0" && resetAt) {
diff --git a/scripts/provision-worktree.sh b/scripts/provision-worktree.sh
index ba90e9ff9f..725f9c6780 100644
--- a/scripts/provision-worktree.sh
+++ b/scripts/provision-worktree.sh
@@ -31,26 +31,35 @@ source_env_path="$(dirname "$source_config_path")/.env"
mkdir -p "$paperclip_dir"
-run_paperclipai_command() {
- local command_args=("$@")
- if command -v pnpm >/dev/null 2>&1 && pnpm paperclipai --help >/dev/null 2>&1; then
- pnpm paperclipai "${command_args[@]}"
+run_isolated_worktree_init() {
+ local base_cli_runner="$base_cwd/cli/node_modules/tsx/dist/cli.mjs"
+ local base_cli_entry="$base_cwd/cli/src/index.ts"
+
+ if [[ -f "$base_cli_runner" && -f "$base_cli_entry" ]]; then
+ (
+ cd "$worktree_cwd"
+ node "$base_cli_runner" "$base_cli_entry" worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path"
+ )
return 0
fi
- local base_cli_tsx_path="$base_cwd/cli/node_modules/tsx/dist/cli.mjs"
- local base_cli_entry_path="$base_cwd/cli/src/index.ts"
- if command -v node >/dev/null 2>&1 && [[ -f "$base_cli_tsx_path" ]] && [[ -f "$base_cli_entry_path" ]]; then
- node "$base_cli_tsx_path" "$base_cli_entry_path" "${command_args[@]}"
+ if command -v pnpm >/dev/null 2>&1 && pnpm paperclipai --help >/dev/null 2>&1; then
+ (
+ cd "$worktree_cwd"
+ pnpm paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path"
+ )
return 0
fi
if command -v paperclipai >/dev/null 2>&1; then
- paperclipai "${command_args[@]}"
+ (
+ cd "$worktree_cwd"
+ paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --from-config "$source_config_path"
+ )
return 0
fi
- return 1
+ return 127
}
paperclipai_command_available() {
@@ -71,19 +80,6 @@ paperclipai_command_available() {
return 1
}
-run_isolated_worktree_init() {
- run_paperclipai_command \
- worktree \
- init \
- --force \
- --seed-mode \
- minimal \
- --name \
- "$worktree_name" \
- --from-config \
- "$source_config_path"
-}
-
write_fallback_worktree_config() {
WORKTREE_NAME="$worktree_name" \
BASE_CWD="$base_cwd" \
diff --git a/server/src/__tests__/access-service.test.ts b/server/src/__tests__/access-service.test.ts
new file mode 100644
index 0000000000..de839370cb
--- /dev/null
+++ b/server/src/__tests__/access-service.test.ts
@@ -0,0 +1,99 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import {
+ companies,
+ companyMemberships,
+ createDb,
+ principalPermissionGrants,
+} from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+import { accessService } from "../services/access.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+async function createCompanyWithOwner(db: ReturnType<typeof createDb>) {
+ const company = await db
+ .insert(companies)
+ .values({
+ name: `Access Service ${randomUUID()}`,
+ issuePrefix: `AS${randomUUID().slice(0, 6).toUpperCase()}`,
+ })
+ .returning()
+ .then((rows) => rows[0]!);
+
+ const owner = await db
+ .insert(companyMemberships)
+ .values({
+ companyId: company.id,
+ principalType: "user",
+ principalId: `owner-${randomUUID()}`,
+ status: "active",
+ membershipRole: "owner",
+ })
+ .returning()
+ .then((rows) => rows[0]!);
+
+ return { company, owner };
+}
+
+describeEmbeddedPostgres("access service", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-access-service-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(principalPermissionGrants);
+ await db.delete(companyMemberships);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ it("rejects combined access updates that would demote the last active owner", async () => {
+ const { company, owner } = await createCompanyWithOwner(db);
+ const access = accessService(db);
+
+ await expect(
+ access.updateMemberAndPermissions(
+ company.id,
+ owner.id,
+ { membershipRole: "admin", grants: [] },
+ "admin-user",
+ ),
+ ).rejects.toThrow("Cannot remove the last active owner");
+
+ const unchanged = await db
+ .select()
+ .from(companyMemberships)
+ .where(eq(companyMemberships.id, owner.id))
+ .then((rows) => rows[0]!);
+ expect(unchanged.membershipRole).toBe("owner");
+ });
+
+ it("rejects role-only updates that would suspend the last active owner", async () => {
+ const { company, owner } = await createCompanyWithOwner(db);
+ const access = accessService(db);
+
+ await expect(
+ access.updateMember(company.id, owner.id, { status: "suspended" }),
+ ).rejects.toThrow("Cannot remove the last active owner");
+
+ const unchanged = await db
+ .select()
+ .from(companyMemberships)
+ .where(eq(companyMemberships.id, owner.id))
+ .then((rows) => rows[0]!);
+ expect(unchanged.status).toBe("active");
+ });
+});
diff --git a/server/src/__tests__/access-validators.test.ts b/server/src/__tests__/access-validators.test.ts
new file mode 100644
index 0000000000..6fa63b9e8c
--- /dev/null
+++ b/server/src/__tests__/access-validators.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import {
+ updateCompanyMemberWithPermissionsSchema,
+ updateCurrentUserProfileSchema,
+} from "@paperclipai/shared";
+
+describe("access validators", () => {
+ it("accepts HTTP(S) and Paperclip asset image URLs", () => {
+ expect(updateCurrentUserProfileSchema.safeParse({
+ name: "Ada Lovelace",
+ image: "https://example.com/avatar.png",
+ }).success).toBe(true);
+ expect(updateCurrentUserProfileSchema.safeParse({
+ name: "Ada Lovelace",
+ image: "/api/assets/avatar/content",
+ }).success).toBe(true);
+ });
+
+ it("rejects data URI profile images", () => {
+ expect(updateCurrentUserProfileSchema.safeParse({
+ name: "Ada Lovelace",
+ image: "data:image/png;base64,AAAA",
+ }).success).toBe(false);
+ });
+
+ it("defaults omitted combined member grants to an empty list", () => {
+ const result = updateCompanyMemberWithPermissionsSchema.parse({
+ membershipRole: "operator",
+ });
+
+ expect(result.grants).toEqual([]);
+ });
+});
diff --git a/server/src/__tests__/adapter-routes.test.ts b/server/src/__tests__/adapter-routes.test.ts
index 31168aecd3..cab559afab 100644
--- a/server/src/__tests__/adapter-routes.test.ts
+++ b/server/src/__tests__/adapter-routes.test.ts
@@ -31,7 +31,7 @@ let setOverridePaused: typeof import("../adapters/registry.js").setOverridePause
let adapterRoutes: typeof import("../routes/adapters.js").adapterRoutes;
let errorHandler: typeof import("../middleware/index.js").errorHandler;
-function createApp() {
+function createApp(actorOverrides: Partial<Express.Request["actor"]> = {}) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
@@ -41,6 +41,7 @@ function createApp() {
companyIds: [],
source: "local_implicit",
isInstanceAdmin: false,
+ ...actorOverrides,
};
next();
});
@@ -166,4 +167,18 @@ describe("adapter routes", () => {
fields: [{ key: "mode" }],
});
});
+
+ it("rejects signed-in users without org access", async () => {
+ const app = createApp({
+ userId: "outsider-1",
+ source: "session",
+ companyIds: [],
+ memberships: [],
+ isInstanceAdmin: false,
+ });
+
+ const res = await request(app).get("/api/adapters/claude_local/config-schema");
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ });
});
diff --git a/server/src/__tests__/agent-skills-routes.test.ts b/server/src/__tests__/agent-skills-routes.test.ts
index 9b0fa6182d..310237b73b 100644
--- a/server/src/__tests__/agent-skills-routes.test.ts
+++ b/server/src/__tests__/agent-skills-routes.test.ts
@@ -395,14 +395,6 @@ describe("agent skill routes", () => {
});
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
- expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "11111111-1111-4111-8111-111111111111",
- adapterType: "claude_local",
- }),
- { "AGENTS.md": "You are QA." },
- { entryFile: "AGENTS.md", replaceExisting: false },
- );
expect(mockAgentService.update).toHaveBeenCalledWith(
"11111111-1111-4111-8111-111111111111",
expect.objectContaining({
diff --git a/server/src/__tests__/auth-routes.test.ts b/server/src/__tests__/auth-routes.test.ts
new file mode 100644
index 0000000000..88033d661d
--- /dev/null
+++ b/server/src/__tests__/auth-routes.test.ts
@@ -0,0 +1,170 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+function createSelectChain(rows: unknown[]) {
+ return {
+ from() {
+ return {
+ where() {
+ return Promise.resolve(rows);
+ },
+ };
+ },
+ };
+}
+
+function createUpdateChain(row: unknown) {
+ return {
+ set(values: unknown) {
+ return {
+ where() {
+ return {
+ returning() {
+ return Promise.resolve([{ ...(row as Record<string, unknown>), ...(values as Record<string, unknown>) }]);
+ },
+ };
+ },
+ };
+ },
+ };
+}
+
+function createDb(row: Record<string, unknown>) {
+ return {
+ select: vi.fn(() => createSelectChain([row])),
+ update: vi.fn(() => createUpdateChain(row)),
+ } as any;
+}
+
+async function createApp(actor: Express.Request["actor"], row: Record<string, unknown>) {
+ const [{ authRoutes }, { errorHandler }] = await Promise.all([
+ import("../routes/auth.js"),
+ import("../middleware/index.js"),
+ ]);
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.actor = actor;
+ next();
+ });
+ app.use("/api/auth", authRoutes(createDb(row)));
+ app.use(errorHandler);
+ return app;
+}
+
+describe("auth routes", () => {
+ const baseUser = {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: "https://example.com/jane.png",
+ };
+
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it("returns the persisted user profile in the session payload", async () => {
+ const app = await createApp(
+ {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ },
+ baseUser,
+ );
+
+ const res = await request(app).get("/api/auth/get-session");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ session: {
+ id: "paperclip:session:user-1",
+ userId: "user-1",
+ },
+ user: baseUser,
+ });
+ });
+
+ it("updates the signed-in profile", async () => {
+ const app = await createApp(
+ {
+ type: "board",
+ userId: "user-1",
+ source: "local_implicit",
+ },
+ baseUser,
+ );
+
+ const res = await request(app)
+ .patch("/api/auth/profile")
+ .send({ name: "Board Operator", image: "" });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ id: "user-1",
+ name: "Board Operator",
+ email: "[email protected]",
+ image: null,
+ });
+ });
+
+ it("preserves the existing avatar when updating only the profile name", async () => {
+ const app = await createApp(
+ {
+ type: "board",
+ userId: "user-1",
+ source: "local_implicit",
+ },
+ baseUser,
+ );
+
+ const res = await request(app)
+ .patch("/api/auth/profile")
+ .send({ name: "Board Operator" });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ id: "user-1",
+ name: "Board Operator",
+ email: "[email protected]",
+ image: "https://example.com/jane.png",
+ });
+ });
+
+ it("accepts Paperclip asset paths for avatars", async () => {
+ const app = await createApp(
+ {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ },
+ baseUser,
+ );
+
+ const res = await request(app)
+ .patch("/api/auth/profile")
+ .send({ name: "Jane Example", image: "/api/assets/asset-1/content" });
+
+ expect(res.status).toBe(200);
+ expect(res.body.image).toBe("/api/assets/asset-1/content");
+ });
+
+ it("rejects invalid avatar image references", async () => {
+ const app = await createApp(
+ {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ },
+ baseUser,
+ );
+
+ const res = await request(app)
+ .patch("/api/auth/profile")
+ .send({ name: "Jane Example", image: "not-a-url" });
+
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/server/src/__tests__/auth-session-route.test.ts b/server/src/__tests__/auth-session-route.test.ts
new file mode 100644
index 0000000000..91eeb8a07f
--- /dev/null
+++ b/server/src/__tests__/auth-session-route.test.ts
@@ -0,0 +1,61 @@
+import express from "express";
+import request from "supertest";
+import { describe, expect, it, vi } from "vitest";
+import { actorMiddleware } from "../middleware/auth.js";
+
+function createSelectChain(rows: unknown[]) {
+ return {
+ from() {
+ return {
+ where() {
+ return Promise.resolve(rows);
+ },
+ };
+ },
+ };
+}
+
+function createDb() {
+ return {
+ select: vi
+ .fn()
+ .mockImplementationOnce(() => createSelectChain([]))
+ .mockImplementationOnce(() => createSelectChain([])),
+ } as any;
+}
+
+describe("actorMiddleware authenticated session profile", () => {
+ it("preserves the signed-in user name and email on the board actor", async () => {
+ const app = express();
+ app.use(
+ actorMiddleware(createDb(), {
+ deploymentMode: "authenticated",
+ resolveSession: async () => ({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "User One",
+ email: "[email protected]",
+ },
+ }),
+ }),
+ );
+ app.get("/actor", (req, res) => {
+ res.json(req.actor);
+ });
+
+ const res = await request(app).get("/actor");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ type: "board",
+ userId: "user-1",
+ userName: "User One",
+ userEmail: "[email protected]",
+ source: "session",
+ companyIds: [],
+ memberships: [],
+ isInstanceAdmin: false,
+ });
+ });
+});
diff --git a/server/src/__tests__/authz-company-access.test.ts b/server/src/__tests__/authz-company-access.test.ts
new file mode 100644
index 0000000000..b4b713592a
--- /dev/null
+++ b/server/src/__tests__/authz-company-access.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from "vitest";
+import { assertBoardOrgAccess, assertCompanyAccess, hasBoardOrgAccess } from "../routes/authz.js";
+
+function makeReq(input: {
+ method?: string;
+ actor: Express.Request["actor"];
+}) {
+ return {
+ method: input.method ?? "GET",
+ actor: input.actor,
+ } as Express.Request;
+}
+
+describe("assertCompanyAccess", () => {
+ it("allows viewer memberships to read", () => {
+ const req = makeReq({
+ method: "GET",
+ actor: {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ companyIds: ["company-1"],
+ memberships: [
+ { companyId: "company-1", membershipRole: "viewer", status: "active" },
+ ],
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).not.toThrow();
+ });
+
+ it("rejects viewer memberships for writes", () => {
+ const req = makeReq({
+ method: "PATCH",
+ actor: {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ companyIds: ["company-1"],
+ memberships: [
+ { companyId: "company-1", membershipRole: "viewer", status: "active" },
+ ],
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).toThrow("Viewer access is read-only");
+ });
+
+ it("rejects writes when membership details are present but omit the target company", () => {
+ const req = makeReq({
+ method: "POST",
+ actor: {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ companyIds: ["company-1"],
+ memberships: [],
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).toThrow("User does not have active company access");
+ });
+
+ it("allows legacy board actors that only provide company ids", () => {
+ const req = makeReq({
+ method: "POST",
+ actor: {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ companyIds: ["company-1"],
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).not.toThrow();
+ });
+
+ it("rejects signed-in instance admins without explicit company access", () => {
+ const req = makeReq({
+ method: "GET",
+ actor: {
+ type: "board",
+ userId: "admin-1",
+ source: "session",
+ isInstanceAdmin: true,
+ companyIds: [],
+ memberships: [],
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).toThrow("User does not have access to this company");
+ });
+
+ it("allows local trusted board access without explicit membership", () => {
+ const req = makeReq({
+ method: "GET",
+ actor: {
+ type: "board",
+ userId: "local-board",
+ source: "local_implicit",
+ isInstanceAdmin: true,
+ },
+ });
+
+ expect(() => assertCompanyAccess(req, "company-1")).not.toThrow();
+ });
+});
+
+describe("assertBoardOrgAccess", () => {
+ it("allows signed-in board users with active company access", () => {
+ const req = makeReq({
+ actor: {
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ companyIds: ["company-1"],
+ memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }],
+ isInstanceAdmin: false,
+ },
+ });
+
+ expect(hasBoardOrgAccess(req)).toBe(true);
+ expect(() => assertBoardOrgAccess(req)).not.toThrow();
+ });
+
+ it("allows instance admins without company memberships", () => {
+ const req = makeReq({
+ actor: {
+ type: "board",
+ userId: "admin-1",
+ source: "session",
+ companyIds: [],
+ memberships: [],
+ isInstanceAdmin: true,
+ },
+ });
+
+ expect(hasBoardOrgAccess(req)).toBe(true);
+ expect(() => assertBoardOrgAccess(req)).not.toThrow();
+ });
+
+ it("rejects signed-in users without company access or instance admin rights", () => {
+ const req = makeReq({
+ actor: {
+ type: "board",
+ userId: "outsider-1",
+ source: "session",
+ companyIds: [],
+ memberships: [],
+ isInstanceAdmin: false,
+ },
+ });
+
+ expect(hasBoardOrgAccess(req)).toBe(false);
+ expect(() => assertBoardOrgAccess(req)).toThrow("Company membership or instance admin access required");
+ });
+});
diff --git a/server/src/__tests__/claude-local-execute.test.ts b/server/src/__tests__/claude-local-execute.test.ts
index 4076639f4c..233615cfe3 100644
--- a/server/src/__tests__/claude-local-execute.test.ts
+++ b/server/src/__tests__/claude-local-execute.test.ts
@@ -15,8 +15,6 @@ const addDir = addDirIndex >= 0 ? argv[addDirIndex + 1] : null;
const instructionsIndex = argv.indexOf("--append-system-prompt-file");
const instructionsFilePath = instructionsIndex >= 0 ? argv[instructionsIndex + 1] : null;
const capturePath = process.env.PAPERCLIP_TEST_CAPTURE_PATH;
-const promptFileFlagIndex = process.argv.indexOf("--append-system-prompt-file");
-const appendedSystemPromptFilePath = promptFileFlagIndex >= 0 ? process.argv[promptFileFlagIndex + 1] : null;
const payload = {
argv,
prompt: fs.readFileSync(0, "utf8"),
@@ -25,8 +23,6 @@ const payload = {
instructionsContents: instructionsFilePath ? fs.readFileSync(instructionsFilePath, "utf8") : null,
skillEntries: addDir ? fs.readdirSync(path.join(addDir, ".claude", "skills")).sort() : [],
claudeConfigDir: process.env.CLAUDE_CONFIG_DIR || null,
- appendedSystemPromptFilePath,
- appendedSystemPromptFileContents: appendedSystemPromptFilePath ? fs.readFileSync(appendedSystemPromptFilePath, "utf8") : null,
};
if (capturePath) {
fs.writeFileSync(capturePath, JSON.stringify(payload), "utf8");
diff --git a/server/src/__tests__/codex-local-execute.test.ts b/server/src/__tests__/codex-local-execute.test.ts
index a4e77f9b7c..ddfa75b263 100644
--- a/server/src/__tests__/codex-local-execute.test.ts
+++ b/server/src/__tests__/codex-local-execute.test.ts
@@ -729,7 +729,6 @@ describe("codex execute", () => {
await fs.rm(root, { recursive: true, force: true });
}
});
-
it("uses a worktree-isolated CODEX_HOME while preserving shared auth and config", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-codex-execute-"));
const workspace = path.join(root, "workspace");
diff --git a/server/src/__tests__/company-user-directory-route.test.ts b/server/src/__tests__/company-user-directory-route.test.ts
new file mode 100644
index 0000000000..c56ea4e0d4
--- /dev/null
+++ b/server/src/__tests__/company-user-directory-route.test.ts
@@ -0,0 +1,132 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+vi.mock("../services/index.js", () => ({
+ accessService: () => ({
+ isInstanceAdmin: vi.fn(),
+ canUser: vi.fn(),
+ hasPermission: vi.fn(),
+ }),
+ agentService: () => ({
+ getById: vi.fn(),
+ }),
+ boardAuthService: () => ({
+ createChallenge: vi.fn(),
+ resolveBoardAccess: vi.fn(),
+ assertCurrentBoardKey: vi.fn(),
+ revokeBoardApiKey: vi.fn(),
+ }),
+ deduplicateAgentName: vi.fn(),
+ logActivity: vi.fn(),
+ notifyHireApproved: vi.fn(),
+}));
+
+function createDbStub() {
+ const activeMemberships = [
+ { principalId: "user-2", status: "active" as const },
+ { principalId: "user-1", status: "active" as const },
+ ];
+ const users = [
+ { id: "user-1", name: "Dotta", email: "[email protected]", image: "https://example.com/dotta.png" },
+ { id: "user-2", name: null, email: "[email protected]", image: null },
+ ];
+
+ const isCompanyMembershipsTable = (table: unknown) =>
+ !!table &&
+ typeof table === "object" &&
+ "membershipRole" in table &&
+ "principalType" in table &&
+ "principalId" in table;
+ const isAuthUsersTable = (table: unknown) =>
+ !!table &&
+ typeof table === "object" &&
+ "emailVerified" in table &&
+ "createdAt" in table &&
+ "updatedAt" in table;
+
+ return {
+ select() {
+ return {
+ from(table: unknown) {
+ if (isCompanyMembershipsTable(table)) {
+ const query = {
+ where() {
+ return query;
+ },
+ orderBy() {
+ return Promise.resolve(activeMemberships);
+ },
+ };
+ return query;
+ }
+ if (isAuthUsersTable(table)) {
+ return {
+ where() {
+ return Promise.resolve(users);
+ },
+ };
+ }
+ throw new Error("Unexpected table");
+ },
+ };
+ },
+ };
+}
+
+function createApp(actor: Express.Request["actor"]) {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.actor = actor;
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(createDbStub() as never, {
+ deploymentMode: "authenticated",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+}
+
+describe("GET /companies/:companyId/user-directory", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns active human users for operators without manage-permissions access", async () => {
+ const app = createApp({
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ isInstanceAdmin: false,
+ companyIds: ["company-1"],
+ memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }],
+ });
+
+ const res = await request(app).get("/api/companies/company-1/user-directory");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ users: [
+ {
+ principalId: "user-2",
+ status: "active",
+ user: { id: "user-2", name: null, email: "[email protected]", image: null },
+ },
+ {
+ principalId: "user-1",
+ status: "active",
+ user: { id: "user-1", name: "Dotta", email: "[email protected]", image: "https://example.com/dotta.png" },
+ },
+ ],
+ });
+ });
+});
diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.ts
index dbeef4720a..1ca6d02fab 100644
--- a/server/src/__tests__/execution-workspaces-service.test.ts
+++ b/server/src/__tests__/execution-workspaces-service.test.ts
@@ -12,7 +12,6 @@ import {
issues,
projectWorkspaces,
projects,
- workspaceRuntimeServices,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
@@ -136,7 +135,6 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
afterEach(async () => {
await db.delete(issues);
- await db.delete(workspaceRuntimeServices);
await db.delete(executionWorkspaces);
await db.delete(projectWorkspaces);
await db.delete(projects);
@@ -326,136 +324,4 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
"git_branch_delete",
]));
}, 20_000);
-
- it("shows inherited shared project runtime services on shared execution workspaces without duplicating old history", async () => {
- const companyId = randomUUID();
- const projectId = randomUUID();
- const projectWorkspaceId = randomUUID();
- const executionWorkspaceId = randomUUID();
- const olderServiceId = randomUUID();
- const currentServiceId = randomUUID();
- const reuseKey = `project_workspace:${projectWorkspaceId}:paperclip-dev`;
- const startedAt = new Date("2026-04-04T17:00:00.000Z");
- const stoppedAt = new Date("2026-04-04T17:05:00.000Z");
- const runningAt = new Date("2026-04-04T17:10:00.000Z");
-
- await db.insert(companies).values({
- id: companyId,
- name: "Paperclip",
- issuePrefix: "PAP",
- requireBoardApprovalForNewAgents: false,
- });
- await db.insert(projects).values({
- id: projectId,
- companyId,
- name: "Workspaces",
- status: "in_progress",
- executionWorkspacePolicy: {
- enabled: true,
- },
- });
- await db.insert(projectWorkspaces).values({
- id: projectWorkspaceId,
- companyId,
- projectId,
- name: "Primary",
- sourceType: "local_path",
- isPrimary: true,
- cwd: "/tmp/paperclip-primary",
- metadata: {
- runtimeConfig: {
- desiredState: "running",
- workspaceRuntime: {
- services: [{ name: "paperclip-dev", command: "pnpm dev" }],
- },
- },
- },
- });
- await db.insert(executionWorkspaces).values({
- id: executionWorkspaceId,
- companyId,
- projectId,
- projectWorkspaceId,
- mode: "shared_workspace",
- strategyType: "project_primary",
- name: "Shared workspace",
- status: "active",
- providerType: "local_fs",
- cwd: "/tmp/paperclip-primary",
- });
- await db.insert(workspaceRuntimeServices).values([
- {
- id: olderServiceId,
- companyId,
- projectId,
- projectWorkspaceId,
- executionWorkspaceId: null,
- issueId: null,
- scopeType: "project_workspace",
- scopeId: projectWorkspaceId,
- serviceName: "paperclip-dev",
- status: "stopped",
- lifecycle: "shared",
- reuseKey,
- command: "pnpm dev",
- cwd: "/tmp/paperclip-primary",
- port: 49195,
- url: "http://127.0.0.1:49195",
- provider: "local_process",
- providerRef: "11111",
- ownerAgentId: null,
- startedByRunId: null,
- lastUsedAt: stoppedAt,
- startedAt,
- stoppedAt,
- stopPolicy: { type: "manual" },
- healthStatus: "unknown",
- createdAt: startedAt,
- updatedAt: stoppedAt,
- },
- {
- id: currentServiceId,
- companyId,
- projectId,
- projectWorkspaceId,
- executionWorkspaceId: null,
- issueId: null,
- scopeType: "project_workspace",
- scopeId: projectWorkspaceId,
- serviceName: "paperclip-dev",
- status: "running",
- lifecycle: "shared",
- reuseKey,
- command: "pnpm dev",
- cwd: "/tmp/paperclip-primary",
- port: 49222,
- url: "http://127.0.0.1:49222",
- provider: "local_process",
- providerRef: "22222",
- ownerAgentId: null,
- startedByRunId: null,
- lastUsedAt: runningAt,
- startedAt: runningAt,
- stoppedAt: null,
- stopPolicy: { type: "manual" },
- healthStatus: "healthy",
- createdAt: runningAt,
- updatedAt: runningAt,
- },
- ]);
-
- const workspace = await svc.getById(executionWorkspaceId);
- const listed = await svc.list(companyId, { projectId });
-
- expect(workspace?.runtimeServices).toHaveLength(1);
- expect(workspace?.runtimeServices?.[0]).toMatchObject({
- id: currentServiceId,
- status: "running",
- projectWorkspaceId,
- executionWorkspaceId: null,
- url: "http://127.0.0.1:49222",
- });
- expect(listed[0]?.runtimeServices).toHaveLength(1);
- expect(listed[0]?.runtimeServices?.[0]?.id).toBe(currentServiceId);
- });
});
diff --git a/server/src/__tests__/health.test.ts b/server/src/__tests__/health.test.ts
index e941776ee8..2d294c0e0d 100644
--- a/server/src/__tests__/health.test.ts
+++ b/server/src/__tests__/health.test.ts
@@ -1,9 +1,10 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import express from "express";
import request from "supertest";
import type { Db } from "@paperclipai/db";
-import { serverVersion } from "../version.js";
import { healthRoutes } from "../routes/health.js";
+import * as devServerStatus from "../dev-server-status.js";
+import { serverVersion } from "../version.js";
const mockReadPersistedDevServerStatus = vi.hoisted(() => vi.fn());
@@ -27,10 +28,8 @@ describe("GET /health", () => {
afterEach(() => {
vi.restoreAllMocks();
});
-
it("returns 200 with status ok", async () => {
const app = createApp();
-
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: "ok", version: serverVersion });
@@ -45,6 +44,7 @@ describe("GET /health", () => {
const res = await request(app).get("/health");
expect(res.status).toBe(200);
+ expect(db.execute).toHaveBeenCalledTimes(1);
expect(res.body).toMatchObject({ status: "ok", version: serverVersion });
});
@@ -60,7 +60,7 @@ describe("GET /health", () => {
expect(res.body).toEqual({
status: "unhealthy",
version: serverVersion,
- error: "database_unreachable",
+ error: "database_unreachable"
});
});
diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts
index 62b82e55f8..5d907470fa 100644
--- a/server/src/__tests__/heartbeat-process-recovery.test.ts
+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts
@@ -536,7 +536,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
});
it("tracks the first heartbeat with the agent role instead of adapter type", async () => {
- const { runId } = await seedRunFixture({
+ const { agentId, runId } = await seedRunFixture({
agentStatus: "running",
includeIssue: false,
});
@@ -548,6 +548,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
mockTelemetryClient,
expect.objectContaining({
agentRole: "engineer",
+ agentId,
}),
);
});
diff --git a/server/src/__tests__/heartbeat-workspace-session.test.ts b/server/src/__tests__/heartbeat-workspace-session.test.ts
index d97f63c70f..23a5808885 100644
--- a/server/src/__tests__/heartbeat-workspace-session.test.ts
+++ b/server/src/__tests__/heartbeat-workspace-session.test.ts
@@ -201,44 +201,6 @@ describe("buildRealizedExecutionWorkspaceFromPersisted", () => {
expect(result.branchName).toBe("PAP-880-thumbs-capture-for-evals-feature");
expect(result.source).toBe("task_session");
});
-
- it("falls back to realization when the persisted workspace has no local path yet", () => {
- const result = buildRealizedExecutionWorkspaceFromPersisted({
- base: buildResolvedWorkspace({
- cwd: "/tmp/project-primary",
- repoRef: "main",
- }),
- workspace: {
- id: "execution-workspace-2",
- companyId: "company-1",
- projectId: "project-1",
- projectWorkspaceId: "workspace-1",
- sourceIssueId: "issue-2",
- mode: "isolated_workspace",
- strategyType: "git_worktree",
- name: "PAP-999-missing-provider-ref",
- status: "active",
- cwd: null,
- repoUrl: "https://example.com/paperclip.git",
- baseRef: "main",
- branchName: "feature/PAP-999-missing-provider-ref",
- providerType: "git_worktree",
- providerRef: null,
- derivedFromExecutionWorkspaceId: null,
- lastUsedAt: new Date(),
- openedAt: new Date(),
- closedAt: null,
- cleanupEligibleAt: null,
- cleanupReason: null,
- config: null,
- metadata: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- },
- });
-
- expect(result).toBeNull();
- });
});
describe("stripWorkspaceRuntimeFromExecutionRunConfig", () => {
diff --git a/server/src/__tests__/instance-settings-routes.test.ts b/server/src/__tests__/instance-settings-routes.test.ts
index ff265001e3..65dfe7ac35 100644
--- a/server/src/__tests__/instance-settings-routes.test.ts
+++ b/server/src/__tests__/instance-settings-routes.test.ts
@@ -176,6 +176,22 @@ describe("instance settings routes", () => {
});
});
+ it("rejects signed-in users without company access from reading general settings", async () => {
+ const app = await createApp({
+ type: "board",
+ userId: "user-2",
+ source: "session",
+ isInstanceAdmin: false,
+ companyIds: [],
+ memberships: [],
+ });
+
+ const res = await request(app).get("/api/instance/settings/general");
+
+ expect(res.status).toBe(403);
+ expect(mockInstanceSettingsService.getGeneral).not.toHaveBeenCalled();
+ });
+
it("rejects non-admin board users from updating general settings", async () => {
const app = await createApp({
type: "board",
diff --git a/server/src/__tests__/invite-accept-existing-member.test.ts b/server/src/__tests__/invite-accept-existing-member.test.ts
new file mode 100644
index 0000000000..913fcdbf32
--- /dev/null
+++ b/server/src/__tests__/invite-accept-existing-member.test.ts
@@ -0,0 +1,126 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+vi.mock("../services/index.js", () => ({
+ accessService: () => ({
+ isInstanceAdmin: vi.fn(),
+ canUser: vi.fn(),
+ hasPermission: vi.fn(),
+ }),
+ agentService: () => ({
+ getById: vi.fn(),
+ }),
+ boardAuthService: () => ({
+ createChallenge: vi.fn(),
+ resolveBoardAccess: vi.fn(),
+ assertCurrentBoardKey: vi.fn(),
+ revokeBoardApiKey: vi.fn(),
+ }),
+ deduplicateAgentName: vi.fn(),
+ logActivity: vi.fn(),
+ notifyHireApproved: vi.fn(),
+}));
+
+function createDbStub() {
+ const updateMock = vi.fn();
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: { humanRole: "viewer" },
+ expiresAt: new Date("2027-03-10T00:00:00.000Z"),
+ invitedByUserId: "user-1",
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+
+ const db = {
+ select() {
+ return {
+ from() {
+ return {
+ where() {
+ return Promise.resolve([invite]);
+ },
+ };
+ },
+ };
+ },
+ update(...args: unknown[]) {
+ updateMock(...args);
+ return {
+ set() {
+ return {
+ where() {
+ return {
+ returning() {
+ return Promise.resolve([]);
+ },
+ };
+ },
+ };
+ },
+ };
+ },
+ };
+
+ return { db, updateMock };
+}
+
+function createApp(db: Record<string, unknown>) {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ (req as any).actor = {
+ type: "board",
+ source: "session",
+ userId: "user-1",
+ companyIds: ["company-1"],
+ memberships: [
+ {
+ companyId: "company-1",
+ membershipRole: "owner",
+ status: "active",
+ },
+ ],
+ };
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(db as any, {
+ deploymentMode: "authenticated",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+}
+
+describe("POST /invites/:token/accept", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not consume a human invite when the signed-in user is already a company member", async () => {
+ const { db, updateMock } = createDbStub();
+ const app = createApp(db);
+
+ const res = await request(app)
+ .post("/api/invites/pcp_invite_test/accept")
+ .send({ requestType: "human" });
+
+ expect(res.status).toBe(409);
+ expect(res.body.error).toBe("You already belong to this company");
+ expect(updateMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/__tests__/invite-create-route.test.ts b/server/src/__tests__/invite-create-route.test.ts
new file mode 100644
index 0000000000..5512d8dce2
--- /dev/null
+++ b/server/src/__tests__/invite-create-route.test.ts
@@ -0,0 +1,126 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+const logActivityMock = vi.fn();
+
+vi.mock("../services/index.js", () => ({
+ accessService: () => ({
+ isInstanceAdmin: vi.fn(),
+ canUser: vi.fn(),
+ hasPermission: vi.fn(),
+ }),
+ agentService: () => ({
+ getById: vi.fn(),
+ }),
+ boardAuthService: () => ({
+ createChallenge: vi.fn(),
+ resolveBoardAccess: vi.fn(),
+ assertCurrentBoardKey: vi.fn(),
+ revokeBoardApiKey: vi.fn(),
+ }),
+ deduplicateAgentName: vi.fn(),
+ logActivity: (...args: unknown[]) => logActivityMock(...args),
+ notifyHireApproved: vi.fn(),
+}));
+
+function createDbStub() {
+ const createdInvite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: { humanRole: "viewer" },
+ expiresAt: new Date("2027-03-10T00:00:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+
+ return {
+ insert() {
+ return {
+ values() {
+ return {
+ returning() {
+ return Promise.resolve([createdInvite]);
+ },
+ };
+ },
+ };
+ },
+ select(_shape?: unknown) {
+ return {
+ from() {
+ const query = {
+ leftJoin() {
+ return query;
+ },
+ where() {
+ return Promise.resolve([{
+ name: "Acme Robotics",
+ brandColor: "#114488",
+ logoAssetId: "logo-1",
+ }]);
+ },
+ };
+ return query;
+ },
+ };
+ },
+ };
+}
+
+function createApp() {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ (req as any).actor = {
+ type: "board",
+ source: "local_implicit",
+ userId: null,
+ companyIds: ["company-1"],
+ };
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(createDbStub() as any, {
+ deploymentMode: "local_trusted",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+}
+
+describe("POST /companies/:companyId/invites", () => {
+ beforeEach(() => {
+ logActivityMock.mockReset();
+ });
+
+ it("returns an absolute invite URL using the request base URL", async () => {
+ const app = createApp();
+
+ const res = await request(app)
+ .post("/api/companies/company-1/invites")
+ .set("host", "paperclip.example")
+ .set("x-forwarded-proto", "https")
+ .send({
+ allowedJoinTypes: "human",
+ humanRole: "viewer",
+ });
+
+ expect(res.status).toBe(201);
+ expect(res.body.companyName).toBe("Acme Robotics");
+ expect(res.body.invitePath).toMatch(/^\/invite\/pcp_invite_/);
+ expect(res.body.inviteUrl).toMatch(/^https:\/\/paperclip\.example\/invite\/pcp_invite_/);
+ });
+});
diff --git a/server/src/__tests__/invite-expiry.test.ts b/server/src/__tests__/invite-expiry.test.ts
index c84a2a9557..66a7e7d280 100644
--- a/server/src/__tests__/invite-expiry.test.ts
+++ b/server/src/__tests__/invite-expiry.test.ts
@@ -2,9 +2,9 @@ import { describe, expect, it } from "vitest";
import { companyInviteExpiresAt } from "../routes/access.js";
describe("companyInviteExpiresAt", () => {
- it("sets invite expiration to 10 minutes after invite creation time", () => {
+ it("sets invite expiration to 72 hours after invite creation time", () => {
const createdAtMs = Date.parse("2026-03-06T00:00:00.000Z");
const expiresAt = companyInviteExpiresAt(createdAtMs);
- expect(expiresAt.toISOString()).toBe("2026-03-06T00:10:00.000Z");
+ expect(expiresAt.toISOString()).toBe("2026-03-09T00:00:00.000Z");
});
});
diff --git a/server/src/__tests__/invite-join-grants.test.ts b/server/src/__tests__/invite-join-grants.test.ts
index 7dd342677f..fae007e059 100644
--- a/server/src/__tests__/invite-join-grants.test.ts
+++ b/server/src/__tests__/invite-join-grants.test.ts
@@ -1,5 +1,13 @@
import { describe, expect, it } from "vitest";
-import { agentJoinGrantsFromDefaults } from "../routes/access.js";
+import {
+ agentJoinGrantsFromDefaults,
+ humanJoinGrantsFromDefaults,
+} from "../services/invite-grants.js";
+import {
+ grantsForHumanRole,
+ normalizeHumanRole,
+ resolveHumanInviteRole,
+} from "../services/company-member-roles.js";
describe("agentJoinGrantsFromDefaults", () => {
it("adds tasks:assign when invite defaults do not specify agent grants", () => {
@@ -55,3 +63,59 @@ describe("agentJoinGrantsFromDefaults", () => {
]);
});
});
+
+describe("human invite roles", () => {
+ it("maps owner to the full management grant set", () => {
+ expect(grantsForHumanRole("owner")).toEqual([
+ { permissionKey: "agents:create", scope: null },
+ { permissionKey: "users:invite", scope: null },
+ { permissionKey: "users:manage_permissions", scope: null },
+ { permissionKey: "tasks:assign", scope: null },
+ { permissionKey: "joins:approve", scope: null },
+ ]);
+ });
+
+ it("defaults legacy or missing roles to operator", () => {
+ expect(normalizeHumanRole("member")).toBe("operator");
+ expect(resolveHumanInviteRole(null)).toBe("operator");
+ });
+
+ it("reads the configured human invite role from defaults", () => {
+ expect(
+ resolveHumanInviteRole({
+ human: {
+ role: "viewer",
+ },
+ }),
+ ).toBe("viewer");
+ });
+
+ it("falls back to role grants when human invite defaults omit explicit grants", () => {
+ expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual([
+ { permissionKey: "tasks:assign", scope: null },
+ ]);
+ });
+
+ it("preserves explicit human invite grants", () => {
+ expect(
+ humanJoinGrantsFromDefaults(
+ {
+ human: {
+ grants: [
+ {
+ permissionKey: "users:invite",
+ scope: { companyId: "company-1" },
+ },
+ ],
+ },
+ },
+ "operator",
+ ),
+ ).toEqual([
+ {
+ permissionKey: "users:invite",
+ scope: { companyId: "company-1" },
+ },
+ ]);
+ });
+});
diff --git a/server/src/__tests__/invite-list-route.test.ts b/server/src/__tests__/invite-list-route.test.ts
new file mode 100644
index 0000000000..30b52b7965
--- /dev/null
+++ b/server/src/__tests__/invite-list-route.test.ts
@@ -0,0 +1,164 @@
+import { randomUUID } from "node:crypto";
+import express from "express";
+import request from "supertest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { companies, createDb, invites, joinRequests } from "@paperclipai/db";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+vi.mock("../services/index.js", () => ({
+ accessService: () => ({
+ isInstanceAdmin: vi.fn(),
+ canUser: vi.fn(),
+ hasPermission: vi.fn(),
+ }),
+ agentService: () => ({
+ getById: vi.fn(),
+ }),
+ boardAuthService: () => ({
+ createChallenge: vi.fn(),
+ resolveBoardAccess: vi.fn(),
+ assertCurrentBoardKey: vi.fn(),
+ revokeBoardApiKey: vi.fn(),
+ }),
+ deduplicateAgentName: vi.fn(),
+ logActivity: vi.fn(),
+ notifyHireApproved: vi.fn(),
+}));
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres invite list route tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
+ );
+}
+
+describeEmbeddedPostgres("GET /companies/:companyId/invites", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let companyId!: string;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-invite-list-route-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ beforeEach(async () => {
+ companyId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ });
+
+ afterEach(async () => {
+ await db.delete(joinRequests);
+ await db.delete(invites);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ function createApp(currentCompanyId: string) {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ (req as any).actor = {
+ type: "board",
+ source: "local_implicit",
+ userId: null,
+ companyIds: [currentCompanyId],
+ };
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(db, {
+ deploymentMode: "local_trusted",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+ }
+
+ it("returns invite history in descending pages with nextOffset", async () => {
+ const inviteOneId = randomUUID();
+ const inviteTwoId = randomUUID();
+ const inviteThreeId = randomUUID();
+
+ await db.insert(invites).values([
+ {
+ id: inviteOneId,
+ companyId,
+ inviteType: "company_join",
+ tokenHash: "invite-token-1",
+ allowedJoinTypes: "human",
+ defaultsPayload: { humanRole: "viewer" },
+ expiresAt: new Date("2026-04-20T00:00:00.000Z"),
+ createdAt: new Date("2026-04-10T00:00:00.000Z"),
+ updatedAt: new Date("2026-04-10T00:00:00.000Z"),
+ },
+ {
+ id: inviteTwoId,
+ companyId,
+ inviteType: "company_join",
+ tokenHash: "invite-token-2",
+ allowedJoinTypes: "human",
+ defaultsPayload: { humanRole: "operator" },
+ expiresAt: new Date("2026-04-21T00:00:00.000Z"),
+ createdAt: new Date("2026-04-11T00:00:00.000Z"),
+ updatedAt: new Date("2026-04-11T00:00:00.000Z"),
+ },
+ {
+ id: inviteThreeId,
+ companyId,
+ inviteType: "company_join",
+ tokenHash: "invite-token-3",
+ allowedJoinTypes: "human",
+ defaultsPayload: { humanRole: "admin" },
+ expiresAt: new Date("2026-04-22T00:00:00.000Z"),
+ createdAt: new Date("2026-04-12T00:00:00.000Z"),
+ updatedAt: new Date("2026-04-12T00:00:00.000Z"),
+ },
+ ]);
+
+ await db.insert(joinRequests).values({
+ id: randomUUID(),
+ inviteId: inviteThreeId,
+ companyId,
+ requestType: "human",
+ status: "pending_approval",
+ requestIp: "127.0.0.1",
+ requestEmailSnapshot: "[email protected]",
+ createdAt: new Date("2026-04-12T00:05:00.000Z"),
+ updatedAt: new Date("2026-04-12T00:05:00.000Z"),
+ });
+
+ const app = createApp(companyId);
+
+ const firstPage = await request(app).get(`/api/companies/${companyId}/invites?limit=2`);
+
+ expect(firstPage.status).toBe(200);
+ expect(firstPage.body.invites).toHaveLength(2);
+ expect(firstPage.body.invites.map((invite: { id: string }) => invite.id)).toEqual([inviteThreeId, inviteTwoId]);
+ expect(firstPage.body.invites[0].relatedJoinRequestId).toBeTruthy();
+ expect(firstPage.body.nextOffset).toBe(2);
+
+ const secondPage = await request(app).get(`/api/companies/${companyId}/invites?limit=2&offset=2`);
+
+ expect(secondPage.status).toBe(200);
+ expect(secondPage.body.invites).toHaveLength(1);
+ expect(secondPage.body.invites[0].id).toBe(inviteOneId);
+ expect(secondPage.body.nextOffset).toBeNull();
+ });
+});
diff --git a/server/src/__tests__/invite-logo-route.test.ts b/server/src/__tests__/invite-logo-route.test.ts
new file mode 100644
index 0000000000..a18137c3ab
--- /dev/null
+++ b/server/src/__tests__/invite-logo-route.test.ts
@@ -0,0 +1,146 @@
+import { Readable } from "node:stream";
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockStorage = vi.hoisted(() => ({
+ getObject: vi.fn(),
+ headObject: vi.fn(),
+}));
+
+vi.mock("../storage/index.js", () => ({
+ getStorageService: () => mockStorage,
+}));
+
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+function createSelectChain(rows: unknown[]) {
+ const query = {
+ leftJoin() {
+ return query;
+ },
+ where() {
+ return Promise.resolve(rows);
+ },
+ };
+ return {
+ from() {
+ return query;
+ },
+ };
+}
+
+function createDbStub(inviteRows: unknown[], companyRows: unknown[]) {
+ let selectCall = 0;
+ return {
+ select() {
+ selectCall += 1;
+ return selectCall === 1
+ ? createSelectChain(inviteRows)
+ : createSelectChain(companyRows);
+ },
+ };
+}
+
+function createApp(db: Record<string, unknown>) {
+ const app = express();
+ app.use((req, _res, next) => {
+ (req as any).actor = { type: "anon" };
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(db as any, {
+ deploymentMode: "local_trusted",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+}
+
+describe("GET /invites/:token/logo", () => {
+ beforeEach(() => {
+ mockStorage.getObject.mockReset();
+ mockStorage.headObject.mockReset();
+ });
+
+ it("serves the company logo for an active invite without company auth", async () => {
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+ mockStorage.headObject.mockResolvedValue({
+ exists: true,
+ contentType: "image/png",
+ contentLength: 3,
+ });
+ mockStorage.getObject.mockResolvedValue({
+ contentType: "image/png",
+ contentLength: 3,
+ stream: Readable.from([Buffer.from("png")]),
+ });
+ const app = createApp(
+ createDbStub([invite], [{
+ companyId: "company-1",
+ objectKey: "assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ }]),
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test/logo");
+
+ expect(res.status).toBe(200);
+ expect(res.headers["content-type"]).toContain("image/png");
+ expect(mockStorage.headObject).toHaveBeenCalledWith("company-1", "assets/companies/logo-1");
+ expect(mockStorage.getObject).toHaveBeenCalledWith("company-1", "assets/companies/logo-1");
+ });
+
+ it("returns 404 when the logo asset record exists but storage does not", async () => {
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+ mockStorage.headObject.mockResolvedValue({ exists: false });
+ const app = createApp(
+ createDbStub([invite], [{
+ companyId: "company-1",
+ objectKey: "assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ }]),
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test/logo");
+
+ expect(res.status).toBe(404);
+ expect(res.body.error).toBe("Invite logo not found");
+ expect(mockStorage.getObject).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/__tests__/invite-summary-route.test.ts b/server/src/__tests__/invite-summary-route.test.ts
new file mode 100644
index 0000000000..6fd7172af6
--- /dev/null
+++ b/server/src/__tests__/invite-summary-route.test.ts
@@ -0,0 +1,270 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockStorage = vi.hoisted(() => ({
+ headObject: vi.fn(),
+}));
+
+vi.mock("../storage/index.js", () => ({
+ getStorageService: () => mockStorage,
+}));
+
+import { accessRoutes } from "../routes/access.js";
+import { errorHandler } from "../middleware/index.js";
+
+function createSelectChain(rows: unknown[]) {
+ const query = {
+ then(resolve: (value: unknown[]) => unknown) {
+ return Promise.resolve(rows).then(resolve);
+ },
+ leftJoin() {
+ return query;
+ },
+ orderBy() {
+ return query;
+ },
+ where() {
+ return query;
+ },
+ };
+ return {
+ from() {
+ return query;
+ },
+ };
+}
+
+function createDbStub(...selectResponses: unknown[][]) {
+ let selectCall = 0;
+ return {
+ select() {
+ const rows = selectResponses[selectCall] ?? [];
+ selectCall += 1;
+ return createSelectChain(rows);
+ },
+ };
+}
+
+function createApp(
+ db: Record<string, unknown>,
+ actor: Record<string, unknown> = { type: "anon" },
+) {
+ const app = express();
+ app.use((req, _res, next) => {
+ (req as any).actor = actor;
+ next();
+ });
+ app.use(
+ "/api",
+ accessRoutes(db as any, {
+ deploymentMode: "local_trusted",
+ deploymentExposure: "private",
+ bindHost: "127.0.0.1",
+ allowedHostnames: [],
+ }),
+ );
+ app.use(errorHandler);
+ return app;
+}
+
+describe("GET /invites/:token", () => {
+ beforeEach(() => {
+ mockStorage.headObject.mockReset();
+ mockStorage.headObject.mockResolvedValue({ exists: true, contentLength: 3, contentType: "image/png" });
+ });
+
+ it("returns company branding in the invite summary response", async () => {
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+ const app = createApp(
+ createDbStub(
+ [invite],
+ [
+ {
+ name: "Acme Robotics",
+ brandColor: "#114488",
+ logoAssetId: "logo-1",
+ },
+ ],
+ [
+ {
+ companyId: "company-1",
+ objectKey: "company-1/assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ },
+ ],
+ ),
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test");
+
+ expect(res.status).toBe(200);
+ expect(res.body.companyId).toBe("company-1");
+ expect(res.body.companyName).toBe("Acme Robotics");
+ expect(res.body.companyBrandColor).toBe("#114488");
+ expect(res.body.companyLogoUrl).toBe("/api/invites/pcp_invite_test/logo");
+ expect(res.body.inviteType).toBe("company_join");
+ });
+
+ it("omits companyLogoUrl when the stored logo object is missing", async () => {
+ mockStorage.headObject.mockResolvedValue({ exists: false });
+
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: null,
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:00:00.000Z"),
+ };
+ const app = createApp(
+ createDbStub(
+ [invite],
+ [
+ {
+ name: "Acme Robotics",
+ brandColor: "#114488",
+ logoAssetId: "logo-1",
+ },
+ ],
+ [
+ {
+ companyId: "company-1",
+ objectKey: "company-1/assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ },
+ ],
+ ),
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test");
+
+ expect(res.status).toBe(200);
+ expect(res.body.companyLogoUrl).toBeNull();
+ });
+
+ it("returns pending join-request status for an already-accepted invite", async () => {
+ const invite = {
+ id: "invite-1",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: new Date("2026-03-07T00:05:00.000Z"),
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:05:00.000Z"),
+ };
+ const app = createApp(
+ createDbStub(
+ [invite],
+ [{ requestType: "human", status: "pending_approval" }],
+ [
+ {
+ name: "Acme Robotics",
+ brandColor: "#114488",
+ logoAssetId: "logo-1",
+ },
+ ],
+ [
+ {
+ companyId: "company-1",
+ objectKey: "company-1/assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ },
+ ],
+ ),
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test");
+
+ expect(res.status).toBe(200);
+ expect(res.body.joinRequestStatus).toBe("pending_approval");
+ expect(res.body.joinRequestType).toBe("human");
+ expect(res.body.companyName).toBe("Acme Robotics");
+ });
+
+ it("falls back to a reusable human join request when the accepted invite reused an existing queue entry", async () => {
+ const invite = {
+ id: "invite-2",
+ companyId: "company-1",
+ inviteType: "company_join",
+ allowedJoinTypes: "human",
+ tokenHash: "hash",
+ defaultsPayload: null,
+ expiresAt: new Date("2027-03-07T00:10:00.000Z"),
+ invitedByUserId: null,
+ revokedAt: null,
+ acceptedAt: new Date("2026-03-07T00:05:00.000Z"),
+ createdAt: new Date("2026-03-07T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-07T00:05:00.000Z"),
+ };
+ const app = createApp(
+ createDbStub(
+ [invite],
+ [],
+ [{ email: "[email protected]" }],
+ [
+ {
+ id: "join-1",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ ],
+ [
+ {
+ name: "Acme Robotics",
+ brandColor: "#114488",
+ logoAssetId: "logo-1",
+ },
+ ],
+ [
+ {
+ companyId: "company-1",
+ objectKey: "company-1/assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ },
+ ],
+ ),
+ { type: "board", userId: "user-1", source: "session" },
+ );
+
+ const res = await request(app).get("/api/invites/pcp_invite_test");
+
+ expect(res.status).toBe(200);
+ expect(res.body.joinRequestStatus).toBe("pending_approval");
+ expect(res.body.joinRequestType).toBe("human");
+ });
+});
diff --git a/server/src/__tests__/issue-feedback-routes.test.ts b/server/src/__tests__/issue-feedback-routes.test.ts
index 1e36c3528f..6a2df50d94 100644
--- a/server/src/__tests__/issue-feedback-routes.test.ts
+++ b/server/src/__tests__/issue-feedback-routes.test.ts
@@ -180,7 +180,6 @@ describe("issue feedback trace routes", () => {
});
const res = await request(app).get("/api/feedback-traces/trace-1");
-
expect(res.status).toBe(403);
expect(mockFeedbackService.getFeedbackTraceById).not.toHaveBeenCalled();
});
diff --git a/server/src/__tests__/issues-service.test.ts b/server/src/__tests__/issues-service.test.ts
index 75aefd6a36..3e233634df 100644
--- a/server/src/__tests__/issues-service.test.ts
+++ b/server/src/__tests__/issues-service.test.ts
@@ -379,7 +379,6 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
it("returns null instead of throwing for malformed non-uuid issue refs", async () => {
await expect(svc.getById("not-a-uuid")).resolves.toBeNull();
});
-
it("filters issues by execution workspace id", async () => {
const companyId = randomUUID();
const projectId = randomUUID();
@@ -1217,6 +1216,283 @@ describeEmbeddedPostgres("issueService blockers and dependency wake readiness",
});
});
+describeEmbeddedPostgres("issueService.create workspace inheritance", () => {
+ let db!: ReturnType<typeof createDb>;
+ let svc!: ReturnType<typeof issueService>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issues-create-");
+ db = createDb(tempDb.connectionString);
+ svc = issueService(db);
+ await ensureIssueRelationsTable(db);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(issueComments);
+ await db.delete(issueRelations);
+ await db.delete(issueInboxArchives);
+ await db.delete(activityLog);
+ await db.delete(issues);
+ await db.delete(executionWorkspaces);
+ await db.delete(projectWorkspaces);
+ await db.delete(projects);
+ await db.delete(agents);
+ await db.delete(instanceSettings);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ it("inherits the parent issue workspace linkage when child workspace fields are omitted", async () => {
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const parentIssueId = randomUUID();
+ const projectWorkspaceId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
+
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Workspace project",
+ status: "in_progress",
+ });
+
+ await db.insert(projectWorkspaces).values({
+ id: projectWorkspaceId,
+ companyId,
+ projectId,
+ name: "Primary workspace",
+ isPrimary: true,
+ sharedWorkspaceKey: "workspace-key",
+ });
+
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Issue worktree",
+ status: "active",
+ providerType: "git_worktree",
+ providerRef: `/tmp/${executionWorkspaceId}`,
+ });
+
+ await db.insert(issues).values({
+ id: parentIssueId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ title: "Parent issue",
+ status: "in_progress",
+ priority: "medium",
+ executionWorkspaceId,
+ executionWorkspacePreference: "reuse_existing",
+ executionWorkspaceSettings: {
+ mode: "isolated_workspace",
+ workspaceRuntime: { profile: "agent" },
+ },
+ });
+
+ const child = await svc.create(companyId, {
+ parentId: parentIssueId,
+ projectId,
+ title: "Child issue",
+ });
+
+ expect(child.parentId).toBe(parentIssueId);
+ expect(child.projectWorkspaceId).toBe(projectWorkspaceId);
+ expect(child.executionWorkspaceId).toBe(executionWorkspaceId);
+ expect(child.executionWorkspacePreference).toBe("reuse_existing");
+ expect(child.executionWorkspaceSettings).toEqual({
+ mode: "isolated_workspace",
+ workspaceRuntime: { profile: "agent" },
+ });
+ });
+
+ it("keeps explicit workspace fields instead of inheriting the parent linkage", async () => {
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const parentIssueId = randomUUID();
+ const parentProjectWorkspaceId = randomUUID();
+ const parentExecutionWorkspaceId = randomUUID();
+ const explicitProjectWorkspaceId = randomUUID();
+ const explicitExecutionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
+
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Workspace project",
+ status: "in_progress",
+ });
+
+ await db.insert(projectWorkspaces).values([
+ {
+ id: parentProjectWorkspaceId,
+ companyId,
+ projectId,
+ name: "Parent workspace",
+ },
+ {
+ id: explicitProjectWorkspaceId,
+ companyId,
+ projectId,
+ name: "Explicit workspace",
+ },
+ ]);
+
+ await db.insert(executionWorkspaces).values([
+ {
+ id: parentExecutionWorkspaceId,
+ companyId,
+ projectId,
+ projectWorkspaceId: parentProjectWorkspaceId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Parent worktree",
+ status: "active",
+ providerType: "git_worktree",
+ },
+ {
+ id: explicitExecutionWorkspaceId,
+ companyId,
+ projectId,
+ projectWorkspaceId: explicitProjectWorkspaceId,
+ mode: "shared_workspace",
+ strategyType: "project_primary",
+ name: "Explicit shared workspace",
+ status: "active",
+ providerType: "local_fs",
+ },
+ ]);
+
+ await db.insert(issues).values({
+ id: parentIssueId,
+ companyId,
+ projectId,
+ projectWorkspaceId: parentProjectWorkspaceId,
+ title: "Parent issue",
+ status: "in_progress",
+ priority: "medium",
+ executionWorkspaceId: parentExecutionWorkspaceId,
+ executionWorkspacePreference: "reuse_existing",
+ executionWorkspaceSettings: {
+ mode: "isolated_workspace",
+ },
+ });
+
+ const child = await svc.create(companyId, {
+ parentId: parentIssueId,
+ projectId,
+ title: "Child issue",
+ projectWorkspaceId: explicitProjectWorkspaceId,
+ executionWorkspaceId: explicitExecutionWorkspaceId,
+ executionWorkspacePreference: "reuse_existing",
+ executionWorkspaceSettings: {
+ mode: "shared_workspace",
+ },
+ });
+
+ expect(child.projectWorkspaceId).toBe(explicitProjectWorkspaceId);
+ expect(child.executionWorkspaceId).toBe(explicitExecutionWorkspaceId);
+ expect(child.executionWorkspacePreference).toBe("reuse_existing");
+ expect(child.executionWorkspaceSettings).toEqual({
+ mode: "shared_workspace",
+ });
+ });
+
+ it("inherits workspace linkage from an explicit source issue without creating a parent-child relationship", async () => {
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const sourceIssueId = randomUUID();
+ const projectWorkspaceId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true });
+
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Workspace project",
+ status: "in_progress",
+ });
+
+ await db.insert(projectWorkspaces).values({
+ id: projectWorkspaceId,
+ companyId,
+ projectId,
+ name: "Primary workspace",
+ });
+
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ mode: "operator_branch",
+ strategyType: "git_worktree",
+ name: "Operator branch",
+ status: "active",
+ providerType: "git_worktree",
+ });
+
+ await db.insert(issues).values({
+ id: sourceIssueId,
+ companyId,
+ projectId,
+ projectWorkspaceId,
+ title: "Source issue",
+ status: "todo",
+ priority: "medium",
+ executionWorkspaceId,
+ executionWorkspacePreference: "reuse_existing",
+ executionWorkspaceSettings: {
+ mode: "operator_branch",
+ },
+ });
+
+ const followUp = await svc.create(companyId, {
+ projectId,
+ title: "Follow-up issue",
+ inheritExecutionWorkspaceFromIssueId: sourceIssueId,
+ });
+
+ expect(followUp.parentId).toBeNull();
+ expect(followUp.projectWorkspaceId).toBe(projectWorkspaceId);
+ expect(followUp.executionWorkspaceId).toBe(executionWorkspaceId);
+ expect(followUp.executionWorkspacePreference).toBe("reuse_existing");
+ expect(followUp.executionWorkspaceSettings).toEqual({
+ mode: "operator_branch",
+ });
+ });
+});
+
describeEmbeddedPostgres("issueService.findMentionedProjectIds", () => {
let db!: ReturnType<typeof createDb>;
let svc!: ReturnType<typeof issueService>;
diff --git a/server/src/__tests__/join-request-dedupe.test.ts b/server/src/__tests__/join-request-dedupe.test.ts
new file mode 100644
index 0000000000..133d6ae9a6
--- /dev/null
+++ b/server/src/__tests__/join-request-dedupe.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+import {
+ collapseDuplicatePendingHumanJoinRequests,
+ findReusableHumanJoinRequest,
+} from "../lib/join-request-dedupe.js";
+
+describe("findReusableHumanJoinRequest", () => {
+ it("reuses the newest pending request for the same user", () => {
+ const rows = [
+ {
+ id: "pending-new",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "pending-old",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "other-user",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-2",
+ requestEmailSnapshot: "[email protected]",
+ },
+ ] as const;
+
+ expect(
+ findReusableHumanJoinRequest(rows, {
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ })?.id
+ ).toBe("pending-new");
+ });
+
+ it("falls back to email matching when the user id is unavailable", () => {
+ const rows = [
+ {
+ id: "approved-existing",
+ requestType: "human",
+ status: "approved",
+ requestingUserId: null,
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "agent-request",
+ requestType: "agent",
+ status: "pending_approval",
+ requestingUserId: null,
+ requestEmailSnapshot: null,
+ },
+ ] as const;
+
+ expect(
+ findReusableHumanJoinRequest(rows, {
+ requestingUserId: null,
+ requestEmailSnapshot: "[email protected]",
+ })?.id
+ ).toBe("approved-existing");
+ });
+});
+
+describe("collapseDuplicatePendingHumanJoinRequests", () => {
+ it("keeps only the newest pending human row per requester", () => {
+ const rows = [
+ {
+ id: "human-new",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "human-old",
+ requestType: "human",
+ status: "pending_approval",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "approved-history",
+ requestType: "human",
+ status: "approved",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ },
+ {
+ id: "agent-pending",
+ requestType: "agent",
+ status: "pending_approval",
+ requestingUserId: null,
+ requestEmailSnapshot: null,
+ },
+ ] as const;
+
+ expect(collapseDuplicatePendingHumanJoinRequests(rows).map((row) => row.id))
+ .toEqual(["human-new", "approved-history", "agent-pending"]);
+ });
+});
diff --git a/server/src/__tests__/openclaw-invite-prompt-route.test.ts b/server/src/__tests__/openclaw-invite-prompt-route.test.ts
index d6537c415c..d813310794 100644
--- a/server/src/__tests__/openclaw-invite-prompt-route.test.ts
+++ b/server/src/__tests__/openclaw-invite-prompt-route.test.ts
@@ -32,6 +32,9 @@ const mockBoardAuthService = vi.hoisted(() => ({
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
+const mockStorage = vi.hoisted(() => ({
+ headObject: vi.fn(),
+}));
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
@@ -44,6 +47,10 @@ function registerModuleMocks() {
}));
}
+vi.mock("../storage/index.js", () => ({
+ getStorageService: () => mockStorage,
+}));
+
function createDbStub() {
const createdInvite = {
id: "invite-1",
@@ -76,20 +83,35 @@ function createDbStub() {
"feedbackDataSharingEnabled" in table;
const select = vi.fn((selection?: unknown) => ({
from(table: unknown) {
- return {
+ const query = {
+ leftJoin: vi.fn().mockReturnThis(),
where: vi.fn().mockImplementation(() => {
if (isInvitesTable(table)) {
return Promise.resolve([createdInvite]);
}
+ if (selection && typeof selection === "object" && "objectKey" in selection) {
+ return Promise.resolve([{
+ companyId: "company-1",
+ objectKey: "company-1/assets/companies/logo-1",
+ contentType: "image/png",
+ byteSize: 3,
+ originalFilename: "logo.png",
+ }]);
+ }
if (
(selection && typeof selection === "object" && "name" in selection) ||
isCompaniesTable(table)
) {
- return Promise.resolve([{ name: "Acme AI" }]);
+ return Promise.resolve([{
+ name: "Acme AI",
+ brandColor: "#225577",
+ logoAssetId: "logo-1",
+ }]);
}
return Promise.resolve([]);
}),
};
+ return query;
},
}));
return {
@@ -135,6 +157,7 @@ describe("POST /companies/:companyId/openclaw/invite-prompt", () => {
mockAccessService.canUser.mockResolvedValue(false);
mockAgentService.getById.mockReset();
mockLogActivity.mockResolvedValue(undefined);
+ mockStorage.headObject.mockResolvedValue({ exists: true, contentLength: 3, contentType: "image/png" });
});
it("rejects non-CEO agent callers", async () => {
@@ -212,6 +235,8 @@ describe("POST /companies/:companyId/openclaw/invite-prompt", () => {
expect(res.status).toBe(200);
expect(res.body.companyName).toBe("Acme AI");
+ expect(res.body.companyBrandColor).toBe("#225577");
+ expect(res.body.companyLogoUrl).toBe("/api/invites/pcp_invite_test/logo");
expect(res.body.inviteType).toBe("company_join");
expect(res.body.allowedJoinTypes).toBe("agent");
});
diff --git a/server/src/__tests__/plugin-routes-authz.test.ts b/server/src/__tests__/plugin-routes-authz.test.ts
index 3150a18225..4c965b0d8b 100644
--- a/server/src/__tests__/plugin-routes-authz.test.ts
+++ b/server/src/__tests__/plugin-routes-authz.test.ts
@@ -5,11 +5,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mockRegistry = vi.hoisted(() => ({
getById: vi.fn(),
getByKey: vi.fn(),
+ upsertConfig: vi.fn(),
}));
const mockLifecycle = vi.hoisted(() => ({
load: vi.fn(),
upgrade: vi.fn(),
+ unload: vi.fn(),
+ enable: vi.fn(),
+ disable: vi.fn(),
}));
vi.mock("../services/plugin-registry.js", () => ({
@@ -138,6 +142,31 @@ describe("plugin install and upgrade authz", () => {
expect(mockLifecycle.upgrade).not.toHaveBeenCalled();
}, 20_000);
+ it.each([
+ ["delete", "delete", "/api/plugins/11111111-1111-4111-8111-111111111111", undefined],
+ ["enable", "post", "/api/plugins/11111111-1111-4111-8111-111111111111/enable", {}],
+ ["disable", "post", "/api/plugins/11111111-1111-4111-8111-111111111111/disable", {}],
+ ["config", "post", "/api/plugins/11111111-1111-4111-8111-111111111111/config", { configJson: {} }],
+ ] as const)("rejects plugin %s for non-admin board users", async (_name, method, path, body) => {
+ const { app } = await createApp({
+ type: "board",
+ userId: "user-1",
+ source: "session",
+ isInstanceAdmin: false,
+ companyIds: ["company-1"],
+ });
+
+ const req = method === "delete" ? request(app).delete(path) : request(app).post(path).send(body);
+ const res = await req;
+
+ expect(res.status).toBe(403);
+ expect(mockRegistry.getById).not.toHaveBeenCalled();
+ expect(mockRegistry.upsertConfig).not.toHaveBeenCalled();
+ expect(mockLifecycle.unload).not.toHaveBeenCalled();
+ expect(mockLifecycle.enable).not.toHaveBeenCalled();
+ expect(mockLifecycle.disable).not.toHaveBeenCalled();
+ }, 20_000);
+
it("allows instance admins to upgrade plugins", async () => {
const pluginId = "11111111-1111-4111-8111-111111111111";
mockRegistry.getById.mockResolvedValue({
diff --git a/server/src/__tests__/shared-telemetry-events.test.ts b/server/src/__tests__/shared-telemetry-events.test.ts
new file mode 100644
index 0000000000..1d6483d2e8
--- /dev/null
+++ b/server/src/__tests__/shared-telemetry-events.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ trackAgentCreated,
+ trackAgentFirstHeartbeat,
+ trackAgentTaskCompleted,
+ trackInstallCompleted,
+} from "@paperclipai/shared/telemetry";
+import type { TelemetryClient } from "@paperclipai/shared/telemetry";
+
+function createClient(): TelemetryClient {
+ return {
+ track: vi.fn(),
+ hashPrivateRef: vi.fn((value: string) => `hashed:${value}`),
+ } as unknown as TelemetryClient;
+}
+
+describe("shared telemetry agent events", () => {
+ it("includes agent_id for agent.created", () => {
+ const client = createClient();
+
+ trackAgentCreated(client, {
+ agentRole: "engineer",
+ agentId: "11111111-1111-4111-8111-111111111111",
+ });
+
+ expect(client.track).toHaveBeenCalledWith("agent.created", {
+ agent_role: "engineer",
+ agent_id: "11111111-1111-4111-8111-111111111111",
+ });
+ });
+
+ it("includes agent_id for agent.first_heartbeat", () => {
+ const client = createClient();
+
+ trackAgentFirstHeartbeat(client, {
+ agentRole: "coder",
+ agentId: "22222222-2222-4222-8222-222222222222",
+ });
+
+ expect(client.track).toHaveBeenCalledWith("agent.first_heartbeat", {
+ agent_role: "coder",
+ agent_id: "22222222-2222-4222-8222-222222222222",
+ });
+ });
+
+ it("includes agent_id for agent.task_completed", () => {
+ const client = createClient();
+
+ trackAgentTaskCompleted(client, {
+ agentRole: "qa",
+ agentId: "33333333-3333-4333-8333-333333333333",
+ });
+
+ expect(client.track).toHaveBeenCalledWith("agent.task_completed", {
+ agent_role: "qa",
+ agent_id: "33333333-3333-4333-8333-333333333333",
+ });
+ });
+
+ it("keeps non-agent event dimensions unchanged", () => {
+ const client = createClient();
+
+ trackInstallCompleted(client, { adapterType: "codex_local" });
+
+ expect(client.track).toHaveBeenCalledWith("install.completed", {
+ adapter_type: "codex_local",
+ });
+ expect(client.track).not.toHaveBeenCalledWith(
+ "install.completed",
+ expect.objectContaining({ agent_id: expect.any(String) }),
+ );
+ });
+});
diff --git a/server/src/__tests__/worktree-config.test.ts b/server/src/__tests__/worktree-config.test.ts
index 3317a25413..d3eb6a9f0e 100644
--- a/server/src/__tests__/worktree-config.test.ts
+++ b/server/src/__tests__/worktree-config.test.ts
@@ -206,6 +206,113 @@ describe("worktree config repair", () => {
expect(repairedConfig.database.embeddedPostgresPort).toBe(54331);
});
+ it("does not persist transient runtime home overrides over repo-local worktree env", async () => {
+ const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-worktree-runtime-override-"));
+ const isolatedHome = path.join(tempRoot, ".paperclip-worktrees");
+ const transientHome = path.join(tempRoot, "tests", "e2e", ".tmp", "multiuser-authenticated");
+ const worktreeRoot = path.join(tempRoot, "PAP-989-multi-user-implementation-using-plan-from-pap-958");
+ const paperclipDir = path.join(worktreeRoot, ".paperclip");
+ const configPath = path.join(paperclipDir, "config.json");
+ const envPath = path.join(paperclipDir, ".env");
+ const instanceId = "pap-989-multi-user-implementation-using-plan-from-pap-958";
+ const stableInstanceRoot = path.join(isolatedHome, "instances", instanceId);
+
+ await fs.mkdir(paperclipDir, { recursive: true });
+ await fs.writeFile(
+ configPath,
+ JSON.stringify(
+ {
+ ...buildLegacyConfig(transientHome),
+ database: {
+ mode: "embedded-postgres",
+ embeddedPostgresDataDir: path.join(transientHome, "instances", instanceId, "db"),
+ embeddedPostgresPort: 54334,
+ backup: {
+ enabled: true,
+ intervalMinutes: 60,
+ retentionDays: 30,
+ dir: path.join(transientHome, "instances", instanceId, "data", "backups"),
+ },
+ },
+ logging: {
+ mode: "file",
+ logDir: path.join(transientHome, "instances", instanceId, "logs"),
+ },
+ server: {
+ deploymentMode: "local_trusted",
+ exposure: "private",
+ host: "127.0.0.1",
+ port: 3104,
+ allowedHostnames: [],
+ serveUi: true,
+ },
+ storage: {
+ provider: "local_disk",
+ localDisk: {
+ baseDir: path.join(transientHome, "instances", instanceId, "data", "storage"),
+ },
+ s3: {
+ bucket: "paperclip",
+ region: "us-east-1",
+ prefix: "",
+ forcePathStyle: false,
+ },
+ },
+ secrets: {
+ provider: "local_encrypted",
+ strictMode: false,
+ localEncrypted: {
+ keyFilePath: path.join(transientHome, "instances", instanceId, "secrets", "master.key"),
+ },
+ },
+ },
+ null,
+ 2,
+ ) + "\n",
+ "utf8",
+ );
+ await fs.writeFile(
+ envPath,
+ [
+ "# Paperclip environment variables",
+ `PAPERCLIP_HOME=${JSON.stringify(isolatedHome)}`,
+ `PAPERCLIP_INSTANCE_ID=${JSON.stringify(instanceId)}`,
+ `PAPERCLIP_CONFIG=${JSON.stringify(configPath)}`,
+ `PAPERCLIP_CONTEXT=${JSON.stringify(path.join(isolatedHome, "context.json"))}`,
+ 'PAPERCLIP_IN_WORKTREE="true"',
+ 'PAPERCLIP_WORKTREE_NAME="PAP-989-multi-user-implementation-using-plan-from-pap-958"',
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+
+ process.chdir(worktreeRoot);
+ process.env.PAPERCLIP_IN_WORKTREE = "true";
+ process.env.PAPERCLIP_WORKTREE_NAME = "PAP-989-multi-user-implementation-using-plan-from-pap-958";
+ process.env.PAPERCLIP_HOME = transientHome;
+ process.env.PAPERCLIP_INSTANCE_ID = instanceId;
+ process.env.PAPERCLIP_CONFIG = configPath;
+
+ const result = maybeRepairLegacyWorktreeConfigAndEnvFiles();
+ const repairedConfig = JSON.parse(await fs.readFile(configPath, "utf8"));
+ const repairedEnv = await fs.readFile(envPath, "utf8");
+
+ expect(result).toEqual({
+ repairedConfig: true,
+ repairedEnv: false,
+ });
+ expect(repairedConfig.database.embeddedPostgresDataDir).toBe(path.join(stableInstanceRoot, "db"));
+ expect(repairedConfig.database.backup.dir).toBe(path.join(stableInstanceRoot, "data", "backups"));
+ expect(repairedConfig.logging.logDir).toBe(path.join(stableInstanceRoot, "logs"));
+ expect(repairedConfig.storage.localDisk.baseDir).toBe(path.join(stableInstanceRoot, "data", "storage"));
+ expect(repairedConfig.secrets.localEncrypted.keyFilePath).toBe(
+ path.join(stableInstanceRoot, "secrets", "master.key"),
+ );
+ expect(repairedEnv).toContain(`PAPERCLIP_HOME=${JSON.stringify(isolatedHome)}`);
+ expect(repairedEnv).not.toContain(`PAPERCLIP_HOME=${JSON.stringify(transientHome)}`);
+ expect(process.env.PAPERCLIP_HOME).toBe(isolatedHome);
+ });
+
it("rebalances duplicate ports for already isolated worktree configs", async () => {
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-worktree-rebalance-"));
const isolatedHome = path.join(tempRoot, ".paperclip-worktrees");
diff --git a/server/src/adapters/utils.ts b/server/src/adapters/utils.ts
index 7c833865b1..96931b0f16 100644
--- a/server/src/adapters/utils.ts
+++ b/server/src/adapters/utils.ts
@@ -38,7 +38,6 @@ export function buildInvocationEnvForLogs(
env: Record<string, string>,
options: BuildInvocationEnvForLogsOptions = {},
): Record<string, string> {
- // TODO: Remove this fallback once @paperclipai/adapter-utils exports buildInvocationEnvForLogs everywhere we consume it.
const maybeBuildInvocationEnvForLogs = (
serverUtils as typeof serverUtils & {
buildInvocationEnvForLogs?: (
diff --git a/server/src/app.ts b/server/src/app.ts
index c60de55526..971645d5e9 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -28,6 +28,7 @@ import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
import { inboxDismissalRoutes } from "./routes/inbox-dismissals.js";
import { instanceSettingsRoutes } from "./routes/instance-settings.js";
import { llmRoutes } from "./routes/llms.js";
+import { authRoutes } from "./routes/auth.js";
import { assetRoutes } from "./routes/assets.js";
import { accessRoutes } from "./routes/access.js";
import { pluginRoutes } from "./routes/plugins.js";
@@ -155,23 +156,7 @@ export async function createApp(
resolveSession: opts.resolveSession,
}),
);
- app.get("/api/auth/get-session", (req, res) => {
- if (req.actor.type !== "board" || !req.actor.userId) {
- res.status(401).json({ error: "Unauthorized" });
- return;
- }
- res.json({
- session: {
- id: `paperclip:${req.actor.source}:${req.actor.userId}`,
- userId: req.actor.userId,
- },
- user: {
- id: req.actor.userId,
- email: null,
- name: req.actor.source === "local_implicit" ? "Local Board" : null,
- },
- });
- });
+ app.use("/api/auth", authRoutes(db));
if (opts.betterAuthHandler) {
app.all("/api/auth/{*authPath}", opts.betterAuthHandler);
}
diff --git a/server/src/lib/join-request-dedupe.ts b/server/src/lib/join-request-dedupe.ts
new file mode 100644
index 0000000000..249ef11f65
--- /dev/null
+++ b/server/src/lib/join-request-dedupe.ts
@@ -0,0 +1,88 @@
+import { joinRequests } from "@paperclipai/db";
+
+type JoinRequestLike = Pick<
+ typeof joinRequests.$inferSelect,
+ | "id"
+ | "requestType"
+ | "status"
+ | "requestingUserId"
+ | "requestEmailSnapshot"
+ | "createdAt"
+ | "updatedAt"
+>;
+
+function nonEmptyTrimmed(value: string | null | undefined): string | null {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed : null;
+}
+
+export function normalizeJoinRequestEmail(
+ email: string | null | undefined
+): string | null {
+ const trimmed = nonEmptyTrimmed(email);
+ return trimmed ? trimmed.toLowerCase() : null;
+}
+
+export function humanJoinRequestIdentity(
+ row: Pick<
+ JoinRequestLike,
+ "requestType" | "requestingUserId" | "requestEmailSnapshot"
+ >
+): string | null {
+ if (row.requestType !== "human") return null;
+ const requestingUserId = nonEmptyTrimmed(row.requestingUserId);
+ if (requestingUserId) return `user:${requestingUserId}`;
+ const email = normalizeJoinRequestEmail(row.requestEmailSnapshot);
+ return email ? `email:${email}` : null;
+}
+
+export function findReusableHumanJoinRequest<
+ T extends Pick<
+ JoinRequestLike,
+ "id" | "requestType" | "status" | "requestingUserId" | "requestEmailSnapshot"
+ >,
+>(
+ rows: T[],
+ actor: { requestingUserId?: string | null; requestEmailSnapshot?: string | null }
+): T | null {
+ const actorUserId = nonEmptyTrimmed(actor.requestingUserId);
+ if (actorUserId) {
+ const sameUser = rows.find(
+ (row) =>
+ row.requestType === "human" &&
+ (row.status === "pending_approval" || row.status === "approved") &&
+ row.requestingUserId === actorUserId
+ );
+ if (sameUser) return sameUser;
+ }
+
+ const actorEmail = normalizeJoinRequestEmail(actor.requestEmailSnapshot);
+ if (!actorEmail) return null;
+ return (
+ rows.find(
+ (row) =>
+ row.requestType === "human" &&
+ (row.status === "pending_approval" || row.status === "approved") &&
+ normalizeJoinRequestEmail(row.requestEmailSnapshot) === actorEmail
+ ) ?? null
+ );
+}
+
+export function collapseDuplicatePendingHumanJoinRequests<
+ T extends Pick<
+ JoinRequestLike,
+ "id" | "requestType" | "status" | "requestingUserId" | "requestEmailSnapshot"
+ >,
+>(rows: T[]): T[] {
+ const seen = new Set<string>();
+ return rows.filter((row) => {
+ if (row.requestType !== "human" || row.status !== "pending_approval") {
+ return true;
+ }
+ const identity = humanJoinRequestIdentity(row);
+ if (!identity) return true;
+ if (seen.has(identity)) return false;
+ seen.add(identity);
+ return true;
+ });
+}
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
index 6140c87d5b..2438aee306 100644
--- a/server/src/middleware/auth.ts
+++ b/server/src/middleware/auth.ts
@@ -23,7 +23,14 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
return async (req, _res, next) => {
req.actor =
opts.deploymentMode === "local_trusted"
- ? { type: "board", userId: "local-board", isInstanceAdmin: true, source: "local_implicit" }
+ ? {
+ type: "board",
+ userId: "local-board",
+ userName: "Local Board",
+ userEmail: null,
+ isInstanceAdmin: true,
+ source: "local_implicit",
+ }
: { type: "none", source: "none" };
const runIdHeader = req.header("x-paperclip-run-id");
@@ -49,7 +56,11 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.then((rows) => rows[0] ?? null),
db
- .select({ companyId: companyMemberships.companyId })
+ .select({
+ companyId: companyMemberships.companyId,
+ membershipRole: companyMemberships.membershipRole,
+ status: companyMemberships.status,
+ })
.from(companyMemberships)
.where(
and(
@@ -62,7 +73,10 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
req.actor = {
type: "board",
userId,
+ userName: session.user.name ?? null,
+ userEmail: session.user.email ?? null,
companyIds: memberships.map((row) => row.companyId),
+ memberships,
isInstanceAdmin: Boolean(roleRow),
runId: runIdHeader ?? undefined,
source: "session",
@@ -90,7 +104,10 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
req.actor = {
type: "board",
userId: boardKey.userId,
+ userName: access.user?.name ?? null,
+ userEmail: access.user?.email ?? null,
companyIds: access.companyIds,
+ memberships: access.memberships,
isInstanceAdmin: access.isInstanceAdmin,
keyId: boardKey.id,
runId: runIdHeader || undefined,
diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts
index 0be3adab1f..c86637caf0 100644
--- a/server/src/routes/access.ts
+++ b/server/src/routes/access.ts
@@ -9,14 +9,18 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { Router } from "express";
import type { Request } from "express";
-import { and, eq, isNull, desc } from "drizzle-orm";
+import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
+ assets,
agentApiKeys,
authUsers,
companies,
+ companyLogos,
+ companyMemberships,
invites,
- joinRequests
+ joinRequests,
+ principalPermissionGrants,
} from "@paperclipai/db";
import {
acceptInviteSchema,
@@ -24,13 +28,17 @@ import {
claimJoinRequestApiKeySchema,
createCompanyInviteSchema,
createOpenClawInvitePromptSchema,
+ listCompanyInvitesQuerySchema,
listJoinRequestsQuerySchema,
resolveCliAuthChallengeSchema,
+ searchAdminUsersQuerySchema,
+ updateCompanyMemberWithPermissionsSchema,
+ updateCompanyMemberSchema,
updateMemberPermissionsSchema,
updateUserCompanyAccessSchema,
PERMISSION_KEYS
} from "@paperclipai/shared";
-import type { DeploymentExposure, DeploymentMode } from "@paperclipai/shared";
+import type { DeploymentExposure, DeploymentMode, PermissionKey } from "@paperclipai/shared";
import {
forbidden,
conflict,
@@ -48,11 +56,22 @@ import {
logActivity,
notifyHireApproved
} from "../services/index.js";
+import {
+ grantsForHumanRole,
+ normalizeHumanRole,
+ resolveHumanInviteRole,
+} from "../services/company-member-roles.js";
+import { humanJoinGrantsFromDefaults } from "../services/invite-grants.js";
+import {
+ collapseDuplicatePendingHumanJoinRequests,
+ findReusableHumanJoinRequest,
+} from "../lib/join-request-dedupe.js";
import { assertAuthenticated, assertCompanyAccess } from "./authz.js";
import {
claimBoardOwnership,
inspectBoardClaimChallenge
} from "../board-claim.js";
+import { getStorageService } from "../storage/index.js";
function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
@@ -62,7 +81,12 @@ const INVITE_TOKEN_PREFIX = "pcp_invite_";
const INVITE_TOKEN_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
const INVITE_TOKEN_SUFFIX_LENGTH = 8;
const INVITE_TOKEN_MAX_RETRIES = 5;
-const COMPANY_INVITE_TTL_MS = 10 * 60 * 1000;
+const COMPANY_INVITE_TTL_MS = 72 * 60 * 60 * 1000;
+
+type MemberGrantPayload = {
+ permissionKey: PermissionKey;
+ scope?: Record<string, unknown> | null;
+};
function createInviteToken() {
const bytes = randomBytes(INVITE_TOKEN_SUFFIX_LENGTH);
@@ -858,9 +882,20 @@ function toInviteSummaryResponse(
req: Request,
token: string,
invite: typeof invites.$inferSelect,
- companyName: string | null = null
+ company:
+ | string
+ | {
+ name: string | null;
+ brandColor: string | null;
+ logoUrl: string | null;
+ }
+ | null = null
) {
+ const companyInfo = typeof company === "string"
+ ? { name: company, brandColor: null, logoUrl: null }
+ : company;
const baseUrl = requestBaseUrl(req);
+ const invitePath = `/invite/${token}`;
const onboardingPath = `/api/invites/${token}/onboarding`;
const onboardingTextPath = `/api/invites/${token}/onboarding.txt`;
const skillIndexPath = `/api/invites/${token}/skills/index`;
@@ -868,10 +903,15 @@ function toInviteSummaryResponse(
return {
id: invite.id,
companyId: invite.companyId,
- companyName,
+ companyName: companyInfo?.name ?? null,
+ companyLogoUrl: companyInfo?.logoUrl ?? null,
+ companyBrandColor: companyInfo?.brandColor ?? null,
inviteType: invite.inviteType,
allowedJoinTypes: invite.allowedJoinTypes,
+ humanRole: extractInviteHumanRole(invite),
expiresAt: invite.expiresAt,
+ invitePath,
+ inviteUrl: baseUrl ? `${baseUrl}${invitePath}` : invitePath,
onboardingPath,
onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath,
onboardingTextPath,
@@ -886,6 +926,353 @@ function toInviteSummaryResponse(
};
}
+function actorHasActiveUserMembership(req: Request, companyId: string) {
+ return (
+ req.actor.type === "board" &&
+ typeof req.actor.userId === "string" &&
+ Array.isArray(req.actor.memberships) &&
+ req.actor.memberships.some(
+ (membership) =>
+ membership.companyId === companyId && membership.status === "active",
+ )
+ );
+}
+
+async function loadUsersById(db: Db, userIds: string[]) {
+ if (userIds.length === 0) return new Map<string, ReturnType<typeof toUserProfile>>();
+ const rows = await db
+ .select({
+ id: authUsers.id,
+ email: authUsers.email,
+ name: authUsers.name,
+ image: authUsers.image,
+ })
+ .from(authUsers)
+ .where(inArray(authUsers.id, userIds));
+ return new Map(rows.map((row) => [row.id, toUserProfile(row)]));
+}
+
+async function loadCompanyAccessSummary(
+ req: Request,
+ access: ReturnType<typeof accessService>,
+ companyId: string,
+) {
+ if (req.actor.type !== "board") {
+ return {
+ currentUserRole: null,
+ canManageMembers: false,
+ canInviteUsers: false,
+ canApproveJoinRequests: false,
+ };
+ }
+ if (isLocalImplicit(req)) {
+ return {
+ currentUserRole: "owner" as const,
+ canManageMembers: true,
+ canInviteUsers: true,
+ canApproveJoinRequests: true,
+ };
+ }
+ const userId = req.actor.userId ?? null;
+ const membership =
+ userId ? await access.getMembership(companyId, "user", userId) : null;
+ const [canManageMembers, canInviteUsers, canApproveJoinRequests] =
+ await Promise.all([
+ access.canUser(companyId, userId, "users:manage_permissions"),
+ access.canUser(companyId, userId, "users:invite"),
+ access.canUser(companyId, userId, "joins:approve"),
+ ]);
+
+ return {
+ currentUserRole:
+ membership?.status === "active" && membership.membershipRole
+ ? normalizeHumanRole(membership.membershipRole, "operator")
+ : null,
+ canManageMembers,
+ canInviteUsers,
+ canApproveJoinRequests,
+ };
+}
+
+async function loadCompanyMemberRecords(db: Db, companyId: string) {
+ const members = await db
+ .select()
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ ),
+ )
+ .orderBy(desc(companyMemberships.updatedAt));
+
+ const userIds = [...new Set(members.map((member) => member.principalId))];
+ const [userMap, grants] = await Promise.all([
+ loadUsersById(db, userIds),
+ userIds.length > 0
+ ? db
+ .select()
+ .from(principalPermissionGrants)
+ .where(
+ and(
+ eq(principalPermissionGrants.companyId, companyId),
+ eq(principalPermissionGrants.principalType, "user"),
+ inArray(principalPermissionGrants.principalId, userIds),
+ ),
+ )
+ : Promise.resolve([]),
+ ]);
+
+ const grantsByPrincipalId = new Map<string, typeof grants>();
+ for (const grant of grants) {
+ const existing = grantsByPrincipalId.get(grant.principalId) ?? [];
+ existing.push(grant);
+ grantsByPrincipalId.set(grant.principalId, existing);
+ }
+
+ return members.map((member) => ({
+ ...member,
+ principalType: "user" as const,
+ membershipRole: member.membershipRole
+ ? normalizeHumanRole(member.membershipRole, "operator")
+ : null,
+ user: userMap.get(member.principalId) ?? null,
+ grants: grantsByPrincipalId.get(member.principalId) ?? [],
+ }));
+}
+
+async function loadCompanyUserDirectory(db: Db, companyId: string) {
+ const members = await db
+ .select({
+ principalId: companyMemberships.principalId,
+ status: companyMemberships.status,
+ })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ ),
+ )
+ .orderBy(desc(companyMemberships.updatedAt));
+
+ const userIds = [...new Set(members.map((member) => member.principalId))];
+ const userMap = await loadUsersById(db, userIds);
+
+ return members.map((member) => ({
+ principalId: member.principalId,
+ status: "active" as const,
+ user: userMap.get(member.principalId) ?? null,
+ }));
+}
+
+function inviteStateWhereClause(
+ state: "active" | "accepted" | "expired" | "revoked" | undefined,
+) {
+ const now = new Date();
+ switch (state) {
+ case "active":
+ return and(
+ isNull(invites.revokedAt),
+ isNull(invites.acceptedAt),
+ gt(invites.expiresAt, now),
+ );
+ case "accepted":
+ return isNotNull(invites.acceptedAt);
+ case "expired":
+ return and(
+ isNull(invites.revokedAt),
+ isNull(invites.acceptedAt),
+ lte(invites.expiresAt, now),
+ );
+ case "revoked":
+ return isNotNull(invites.revokedAt);
+ default:
+ return undefined;
+ }
+}
+
+async function loadCompanyInviteRecords(
+ db: Db,
+ companyId: string,
+ options: {
+ state?: "active" | "accepted" | "expired" | "revoked";
+ limit: number;
+ offset: number;
+ },
+) {
+ const whereClause = inviteStateWhereClause(options.state);
+ const rows = await db
+ .select()
+ .from(invites)
+ .where(whereClause ? and(eq(invites.companyId, companyId), whereClause) : eq(invites.companyId, companyId))
+ .orderBy(desc(invites.createdAt))
+ .limit(options.limit + 1)
+ .offset(options.offset);
+ const hasMore = rows.length > options.limit;
+ const visibleRows = hasMore ? rows.slice(0, options.limit) : rows;
+ const userIds = [
+ ...new Set(
+ visibleRows
+ .map((invite) => invite.invitedByUserId)
+ .filter((value): value is string => Boolean(value)),
+ ),
+ ];
+ const [userMap, joinRows, companyName] = await Promise.all([
+ loadUsersById(db, userIds),
+ visibleRows.length
+ ? db
+ .select({ id: joinRequests.id, inviteId: joinRequests.inviteId })
+ .from(joinRequests)
+ .where(
+ and(
+ eq(joinRequests.companyId, companyId),
+ inArray(
+ joinRequests.inviteId,
+ visibleRows.map((invite) => invite.id),
+ ),
+ ),
+ )
+ : Promise.resolve([]),
+ db
+ .select({ name: companies.name })
+ .from(companies)
+ .where(eq(companies.id, companyId))
+ .then((companyRows) => companyRows[0]?.name ?? null),
+ ]);
+ const joinRequestIdByInviteId = new Map(
+ joinRows.map((row: { inviteId: string; id: string }) => [row.inviteId, row.id]),
+ );
+
+ return {
+ invites: visibleRows.map((invite) => ({
+ ...invite,
+ companyName,
+ humanRole: extractInviteHumanRole(invite),
+ inviteMessage: extractInviteMessage(invite),
+ state: inviteState(invite),
+ invitedByUser: invite.invitedByUserId
+ ? userMap.get(invite.invitedByUserId) ?? null
+ : null,
+ relatedJoinRequestId: joinRequestIdByInviteId.get(invite.id) ?? null,
+ })),
+ nextOffset: hasMore ? options.offset + options.limit : null,
+ };
+}
+
+async function loadJoinRequestRecords(db: Db, companyId: string) {
+ const rows = collapseDuplicatePendingHumanJoinRequests(
+ await db
+ .select()
+ .from(joinRequests)
+ .where(eq(joinRequests.companyId, companyId))
+ .orderBy(desc(joinRequests.createdAt))
+ );
+ const inviteIds = [...new Set(rows.map((row) => row.inviteId))];
+ const inviteRows = inviteIds.length
+ ? await db
+ .select()
+ .from(invites)
+ .where(inArray(invites.id, inviteIds))
+ : [];
+ const userIds = [
+ ...new Set(
+ [
+ ...rows.map((row) => row.requestingUserId),
+ ...rows.map((row) => row.approvedByUserId),
+ ...rows.map((row) => row.rejectedByUserId),
+ ...inviteRows.map((invite) => invite.invitedByUserId),
+ ].filter((value): value is string => Boolean(value)),
+ ),
+ ];
+ const userMap = await loadUsersById(db, userIds);
+ const inviteMap = new Map(inviteRows.map((invite) => [invite.id, invite]));
+
+ return rows.map((row) => {
+ const invite = inviteMap.get(row.inviteId) ?? null;
+ return {
+ ...toJoinRequestResponse(row),
+ requesterUser: row.requestingUserId
+ ? userMap.get(row.requestingUserId) ?? null
+ : null,
+ approvedByUser: row.approvedByUserId
+ ? userMap.get(row.approvedByUserId) ?? null
+ : null,
+ rejectedByUser: row.rejectedByUserId
+ ? userMap.get(row.rejectedByUserId) ?? null
+ : null,
+ invite: invite
+ ? {
+ id: invite.id,
+ inviteType: invite.inviteType,
+ allowedJoinTypes: invite.allowedJoinTypes,
+ humanRole: extractInviteHumanRole(invite),
+ inviteMessage: extractInviteMessage(invite),
+ createdAt: invite.createdAt,
+ expiresAt: invite.expiresAt,
+ revokedAt: invite.revokedAt,
+ acceptedAt: invite.acceptedAt,
+ invitedByUser: invite.invitedByUserId
+ ? userMap.get(invite.invitedByUserId) ?? null
+ : null,
+ }
+ : null,
+ };
+ });
+}
+
+async function loadUserCompanyAccessResponse(
+ db: Db,
+ access: ReturnType<typeof accessService>,
+ userId: string,
+) {
+ const [memberships, user, isInstanceAdmin] = await Promise.all([
+ access.listUserCompanyAccess(userId),
+ db
+ .select({
+ id: authUsers.id,
+ email: authUsers.email,
+ name: authUsers.name,
+ image: authUsers.image,
+ })
+ .from(authUsers)
+ .where(eq(authUsers.id, userId))
+ .then((rows) => rows[0] ?? null),
+ access.isInstanceAdmin(userId),
+ ]);
+ const companyIds = [...new Set(memberships.map((membership) => membership.companyId))];
+ const companyRows = companyIds.length
+ ? await db
+ .select({
+ id: companies.id,
+ name: companies.name,
+ status: companies.status,
+ })
+ .from(companies)
+ .where(inArray(companies.id, companyIds))
+ : [];
+ const companyMap = new Map(companyRows.map((company) => [company.id, company]));
+
+ return {
+ user: user
+ ? {
+ ...toUserProfile(user),
+ isInstanceAdmin,
+ }
+ : null,
+ companyAccess: memberships.map((membership) => {
+ const company = companyMap.get(membership.companyId) ?? null;
+ return {
+ ...membership,
+ principalType: "user" as const,
+ companyName: company?.name ?? null,
+ companyStatus: company?.status ?? null,
+ };
+ }),
+ };
+}
+
function buildOnboardingDiscoveryDiagnostics(input: {
apiBaseUrl: string;
deploymentMode: DeploymentMode;
@@ -1350,12 +1737,22 @@ function extractInviteMessage(
function mergeInviteDefaults(
defaultsPayload: Record<string, unknown> | null | undefined,
- agentMessage: string | null
+ agentMessage: string | null,
+ humanRole: "owner" | "admin" | "operator" | "viewer" | null = null,
): Record<string, unknown> | null {
const merged =
defaultsPayload && typeof defaultsPayload === "object"
? { ...defaultsPayload }
: {};
+ if (humanRole) {
+ const existingHuman =
+ isPlainObject(merged.human) ? { ...(merged.human as Record<string, unknown>) } : {};
+ merged.human = {
+ ...existingHuman,
+ role: humanRole,
+ grants: grantsForHumanRole(humanRole),
+ };
+ }
if (agentMessage) {
merged.agentMessage = agentMessage;
}
@@ -1375,10 +1772,44 @@ function inviteExpired(invite: typeof invites.$inferSelect) {
return invite.expiresAt.getTime() <= Date.now();
}
+function inviteState(invite: typeof invites.$inferSelect) {
+ if (invite.revokedAt) return "revoked" as const;
+ if (invite.acceptedAt) return "accepted" as const;
+ if (inviteExpired(invite)) return "expired" as const;
+ return "active" as const;
+}
+
+function extractInviteHumanRole(invite: typeof invites.$inferSelect) {
+ if (invite.allowedJoinTypes === "agent") return null;
+ return resolveHumanInviteRole(
+ invite.defaultsPayload as Record<string, unknown> | null | undefined,
+ );
+}
+
function isLocalImplicit(req: Request) {
return req.actor.type === "board" && req.actor.source === "local_implicit";
}
+function toUserProfile(
+ user:
+ | {
+ id: string;
+ email: string | null;
+ name: string | null;
+ image?: string | null;
+ }
+ | null
+ | undefined,
+) {
+ if (!user) return null;
+ return {
+ id: user.id,
+ email: user.email ?? null,
+ name: user.name ?? null,
+ image: user.image ?? null,
+ };
+}
+
async function resolveActorEmail(db: Db, req: Request): Promise<string | null> {
if (isLocalImplicit(req)) return "[email protected]";
const userId = req.actor.userId;
@@ -1391,6 +1822,57 @@ async function resolveActorEmail(db: Db, req: Request): Promise<string | null> {
return user?.email ?? null;
}
+async function resolveAcceptedInviteJoinRequest(
+ db: Db,
+ req: Request,
+ invite: typeof invites.$inferSelect | null,
+) {
+ if (!invite?.acceptedAt) return null;
+
+ const directJoinRequest = await db
+ .select({
+ requestType: joinRequests.requestType,
+ status: joinRequests.status,
+ requestingUserId: joinRequests.requestingUserId,
+ requestEmailSnapshot: joinRequests.requestEmailSnapshot,
+ })
+ .from(joinRequests)
+ .where(eq(joinRequests.inviteId, invite.id))
+ .then((rows) => rows[0] ?? null);
+ if (directJoinRequest) return directJoinRequest;
+
+ if (!invite.companyId) return null;
+
+ const actorRequestingUserId = isLocalImplicit(req)
+ ? "local-board"
+ : req.actor.userId ?? null;
+ const actorEmail = await resolveActorEmail(db, req);
+ if (!actorRequestingUserId && !actorEmail) return null;
+
+ return findReusableHumanJoinRequest(
+ await db
+ .select({
+ id: joinRequests.id,
+ requestType: joinRequests.requestType,
+ status: joinRequests.status,
+ requestingUserId: joinRequests.requestingUserId,
+ requestEmailSnapshot: joinRequests.requestEmailSnapshot,
+ })
+ .from(joinRequests)
+ .where(
+ and(
+ eq(joinRequests.companyId, invite.companyId),
+ eq(joinRequests.requestType, "human"),
+ ),
+ )
+ .orderBy(desc(joinRequests.createdAt)),
+ {
+ requestingUserId: actorRequestingUserId,
+ requestEmailSnapshot: actorEmail,
+ },
+ );
+}
+
function grantsFromDefaults(
defaultsPayload: Record<string, unknown> | null | undefined,
key: "human" | "agent"
@@ -1849,6 +2331,7 @@ export function accessRoutes(
req: Request;
companyId: string;
allowedJoinTypes: "human" | "agent" | "both";
+ humanRole?: "owner" | "admin" | "operator" | "viewer" | null;
defaultsPayload?: Record<string, unknown> | null;
agentMessage?: string | null;
}) {
@@ -1856,13 +2339,18 @@ export function accessRoutes(
typeof input.agentMessage === "string"
? input.agentMessage.trim() || null
: null;
+ const effectiveHumanRole =
+ input.allowedJoinTypes === "agent"
+ ? null
+ : input.humanRole ?? "operator";
const insertValues = {
companyId: input.companyId,
inviteType: "company_join" as const,
allowedJoinTypes: input.allowedJoinTypes,
defaultsPayload: mergeInviteDefaults(
input.defaultsPayload ?? null,
- normalizedAgentMessage
+ normalizedAgentMessage,
+ effectiveHumanRole,
),
expiresAt: companyInviteExpiresAt(),
invitedByUserId: input.req.actor.userId ?? null
@@ -1897,14 +2385,89 @@ export function accessRoutes(
return { token, created, normalizedAgentMessage };
}
- async function getInviteCompanyName(companyId: string | null) {
- if (!companyId) return null;
+ async function getInviteCompanyBranding(
+ companyId: string | null,
+ inviteToken: string | null = null,
+ ): Promise<{
+ name: string | null;
+ brandColor: string | null;
+ logoAssetId: string | null;
+ logoUrl: string | null;
+ }> {
+ if (!companyId) {
+ return { name: null, brandColor: null, logoAssetId: null, logoUrl: null };
+ }
const company = await db
- .select({ name: companies.name })
+ .select({
+ name: companies.name,
+ brandColor: companies.brandColor,
+ logoAssetId: companyLogos.assetId,
+ })
.from(companies)
+ .leftJoin(companyLogos, eq(companyLogos.companyId, companies.id))
.where(eq(companies.id, companyId))
.then((rows) => rows[0] ?? null);
- return company?.name ?? null;
+ let logoUrl: string | null = null;
+ if (inviteToken && company?.logoAssetId) {
+ const logoAsset = await getInviteLogoAsset(companyId);
+ if (logoAsset?.companyId) {
+ try {
+ const storage = getStorageService();
+ const logoObject = await storage.headObject(logoAsset.companyId, logoAsset.objectKey);
+ if (logoObject.exists) {
+ logoUrl = `/api/invites/${inviteToken}/logo`;
+ }
+ } catch (err) {
+ logger.warn(
+ {
+ err,
+ companyId,
+ logoAssetId: company.logoAssetId,
+ },
+ "invite logo storage check failed",
+ );
+ }
+ }
+ }
+
+ return {
+ name: company?.name ?? null,
+ brandColor: company?.brandColor ?? null,
+ logoAssetId: company?.logoAssetId ?? null,
+ logoUrl,
+ };
+ }
+
+ async function getInviteLogoAsset(companyId: string | null): Promise<{
+ companyId: string | null;
+ objectKey: string;
+ contentType: string | null;
+ byteSize: number | null;
+ originalFilename: string | null;
+ } | null> {
+ if (!companyId) return null;
+ const logoAsset = await db
+ .select({
+ companyId: companies.id,
+ objectKey: assets.objectKey,
+ contentType: assets.contentType,
+ byteSize: assets.byteSize,
+ originalFilename: assets.originalFilename,
+ })
+ .from(companies)
+ .leftJoin(companyLogos, eq(companyLogos.companyId, companies.id))
+ .leftJoin(assets, eq(assets.id, companyLogos.assetId))
+ .where(eq(companies.id, companyId))
+ .then((rows) => rows[0] ?? null);
+
+ if (!logoAsset?.objectKey) return null;
+ return {
+ companyId: logoAsset.companyId,
+ objectKey: logoAsset.objectKey,
+ contentType: logoAsset.contentType,
+ byteSize: logoAsset.byteSize,
+ originalFilename: logoAsset.originalFilename,
+ };
}
router.get("/skills/available", (req, res) => {
@@ -1948,6 +2511,7 @@ export function accessRoutes(
req,
companyId,
allowedJoinTypes: req.body.allowedJoinTypes,
+ humanRole: req.body.humanRole ?? null,
defaultsPayload: req.body.defaultsPayload ?? null,
agentMessage: req.body.agentMessage ?? null
});
@@ -1966,22 +2530,24 @@ export function accessRoutes(
inviteType: created.inviteType,
allowedJoinTypes: created.allowedJoinTypes,
expiresAt: created.expiresAt.toISOString(),
+ humanRole: extractInviteHumanRole(created),
hasAgentMessage: Boolean(normalizedAgentMessage)
}
});
- const companyName = await getInviteCompanyName(created.companyId);
+ const companyBranding = await getInviteCompanyBranding(created.companyId, token);
const inviteSummary = toInviteSummaryResponse(
req,
token,
created,
- companyName
+ companyBranding
);
res.status(201).json({
...created,
token,
- inviteUrl: `/invite/${token}`,
- companyName,
+ invitePath: inviteSummary.invitePath,
+ inviteUrl: inviteSummary.inviteUrl,
+ companyName: companyBranding.name,
onboardingTextPath: inviteSummary.onboardingTextPath,
onboardingTextUrl: inviteSummary.onboardingTextUrl,
inviteMessage: inviteSummary.inviteMessage
@@ -2000,6 +2566,7 @@ export function accessRoutes(
req,
companyId,
allowedJoinTypes: "agent",
+ humanRole: null,
defaultsPayload: null,
agentMessage: req.body.agentMessage ?? null
});
@@ -2022,18 +2589,19 @@ export function accessRoutes(
}
});
- const companyName = await getInviteCompanyName(created.companyId);
+ const companyBranding = await getInviteCompanyBranding(created.companyId, token);
const inviteSummary = toInviteSummaryResponse(
req,
token,
created,
- companyName
+ companyBranding
);
res.status(201).json({
...created,
token,
- inviteUrl: `/invite/${token}`,
- companyName,
+ invitePath: inviteSummary.invitePath,
+ inviteUrl: inviteSummary.inviteUrl,
+ companyName: companyBranding.name,
onboardingTextPath: inviteSummary.onboardingTextPath,
onboardingTextUrl: inviteSummary.onboardingTextUrl,
inviteMessage: inviteSummary.inviteMessage
@@ -2049,17 +2617,82 @@ export function accessRoutes(
.from(invites)
.where(eq(invites.tokenHash, hashToken(token)))
.then((rows) => rows[0] ?? null);
+ const inviteJoinRequest = await resolveAcceptedInviteJoinRequest(db, req, invite);
if (
!invite ||
invite.revokedAt ||
- invite.acceptedAt ||
- inviteExpired(invite)
+ inviteExpired(invite) ||
+ (invite.acceptedAt && !inviteJoinRequest)
) {
throw notFound("Invite not found");
}
- const companyName = await getInviteCompanyName(invite.companyId);
- res.json(toInviteSummaryResponse(req, token, invite, companyName));
+ const companyBranding = await getInviteCompanyBranding(invite.companyId, token);
+ const inviterName = invite.invitedByUserId
+ ? await loadUsersById(db, [invite.invitedByUserId]).then(
+ (m) => m.get(invite.invitedByUserId!)?.name ?? null
+ )
+ : null;
+ res.json({
+ ...toInviteSummaryResponse(req, token, invite, companyBranding),
+ invitedByUserName: inviterName,
+ joinRequestStatus: inviteJoinRequest?.status ?? null,
+ joinRequestType: inviteJoinRequest?.requestType ?? null,
+ });
+ });
+
+ router.get("/invites/:token/logo", async (req, res, next) => {
+ const token = (req.params.token as string).trim();
+ if (!token) throw notFound("Invite not found");
+ const invite = await db
+ .select()
+ .from(invites)
+ .where(eq(invites.tokenHash, hashToken(token)))
+ .then((rows) => rows[0] ?? null);
+ const inviteJoinRequest = await resolveAcceptedInviteJoinRequest(db, req, invite);
+ if (
+ !invite ||
+ invite.revokedAt ||
+ inviteExpired(invite) ||
+ (invite.acceptedAt && !inviteJoinRequest)
+ ) {
+ throw notFound("Invite not found");
+ }
+
+ const logoAsset = await getInviteLogoAsset(invite.companyId);
+ if (!logoAsset || !logoAsset.companyId) {
+ throw notFound("Invite logo not found");
+ }
+ const companyId = logoAsset.companyId;
+
+ const storage = getStorageService();
+ const logoHead = await storage.headObject(companyId, logoAsset.objectKey);
+ if (!logoHead.exists) {
+ throw notFound("Invite logo not found");
+ }
+ const object = await storage.getObject(companyId, logoAsset.objectKey);
+ const responseContentType =
+ logoAsset.contentType ||
+ logoHead.contentType ||
+ object.contentType ||
+ "application/octet-stream";
+ res.setHeader("Content-Type", responseContentType);
+ res.setHeader(
+ "Content-Length",
+ String(logoAsset.byteSize || logoHead.contentLength || object.contentLength || 0),
+ );
+ res.setHeader("Cache-Control", "private, max-age=60");
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ if (responseContentType === "image/svg+xml") {
+ res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'");
+ }
+ const filename = logoAsset.originalFilename ?? "company-logo";
+ res.setHeader("Content-Disposition", `inline; filename=\"${filename.replaceAll("\"", "")}\"`);
+
+ object.stream.on("error", (err) => {
+ next(err);
+ });
+ object.stream.pipe(res);
});
router.get("/invites/:token/onboarding", async (req, res) => {
@@ -2074,10 +2707,10 @@ export function accessRoutes(
throw notFound("Invite not found");
}
- const companyName = await getInviteCompanyName(invite.companyId);
+ const companyBranding = await getInviteCompanyBranding(invite.companyId);
res.json(buildInviteOnboardingManifest(req, token, invite, {
...opts,
- companyName
+ companyName: companyBranding.name
}));
});
@@ -2093,13 +2726,13 @@ export function accessRoutes(
throw notFound("Invite not found");
}
- const companyName = await getInviteCompanyName(invite.companyId);
+ const companyBranding = await getInviteCompanyBranding(invite.companyId);
res
.type("text/plain; charset=utf-8")
.send(
buildInviteOnboardingTextDocument(req, token, invite, {
...opts,
- companyName
+ companyName: companyBranding.name
})
);
});
@@ -2266,6 +2899,12 @@ export function accessRoutes(
) {
throw unauthorized("Authenticated user is required");
}
+ if (
+ requestType === "human" &&
+ actorHasActiveUserMembership(req, companyId)
+ ) {
+ throw conflict("You already belong to this company");
+ }
if (requestType === "agent" && !req.body.agentName) {
if (
!inviteAlreadyAccepted ||
@@ -2358,48 +2997,82 @@ export function accessRoutes(
const actorEmail =
requestType === "human" ? await resolveActorEmail(db, req) : null;
- const created = !inviteAlreadyAccepted
- ? await db.transaction(async (tx) => {
- await tx
- .update(invites)
- .set({ acceptedAt: new Date(), updatedAt: new Date() })
- .where(
- and(
- eq(invites.id, invite.id),
- isNull(invites.acceptedAt),
- isNull(invites.revokedAt)
+ const existingHumanJoinRequest =
+ requestType === "human"
+ ? findReusableHumanJoinRequest(
+ await db
+ .select()
+ .from(joinRequests)
+ .where(
+ and(
+ eq(joinRequests.companyId, companyId),
+ eq(joinRequests.requestType, "human")
+ )
)
- );
-
- const row = await tx
- .insert(joinRequests)
- .values({
- inviteId: invite.id,
- companyId,
- requestType,
- status: "pending_approval",
- requestIp: requestIp(req),
- requestingUserId:
- requestType === "human"
- ? req.actor.userId ?? "local-board"
- : null,
- requestEmailSnapshot:
- requestType === "human" ? actorEmail : null,
- agentName: requestType === "agent" ? req.body.agentName : null,
- adapterType: requestType === "agent" ? adapterType : null,
- capabilities:
- requestType === "agent"
- ? req.body.capabilities ?? null
- : null,
- agentDefaultsPayload:
- requestType === "agent" ? joinDefaults.normalized : null,
- claimSecretHash,
- claimSecretExpiresAt
- })
- .returning()
- .then((rows) => rows[0]);
- return row;
- })
+ .orderBy(desc(joinRequests.createdAt)),
+ {
+ requestingUserId: req.actor.userId ?? "local-board",
+ requestEmailSnapshot: actorEmail
+ }
+ )
+ : null;
+ const created = !inviteAlreadyAccepted
+ ? existingHumanJoinRequest
+ ? await db.transaction(async (tx) => {
+ await tx
+ .update(invites)
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
+ .where(
+ and(
+ eq(invites.id, invite.id),
+ isNull(invites.acceptedAt),
+ isNull(invites.revokedAt)
+ )
+ );
+ return existingHumanJoinRequest;
+ })
+ : await db.transaction(async (tx) => {
+ await tx
+ .update(invites)
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
+ .where(
+ and(
+ eq(invites.id, invite.id),
+ isNull(invites.acceptedAt),
+ isNull(invites.revokedAt)
+ )
+ );
+
+ const row = await tx
+ .insert(joinRequests)
+ .values({
+ inviteId: invite.id,
+ companyId,
+ requestType,
+ status: "pending_approval",
+ requestIp: requestIp(req),
+ requestingUserId:
+ requestType === "human"
+ ? req.actor.userId ?? "local-board"
+ : null,
+ requestEmailSnapshot:
+ requestType === "human" ? actorEmail : null,
+ agentName:
+ requestType === "agent" ? req.body.agentName : null,
+ adapterType: requestType === "agent" ? adapterType : null,
+ capabilities:
+ requestType === "agent"
+ ? req.body.capabilities ?? null
+ : null,
+ agentDefaultsPayload:
+ requestType === "agent" ? joinDefaults.normalized : null,
+ claimSecretHash,
+ claimSecretExpiresAt
+ })
+ .returning()
+ .then((rows) => rows[0]);
+ return row;
+ })
: await db
.update(joinRequests)
.set({
@@ -2545,21 +3218,23 @@ export function accessRoutes(
entityId: created.id,
details: {
requestType,
- requestIp: created.requestIp,
- inviteReplay: inviteAlreadyAccepted
+ requestIp: requestIp(req),
+ inviteReplay: inviteAlreadyAccepted,
+ reusedExistingJoinRequest:
+ Boolean(existingHumanJoinRequest) && !inviteAlreadyAccepted
}
});
const response = toJoinRequestResponse(created);
if (claimSecret) {
- const companyName = await getInviteCompanyName(invite.companyId);
+ const companyBranding = await getInviteCompanyBranding(invite.companyId);
const onboardingManifest = buildInviteOnboardingManifest(
req,
token,
invite,
{
...opts,
- companyName
+ companyName: companyBranding.name
}
);
res.status(202).json({
@@ -2621,22 +3296,26 @@ export function accessRoutes(
res.json(revoked);
});
+ router.get("/companies/:companyId/invites", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ await assertCompanyPermission(req, companyId, "users:invite");
+ const query = listCompanyInvitesQuerySchema.parse(req.query);
+ const invitesForCompany = await loadCompanyInviteRecords(db, companyId, query);
+ res.json(invitesForCompany);
+ });
+
router.get("/companies/:companyId/join-requests", async (req, res) => {
const companyId = req.params.companyId as string;
await assertCompanyPermission(req, companyId, "joins:approve");
const query = listJoinRequestsQuerySchema.parse(req.query);
- const all = await db
- .select()
- .from(joinRequests)
- .where(eq(joinRequests.companyId, companyId))
- .orderBy(desc(joinRequests.createdAt));
+ const all = await loadJoinRequestRecords(db, companyId);
const filtered = all.filter((row) => {
if (query.status && row.status !== query.status) return false;
if (query.requestType && row.requestType !== query.requestType)
return false;
return true;
});
- res.json(filtered.map(toJoinRequestResponse));
+ res.json(filtered);
});
router.post(
@@ -2671,16 +3350,19 @@ export function accessRoutes(
if (existing.requestType === "human") {
if (!existing.requestingUserId)
throw conflict("Join request missing user identity");
+ const membershipRole = resolveHumanInviteRole(
+ invite.defaultsPayload as Record<string, unknown> | null,
+ );
await access.ensureMembership(
companyId,
"user",
existing.requestingUserId,
- "member",
+ membershipRole,
"active"
);
- const grants = grantsFromDefaults(
+ const grants = humanJoinGrantsFromDefaults(
invite.defaultsPayload as Record<string, unknown> | null,
- "human"
+ membershipRole
);
await access.setPrincipalGrants(
companyId,
@@ -2917,10 +3599,241 @@ export function accessRoutes(
router.get("/companies/:companyId/members", async (req, res) => {
const companyId = req.params.companyId as string;
await assertCompanyPermission(req, companyId, "users:manage_permissions");
- const members = await access.listMembers(companyId);
- res.json(members);
+ const [members, currentAccess] = await Promise.all([
+ loadCompanyMemberRecords(db, companyId),
+ loadCompanyAccessSummary(req, access, companyId),
+ ]);
+ res.json({
+ members,
+ access: currentAccess,
+ });
+ });
+
+ router.get("/companies/:companyId/user-directory", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertCompanyAccess(req, companyId);
+ const users = await loadCompanyUserDirectory(db, companyId);
+ res.json({ users });
});
+ router.patch(
+ "/companies/:companyId/members/:memberId",
+ validate(updateCompanyMemberSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const memberId = req.params.memberId as string;
+ await assertCompanyPermission(req, companyId, "users:manage_permissions");
+
+ const updated = await db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select ${companyMemberships.id}
+ from ${companyMemberships}
+ where ${companyMemberships.companyId} = ${companyId}
+ and ${companyMemberships.principalType} = 'user'
+ and ${companyMemberships.status} = 'active'
+ and ${companyMemberships.membershipRole} = 'owner'
+ for update
+ `);
+
+ const existing = await tx
+ .select()
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.id, memberId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+
+ const nextMembershipRole =
+ req.body.membershipRole !== undefined
+ ? req.body.membershipRole
+ : existing.membershipRole;
+ const nextStatus = req.body.status ?? existing.status;
+
+ if (
+ existing.principalType === "user" &&
+ existing.status === "active" &&
+ existing.membershipRole === "owner" &&
+ (nextStatus !== "active" || nextMembershipRole !== "owner")
+ ) {
+ const activeOwnerCount = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ eq(companyMemberships.membershipRole, "owner"),
+ ),
+ )
+ .then((rows) => rows.length);
+ if (activeOwnerCount <= 1) {
+ throw conflict("Cannot remove the last active owner");
+ }
+ }
+
+ return tx
+ .update(companyMemberships)
+ .set({
+ membershipRole: nextMembershipRole,
+ status: nextStatus,
+ updatedAt: new Date(),
+ })
+ .where(eq(companyMemberships.id, existing.id))
+ .returning()
+ .then((rows) => rows[0] ?? existing);
+ });
+ if (!updated) throw notFound("Member not found");
+
+ await logActivity(db, {
+ companyId,
+ actorType: "user",
+ actorId: req.actor.userId ?? "board",
+ action: "company_member.updated",
+ entityType: "company_membership",
+ entityId: memberId,
+ details: {
+ membershipRole: updated.membershipRole,
+ status: updated.status,
+ },
+ });
+
+ const member = (await loadCompanyMemberRecords(db, companyId)).find(
+ (entry) => entry.id === memberId,
+ );
+ if (!member) throw notFound("Member not found");
+ res.json(member);
+ }
+ );
+
+ router.patch(
+ "/companies/:companyId/members/:memberId/role-and-grants",
+ validate(updateCompanyMemberWithPermissionsSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const memberId = req.params.memberId as string;
+ await assertCompanyPermission(req, companyId, "users:manage_permissions");
+
+ const updated = await db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select ${companyMemberships.id}
+ from ${companyMemberships}
+ where ${companyMemberships.companyId} = ${companyId}
+ and ${companyMemberships.principalType} = 'user'
+ and ${companyMemberships.status} = 'active'
+ and ${companyMemberships.membershipRole} = 'owner'
+ for update
+ `);
+
+ const existing = await tx
+ .select()
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.id, memberId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+
+ const nextMembershipRole =
+ req.body.membershipRole !== undefined
+ ? req.body.membershipRole
+ : existing.membershipRole;
+ const nextStatus = req.body.status ?? existing.status;
+
+ if (
+ existing.principalType === "user" &&
+ existing.status === "active" &&
+ existing.membershipRole === "owner" &&
+ (nextStatus !== "active" || nextMembershipRole !== "owner")
+ ) {
+ const activeOwnerCount = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ eq(companyMemberships.membershipRole, "owner"),
+ ),
+ )
+ .then((rows) => rows.length);
+ if (activeOwnerCount <= 1) {
+ throw conflict("Cannot remove the last active owner");
+ }
+ }
+
+ const now = new Date();
+ const updatedMember = await tx
+ .update(companyMemberships)
+ .set({
+ membershipRole: nextMembershipRole,
+ status: nextStatus,
+ updatedAt: now,
+ })
+ .where(eq(companyMemberships.id, existing.id))
+ .returning()
+ .then((rows) => rows[0] ?? existing);
+
+ await tx
+ .delete(principalPermissionGrants)
+ .where(
+ and(
+ eq(principalPermissionGrants.companyId, companyId),
+ eq(principalPermissionGrants.principalType, existing.principalType),
+ eq(principalPermissionGrants.principalId, existing.principalId),
+ ),
+ );
+
+ const grants = (req.body.grants ?? []) as MemberGrantPayload[];
+ if (grants.length > 0) {
+ await tx.insert(principalPermissionGrants).values(
+ grants.map((grant) => ({
+ companyId,
+ principalType: existing.principalType,
+ principalId: existing.principalId,
+ permissionKey: grant.permissionKey,
+ scope: grant.scope ?? null,
+ grantedByUserId: req.actor.userId ?? null,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ );
+ }
+
+ return updatedMember;
+ });
+ if (!updated) throw notFound("Member not found");
+
+ await logActivity(db, {
+ companyId,
+ actorType: "user",
+ actorId: req.actor.userId ?? "board",
+ action: "company_member.access_updated",
+ entityType: "company_membership",
+ entityId: memberId,
+ details: {
+ membershipRole: updated.membershipRole,
+ status: updated.status,
+ grantCount: req.body.grants?.length ?? 0,
+ },
+ });
+
+ const member = (await loadCompanyMemberRecords(db, companyId)).find(
+ (entry) => entry.id === memberId,
+ );
+ if (!member) throw notFound("Member not found");
+ res.json(member);
+ }
+ );
+
router.patch(
"/companies/:companyId/members/:memberId/permissions",
validate(updateMemberPermissionsSchema),
@@ -2935,7 +3848,22 @@ export function accessRoutes(
req.actor.userId ?? null
);
if (!updated) throw notFound("Member not found");
- res.json(updated);
+ await logActivity(db, {
+ companyId,
+ actorType: "user",
+ actorId: req.actor.userId ?? "board",
+ action: "company_member.permissions_updated",
+ entityType: "company_membership",
+ entityId: memberId,
+ details: {
+ grantCount: req.body.grants?.length ?? 0,
+ },
+ });
+ const member = (await loadCompanyMemberRecords(db, companyId)).find(
+ (entry) => entry.id === memberId,
+ );
+ if (!member) throw notFound("Member not found");
+ res.json(member);
}
);
@@ -2949,6 +3877,66 @@ export function accessRoutes(
}
);
+ router.get("/admin/users", async (req, res) => {
+ await assertInstanceAdmin(req);
+ const query = searchAdminUsersQuerySchema.parse(req.query);
+ const needle = query.query.trim().toLowerCase();
+ const users = await db
+ .select({
+ id: authUsers.id,
+ email: authUsers.email,
+ name: authUsers.name,
+ image: authUsers.image,
+ })
+ .from(authUsers)
+ .orderBy(desc(authUsers.updatedAt));
+ const filteredUsers = needle
+ ? users.filter((user) =>
+ [user.name, user.email]
+ .filter((value): value is string => Boolean(value))
+ .some((value) => value.toLowerCase().includes(needle)),
+ )
+ : users;
+ const userIds = filteredUsers.slice(0, 50).map((user) => user.id);
+ const memberships = userIds.length
+ ? await db
+ .select({
+ principalId: companyMemberships.principalId,
+ })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ inArray(companyMemberships.principalId, userIds),
+ ),
+ )
+ : [];
+ const membershipCountByUserId = new Map<string, number>();
+ for (const membership of memberships) {
+ membershipCountByUserId.set(
+ membership.principalId,
+ (membershipCountByUserId.get(membership.principalId) ?? 0) + 1,
+ );
+ }
+ const adminIds = new Set(
+ await Promise.all(
+ userIds.map(async (userId) =>
+ (await access.isInstanceAdmin(userId)) ? userId : null,
+ ),
+ ).then((values) => values.filter((value): value is string => Boolean(value))),
+ );
+
+ res.json(
+ filteredUsers.slice(0, 50).map((user) => ({
+ ...toUserProfile(user),
+ isInstanceAdmin: adminIds.has(user.id),
+ activeCompanyMembershipCount:
+ membershipCountByUserId.get(user.id) ?? 0,
+ })),
+ );
+ });
+
router.post(
"/admin/users/:userId/demote-instance-admin",
async (req, res) => {
@@ -2963,8 +3951,7 @@ export function accessRoutes(
router.get("/admin/users/:userId/company-access", async (req, res) => {
await assertInstanceAdmin(req);
const userId = req.params.userId as string;
- const memberships = await access.listUserCompanyAccess(userId);
- res.json(memberships);
+ res.json(await loadUserCompanyAccessResponse(db, access, userId));
});
router.put(
@@ -2973,11 +3960,11 @@ export function accessRoutes(
async (req, res) => {
await assertInstanceAdmin(req);
const userId = req.params.userId as string;
- const memberships = await access.setUserCompanyAccess(
+ await access.setUserCompanyAccess(
userId,
req.body.companyIds ?? []
);
- res.json(memberships);
+ res.json(await loadUserCompanyAccessResponse(db, access, userId));
}
);
diff --git a/server/src/routes/adapters.ts b/server/src/routes/adapters.ts
index 811060adab..a01f3132ba 100644
--- a/server/src/routes/adapters.ts
+++ b/server/src/routes/adapters.ts
@@ -41,7 +41,7 @@ import type { AdapterPluginRecord } from "../services/adapter-plugin-store.js";
import type { ServerAdapterModule, AdapterConfigSchema } from "../adapters/types.js";
import { loadExternalAdapterPackage, getUiParserSource, getOrExtractUiParserSource, reloadExternalAdapter } from "../adapters/plugin-loader.js";
import { logger } from "../middleware/logger.js";
-import { assertBoard } from "./authz.js";
+import { assertBoardOrgAccess } from "./authz.js";
import { BUILTIN_ADAPTER_TYPES } from "../adapters/builtin-adapter-types.js";
const execFileAsync = promisify(execFile);
@@ -192,7 +192,7 @@ export function adapterRoutes() {
* its model count, and load status.
*/
router.get("/adapters", async (_req, res) => {
- assertBoard(_req);
+ assertBoardOrgAccess(_req);
const registeredAdapters = listServerAdapters();
const externalRecords = new Map(
@@ -218,7 +218,7 @@ export function adapterRoutes() {
* - version?: string — target version for npm packages
*/
router.post("/adapters/install", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { packageName, isLocalPath = false, version } = req.body as AdapterInstallRequest;
@@ -350,7 +350,7 @@ export function adapterRoutes() {
* Request body: { "disabled": boolean }
*/
router.patch("/adapters/:type", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const adapterType = req.params.type;
const { disabled } = req.body as { disabled?: boolean };
@@ -385,7 +385,7 @@ export function adapterRoutes() {
* keep the adapter they started with.
*/
router.patch("/adapters/:type/override", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const adapterType = req.params.type;
const { paused } = req.body as { paused?: boolean };
@@ -413,7 +413,7 @@ export function adapterRoutes() {
* Unregister an external adapter. Built-in adapters cannot be removed.
*/
router.delete("/adapters/:type", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const adapterType = req.params.type;
@@ -488,7 +488,7 @@ export function adapterRoutes() {
* Cannot be used on built-in adapter types.
*/
router.post("/adapters/:type/reload", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const type = req.params.type;
@@ -540,7 +540,7 @@ export function adapterRoutes() {
// This is a convenience shortcut for remove + install with the same
// package name, but without the risk of losing the store record.
router.post("/adapters/:type/reinstall", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const type = req.params.type;
@@ -613,7 +613,7 @@ export function adapterRoutes() {
const CONFIG_SCHEMA_TTL_MS = 30_000;
router.get("/adapters/:type/config-schema", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { type } = req.params;
const adapter = findActiveServerAdapter(type);
@@ -651,7 +651,7 @@ export function adapterRoutes() {
// The adapter package must export a "./ui-parser" entry in package.json
// pointing to a self-contained ESM module with zero runtime dependencies.
router.get("/adapters/:type/ui-parser.js", (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { type } = req.params;
const source = getOrExtractUiParserSource(type);
if (!source) {
diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts
new file mode 100644
index 0000000000..ee94341c8f
--- /dev/null
+++ b/server/src/routes/auth.ts
@@ -0,0 +1,100 @@
+import { Router } from "express";
+import { eq } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { authUsers } from "@paperclipai/db";
+import {
+ authSessionSchema,
+ currentUserProfileSchema,
+ updateCurrentUserProfileSchema,
+} from "@paperclipai/shared";
+import { unauthorized } from "../errors.js";
+import { validate } from "../middleware/validate.js";
+
+async function loadCurrentUserProfile(db: Db, userId: string) {
+ const user = await db
+ .select({
+ id: authUsers.id,
+ email: authUsers.email,
+ name: authUsers.name,
+ image: authUsers.image,
+ })
+ .from(authUsers)
+ .where(eq(authUsers.id, userId))
+ .then((rows) => rows[0] ?? null);
+
+ if (!user) {
+ throw unauthorized("Signed-in user not found");
+ }
+
+ return currentUserProfileSchema.parse({
+ id: user.id,
+ email: user.email ?? null,
+ name: user.name ?? null,
+ image: user.image ?? null,
+ });
+}
+
+export function authRoutes(db: Db) {
+ const router = Router();
+
+ router.get("/get-session", async (req, res) => {
+ if (req.actor.type !== "board" || !req.actor.userId) {
+ throw unauthorized("Board authentication required");
+ }
+
+ const user = await loadCurrentUserProfile(db, req.actor.userId);
+ res.json(authSessionSchema.parse({
+ session: {
+ id: `paperclip:${req.actor.source ?? "none"}:${req.actor.userId}`,
+ userId: req.actor.userId,
+ },
+ user,
+ }));
+ });
+
+ router.get("/profile", async (req, res) => {
+ if (req.actor.type !== "board" || !req.actor.userId) {
+ throw unauthorized("Board authentication required");
+ }
+
+ res.json(await loadCurrentUserProfile(db, req.actor.userId));
+ });
+
+ router.patch("/profile", validate(updateCurrentUserProfileSchema), async (req, res) => {
+ if (req.actor.type !== "board" || !req.actor.userId) {
+ throw unauthorized("Board authentication required");
+ }
+
+ const patch = updateCurrentUserProfileSchema.parse(req.body);
+ const now = new Date();
+
+ const updated = await db
+ .update(authUsers)
+ .set({
+ name: patch.name,
+ ...(patch.image !== undefined ? { image: patch.image } : {}),
+ updatedAt: now,
+ })
+ .where(eq(authUsers.id, req.actor.userId))
+ .returning({
+ id: authUsers.id,
+ email: authUsers.email,
+ name: authUsers.name,
+ image: authUsers.image,
+ })
+ .then((rows) => rows[0] ?? null);
+
+ if (!updated) {
+ throw unauthorized("Signed-in user not found");
+ }
+
+ res.json(currentUserProfileSchema.parse({
+ id: updated.id,
+ email: updated.email ?? null,
+ name: updated.name ?? null,
+ image: updated.image ?? null,
+ }));
+ });
+
+ return router;
+}
diff --git a/server/src/routes/authz.ts b/server/src/routes/authz.ts
index e9017c93a3..ec6c49621d 100644
--- a/server/src/routes/authz.ts
+++ b/server/src/routes/authz.ts
@@ -13,6 +13,24 @@ export function assertBoard(req: Request) {
}
}
+export function hasBoardOrgAccess(req: Request) {
+ if (req.actor.type !== "board") {
+ return false;
+ }
+ if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) {
+ return true;
+ }
+ return Array.isArray(req.actor.companyIds) && req.actor.companyIds.length > 0;
+}
+
+export function assertBoardOrgAccess(req: Request) {
+ assertBoard(req);
+ if (hasBoardOrgAccess(req)) {
+ return;
+ }
+ throw forbidden("Company membership or instance admin access required");
+}
+
export function assertInstanceAdmin(req: Request) {
assertBoard(req);
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) {
@@ -26,11 +44,22 @@ export function assertCompanyAccess(req: Request, companyId: string) {
if (req.actor.type === "agent" && req.actor.companyId !== companyId) {
throw forbidden("Agent key cannot access another company");
}
- if (req.actor.type === "board" && req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin) {
+ if (req.actor.type === "board" && req.actor.source !== "local_implicit") {
const allowedCompanies = req.actor.companyIds ?? [];
if (!allowedCompanies.includes(companyId)) {
throw forbidden("User does not have access to this company");
}
+ const method = typeof req.method === "string" ? req.method.toUpperCase() : "GET";
+ const isSafeMethod = ["GET", "HEAD", "OPTIONS"].includes(method);
+ if (!isSafeMethod && !req.actor.isInstanceAdmin && Array.isArray(req.actor.memberships)) {
+ const membership = req.actor.memberships.find((item) => item.companyId === companyId);
+ if (!membership || membership.status !== "active") {
+ throw forbidden("User does not have active company access");
+ }
+ if (membership.membershipRole === "viewer") {
+ throw forbidden("Viewer access is read-only");
+ }
+ }
}
}
diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts
index d5216e72d8..a1992dd41c 100644
--- a/server/src/routes/health.ts
+++ b/server/src/routes/health.ts
@@ -4,6 +4,7 @@ import { and, count, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { heartbeatRuns, instanceUserRoles, invites } from "@paperclipai/db";
import type { DeploymentExposure, DeploymentMode } from "@paperclipai/shared";
import { readPersistedDevServerStatus, toDevServerHealthStatus } from "../dev-server-status.js";
+import { logger } from "../middleware/logger.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { serverVersion } from "../version.js";
@@ -49,11 +50,12 @@ export function healthRoutes(
try {
await db.execute(sql`SELECT 1`);
- } catch {
+ } catch (error) {
+ logger.warn({ err: error }, "Health check database probe failed");
res.status(503).json({
status: "unhealthy",
version: serverVersion,
- error: "database_unreachable",
+ error: "database_unreachable"
});
return;
}
diff --git a/server/src/routes/instance-settings.ts b/server/src/routes/instance-settings.ts
index 7bd24e36a3..946278ef4e 100644
--- a/server/src/routes/instance-settings.ts
+++ b/server/src/routes/instance-settings.ts
@@ -4,7 +4,7 @@ import { patchInstanceExperimentalSettingsSchema, patchInstanceGeneralSettingsSc
import { forbidden } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { instanceSettingsService, logActivity } from "../services/index.js";
-import { getActorInfo } from "./authz.js";
+import { assertBoardOrgAccess, getActorInfo } from "./authz.js";
function assertCanManageInstanceSettings(req: Request) {
if (req.actor.type !== "board") {
@@ -22,10 +22,8 @@ export function instanceSettingsRoutes(db: Db) {
router.get("/instance/settings/general", async (req, res) => {
// General settings (e.g. keyboardShortcuts) are readable by any
- // authenticated board user. Only PATCH requires instance-admin.
- if (req.actor.type !== "board") {
- throw forbidden("Board access required");
- }
+ // authenticated org member or instance admin. Only PATCH requires instance-admin.
+ assertBoardOrgAccess(req);
res.json(await svc.getGeneral());
});
@@ -60,11 +58,9 @@ export function instanceSettingsRoutes(db: Db) {
);
router.get("/instance/settings/experimental", async (req, res) => {
- // Experimental settings are readable by any authenticated board user.
- // Only PATCH requires instance-admin.
- if (req.actor.type !== "board") {
- throw forbidden("Board access required");
- }
+ // Experimental settings are readable by any authenticated org member
+ // or instance admin. Only PATCH requires instance-admin.
+ assertBoardOrgAccess(req);
res.json(await svc.getExperimental());
});
diff --git a/server/src/routes/plugins.ts b/server/src/routes/plugins.ts
index a6368be9c6..d75912d07c 100644
--- a/server/src/routes/plugins.ts
+++ b/server/src/routes/plugins.ts
@@ -48,7 +48,7 @@ import type { PluginStreamBus } from "../services/plugin-stream-bus.js";
import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js";
import type { ToolRunContext } from "@paperclipai/plugin-sdk";
import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
-import { assertBoard, assertCompanyAccess, assertInstanceAdmin, getActorInfo } from "./authz.js";
+import { assertBoardOrgAccess, assertCompanyAccess, assertInstanceAdmin, getActorInfo } from "./authz.js";
import { validateInstanceConfig } from "../services/plugin-config-validator.js";
/** UI slot declaration extracted from plugin manifest */
@@ -372,7 +372,7 @@ export function pluginRoutes(
* Response: `PluginRecord[]`
*/
router.get("/plugins", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const rawStatus = req.query.status;
if (rawStatus !== undefined) {
if (typeof rawStatus !== "string" || !(PLUGIN_STATUSES as readonly string[]).includes(rawStatus)) {
@@ -396,7 +396,7 @@ export function pluginRoutes(
* These can be installed through the normal local-path install flow.
*/
router.get("/plugins/examples", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
res.json(listBundledPluginExamples());
});
@@ -441,7 +441,7 @@ export function pluginRoutes(
* Response: PluginUiContribution[]
*/
router.get("/plugins/ui-contributions", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const plugins = await registry.listByStatus("ready");
const contributions: PluginUiContribution[] = plugins
@@ -484,7 +484,7 @@ export function pluginRoutes(
* Errors: 501 if tool dispatcher is not configured
*/
router.get("/plugins/tools", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!toolDeps) {
res.status(501).json({ error: "Plugin tool dispatch is not enabled" });
@@ -518,7 +518,7 @@ export function pluginRoutes(
* - 502 if the plugin worker is unavailable or the RPC call fails
*/
router.post("/plugins/tools/execute", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!toolDeps) {
res.status(501).json({ error: "Plugin tool dispatch is not enabled" });
@@ -797,7 +797,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/bridge/data", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@@ -880,7 +880,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/bridge/action", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@@ -964,7 +964,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/data/:key", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@@ -1043,7 +1043,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/actions/:key", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@@ -1124,7 +1124,7 @@ export function pluginRoutes(
* - 501 if bridge deps or stream bus are not configured
*/
router.get("/plugins/:pluginId/bridge/stream/:channel", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps?.streamBus) {
res.status(501).json({ error: "Plugin stream bridge is not enabled" });
@@ -1202,7 +1202,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
if (!plugin) {
@@ -1232,7 +1232,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found, 400 for lifecycle errors
*/
router.delete("/plugins/:pluginId", async (req, res) => {
- assertBoard(req);
+ assertInstanceAdmin(req);
const { pluginId } = req.params;
const purge = req.query.purge === "true";
@@ -1268,7 +1268,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found, 400 for lifecycle errors
*/
router.post("/plugins/:pluginId/enable", async (req, res) => {
- assertBoard(req);
+ assertInstanceAdmin(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
@@ -1306,7 +1306,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found, 400 for lifecycle errors
*/
router.post("/plugins/:pluginId/disable", async (req, res) => {
- assertBoard(req);
+ assertInstanceAdmin(req);
const { pluginId } = req.params;
const body = req.body as { reason?: string } | undefined;
const reason = body?.reason;
@@ -1347,7 +1347,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId/health", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
@@ -1415,7 +1415,7 @@ export function pluginRoutes(
* Response: Array of log entries, newest first.
*/
router.get("/plugins/:pluginId/logs", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
@@ -1517,7 +1517,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId/config", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
@@ -1547,7 +1547,7 @@ export function pluginRoutes(
* - 404 if plugin not found
*/
router.post("/plugins/:pluginId/config", async (req, res) => {
- assertBoard(req);
+ assertInstanceAdmin(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
@@ -1652,7 +1652,7 @@ export function pluginRoutes(
* - 502 if the worker is unavailable
*/
router.post("/plugins/:pluginId/config/test", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@@ -1749,7 +1749,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId/jobs", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!jobDeps) {
res.status(501).json({ error: "Job scheduling is not enabled" });
return;
@@ -1795,7 +1795,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId/jobs/:jobId/runs", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!jobDeps) {
res.status(501).json({ error: "Job scheduling is not enabled" });
return;
@@ -1843,7 +1843,7 @@ export function pluginRoutes(
* - 400 if job not found, not active, already running, or worker unavailable
*/
router.post("/plugins/:pluginId/jobs/:jobId/trigger", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
if (!jobDeps) {
res.status(501).json({ error: "Job scheduling is not enabled" });
return;
@@ -2049,7 +2049,7 @@ export function pluginRoutes(
* Errors: 404 if plugin not found
*/
router.get("/plugins/:pluginId/dashboard", async (req, res) => {
- assertBoard(req);
+ assertBoardOrgAccess(req);
const { pluginId } = req.params;
const plugin = await resolvePlugin(registry, pluginId);
diff --git a/server/src/routes/sidebar-badges.ts b/server/src/routes/sidebar-badges.ts
index 505b770475..8b4d1f2285 100644
--- a/server/src/routes/sidebar-badges.ts
+++ b/server/src/routes/sidebar-badges.ts
@@ -5,6 +5,7 @@ import { inboxDismissals, joinRequests } from "@paperclipai/db";
import { sidebarBadgeService } from "../services/sidebar-badges.js";
import { accessService } from "../services/access.js";
import { dashboardService } from "../services/dashboard.js";
+import { collapseDuplicatePendingHumanJoinRequests } from "../lib/join-request-dedupe.js";
import { assertCompanyAccess } from "./authz.js";
function buildDismissedAtByKey(
@@ -35,14 +36,24 @@ export function sidebarBadgeRoutes(db: Db) {
}
const visibleJoinRequests = canApproveJoins
- ? await db
- .select({
- id: joinRequests.id,
- updatedAt: joinRequests.updatedAt,
- createdAt: joinRequests.createdAt,
- })
- .from(joinRequests)
- .where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.status, "pending_approval")))
+ ? collapseDuplicatePendingHumanJoinRequests(
+ await db
+ .select({
+ id: joinRequests.id,
+ requestType: joinRequests.requestType,
+ status: joinRequests.status,
+ requestingUserId: joinRequests.requestingUserId,
+ requestEmailSnapshot: joinRequests.requestEmailSnapshot,
+ updatedAt: joinRequests.updatedAt,
+ createdAt: joinRequests.createdAt,
+ })
+ .from(joinRequests)
+ .where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.status, "pending_approval")))
+ ).map(({ id, updatedAt, createdAt }) => ({
+ id,
+ updatedAt,
+ createdAt,
+ }))
: [];
const dismissedAtByKey =
diff --git a/server/src/services/access.ts b/server/src/services/access.ts
index 3e30e1ab3b..792c28f460 100644
--- a/server/src/services/access.ts
+++ b/server/src/services/access.ts
@@ -6,6 +6,7 @@ import {
principalPermissionGrants,
} from "@paperclipai/db";
import type { PermissionKey, PrincipalType } from "@paperclipai/shared";
+import { conflict } from "../errors.js";
type MembershipRow = typeof companyMemberships.$inferSelect;
type GrantInput = {
@@ -83,6 +84,14 @@ export function accessService(db: Db) {
.orderBy(sql`${companyMemberships.createdAt} desc`);
}
+ async function getMemberById(companyId: string, memberId: string) {
+ return db
+ .select()
+ .from(companyMemberships)
+ .where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
+ .then((rows) => rows[0] ?? null);
+ }
+
async function listActiveUserMemberships(companyId: string) {
return db
.select()
@@ -103,11 +112,7 @@ export function accessService(db: Db) {
grants: GrantInput[],
grantedByUserId: string | null,
) {
- const member = await db
- .select()
- .from(companyMemberships)
- .where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
- .then((rows) => rows[0] ?? null);
+ const member = await getMemberById(companyId, memberId);
if (!member) return null;
await db.transaction(async (tx) => {
@@ -139,6 +144,101 @@ export function accessService(db: Db) {
return member;
}
+ async function updateMemberAndPermissions(
+ companyId: string,
+ memberId: string,
+ data: {
+ membershipRole?: string | null;
+ status?: "pending" | "active" | "suspended";
+ grants: GrantInput[];
+ },
+ grantedByUserId: string | null,
+ ) {
+ return db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select ${companyMemberships.id}
+ from ${companyMemberships}
+ where ${companyMemberships.companyId} = ${companyId}
+ and ${companyMemberships.principalType} = 'user'
+ and ${companyMemberships.status} = 'active'
+ and ${companyMemberships.membershipRole} = 'owner'
+ for update
+ `);
+
+ const existing = await tx
+ .select()
+ .from(companyMemberships)
+ .where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+
+ const nextMembershipRole =
+ data.membershipRole !== undefined ? data.membershipRole : existing.membershipRole;
+ const nextStatus = data.status ?? existing.status;
+
+ if (
+ existing.principalType === "user" &&
+ existing.status === "active" &&
+ existing.membershipRole === "owner" &&
+ (nextStatus !== "active" || nextMembershipRole !== "owner")
+ ) {
+ const activeOwnerCount = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ eq(companyMemberships.membershipRole, "owner"),
+ ),
+ )
+ .then((rows) => rows.length);
+ if (activeOwnerCount <= 1) {
+ throw conflict("Cannot remove the last active owner");
+ }
+ }
+
+ const now = new Date();
+ const updated = await tx
+ .update(companyMemberships)
+ .set({
+ membershipRole: nextMembershipRole,
+ status: nextStatus,
+ updatedAt: now,
+ })
+ .where(eq(companyMemberships.id, existing.id))
+ .returning()
+ .then((rows) => rows[0] ?? existing);
+
+ await tx
+ .delete(principalPermissionGrants)
+ .where(
+ and(
+ eq(principalPermissionGrants.companyId, companyId),
+ eq(principalPermissionGrants.principalType, existing.principalType),
+ eq(principalPermissionGrants.principalId, existing.principalId),
+ ),
+ );
+ if (data.grants.length > 0) {
+ await tx.insert(principalPermissionGrants).values(
+ data.grants.map((grant) => ({
+ companyId,
+ principalType: existing.principalType,
+ principalId: existing.principalId,
+ permissionKey: grant.permissionKey,
+ scope: grant.scope ?? null,
+ grantedByUserId,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ );
+ }
+
+ return updated;
+ });
+ }
+
async function promoteInstanceAdmin(userId: string) {
const existing = await db
.select()
@@ -190,7 +290,7 @@ export function accessService(db: Db) {
principalType: "user",
principalId: userId,
status: "active",
- membershipRole: "member",
+ membershipRole: "operator",
});
}
});
@@ -359,16 +459,84 @@ export function accessService(db: Db) {
});
}
+ async function updateMember(
+ companyId: string,
+ memberId: string,
+ data: {
+ membershipRole?: string | null;
+ status?: "pending" | "active" | "suspended";
+ },
+ ) {
+ return db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select ${companyMemberships.id}
+ from ${companyMemberships}
+ where ${companyMemberships.companyId} = ${companyId}
+ and ${companyMemberships.principalType} = 'user'
+ and ${companyMemberships.status} = 'active'
+ and ${companyMemberships.membershipRole} = 'owner'
+ for update
+ `);
+
+ const existing = await tx
+ .select()
+ .from(companyMemberships)
+ .where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+
+ const nextMembershipRole =
+ data.membershipRole !== undefined ? data.membershipRole : existing.membershipRole;
+ const nextStatus = data.status ?? existing.status;
+
+ if (
+ existing.principalType === "user" &&
+ existing.status === "active" &&
+ existing.membershipRole === "owner" &&
+ (nextStatus !== "active" || nextMembershipRole !== "owner")
+ ) {
+ const activeOwnerCount = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ eq(companyMemberships.membershipRole, "owner"),
+ ),
+ )
+ .then((rows) => rows.length);
+ if (activeOwnerCount <= 1) {
+ throw conflict("Cannot remove the last active owner");
+ }
+ }
+
+ return tx
+ .update(companyMemberships)
+ .set({
+ membershipRole: nextMembershipRole,
+ status: nextStatus,
+ updatedAt: new Date(),
+ })
+ .where(eq(companyMemberships.id, existing.id))
+ .returning()
+ .then((rows) => rows[0] ?? existing);
+ });
+ }
+
return {
isInstanceAdmin,
canUser,
hasPermission,
getMembership,
+ getMemberById,
ensureMembership,
listMembers,
listActiveUserMemberships,
copyActiveUserMemberships,
setMemberPermissions,
+ updateMemberAndPermissions,
promoteInstanceAdmin,
demoteInstanceAdmin,
listUserCompanyAccess,
@@ -376,5 +544,6 @@ export function accessService(db: Db) {
setPrincipalGrants,
listPrincipalGrants,
setPrincipalPermission,
+ updateMember,
};
}
diff --git a/server/src/services/board-auth.ts b/server/src/services/board-auth.ts
index 19e533c116..0637457c54 100644
--- a/server/src/services/board-auth.ts
+++ b/server/src/services/board-auth.ts
@@ -62,7 +62,11 @@ export function boardAuthService(db: Db) {
.where(eq(authUsers.id, userId))
.then((rows) => rows[0] ?? null),
db
- .select({ companyId: companyMemberships.companyId })
+ .select({
+ companyId: companyMemberships.companyId,
+ membershipRole: companyMemberships.membershipRole,
+ status: companyMemberships.status,
+ })
.from(companyMemberships)
.where(
and(
@@ -71,7 +75,7 @@ export function boardAuthService(db: Db) {
eq(companyMemberships.status, "active"),
),
)
- .then((rows) => rows.map((row) => row.companyId)),
+ .then((rows) => rows),
db
.select({ id: instanceUserRoles.id })
.from(instanceUserRoles)
@@ -81,7 +85,8 @@ export function boardAuthService(db: Db) {
return {
user,
- companyIds: memberships,
+ companyIds: memberships.map((row) => row.companyId),
+ memberships,
isInstanceAdmin: Boolean(adminRole),
};
}
diff --git a/server/src/services/company-member-roles.ts b/server/src/services/company-member-roles.ts
new file mode 100644
index 0000000000..6e8513ee45
--- /dev/null
+++ b/server/src/services/company-member-roles.ts
@@ -0,0 +1,59 @@
+import { PERMISSION_KEYS } from "@paperclipai/shared";
+import type { HumanCompanyMembershipRole } from "@paperclipai/shared";
+
+const HUMAN_COMPANY_MEMBERSHIP_ROLES: HumanCompanyMembershipRole[] = [
+ "owner",
+ "admin",
+ "operator",
+ "viewer",
+];
+
+export function normalizeHumanRole(
+ value: unknown,
+ fallback: HumanCompanyMembershipRole = "operator"
+): HumanCompanyMembershipRole {
+ if (value === "member") return "operator";
+ return HUMAN_COMPANY_MEMBERSHIP_ROLES.includes(value as HumanCompanyMembershipRole)
+ ? (value as HumanCompanyMembershipRole)
+ : fallback;
+}
+
+export function grantsForHumanRole(
+ role: HumanCompanyMembershipRole
+): Array<{
+ permissionKey: (typeof PERMISSION_KEYS)[number];
+ scope: Record<string, unknown> | null;
+}> {
+ switch (role) {
+ case "owner":
+ return [
+ { permissionKey: "agents:create", scope: null },
+ { permissionKey: "users:invite", scope: null },
+ { permissionKey: "users:manage_permissions", scope: null },
+ { permissionKey: "tasks:assign", scope: null },
+ { permissionKey: "joins:approve", scope: null },
+ ];
+ case "admin":
+ return [
+ { permissionKey: "agents:create", scope: null },
+ { permissionKey: "users:invite", scope: null },
+ { permissionKey: "tasks:assign", scope: null },
+ { permissionKey: "joins:approve", scope: null },
+ ];
+ case "operator":
+ return [{ permissionKey: "tasks:assign", scope: null }];
+ case "viewer":
+ return [];
+ }
+}
+
+export function resolveHumanInviteRole(
+ defaultsPayload: Record<string, unknown> | null | undefined
+): HumanCompanyMembershipRole {
+ if (!defaultsPayload || typeof defaultsPayload !== "object") return "operator";
+ const scoped = defaultsPayload.human;
+ if (!scoped || typeof scoped !== "object" || Array.isArray(scoped)) {
+ return "operator";
+ }
+ return normalizeHumanRole((scoped as Record<string, unknown>).role, "operator");
+}
diff --git a/server/src/services/invite-grants.ts b/server/src/services/invite-grants.ts
new file mode 100644
index 0000000000..32c9aa42fe
--- /dev/null
+++ b/server/src/services/invite-grants.ts
@@ -0,0 +1,68 @@
+import { PERMISSION_KEYS } from "@paperclipai/shared";
+import type { HumanCompanyMembershipRole } from "@paperclipai/shared";
+import { grantsForHumanRole } from "./company-member-roles.js";
+
+export function grantsFromDefaults(
+ defaultsPayload: Record<string, unknown> | null | undefined,
+ key: "human" | "agent"
+): Array<{
+ permissionKey: (typeof PERMISSION_KEYS)[number];
+ scope: Record<string, unknown> | null;
+}> {
+ if (!defaultsPayload || typeof defaultsPayload !== "object") return [];
+ const scoped = defaultsPayload[key];
+ if (!scoped || typeof scoped !== "object") return [];
+ const grants = (scoped as Record<string, unknown>).grants;
+ if (!Array.isArray(grants)) return [];
+ const validPermissionKeys = new Set<string>(PERMISSION_KEYS);
+ const result: Array<{
+ permissionKey: (typeof PERMISSION_KEYS)[number];
+ scope: Record<string, unknown> | null;
+ }> = [];
+ for (const item of grants) {
+ if (!item || typeof item !== "object") continue;
+ const record = item as Record<string, unknown>;
+ if (typeof record.permissionKey !== "string") continue;
+ if (!validPermissionKeys.has(record.permissionKey)) continue;
+ result.push({
+ permissionKey: record.permissionKey as (typeof PERMISSION_KEYS)[number],
+ scope:
+ record.scope &&
+ typeof record.scope === "object" &&
+ !Array.isArray(record.scope)
+ ? (record.scope as Record<string, unknown>)
+ : null,
+ });
+ }
+ return result;
+}
+
+export function agentJoinGrantsFromDefaults(
+ defaultsPayload: Record<string, unknown> | null | undefined
+): Array<{
+ permissionKey: (typeof PERMISSION_KEYS)[number];
+ scope: Record<string, unknown> | null;
+}> {
+ const grants = grantsFromDefaults(defaultsPayload, "agent");
+ if (grants.some((grant) => grant.permissionKey === "tasks:assign")) {
+ return grants;
+ }
+ return [
+ ...grants,
+ {
+ permissionKey: "tasks:assign",
+ scope: null,
+ },
+ ];
+}
+
+export function humanJoinGrantsFromDefaults(
+ defaultsPayload: Record<string, unknown> | null | undefined,
+ membershipRole: HumanCompanyMembershipRole
+): Array<{
+ permissionKey: (typeof PERMISSION_KEYS)[number];
+ scope: Record<string, unknown> | null;
+}> {
+ const grants = grantsFromDefaults(defaultsPayload, "human");
+ return grants.length > 0 ? grants : grantsForHumanRole(membershipRole);
+}
diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts
index 78b301eef3..1915e2ffdb 100644
--- a/server/src/types/express.d.ts
+++ b/server/src/types/express.d.ts
@@ -6,9 +6,16 @@ declare global {
actor: {
type: "board" | "agent" | "none";
userId?: string;
+ userName?: string | null;
+ userEmail?: string | null;
agentId?: string;
companyId?: string;
companyIds?: string[];
+ memberships?: Array<{
+ companyId: string;
+ membershipRole?: string | null;
+ status?: string;
+ }>;
isInstanceAdmin?: boolean;
keyId?: string;
runId?: string;
diff --git a/server/src/worktree-config.ts b/server/src/worktree-config.ts
index 3656b7dc6a..2c6170bca5 100644
--- a/server/src/worktree-config.ts
+++ b/server/src/worktree-config.ts
@@ -118,11 +118,19 @@ function resolveWorktreeRuntimeContext(
const configPath = resolvePaperclipConfigPath(overrideConfigPath);
const envPath = resolvePaperclipEnvPath(configPath);
+ const persistedEnv = readEnvEntries(envPath);
const worktreeRoot = path.resolve(path.dirname(configPath), "..");
- const worktreeName = nonEmpty(env.PAPERCLIP_WORKTREE_NAME) ?? path.basename(worktreeRoot);
- const instanceId = nonEmpty(env.PAPERCLIP_INSTANCE_ID) ?? sanitizeWorktreeInstanceId(worktreeName);
+ const worktreeName =
+ nonEmpty(persistedEnv.PAPERCLIP_WORKTREE_NAME) ??
+ nonEmpty(env.PAPERCLIP_WORKTREE_NAME) ??
+ path.basename(worktreeRoot);
+ const instanceId =
+ nonEmpty(persistedEnv.PAPERCLIP_INSTANCE_ID) ??
+ nonEmpty(env.PAPERCLIP_INSTANCE_ID) ??
+ sanitizeWorktreeInstanceId(worktreeName);
const homeDir = resolveHomeAwarePath(
- nonEmpty(env.PAPERCLIP_HOME) ??
+ nonEmpty(persistedEnv.PAPERCLIP_HOME) ??
+ nonEmpty(env.PAPERCLIP_HOME) ??
nonEmpty(env.PAPERCLIP_WORKTREES_DIR) ??
"~/.paperclip-worktrees",
);
diff --git a/tests/e2e/multi-user-authenticated.spec.ts b/tests/e2e/multi-user-authenticated.spec.ts
new file mode 100644
index 0000000000..2652da389f
--- /dev/null
+++ b/tests/e2e/multi-user-authenticated.spec.ts
@@ -0,0 +1,326 @@
+import { execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import path from "node:path";
+import { test, expect, type Browser, type Page } from "@playwright/test";
+
+const BASE = process.env.PAPERCLIP_E2E_BASE_URL ?? "http://127.0.0.1:3105";
+const DATA_DIR = process.env.PAPERCLIP_E2E_DATA_DIR ?? process.env.PAPERCLIP_HOME;
+const CONFIG_PATH = process.env.PAPERCLIP_E2E_CONFIG_PATH ?? path.resolve(process.cwd(), ".paperclip/config.json");
+const BOOTSTRAP_SCRIPT_PATH = path.resolve(process.cwd(), "packages/db/scripts/create-auth-bootstrap-invite.ts");
+const OWNER_PASSWORD = "paperclip-owner-password";
+const INVITED_PASSWORD = "paperclip-invited-password";
+
+type HumanUser = {
+ name: string;
+ email: string;
+ password: string;
+};
+
+type CompanySummary = {
+ id: string;
+ name: string;
+ issuePrefix?: string | null;
+};
+
+type CompanyMember = {
+ id: string;
+ membershipRole: "owner" | "admin" | "operator" | "viewer";
+ status: "pending" | "active" | "suspended";
+ user: { id: string; email: string | null; name: string | null } | null;
+};
+
+type SessionJsonResponse<T> = {
+ ok: boolean;
+ status: number;
+ text: string;
+ json: T | null;
+};
+
+const runId = Date.now();
+const companyName = `MU-Auth-${runId}`;
+const ownerUser: HumanUser = {
+ name: "Owner User",
+ email: `owner-${runId}@paperclip.local`,
+ password: OWNER_PASSWORD,
+};
+const invitedUser: HumanUser = {
+ name: "Invited User",
+ email: `invitee-${runId}@paperclip.local`,
+ password: INVITED_PASSWORD,
+};
+
+function createBootstrapInvite() {
+ if (!DATA_DIR) {
+ throw new Error("PAPERCLIP_E2E_DATA_DIR or PAPERCLIP_HOME is required for authenticated bootstrap tests");
+ }
+ if (!existsSync(CONFIG_PATH)) {
+ throw new Error(`Authenticated bootstrap config not found at ${CONFIG_PATH}`);
+ }
+ if (!existsSync(BOOTSTRAP_SCRIPT_PATH)) {
+ throw new Error(`Authenticated bootstrap helper not found at ${BOOTSTRAP_SCRIPT_PATH}`);
+ }
+
+ const pnpmCommand = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
+ return execFileSync(
+ pnpmCommand,
+ [
+ "--filter",
+ "@paperclipai/db",
+ "exec",
+ "tsx",
+ BOOTSTRAP_SCRIPT_PATH,
+ "--config",
+ CONFIG_PATH,
+ "--base-url",
+ BASE,
+ ],
+ {
+ cwd: process.cwd(),
+ env: {
+ ...process.env,
+ FORCE_COLOR: "0",
+ NO_COLOR: "1",
+ PAPERCLIP_HOME: DATA_DIR,
+ },
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ }
+ ).trim();
+}
+
+async function signUp(page: Page, user: HumanUser) {
+ await page.goto(`${BASE}/auth`);
+ await expect(page.getByRole("heading", { name: "Sign in to Paperclip" })).toBeVisible();
+ await page.getByRole("button", { name: "Create one" }).click();
+ await expect(page.getByRole("heading", { name: "Create your Paperclip account" })).toBeVisible();
+ await page.getByLabel("Name").fill(user.name);
+ await page.getByLabel("Email").fill(user.email);
+ await page.getByLabel("Password").fill(user.password);
+ await page.getByRole("button", { name: "Create Account" }).click();
+ await expect(page).not.toHaveURL(/\/auth/, { timeout: 20_000 });
+}
+
+async function acceptBootstrapInvite(page: Page, inviteUrl: string) {
+ await page.goto(inviteUrl);
+ await expect(page.getByRole("heading", { name: "Bootstrap your Paperclip instance" })).toBeVisible();
+ await page.getByRole("button", { name: "Accept bootstrap invite" }).click();
+ await expect(page.getByRole("heading", { name: "Bootstrap complete" })).toBeVisible({
+ timeout: 20_000,
+ });
+ await page.getByRole("link", { name: "Open board" }).click();
+}
+
+async function createCompanyForSession(page: Page, nextCompanyName: string) {
+ const createRes = await sessionJsonRequest<CompanySummary>(page, `${BASE}/api/companies`, {
+ method: "POST",
+ data: { name: nextCompanyName },
+ });
+ expect(createRes.ok).toBe(true);
+ expect(createRes.json).toBeTruthy();
+ return createRes.json!;
+}
+
+async function createAuthenticatedInvite(page: Page, companyPrefix: string) {
+ await page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ await expect(page.getByTestId("company-settings-invites-section")).toBeVisible({
+ timeout: 20_000,
+ });
+ await page.getByTestId("company-settings-human-invite-role").selectOption("operator");
+ await page.getByTestId("company-settings-create-human-invite").click();
+ const inviteField = page.getByTestId("company-settings-human-invite-url");
+ await expect(inviteField).toBeVisible({ timeout: 20_000 });
+ return (await inviteField.inputValue()).trim();
+}
+
+async function signUpFromInvite(page: Page, inviteUrl: string, user: HumanUser) {
+ await page.goto(inviteUrl);
+ await expect(page.getByText("Sign in or create an account before submitting a human join request.")).toBeVisible();
+ await page.getByRole("link", { name: "Sign in / Create account" }).click();
+ await expect(page).toHaveURL(/\/auth\?next=/);
+ await expect(page.getByRole("heading", { name: "Sign in to Paperclip" })).toBeVisible();
+ await page.getByRole("button", { name: "Create one" }).click();
+ await page.getByLabel("Name").fill(user.name);
+ await page.getByLabel("Email").fill(user.email);
+ await page.getByLabel("Password").fill(user.password);
+ await page.getByRole("button", { name: "Create Account" }).click();
+ await expect(page).toHaveURL(new RegExp(`/invite/[^/]+$`), { timeout: 20_000 });
+}
+
+async function acceptHumanInvite(page: Page) {
+ await expect(page.getByRole("button", { name: "Join company" })).toBeEnabled();
+ await page.getByRole("button", { name: "Join company" }).click();
+ await expect(page.getByRole("heading", { name: "You joined the company" })).toBeVisible({
+ timeout: 20_000,
+ });
+ await page.getByRole("link", { name: "Open board" }).click();
+}
+
+async function sessionJsonRequest<T>(
+ page: Page,
+ url: string,
+ options: {
+ method?: string;
+ data?: unknown;
+ } = {}
+) {
+ return page.evaluate(
+ async ({ url: targetUrl, method, data }) => {
+ const response = await fetch(targetUrl, {
+ method,
+ credentials: "include",
+ headers: data === undefined ? undefined : { "Content-Type": "application/json" },
+ body: data === undefined ? undefined : JSON.stringify(data),
+ });
+ const text = await response.text();
+ let json: unknown = null;
+ if (text.length > 0) {
+ try {
+ json = JSON.parse(text);
+ } catch {
+ json = null;
+ }
+ }
+ return {
+ ok: response.ok,
+ status: response.status,
+ text,
+ json,
+ };
+ },
+ {
+ url,
+ method: options.method ?? "GET",
+ data: options.data,
+ }
+ ) as Promise<SessionJsonResponse<T>>;
+}
+
+async function waitForMember(page: Page, companyId: string, email: string) {
+ let member: CompanyMember | null = null;
+ await expect
+ .poll(
+ async () => {
+ const membersRes = await sessionJsonRequest<{ members: CompanyMember[] }>(
+ page,
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ expect(membersRes.ok).toBe(true);
+ const body = membersRes.json;
+ if (!body) return null;
+ member = body.members.find((entry) => entry.user?.email === email) ?? null;
+ return member;
+ },
+ {
+ timeout: 20_000,
+ intervals: [500, 1_000, 2_000],
+ }
+ )
+ .toMatchObject({
+ status: "active",
+ membershipRole: "operator",
+ user: { email },
+ });
+ return member!;
+}
+
+async function waitForMemberRole(
+ page: Page,
+ companyId: string,
+ memberId: string,
+ membershipRole: CompanyMember["membershipRole"]
+) {
+ await expect
+ .poll(
+ async () => {
+ const membersRes = await sessionJsonRequest<{ members: CompanyMember[] }>(
+ page,
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ expect(membersRes.ok).toBe(true);
+ const body = membersRes.json;
+ if (!body) return null;
+ return body.members.find((member) => member.id === memberId) ?? null;
+ },
+ {
+ timeout: 20_000,
+ intervals: [500, 1_000, 2_000],
+ }
+ )
+ .toMatchObject({
+ id: memberId,
+ membershipRole,
+ });
+}
+
+async function newPage(browser: Browser) {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ return { context, page };
+}
+
+test.describe("Multi-user: authenticated mode", () => {
+ test("authenticated humans can bootstrap, invite, join, and respect viewer restrictions", async ({
+ browser,
+ page,
+ }) => {
+ test.setTimeout(180_000);
+
+ const healthRes = await page.request.get(`${BASE}/api/health`);
+ expect(healthRes.ok()).toBe(true);
+ const health = (await healthRes.json()) as {
+ deploymentMode?: string;
+ bootstrapStatus?: string;
+ };
+ expect(health.deploymentMode).toBe("authenticated");
+
+ await signUp(page, ownerUser);
+ await acceptBootstrapInvite(page, createBootstrapInvite());
+
+ const company = await createCompanyForSession(page, companyName);
+ const companyPrefix = company.issuePrefix ?? company.id;
+ await page.goto(`${BASE}/${companyPrefix}/dashboard`);
+ await expect(page.getByTestId("layout-account-menu-trigger")).toContainText(ownerUser.name);
+ await page.getByTestId("layout-account-menu-trigger").click();
+ await expect(page.getByText(ownerUser.email)).toBeVisible();
+ const inviteUrl = await createAuthenticatedInvite(page, companyPrefix);
+
+ const invited = await newPage(browser);
+ try {
+ await signUpFromInvite(invited.page, inviteUrl, invitedUser);
+ await acceptHumanInvite(invited.page);
+ await expect(invited.page).not.toHaveURL(/\/auth/, { timeout: 10_000 });
+
+ const joinedMember = await waitForMember(page, company.id, invitedUser.email);
+
+ await page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ const roleSelect = page.getByTestId(`company-settings-member-role-${joinedMember.id}`);
+ await expect(roleSelect).toBeVisible({ timeout: 20_000 });
+ await roleSelect.selectOption("viewer");
+ await expect(roleSelect).toHaveValue("viewer");
+ await waitForMemberRole(page, company.id, joinedMember.id, "viewer");
+
+ await invited.page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ await expect(
+ invited.page.getByText("Your current company role cannot create human invites.")
+ ).toBeVisible({ timeout: 20_000 });
+ await expect(
+ invited.page.getByTestId("company-settings-create-human-invite")
+ ).toHaveCount(0);
+
+ const forbiddenInviteRes = await sessionJsonRequest(
+ invited.page,
+ `${BASE}/api/companies/${company.id}/invites`,
+ {
+ method: "POST",
+ data: {
+ allowedJoinTypes: "human",
+ humanRole: "viewer",
+ },
+ }
+ );
+ expect(forbiddenInviteRes.status).toBe(403);
+ } finally {
+ await invited.context.close();
+ }
+ });
+});
diff --git a/tests/e2e/multi-user.spec.ts b/tests/e2e/multi-user.spec.ts
new file mode 100644
index 0000000000..d03eac3553
--- /dev/null
+++ b/tests/e2e/multi-user.spec.ts
@@ -0,0 +1,518 @@
+import { test, expect, type Page, type APIRequestContext } from "@playwright/test";
+
+/**
+ * E2E: Multi-user implementation tests (local_trusted mode).
+ *
+ * Covers:
+ * 1. Company member management API (list, update role, suspend)
+ * 2. Human invite creation and acceptance API
+ * 3. Company Settings UI — member list, role editing, invite creation
+ * 4. Invite landing page UI
+ * 5. Role-based access control (viewer read-only)
+ * 6. Last-owner protection
+ */
+
+const BASE = process.env.PAPERCLIP_E2E_BASE_URL ?? "http://127.0.0.1:3104";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/** Ensure the server is bootstrapped (claimed) before running tests. */
+async function ensureBootstrapped(request: APIRequestContext): Promise<void> {
+ const healthRes = await request.get(`${BASE}/api/health`);
+ const health = await healthRes.json();
+ if (health.bootstrapStatus === "ready") return;
+
+ // If bootstrap_pending, we need to use the claim token from the bootstrap invite.
+ // In local_trusted mode, just try hitting companies — that should auto-bootstrap.
+ if (health.deploymentMode === "local_trusted") {
+ // local_trusted should work without explicit bootstrap
+ return;
+ }
+}
+
+/** Create a company via the onboarding wizard API shortcut. */
+async function createCompanyViaWizard(
+ request: APIRequestContext,
+ name: string
+): Promise<{ companyId: string; agentId: string; prefix: string }> {
+ await ensureBootstrapped(request);
+
+ const createRes = await request.post(`${BASE}/api/companies`, {
+ data: { name },
+ });
+ if (!createRes.ok()) {
+ const errText = await createRes.text();
+ throw new Error(
+ `Failed to create company (${createRes.status()}): ${errText}`
+ );
+ }
+ const company = await createRes.json();
+
+ // Create a CEO agent
+ const agentRes = await request.post(
+ `${BASE}/api/companies/${company.id}/agents`,
+ {
+ data: {
+ name: "CEO",
+ role: "ceo",
+ title: "CEO",
+ adapterType: "claude_local",
+ },
+ }
+ );
+ expect(agentRes.ok()).toBe(true);
+ const agent = await agentRes.json();
+
+ return {
+ companyId: company.id,
+ agentId: agent.id,
+ prefix: company.issuePrefix ?? company.id,
+ };
+}
+
+/** Create a human invite and return token + invite URL. */
+async function createHumanInvite(
+ request: APIRequestContext,
+ companyId: string,
+ role: string = "operator"
+): Promise<{ token: string; inviteUrl: string; inviteId: string }> {
+ const res = await request.post(
+ `${BASE}/api/companies/${companyId}/invites`,
+ {
+ data: {
+ allowedJoinTypes: "human",
+ humanRole: role,
+ },
+ }
+ );
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+ return {
+ token: body.token,
+ inviteUrl: body.inviteUrl,
+ inviteId: body.id,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+test.describe("Multi-user: API", () => {
+ let companyId: string;
+
+ test.beforeAll(async ({ request }) => {
+ const result = await createCompanyViaWizard(
+ request,
+ `MU-API-${Date.now()}`
+ );
+ companyId = result.companyId;
+ });
+
+ test("GET /companies/:id/members returns member list with access info", async ({
+ request,
+ }) => {
+ const res = await request.get(
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+
+ expect(body).toHaveProperty("members");
+ expect(body).toHaveProperty("access");
+ expect(Array.isArray(body.members)).toBe(true);
+ expect(body.access).toHaveProperty("currentUserRole");
+ expect(body.access).toHaveProperty("canManageMembers");
+ expect(body.access).toHaveProperty("canInviteUsers");
+ });
+
+ test("POST /companies/:id/invites creates a human invite with role", async ({
+ request,
+ }) => {
+ const res = await request.post(
+ `${BASE}/api/companies/${companyId}/invites`,
+ {
+ data: {
+ allowedJoinTypes: "human",
+ humanRole: "operator",
+ },
+ }
+ );
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+
+ expect(body).toHaveProperty("token");
+ expect(body).toHaveProperty("inviteUrl");
+ expect(body.allowedJoinTypes).toBe("human");
+ expect(body.inviteUrl).toContain("/invite/");
+ });
+
+ test("GET /invites/:token returns invite summary", async ({ request }) => {
+ const invite = await createHumanInvite(request, companyId, "viewer");
+ const res = await request.get(`${BASE}/api/invites/${invite.token}`);
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+
+ expect(body).toHaveProperty("companyId");
+ expect(body).toHaveProperty("allowedJoinTypes");
+ expect(body.allowedJoinTypes).toBe("human");
+ expect(body).toHaveProperty("inviteType");
+ expect(body.inviteType).toBe("company_join");
+ });
+
+ test("POST /invites/:token/accept (human) creates membership", async ({
+ request,
+ }) => {
+ const invite = await createHumanInvite(request, companyId, "operator");
+ const acceptRes = await request.post(
+ `${BASE}/api/invites/${invite.token}/accept`,
+ {
+ data: { requestType: "human" },
+ }
+ );
+ expect(acceptRes.ok()).toBe(true);
+ const body = await acceptRes.json();
+
+ // In local_trusted, human accept should succeed
+ expect(body).toHaveProperty("id");
+ });
+
+ test("POST /invites/:token/accept rejects agent on human-only invite", async ({
+ request,
+ }) => {
+ const invite = await createHumanInvite(request, companyId, "operator");
+ const acceptRes = await request.post(
+ `${BASE}/api/invites/${invite.token}/accept`,
+ {
+ data: { requestType: "agent", agentName: "Rogue" },
+ }
+ );
+ expect(acceptRes.ok()).toBe(false);
+ expect(acceptRes.status()).toBe(400);
+ });
+
+ test("POST /companies/:id/invites supports all four roles", async ({
+ request,
+ }) => {
+ for (const role of ["owner", "admin", "operator", "viewer"]) {
+ const res = await request.post(
+ `${BASE}/api/companies/${companyId}/invites`,
+ {
+ data: { allowedJoinTypes: "human", humanRole: role },
+ }
+ );
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+ expect(body.token).toBeTruthy();
+ }
+ });
+
+ test("PATCH /companies/:id/members/:memberId cannot remove last owner", async ({
+ request,
+ }) => {
+ // Create a fresh company for this test
+ const fresh = await createCompanyViaWizard(
+ request,
+ `MU-LastOwner-${Date.now()}`
+ );
+
+ // First promote the local-board member to owner
+ const membersRes = await request.get(
+ `${BASE}/api/companies/${fresh.companyId}/members`
+ );
+ const { members } = await membersRes.json();
+
+ // Find the board member (should be the only one)
+ const boardMember = members.find(
+ (m: { principalId: string }) => m.principalId === "local-board"
+ );
+ if (!boardMember) {
+ test.skip();
+ return;
+ }
+
+ // Promote to owner first
+ const promoteRes = await request.patch(
+ `${BASE}/api/companies/${fresh.companyId}/members/${boardMember.id}`,
+ { data: { membershipRole: "owner" } }
+ );
+ expect(promoteRes.ok()).toBe(true);
+
+ // Now try to demote the last (and only) owner to operator — should fail
+ const demoteRes = await request.patch(
+ `${BASE}/api/companies/${fresh.companyId}/members/${boardMember.id}`,
+ { data: { membershipRole: "operator" } }
+ );
+ expect(demoteRes.status()).toBe(409);
+ const errBody = await demoteRes.json();
+ expect(JSON.stringify(errBody)).toContain("last active owner");
+ });
+
+ test("POST /companies/:id/openclaw/invite-prompt creates agent invite", async ({
+ request,
+ }) => {
+ const res = await request.post(
+ `${BASE}/api/companies/${companyId}/openclaw/invite-prompt`,
+ {
+ data: { agentMessage: "E2E test agent invite" },
+ }
+ );
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+
+ expect(body).toHaveProperty("token");
+ expect(body).toHaveProperty("inviteUrl");
+ expect(body.allowedJoinTypes).toBe("agent");
+ });
+});
+
+test.describe("Multi-user: Company Settings UI", () => {
+ let companyId: string;
+ let companyPrefix: string;
+
+ test.beforeAll(async ({ request }) => {
+ const result = await createCompanyViaWizard(
+ request,
+ `MU-UI-${Date.now()}`
+ );
+ companyId = result.companyId;
+ companyPrefix = result.prefix;
+ });
+
+ test("shows Team and Invites sections on settings page", async ({ page }) => {
+ await page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ await page.waitForLoadState("networkidle");
+ await expect(page.getByTestId("company-settings-invites-section")).toBeVisible({
+ timeout: 10_000,
+ });
+ await expect(page.getByTestId("company-settings-team-section")).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+
+ test("shows human invite creation controls", async ({ page }) => {
+ await page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ await page.waitForLoadState("networkidle");
+ const inviteButton = page.getByTestId("company-settings-create-human-invite");
+ await expect(inviteButton).toBeVisible({ timeout: 10_000 });
+
+ const roleSelect = page.getByTestId("company-settings-human-invite-role");
+ await expect(roleSelect).toBeVisible();
+ });
+
+ test("can create human invite and shows URL", async ({ page }) => {
+ await page.goto(`${BASE}/${companyPrefix}/company/settings`);
+ await page.waitForLoadState("networkidle");
+ const inviteButton = page.getByTestId("company-settings-create-human-invite");
+ await expect(inviteButton).toBeVisible({ timeout: 10_000 });
+ await inviteButton.click();
+
+ await expect(page.getByTestId("company-settings-human-invite-url")).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+});
+
+test.describe("Multi-user: Invite Landing UI", () => {
+ let companyId: string;
+ let inviteToken: string;
+
+ test.beforeAll(async ({ request }) => {
+ const result = await createCompanyViaWizard(
+ request,
+ `MU-Invite-${Date.now()}`
+ );
+ companyId = result.companyId;
+
+ const invite = await createHumanInvite(request, companyId, "operator");
+ inviteToken = invite.token;
+ });
+
+ test("invite landing page loads with join options", async ({ page }) => {
+ await page.goto(`${BASE}/invite/${inviteToken}`);
+ await page.waitForLoadState("networkidle");
+
+ // Should show the invite landing page heading
+ await expect(
+ page.getByRole("heading", { name: /join/i })
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("invite landing shows human join type", async ({ page }) => {
+ await page.goto(`${BASE}/invite/${inviteToken}`);
+ await page.waitForLoadState("networkidle");
+
+ // For a human-only invite, should show human join option
+ const humanOption = page.locator("text=/human/i");
+ await expect(humanOption).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("expired/invalid invite token returns error", async ({ page }) => {
+ await page.goto(`${BASE}/invite/invalid-token-e2e-test`);
+ await page.waitForLoadState("networkidle");
+ await expect(page.getByTestId("invite-error")).toBeVisible({ timeout: 10_000 });
+ });
+});
+
+test.describe("Multi-user: Member role management API", () => {
+ let companyId: string;
+
+ test.beforeAll(async ({ request }) => {
+ const result = await createCompanyViaWizard(
+ request,
+ `MU-Roles-${Date.now()}`
+ );
+ companyId = result.companyId;
+ });
+
+ test("invite + accept creates member with correct role", async ({
+ request,
+ }) => {
+ // Create invite for 'viewer' role
+ const invite = await createHumanInvite(request, companyId, "viewer");
+
+ // Accept the invite
+ const acceptRes = await request.post(
+ `${BASE}/api/invites/${invite.token}/accept`,
+ { data: { requestType: "human" } }
+ );
+ expect(acceptRes.ok()).toBe(true);
+
+ // Check members list
+ const membersRes = await request.get(
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ const { members } = await membersRes.json();
+
+ // Should have at least one member (the creator/local-board)
+ expect(members.length).toBeGreaterThanOrEqual(1);
+ });
+
+ test("PATCH member role updates correctly", async ({ request }) => {
+ // First create an invite and accept it to get a second member
+ const invite = await createHumanInvite(request, companyId, "operator");
+ const acceptRes = await request.post(
+ `${BASE}/api/invites/${invite.token}/accept`,
+ { data: { requestType: "human" } }
+ );
+ expect(acceptRes.ok()).toBe(true);
+
+ // List members
+ const membersRes = await request.get(
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ const { members } = await membersRes.json();
+
+ // Find a non-owner member to modify
+ const nonOwner = members.find(
+ (m: { membershipRole: string }) => m.membershipRole !== "owner"
+ );
+ if (!nonOwner) {
+ test.skip();
+ return;
+ }
+
+ // Update role to admin
+ const patchRes = await request.patch(
+ `${BASE}/api/companies/${companyId}/members/${nonOwner.id}`,
+ { data: { membershipRole: "admin" } }
+ );
+ expect(patchRes.ok()).toBe(true);
+ const updated = await patchRes.json();
+ expect(updated.membershipRole).toBe("admin");
+ });
+
+ test("PATCH member status to suspended works", async ({ request }) => {
+ // Create another member
+ const invite = await createHumanInvite(request, companyId, "operator");
+ await request.post(`${BASE}/api/invites/${invite.token}/accept`, {
+ data: { requestType: "human" },
+ });
+
+ const membersRes = await request.get(
+ `${BASE}/api/companies/${companyId}/members`
+ );
+ const { members } = await membersRes.json();
+
+ const nonOwner = members.find(
+ (m: { membershipRole: string; status: string }) =>
+ m.membershipRole !== "owner" && m.status === "active"
+ );
+ if (!nonOwner) {
+ test.skip();
+ return;
+ }
+
+ const patchRes = await request.patch(
+ `${BASE}/api/companies/${companyId}/members/${nonOwner.id}`,
+ { data: { status: "suspended" } }
+ );
+ expect(patchRes.ok()).toBe(true);
+ const updated = await patchRes.json();
+ expect(updated.status).toBe("suspended");
+ });
+});
+
+test.describe("Multi-user: Agent invite flow", () => {
+ let companyId: string;
+
+ test.beforeAll(async ({ request }) => {
+ const result = await createCompanyViaWizard(
+ request,
+ `MU-Agent-${Date.now()}`
+ );
+ companyId = result.companyId;
+ });
+
+ test("agent invite accept creates pending join request", async ({
+ request,
+ }) => {
+ // Create agent invite
+ const res = await request.post(
+ `${BASE}/api/companies/${companyId}/openclaw/invite-prompt`,
+ { data: {} }
+ );
+ expect(res.ok()).toBe(true);
+ const { token } = await res.json();
+
+ // Accept as agent
+ const acceptRes = await request.post(
+ `${BASE}/api/invites/${token}/accept`,
+ {
+ data: {
+ requestType: "agent",
+ agentName: "TestAgent",
+ adapterType: "claude_local",
+ },
+ }
+ );
+ expect(acceptRes.ok()).toBe(true);
+ const body = await acceptRes.json();
+ expect(body).toHaveProperty("id");
+ expect(body.status).toBe("pending_approval");
+ });
+
+ test("join requests list shows pending agent request", async ({
+ request,
+ }) => {
+ const res = await request.get(
+ `${BASE}/api/companies/${companyId}/join-requests?status=pending_approval`
+ );
+ expect(res.ok()).toBe(true);
+ const requests = await res.json();
+ expect(Array.isArray(requests)).toBe(true);
+ });
+});
+
+test.describe("Multi-user: Health check integration", () => {
+ test("health endpoint reports deployment mode", async ({ request }) => {
+ const res = await request.get(`${BASE}/api/health`);
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+ expect(body).toHaveProperty("deploymentMode");
+ expect(body).toHaveProperty("authReady");
+ expect(body.authReady).toBe(true);
+ });
+});
diff --git a/tests/e2e/playwright-multiuser-authenticated.config.ts b/tests/e2e/playwright-multiuser-authenticated.config.ts
new file mode 100644
index 0000000000..f80f13372a
--- /dev/null
+++ b/tests/e2e/playwright-multiuser-authenticated.config.ts
@@ -0,0 +1,28 @@
+import { defineConfig } from "@playwright/test";
+
+const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3105);
+const BASE_URL = process.env.PAPERCLIP_E2E_BASE_URL ?? `http://127.0.0.1:${PORT}`;
+
+export default defineConfig({
+ testDir: ".",
+ testMatch: "multi-user-authenticated.spec.ts",
+ timeout: 180_000,
+ expect: {
+ timeout: 20_000,
+ },
+ retries: 0,
+ use: {
+ baseURL: BASE_URL,
+ headless: true,
+ screenshot: "only-on-failure",
+ trace: "on-first-retry",
+ },
+ projects: [
+ {
+ name: "chromium",
+ use: { browserName: "chromium" },
+ },
+ ],
+ outputDir: "./test-results",
+ reporter: [["list"], ["html", { open: "never", outputFolder: "./playwright-report" }]],
+});
diff --git a/tests/e2e/playwright-multiuser.config.ts b/tests/e2e/playwright-multiuser.config.ts
new file mode 100644
index 0000000000..0c2d79be1a
--- /dev/null
+++ b/tests/e2e/playwright-multiuser.config.ts
@@ -0,0 +1,26 @@
+import { defineConfig } from "@playwright/test";
+
+const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3104);
+const BASE_URL = `http://127.0.0.1:${PORT}`;
+
+export default defineConfig({
+ testDir: ".",
+ testMatch: "multi-user.spec.ts",
+ timeout: 60_000,
+ retries: 0,
+ use: {
+ baseURL: BASE_URL,
+ headless: true,
+ screenshot: "only-on-failure",
+ trace: "on-first-retry",
+ },
+ projects: [
+ {
+ name: "chromium",
+ use: { browserName: "chromium" },
+ },
+ ],
+ // No webServer — expects an already-running server at BASE_URL.
+ outputDir: "./test-results",
+ reporter: [["list"], ["html", { open: "never", outputFolder: "./playwright-report" }]],
+});
diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts
index 46579bc9c0..4f1c720668 100644
--- a/tests/e2e/playwright.config.ts
+++ b/tests/e2e/playwright.config.ts
@@ -12,6 +12,9 @@ const PAPERCLIP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-home
export default defineConfig({
testDir: ".",
testMatch: "**/*.spec.ts",
+ // These suites target dedicated multi-user configurations/ports and are
+ // intentionally not part of the default local_trusted e2e run.
+ testIgnore: ["multi-user.spec.ts", "multi-user-authenticated.spec.ts"],
timeout: 60_000,
retries: 0,
use: {
diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsx
new file mode 100644
index 0000000000..bec9c199ae
--- /dev/null
+++ b/ui/src/App.test.tsx
@@ -0,0 +1,146 @@
+// @vitest-environment jsdom
+
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CloudAccessGate } from "./components/CloudAccessGate";
+
+const mockHealthApi = vi.hoisted(() => ({
+ get: vi.fn(),
+}));
+
+const mockAuthApi = vi.hoisted(() => ({
+ getSession: vi.fn(),
+}));
+
+const mockAccessApi = vi.hoisted(() => ({
+ getCurrentBoardAccess: vi.fn(),
+}));
+
+vi.mock("./api/health", () => ({
+ healthApi: mockHealthApi,
+}));
+
+vi.mock("./api/auth", () => ({
+ authApi: mockAuthApi,
+}));
+
+vi.mock("./api/access", () => ({
+ accessApi: mockAccessApi,
+}));
+
+vi.mock("@/lib/router", () => ({
+ Navigate: ({ to }: { to: string }) => <div>Navigate:{to}</div>,
+ Outlet: () => <div>Outlet content</div>,
+ Route: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ Routes: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLocation: () => ({ pathname: "/instance/settings/general", search: "", hash: "" }),
+ useParams: () => ({}),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("CloudAccessGate", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockHealthApi.get.mockResolvedValue({
+ status: "ok",
+ deploymentMode: "authenticated",
+ bootstrapStatus: "ready",
+ });
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("shows a no-access message for signed-in users without org access", async () => {
+ mockAuthApi.getSession.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: { id: "user-1", email: "[email protected]", name: "User", image: null },
+ });
+ mockAccessApi.getCurrentBoardAccess.mockResolvedValue({
+ user: { id: "user-1", email: "[email protected]", name: "User", image: null },
+ userId: "user-1",
+ isInstanceAdmin: false,
+ companyIds: [],
+ source: "session",
+ keyId: null,
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <CloudAccessGate />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("No company access");
+ expect(container.textContent).not.toContain("Outlet content");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("allows authenticated users with company access through to the board", async () => {
+ mockAuthApi.getSession.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: { id: "user-1", email: "[email protected]", name: "User", image: null },
+ });
+ mockAccessApi.getCurrentBoardAccess.mockResolvedValue({
+ user: { id: "user-1", email: "[email protected]", name: "User", image: null },
+ userId: "user-1",
+ isInstanceAdmin: false,
+ companyIds: ["company-1"],
+ source: "session",
+ keyId: null,
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <CloudAccessGate />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Outlet content");
+ expect(container.textContent).not.toContain("No company access");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index cfe0f487e2..9fe1f9d9df 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -1,10 +1,8 @@
import { Navigate, Outlet, Route, Routes, useLocation, useParams } from "@/lib/router";
-import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Layout } from "./components/Layout";
import { OnboardingWizard } from "./components/OnboardingWizard";
-import { authApi } from "./api/auth";
-import { healthApi } from "./api/health";
+import { CloudAccessGate } from "./components/CloudAccessGate";
import { Dashboard } from "./pages/Dashboard";
import { Companies } from "./pages/Companies";
import { Agents } from "./pages/Agents";
@@ -25,18 +23,23 @@ import { Costs } from "./pages/Costs";
import { Activity } from "./pages/Activity";
import { Inbox } from "./pages/Inbox";
import { CompanySettings } from "./pages/CompanySettings";
+import { CompanyAccess } from "./pages/CompanyAccess";
+import { CompanyInvites } from "./pages/CompanyInvites";
import { CompanySkills } from "./pages/CompanySkills";
import { CompanyExport } from "./pages/CompanyExport";
import { CompanyImport } from "./pages/CompanyImport";
import { DesignGuide } from "./pages/DesignGuide";
import { InstanceGeneralSettings } from "./pages/InstanceGeneralSettings";
+import { InstanceAccess } from "./pages/InstanceAccess";
import { InstanceSettings } from "./pages/InstanceSettings";
import { InstanceExperimentalSettings } from "./pages/InstanceExperimentalSettings";
+import { ProfileSettings } from "./pages/ProfileSettings";
import { PluginManager } from "./pages/PluginManager";
import { PluginSettings } from "./pages/PluginSettings";
import { AdapterManager } from "./pages/AdapterManager";
import { PluginPage } from "./pages/PluginPage";
import { IssueChatUxLab } from "./pages/IssueChatUxLab";
+import { InviteUxLab } from "./pages/InviteUxLab";
import { RunTranscriptUxLab } from "./pages/RunTranscriptUxLab";
import { OrgChart } from "./pages/OrgChart";
import { NewAgent } from "./pages/NewAgent";
@@ -44,80 +47,13 @@ import { AuthPage } from "./pages/Auth";
import { BoardClaimPage } from "./pages/BoardClaim";
import { CliAuthPage } from "./pages/CliAuth";
import { InviteLandingPage } from "./pages/InviteLanding";
+import { JoinRequestQueue } from "./pages/JoinRequestQueue";
import { NotFoundPage } from "./pages/NotFound";
-import { queryKeys } from "./lib/queryKeys";
import { useCompany } from "./context/CompanyContext";
import { useDialog } from "./context/DialogContext";
import { loadLastInboxTab } from "./lib/inbox";
import { shouldRedirectCompanylessRouteToOnboarding } from "./lib/onboarding-route";
-function BootstrapPendingPage({ hasActiveInvite = false }: { hasActiveInvite?: boolean }) {
- return (
- <div className="mx-auto max-w-xl py-10">
- <div className="rounded-lg border border-border bg-card p-6">
- <h1 className="text-xl font-semibold">Instance setup required</h1>
- <p className="mt-2 text-sm text-muted-foreground">
- {hasActiveInvite
- ? "No instance admin exists yet. A bootstrap invite is already active. Check your Paperclip startup logs for the first admin invite URL, or run this command to rotate it:"
- : "No instance admin exists yet. Run this command in your Paperclip environment to generate the first admin invite URL:"}
- </p>
- <pre className="mt-4 overflow-x-auto rounded-md border border-border bg-muted/30 p-3 text-xs">
-{`pnpm paperclipai auth bootstrap-ceo`}
- </pre>
- </div>
- </div>
- );
-}
-
-function CloudAccessGate() {
- const location = useLocation();
- const healthQuery = useQuery({
- queryKey: queryKeys.health,
- queryFn: () => healthApi.get(),
- retry: false,
- refetchInterval: (query) => {
- const data = query.state.data as
- | { deploymentMode?: "local_trusted" | "authenticated"; bootstrapStatus?: "ready" | "bootstrap_pending" }
- | undefined;
- return data?.deploymentMode === "authenticated" && data.bootstrapStatus === "bootstrap_pending"
- ? 2000
- : false;
- },
- refetchIntervalInBackground: true,
- });
-
- const isAuthenticatedMode = healthQuery.data?.deploymentMode === "authenticated";
- const sessionQuery = useQuery({
- queryKey: queryKeys.auth.session,
- queryFn: () => authApi.getSession(),
- enabled: isAuthenticatedMode,
- retry: false,
- });
-
- if (healthQuery.isLoading || (isAuthenticatedMode && sessionQuery.isLoading)) {
- return <div className="mx-auto max-w-xl py-10 text-sm text-muted-foreground">Loading...</div>;
- }
-
- if (healthQuery.error) {
- return (
- <div className="mx-auto max-w-xl py-10 text-sm text-destructive">
- {healthQuery.error instanceof Error ? healthQuery.error.message : "Failed to load app state"}
- </div>
- );
- }
-
- if (isAuthenticatedMode && healthQuery.data?.bootstrapStatus === "bootstrap_pending") {
- return <BootstrapPendingPage hasActiveInvite={healthQuery.data.bootstrapInviteActive} />;
- }
-
- if (isAuthenticatedMode && !sessionQuery.data) {
- const next = encodeURIComponent(`${location.pathname}${location.search}`);
- return <Navigate to={`/auth?next=${next}`} replace />;
- }
-
- return <Outlet />;
-}
-
function boardRoutes() {
return (
<>
@@ -126,6 +62,8 @@ function boardRoutes() {
<Route path="onboarding" element={<OnboardingRoutePage />} />
<Route path="companies" element={<Companies />} />
<Route path="company/settings" element={<CompanySettings />} />
+ <Route path="company/settings/access" element={<CompanyAccess />} />
+ <Route path="company/settings/invites" element={<CompanyInvites />} />
<Route path="company/export/*" element={<CompanyExport />} />
<Route path="company/import" element={<CompanyImport />} />
<Route path="skills/*" element={<CompanySkills />} />
@@ -177,9 +115,11 @@ function boardRoutes() {
<Route path="inbox/recent" element={<Inbox />} />
<Route path="inbox/unread" element={<Inbox />} />
<Route path="inbox/all" element={<Inbox />} />
+ <Route path="inbox/requests" element={<JoinRequestQueue />} />
<Route path="inbox/new" element={<Navigate to="/inbox/mine" replace />} />
<Route path="design-guide" element={<DesignGuide />} />
<Route path="tests/ux/chat" element={<IssueChatUxLab />} />
+ <Route path="tests/ux/invites" element={<InviteUxLab />} />
<Route path="tests/ux/runs" element={<RunTranscriptUxLab />} />
<Route path="instance/settings/adapters" element={<AdapterManager />} />
<Route path=":pluginRoutePath" element={<PluginPage />} />
@@ -323,7 +263,9 @@ export function App() {
<Route path="instance" element={<Navigate to="/instance/settings/general" replace />} />
<Route path="instance/settings" element={<Layout />}>
<Route index element={<Navigate to="general" replace />} />
+ <Route path="profile" element={<ProfileSettings />} />
<Route path="general" element={<InstanceGeneralSettings />} />
+ <Route path="access" element={<InstanceAccess />} />
<Route path="heartbeats" element={<InstanceSettings />} />
<Route path="experimental" element={<InstanceExperimentalSettings />} />
<Route path="plugins" element={<PluginManager />} />
diff --git a/ui/src/api/access.ts b/ui/src/api/access.ts
index 0a1111502e..917a049fa0 100644
--- a/ui/src/api/access.ts
+++ b/ui/src/api/access.ts
@@ -1,12 +1,17 @@
-import type { AgentAdapterType, JoinRequest } from "@paperclipai/shared";
+import type { AgentAdapterType, JoinRequest, PermissionKey } from "@paperclipai/shared";
import { api } from "./client";
+export type HumanCompanyRole = "owner" | "admin" | "operator" | "viewer";
+
type InviteSummary = {
id: string;
companyId: string | null;
companyName?: string | null;
+ companyLogoUrl?: string | null;
+ companyBrandColor?: string | null;
inviteType: "company_join" | "bootstrap_ceo";
allowedJoinTypes: "human" | "agent" | "both";
+ humanRole?: HumanCompanyRole | null;
expiresAt: string;
onboardingPath?: string;
onboardingUrl?: string;
@@ -15,6 +20,9 @@ type InviteSummary = {
skillIndexPath?: string;
skillIndexUrl?: string;
inviteMessage?: string | null;
+ invitedByUserName?: string | null;
+ joinRequestStatus?: JoinRequest["status"] | null;
+ joinRequestType?: JoinRequest["requestType"] | null;
};
type AcceptInviteInput =
@@ -88,17 +96,162 @@ type CompanyInviteCreated = {
inviteUrl: string;
expiresAt: string;
allowedJoinTypes: "human" | "agent" | "both";
+ humanRole?: HumanCompanyRole | null;
companyName?: string | null;
onboardingTextPath?: string;
onboardingTextUrl?: string;
inviteMessage?: string | null;
};
+export type CompanyMemberGrant = {
+ id: string;
+ companyId: string;
+ principalType: "user";
+ principalId: string;
+ permissionKey: PermissionKey;
+ scope: Record<string, unknown> | null;
+ grantedByUserId: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type CompanyMember = {
+ id: string;
+ companyId: string;
+ principalType: "user";
+ principalId: string;
+ status: "pending" | "active" | "suspended";
+ membershipRole: HumanCompanyRole | null;
+ createdAt: string;
+ updatedAt: string;
+ user: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ grants: CompanyMemberGrant[];
+};
+
+export type CompanyMembersResponse = {
+ members: CompanyMember[];
+ access: {
+ currentUserRole: HumanCompanyRole | null;
+ canManageMembers: boolean;
+ canInviteUsers: boolean;
+ canApproveJoinRequests: boolean;
+ };
+};
+
+export type CompanyUserDirectoryEntry = {
+ principalId: string;
+ status: "active";
+ user: { id: string; email: string | null; name: string | null; image: string | null } | null;
+};
+
+export type CompanyUserDirectoryResponse = {
+ users: CompanyUserDirectoryEntry[];
+};
+
+export type CompanyInviteRecord = {
+ id: string;
+ companyId: string | null;
+ companyName: string | null;
+ inviteType: "company_join" | "bootstrap_ceo";
+ allowedJoinTypes: "human" | "agent" | "both";
+ humanRole: HumanCompanyRole | null;
+ defaultsPayload: Record<string, unknown> | null;
+ expiresAt: string;
+ invitedByUserId: string | null;
+ revokedAt: string | null;
+ acceptedAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+ inviteMessage: string | null;
+ state: "active" | "revoked" | "accepted" | "expired";
+ invitedByUser: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ relatedJoinRequestId: string | null;
+};
+
+export type CompanyInviteListResponse = {
+ invites: CompanyInviteRecord[];
+ nextOffset: number | null;
+};
+
+export type CompanyJoinRequest = JoinRequest & {
+ requesterUser: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ approvedByUser: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ rejectedByUser: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ invite: {
+ id: string;
+ inviteType: "company_join" | "bootstrap_ceo";
+ allowedJoinTypes: "human" | "agent" | "both";
+ humanRole: HumanCompanyRole | null;
+ inviteMessage: string | null;
+ createdAt: string;
+ expiresAt: string;
+ revokedAt: string | null;
+ acceptedAt: string | null;
+ invitedByUser: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ } | null;
+};
+
+export type AdminUserDirectoryEntry = {
+ id: string;
+ email: string | null;
+ name: string | null;
+ image: string | null;
+ isInstanceAdmin: boolean;
+ activeCompanyMembershipCount: number;
+};
+
+export type UserCompanyAccessEntry = {
+ id: string;
+ companyId: string;
+ principalType: "user";
+ principalId: string;
+ status: "pending" | "active" | "suspended";
+ membershipRole: HumanCompanyRole | "member" | null;
+ createdAt: string;
+ updatedAt: string;
+ companyName: string | null;
+ companyStatus: "active" | "paused" | "archived" | null;
+};
+
+export type UserCompanyAccessResponse = {
+ user: {
+ id: string;
+ email: string | null;
+ name: string | null;
+ image: string | null;
+ isInstanceAdmin: boolean;
+ } | null;
+ companyAccess: UserCompanyAccessEntry[];
+};
+
+export type CurrentBoardAccess = {
+ user: { id: string; email: string | null; name: string | null; image: string | null } | null;
+ userId: string;
+ isInstanceAdmin: boolean;
+ companyIds: string[];
+ source: string;
+ keyId: string | null;
+};
+
+function buildInviteListQuery(options: {
+ state?: "active" | "revoked" | "accepted" | "expired";
+ limit?: number;
+ offset?: number;
+}) {
+ const params = new URLSearchParams();
+ if (options.state) params.set("state", options.state);
+ if (options.limit) params.set("limit", String(options.limit));
+ if (options.offset) params.set("offset", String(options.offset));
+ const query = params.toString();
+ return query ? `?${query}` : "";
+}
+
export const accessApi = {
createCompanyInvite: (
companyId: string,
input: {
allowedJoinTypes?: "human" | "agent" | "both";
+ humanRole?: HumanCompanyRole | null;
defaultsPayload?: Record<string, unknown> | null;
agentMessage?: string | null;
} = {},
@@ -126,8 +279,67 @@ export const accessApi = {
input,
),
- listJoinRequests: (companyId: string, status: "pending_approval" | "approved" | "rejected" = "pending_approval") =>
- api.get<JoinRequest[]>(`/companies/${companyId}/join-requests?status=${status}`),
+ listInvites: (
+ companyId: string,
+ options: {
+ state?: "active" | "revoked" | "accepted" | "expired";
+ limit?: number;
+ offset?: number;
+ } = {},
+ ) =>
+ api.get<CompanyInviteListResponse>(
+ `/companies/${companyId}/invites${buildInviteListQuery(options)}`,
+ ),
+
+ revokeInvite: (inviteId: string) => api.post(`/invites/${inviteId}/revoke`, {}),
+
+ listJoinRequests: (
+ companyId: string,
+ status: "pending_approval" | "approved" | "rejected" = "pending_approval",
+ requestType?: "human" | "agent",
+ ) =>
+ api.get<CompanyJoinRequest[]>(
+ `/companies/${companyId}/join-requests?status=${status}${requestType ? `&requestType=${requestType}` : ""}`,
+ ),
+
+ listMembers: (companyId: string) =>
+ api.get<CompanyMembersResponse>(`/companies/${companyId}/members`),
+
+ listUserDirectory: (companyId: string) =>
+ api.get<CompanyUserDirectoryResponse>(`/companies/${companyId}/user-directory`),
+
+ updateMember: (
+ companyId: string,
+ memberId: string,
+ input: {
+ membershipRole?: HumanCompanyRole | null;
+ status?: "pending" | "active" | "suspended";
+ },
+ ) => api.patch<CompanyMember>(`/companies/${companyId}/members/${memberId}`, input),
+
+ updateMemberPermissions: (
+ companyId: string,
+ memberId: string,
+ input: {
+ grants: Array<{
+ permissionKey: PermissionKey;
+ scope?: Record<string, unknown> | null;
+ }>;
+ },
+ ) => api.patch<CompanyMember>(`/companies/${companyId}/members/${memberId}/permissions`, input),
+
+ updateMemberAccess: (
+ companyId: string,
+ memberId: string,
+ input: {
+ membershipRole?: HumanCompanyRole | null;
+ status?: "pending" | "active" | "suspended";
+ grants: Array<{
+ permissionKey: PermissionKey;
+ scope?: Record<string, unknown> | null;
+ }>;
+ },
+ ) => api.patch<CompanyMember>(`/companies/${companyId}/members/${memberId}/role-and-grants`, input),
approveJoinRequest: (companyId: string, requestId: string) =>
api.post<JoinRequest>(`/companies/${companyId}/join-requests/${requestId}/approve`, {}),
@@ -158,4 +370,22 @@ export const accessApi = {
cancelCliAuthChallenge: (id: string, token: string) =>
api.post<{ cancelled: boolean; status: string }>(`/cli-auth/challenges/${id}/cancel`, { token }),
+
+ searchAdminUsers: (query: string) =>
+ api.get<AdminUserDirectoryEntry[]>(`/admin/users?query=${encodeURIComponent(query)}`),
+
+ promoteInstanceAdmin: (userId: string) =>
+ api.post(`/admin/users/${userId}/promote-instance-admin`, {}),
+
+ demoteInstanceAdmin: (userId: string) =>
+ api.post(`/admin/users/${userId}/demote-instance-admin`, {}),
+
+ getUserCompanyAccess: (userId: string) =>
+ api.get<UserCompanyAccessResponse>(`/admin/users/${userId}/company-access`),
+
+ setUserCompanyAccess: (userId: string, companyIds: string[]) =>
+ api.put<UserCompanyAccessResponse>(`/admin/users/${userId}/company-access`, { companyIds }),
+
+ getCurrentBoardAccess: () =>
+ api.get<CurrentBoardAccess>("/cli-auth/me"),
};
diff --git a/ui/src/api/auth.ts b/ui/src/api/auth.ts
index 5aa5b69ad2..b0da51651a 100644
--- a/ui/src/api/auth.ts
+++ b/ui/src/api/auth.ts
@@ -1,27 +1,63 @@
-export type AuthSession = {
- session: { id: string; userId: string };
- user: { id: string; email: string | null; name: string | null };
-};
+import {
+ authSessionSchema,
+ currentUserProfileSchema,
+ type AuthSession,
+ type CurrentUserProfile,
+ type UpdateCurrentUserProfile,
+} from "@paperclipai/shared";
+
+type AuthErrorBody =
+ | {
+ code?: string;
+ message?: string;
+ error?: string | { code?: string; message?: string };
+ }
+ | null;
+
+export class AuthApiError extends Error {
+ status: number;
+ code: string | null;
+ body: unknown;
+
+ constructor(message: string, status: number, body: unknown, code: string | null = null) {
+ super(message);
+ this.name = "AuthApiError";
+ this.status = status;
+ this.code = code;
+ this.body = body;
+ }
+}
function toSession(value: unknown): AuthSession | null {
+ const direct = authSessionSchema.safeParse(value);
+ if (direct.success) return direct.data;
+
if (!value || typeof value !== "object") return null;
- const record = value as Record<string, unknown>;
- const sessionValue = record.session;
- const userValue = record.user;
- if (!sessionValue || typeof sessionValue !== "object") return null;
- if (!userValue || typeof userValue !== "object") return null;
- const session = sessionValue as Record<string, unknown>;
- const user = userValue as Record<string, unknown>;
- if (typeof session.id !== "string" || typeof session.userId !== "string") return null;
- if (typeof user.id !== "string") return null;
- return {
- session: { id: session.id, userId: session.userId },
- user: {
- id: user.id,
- email: typeof user.email === "string" ? user.email : null,
- name: typeof user.name === "string" ? user.name : null,
- },
- };
+ const nested = authSessionSchema.safeParse((value as Record<string, unknown>).data);
+ return nested.success ? nested.data : null;
+}
+
+function extractAuthError(payload: AuthErrorBody, status: number) {
+ const nested =
+ payload?.error && typeof payload.error === "object"
+ ? payload.error
+ : null;
+ const code =
+ typeof nested?.code === "string"
+ ? nested.code
+ : typeof payload?.code === "string"
+ ? payload.code
+ : null;
+ const message =
+ typeof nested?.message === "string" && nested.message.trim().length > 0
+ ? nested.message
+ : typeof payload?.message === "string" && payload.message.trim().length > 0
+ ? payload.message
+ : typeof payload?.error === "string" && payload.error.trim().length > 0
+ ? payload.error
+ : `Request failed: ${status}`;
+
+ return new AuthApiError(message, status, payload, code);
}
async function authPost(path: string, body: Record<string, unknown>) {
@@ -33,16 +69,25 @@ async function authPost(path: string, body: Record<string, unknown>) {
});
const payload = await res.json().catch(() => null);
if (!res.ok) {
- const message =
- (payload as { error?: { message?: string } | string } | null)?.error &&
- typeof (payload as { error?: { message?: string } | string }).error === "object"
- ? ((payload as { error?: { message?: string } }).error?.message ?? `Request failed: ${res.status}`)
- : (payload as { error?: string } | null)?.error ?? `Request failed: ${res.status}`;
- throw new Error(message);
+ throw extractAuthError(payload as AuthErrorBody, res.status);
}
return payload;
}
+async function authPatch<T>(path: string, body: Record<string, unknown>, parse: (value: unknown) => T): Promise<T> {
+ const res = await fetch(`/api/auth${path}`, {
+ method: "PATCH",
+ credentials: "include",
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
+ body: JSON.stringify(body),
+ });
+ const payload = await res.json().catch(() => null);
+ if (!res.ok) {
+ throw extractAuthError(payload as AuthErrorBody, res.status);
+ }
+ return parse(payload);
+}
+
export const authApi = {
getSession: async (): Promise<AuthSession | null> => {
const res = await fetch("/api/auth/get-session", {
@@ -68,6 +113,21 @@ export const authApi = {
await authPost("/sign-up/email", input);
},
+ getProfile: async (): Promise<CurrentUserProfile> => {
+ const res = await fetch("/api/auth/profile", {
+ credentials: "include",
+ headers: { Accept: "application/json" },
+ });
+ const payload = await res.json().catch(() => null);
+ if (!res.ok) {
+ throw new Error((payload as { error?: string } | null)?.error ?? `Failed to load profile (${res.status})`);
+ }
+ return currentUserProfileSchema.parse(payload);
+ },
+
+ updateProfile: async (input: UpdateCurrentUserProfile): Promise<CurrentUserProfile> =>
+ authPatch("/profile", input, (payload) => currentUserProfileSchema.parse(payload)),
+
signOut: async () => {
await authPost("/sign-out", {});
},
diff --git a/ui/src/components/ActivityRow.tsx b/ui/src/components/ActivityRow.tsx
index dbe8878527..c969a9599a 100644
--- a/ui/src/components/ActivityRow.tsx
+++ b/ui/src/components/ActivityRow.tsx
@@ -4,6 +4,7 @@ import { timeAgo } from "../lib/timeAgo";
import { cn } from "../lib/utils";
import { formatActivityVerb } from "../lib/activity-format";
import { deriveProjectUrlKey, type ActivityEvent, type Agent } from "@paperclipai/shared";
+import type { CompanyUserProfile } from "../lib/company-members";
function entityLink(entityType: string, entityId: string, name?: string | null): string | null {
switch (entityType) {
@@ -19,13 +20,14 @@ function entityLink(entityType: string, entityId: string, name?: string | null):
interface ActivityRowProps {
event: ActivityEvent;
agentMap: Map<string, Agent>;
+ userProfileMap?: Map<string, CompanyUserProfile>;
entityNameMap: Map<string, string>;
entityTitleMap?: Map<string, string>;
className?: string;
}
-export function ActivityRow({ event, agentMap, entityNameMap, entityTitleMap, className }: ActivityRowProps) {
- const verb = formatActivityVerb(event.action, event.details, { agentMap });
+export function ActivityRow({ event, agentMap, userProfileMap, entityNameMap, entityTitleMap, className }: ActivityRowProps) {
+ const verb = formatActivityVerb(event.action, event.details, { agentMap, userProfileMap });
const isHeartbeatEvent = event.entityType === "heartbeat_run";
const heartbeatAgentId = isHeartbeatEvent
@@ -43,13 +45,16 @@ export function ActivityRow({ event, agentMap, entityNameMap, entityTitleMap, cl
: entityLink(event.entityType, event.entityId, name);
const actor = event.actorType === "agent" ? agentMap.get(event.actorId) : null;
- const actorName = actor?.name ?? (event.actorType === "system" ? "System" : event.actorType === "user" ? "Board" : event.actorId || "Unknown");
+ const userProfile = event.actorType === "user" ? userProfileMap?.get(event.actorId) : null;
+ const actorName = actor?.name ?? (event.actorType === "system" ? "System" : userProfile?.label ?? (event.actorType === "user" ? "Board" : event.actorId || "Unknown"));
+ const actorAvatarUrl = userProfile?.image ?? null;
const inner = (
<div className="flex gap-3">
<p className="flex-1 min-w-0 truncate">
<Identity
name={actorName}
+ avatarUrl={actorAvatarUrl}
size="xs"
className="align-baseline"
/>
diff --git a/ui/src/components/CloudAccessGate.tsx b/ui/src/components/CloudAccessGate.tsx
new file mode 100644
index 0000000000..eaea736bcd
--- /dev/null
+++ b/ui/src/components/CloudAccessGate.tsx
@@ -0,0 +1,114 @@
+import { Navigate, Outlet, useLocation } from "@/lib/router";
+import { useQuery } from "@tanstack/react-query";
+import { accessApi } from "@/api/access";
+import { authApi } from "@/api/auth";
+import { healthApi } from "@/api/health";
+import { queryKeys } from "@/lib/queryKeys";
+
+function BootstrapPendingPage({ hasActiveInvite = false }: { hasActiveInvite?: boolean }) {
+ return (
+ <div className="mx-auto max-w-xl py-10">
+ <div className="rounded-lg border border-border bg-card p-6">
+ <h1 className="text-xl font-semibold">Instance setup required</h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ {hasActiveInvite
+ ? "No instance admin exists yet. A bootstrap invite is already active. Check your Paperclip startup logs for the first admin invite URL, or run this command to rotate it:"
+ : "No instance admin exists yet. Run this command in your Paperclip environment to generate the first admin invite URL:"}
+ </p>
+ <pre className="mt-4 overflow-x-auto rounded-md border border-border bg-muted/30 p-3 text-xs">
+{`pnpm paperclipai auth bootstrap-ceo`}
+ </pre>
+ </div>
+ </div>
+ );
+}
+
+function NoBoardAccessPage() {
+ return (
+ <div className="mx-auto max-w-xl py-10">
+ <div className="rounded-lg border border-border bg-card p-6">
+ <h1 className="text-xl font-semibold">No company access</h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ This account is signed in, but it does not have an active company membership or instance-admin access on
+ this Paperclip instance.
+ </p>
+ <p className="mt-2 text-sm text-muted-foreground">
+ Use a company invite or sign in with an account that already belongs to this org.
+ </p>
+ </div>
+ </div>
+ );
+}
+
+export function CloudAccessGate() {
+ const location = useLocation();
+ const healthQuery = useQuery({
+ queryKey: queryKeys.health,
+ queryFn: () => healthApi.get(),
+ retry: false,
+ refetchInterval: (query) => {
+ const data = query.state.data as
+ | { deploymentMode?: "local_trusted" | "authenticated"; bootstrapStatus?: "ready" | "bootstrap_pending" }
+ | undefined;
+ return data?.deploymentMode === "authenticated" && data.bootstrapStatus === "bootstrap_pending"
+ ? 2000
+ : false;
+ },
+ refetchIntervalInBackground: true,
+ });
+
+ const isAuthenticatedMode = healthQuery.data?.deploymentMode === "authenticated";
+ const sessionQuery = useQuery({
+ queryKey: queryKeys.auth.session,
+ queryFn: () => authApi.getSession(),
+ enabled: isAuthenticatedMode,
+ retry: false,
+ });
+
+ const boardAccessQuery = useQuery({
+ queryKey: queryKeys.access.currentBoardAccess,
+ queryFn: () => accessApi.getCurrentBoardAccess(),
+ enabled: isAuthenticatedMode && !!sessionQuery.data,
+ retry: false,
+ });
+
+ if (
+ healthQuery.isLoading ||
+ (isAuthenticatedMode && sessionQuery.isLoading) ||
+ (isAuthenticatedMode && !!sessionQuery.data && boardAccessQuery.isLoading)
+ ) {
+ return <div className="mx-auto max-w-xl py-10 text-sm text-muted-foreground">Loading...</div>;
+ }
+
+ if (healthQuery.error || boardAccessQuery.error) {
+ return (
+ <div className="mx-auto max-w-xl py-10 text-sm text-destructive">
+ {healthQuery.error instanceof Error
+ ? healthQuery.error.message
+ : boardAccessQuery.error instanceof Error
+ ? boardAccessQuery.error.message
+ : "Failed to load app state"}
+ </div>
+ );
+ }
+
+ if (isAuthenticatedMode && healthQuery.data?.bootstrapStatus === "bootstrap_pending") {
+ return <BootstrapPendingPage hasActiveInvite={healthQuery.data.bootstrapInviteActive} />;
+ }
+
+ if (isAuthenticatedMode && !sessionQuery.data) {
+ const next = encodeURIComponent(`${location.pathname}${location.search}`);
+ return <Navigate to={`/auth?next=${next}`} replace />;
+ }
+
+ if (
+ isAuthenticatedMode &&
+ sessionQuery.data &&
+ !boardAccessQuery.data?.isInstanceAdmin &&
+ (boardAccessQuery.data?.companyIds.length ?? 0) === 0
+ ) {
+ return <NoBoardAccessPage />;
+ }
+
+ return <Outlet />;
+}
diff --git a/ui/src/components/CompanyPatternIcon.tsx b/ui/src/components/CompanyPatternIcon.tsx
index 6ea4078859..6591f7d13a 100644
--- a/ui/src/components/CompanyPatternIcon.tsx
+++ b/ui/src/components/CompanyPatternIcon.tsx
@@ -13,6 +13,7 @@ interface CompanyPatternIconProps {
logoUrl?: string | null;
brandColor?: string | null;
className?: string;
+ logoFit?: "cover" | "contain";
}
function hashString(value: string): number {
@@ -165,6 +166,7 @@ export function CompanyPatternIcon({
logoUrl,
brandColor,
className,
+ logoFit = "cover",
}: CompanyPatternIconProps) {
const initial = companyName.trim().charAt(0).toUpperCase() || "?";
const [imageError, setImageError] = useState(false);
@@ -189,7 +191,10 @@ export function CompanyPatternIcon({
src={logo}
alt={`${companyName} logo`}
onError={() => setImageError(true)}
- className="absolute inset-0 h-full w-full object-cover"
+ className={cn(
+ "absolute inset-0 h-full w-full",
+ logoFit === "contain" ? "object-contain" : "object-cover",
+ )}
/>
) : patternDataUrl ? (
<img
diff --git a/ui/src/components/CompanySettingsSidebar.test.tsx b/ui/src/components/CompanySettingsSidebar.test.tsx
new file mode 100644
index 0000000000..fa9a777af7
--- /dev/null
+++ b/ui/src/components/CompanySettingsSidebar.test.tsx
@@ -0,0 +1,137 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CompanySettingsSidebar } from "./CompanySettingsSidebar";
+
+const sidebarNavItemMock = vi.hoisted(() => vi.fn());
+const mockSidebarBadgesApi = vi.hoisted(() => ({
+ get: vi.fn(),
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({
+ children,
+ to,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ to: string;
+ onClick?: () => void;
+ }) => (
+ <button type="button" data-to={to} onClick={onClick}>
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompanyId: "company-1",
+ selectedCompany: { id: "company-1", name: "Paperclip" },
+ }),
+}));
+
+vi.mock("@/context/SidebarContext", () => ({
+ useSidebar: () => ({
+ isMobile: false,
+ setSidebarOpen: vi.fn(),
+ }),
+}));
+
+vi.mock("./SidebarNavItem", () => ({
+ SidebarNavItem: (props: {
+ to: string;
+ label: string;
+ end?: boolean;
+ badge?: number;
+ }) => {
+ sidebarNavItemMock(props);
+ return <div>{props.label}</div>;
+ },
+}));
+
+vi.mock("@/api/sidebarBadges", () => ({
+ sidebarBadgesApi: mockSidebarBadgesApi,
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("CompanySettingsSidebar", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockSidebarBadgesApi.get.mockResolvedValue({
+ inbox: 0,
+ approvals: 0,
+ failedRuns: 0,
+ joinRequests: 2,
+ });
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("renders the company back link and the settings sections in the sidebar", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <CompanySettingsSidebar />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(container.textContent).toContain("Paperclip");
+ expect(container.textContent).toContain("Company Settings");
+ expect(container.textContent).toContain("General");
+ expect(container.textContent).toContain("Access");
+ expect(container.textContent).toContain("Invites");
+ expect(sidebarNavItemMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ to: "/company/settings",
+ label: "General",
+ end: true,
+ }),
+ );
+ expect(sidebarNavItemMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ to: "/company/settings/access",
+ label: "Access",
+ badge: 2,
+ end: true,
+ }),
+ );
+ expect(sidebarNavItemMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ to: "/company/settings/invites",
+ label: "Invites",
+ end: true,
+ }),
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/CompanySettingsSidebar.tsx b/ui/src/components/CompanySettingsSidebar.tsx
new file mode 100644
index 0000000000..6339cf1fdd
--- /dev/null
+++ b/ui/src/components/CompanySettingsSidebar.tsx
@@ -0,0 +1,69 @@
+import { useQuery } from "@tanstack/react-query";
+import { ChevronLeft, MailPlus, Settings, Shield, SlidersHorizontal } from "lucide-react";
+import { sidebarBadgesApi } from "@/api/sidebarBadges";
+import { ApiError } from "@/api/client";
+import { Link } from "@/lib/router";
+import { queryKeys } from "@/lib/queryKeys";
+import { useCompany } from "@/context/CompanyContext";
+import { useSidebar } from "@/context/SidebarContext";
+import { SidebarNavItem } from "./SidebarNavItem";
+
+export function CompanySettingsSidebar() {
+ const { selectedCompany, selectedCompanyId } = useCompany();
+ const { isMobile, setSidebarOpen } = useSidebar();
+ const { data: badges } = useQuery({
+ queryKey: selectedCompanyId
+ ? queryKeys.sidebarBadges(selectedCompanyId)
+ : ["sidebar-badges", "__disabled__"] as const,
+ queryFn: async () => {
+ try {
+ return await sidebarBadgesApi.get(selectedCompanyId!);
+ } catch (error) {
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
+ return null;
+ }
+ throw error;
+ }
+ },
+ enabled: !!selectedCompanyId,
+ retry: false,
+ refetchInterval: 15_000,
+ });
+
+ return (
+ <aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">
+ <div className="flex flex-col gap-1 px-3 py-3 shrink-0">
+ <Link
+ to="/dashboard"
+ onClick={() => {
+ if (isMobile) setSidebarOpen(false);
+ }}
+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
+ >
+ <ChevronLeft className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{selectedCompany?.name ?? "Company"}</span>
+ </Link>
+ <div className="flex items-center gap-2 px-2 py-1">
+ <Settings className="h-4 w-4 text-muted-foreground shrink-0" />
+ <span className="flex-1 truncate text-sm font-bold text-foreground">
+ Company Settings
+ </span>
+ </div>
+ </div>
+
+ <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">
+ <div className="flex flex-col gap-0.5">
+ <SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />
+ <SidebarNavItem
+ to="/company/settings/access"
+ label="Access"
+ icon={Shield}
+ badge={badges?.joinRequests ?? 0}
+ end
+ />
+ <SidebarNavItem to="/company/settings/invites" label="Invites" icon={MailPlus} end />
+ </div>
+ </nav>
+ </aside>
+ );
+}
diff --git a/ui/src/components/ExecutionParticipantPicker.tsx b/ui/src/components/ExecutionParticipantPicker.tsx
index 7e8942b58d..cf21a5c35f 100644
--- a/ui/src/components/ExecutionParticipantPicker.tsx
+++ b/ui/src/components/ExecutionParticipantPicker.tsx
@@ -1,6 +1,10 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import type { Agent, Issue } from "@paperclipai/shared";
+import { useQuery } from "@tanstack/react-query";
+import { accessApi } from "../api/access";
import { formatAssigneeUserLabel } from "../lib/assignees";
+import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap } from "../lib/company-members";
+import { queryKeys } from "../lib/queryKeys";
import { sortAgentsByRecency, getRecentAssigneeIds } from "../lib/recent-assignees";
import {
buildExecutionPolicy,
@@ -34,14 +38,27 @@ export function ExecutionParticipantPicker({
const reviewerValues = stageParticipantValues(issue.executionPolicy, "review");
const approverValues = stageParticipantValues(issue.executionPolicy, "approval");
const values = stageType === "review" ? reviewerValues : approverValues;
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(issue.companyId),
+ queryFn: () => accessApi.listUserDirectory(issue.companyId),
+ enabled: !!issue.companyId,
+ });
const sortedAgents = sortAgentsByRecency(
agents.filter((a) => a.status !== "terminated"),
getRecentAssigneeIds(),
);
+ const userLabelMap = useMemo(
+ () => buildCompanyUserLabelMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+ const otherUserOptions = useMemo(
+ () => buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId, issue.createdByUserId] }),
+ [companyMembers?.users, currentUserId, issue.createdByUserId],
+ );
const userLabel = (userId: string | null | undefined) =>
- formatAssigneeUserLabel(userId, currentUserId);
+ formatAssigneeUserLabel(userId, currentUserId, userLabelMap);
const creatorUserLabel = userLabel(issue.createdByUserId);
const agentName = (id: string) => {
@@ -138,6 +155,24 @@ export function ExecutionParticipantPicker({
{creatorUserLabel ?? "Requester"}
</button>
)}
+ {otherUserOptions
+ .filter((option) => {
+ if (!search.trim()) return true;
+ return `${option.label} ${option.searchText ?? ""}`.toLowerCase().includes(search.toLowerCase());
+ })
+ .map((option) => (
+ <button
+ key={option.id}
+ className={cn(
+ "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
+ values.includes(option.id) && "bg-accent",
+ )}
+ onClick={() => toggle(option.id)}
+ >
+ <User className="h-3 w-3 shrink-0 text-muted-foreground" />
+ {option.label}
+ </button>
+ ))}
{sortedAgents
.filter((agent) => {
if (!search.trim()) return true;
diff --git a/ui/src/components/ExecutionWorkspaceCloseDialog.tsx b/ui/src/components/ExecutionWorkspaceCloseDialog.tsx
index e37bc16659..fe4477966a 100644
--- a/ui/src/components/ExecutionWorkspaceCloseDialog.tsx
+++ b/ui/src/components/ExecutionWorkspaceCloseDialog.tsx
@@ -88,27 +88,27 @@ export function ExecutionWorkspaceCloseDialog({
<Dialog open={open} onOpenChange={(nextOpen) => {
if (!closeWorkspace.isPending) onOpenChange(nextOpen);
}}>
- <DialogContent className="max-h-[85vh] overflow-x-hidden overflow-y-auto p-4 sm:max-w-2xl sm:p-6 [&>*]:min-w-0">
+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{actionLabel}</DialogTitle>
- <DialogDescription className="break-words text-xs sm:text-sm">
+ <DialogDescription className="break-words">
Archive <span className="font-medium text-foreground">{workspaceName}</span> and clean up any owned workspace
artifacts. Paperclip keeps the workspace record and issue history, but removes it from active workspace views.
</DialogDescription>
</DialogHeader>
{readinessQuery.isLoading ? (
- <div className="flex items-center gap-2 rounded-xl border border-border bg-muted/30 px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin shrink-0" />
+ <div className="flex items-center gap-2 rounded-xl border border-border bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
Checking whether this workspace is safe to close...
</div>
) : readinessQuery.error ? (
- <div className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm text-destructive">
+ <div className="rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
{readinessQuery.error instanceof Error ? readinessQuery.error.message : "Failed to inspect workspace close readiness."}
</div>
) : readiness ? (
- <div className="min-w-0 space-y-3 sm:space-y-4">
- <div className={`rounded-xl border px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm ${readinessTone(readiness.state)}`}>
+ <div className="space-y-4">
+ <div className={`rounded-xl border px-4 py-3 text-sm ${readinessTone(readiness.state)}`}>
<div className="font-medium">
{readiness.state === "blocked"
? "Close is blocked"
@@ -129,10 +129,10 @@ export function ExecutionWorkspaceCloseDialog({
{blockingIssues.length > 0 ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Blocking issues</h3>
- <div className="space-y-1.5 sm:space-y-2">
+ <h3 className="text-sm font-medium">Blocking issues</h3>
+ <div className="space-y-2">
{blockingIssues.map((issue) => (
- <div key={issue.id} className="rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs sm:px-4 sm:py-3 sm:text-sm">
+ <div key={issue.id} className="rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<Link to={issueUrl(issue)} className="min-w-0 break-words font-medium hover:underline">
{issue.identifier ?? issue.id} · {issue.title}
@@ -147,10 +147,10 @@ export function ExecutionWorkspaceCloseDialog({
{readiness.blockingReasons.length > 0 ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Blocking reasons</h3>
- <ul className="space-y-1.5 text-xs sm:space-y-2 sm:text-sm text-muted-foreground">
- {readiness.blockingReasons.map((reason, idx) => (
- <li key={`blocking-${idx}`} className="break-words rounded-lg border border-destructive/20 bg-destructive/5 px-2.5 py-1.5 sm:px-3 sm:py-2 text-destructive">
+ <h3 className="text-sm font-medium">Blocking reasons</h3>
+ <ul className="space-y-2 text-sm text-muted-foreground">
+ {readiness.blockingReasons.map((reason) => (
+ <li key={reason} className="break-words rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-destructive">
{reason}
</li>
))}
@@ -160,10 +160,10 @@ export function ExecutionWorkspaceCloseDialog({
{readiness.warnings.length > 0 ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Warnings</h3>
- <ul className="space-y-1.5 text-xs sm:space-y-2 sm:text-sm text-muted-foreground">
- {readiness.warnings.map((warning, idx) => (
- <li key={`warning-${idx}`} className="break-words rounded-lg border border-amber-500/20 bg-amber-500/5 px-2.5 py-1.5 sm:px-3 sm:py-2">
+ <h3 className="text-sm font-medium">Warnings</h3>
+ <ul className="space-y-2 text-sm text-muted-foreground">
+ {readiness.warnings.map((warning) => (
+ <li key={warning} className="break-words rounded-lg border border-amber-500/20 bg-amber-500/5 px-3 py-2">
{warning}
</li>
))}
@@ -173,16 +173,16 @@ export function ExecutionWorkspaceCloseDialog({
{readiness.git ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Git status</h3>
- <div className="overflow-hidden rounded-xl border border-border bg-muted/20 px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm">
- <div className="grid grid-cols-2 gap-2">
- <div className="min-w-0">
+ <h3 className="text-sm font-medium">Git status</h3>
+ <div className="rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm">
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div>
<div className="text-xs uppercase tracking-[0.16em] text-muted-foreground">Branch</div>
- <div className="truncate font-mono text-xs">{readiness.git.branchName ?? "Unknown"}</div>
+ <div className="font-mono text-xs">{readiness.git.branchName ?? "Unknown"}</div>
</div>
- <div className="min-w-0">
+ <div>
<div className="text-xs uppercase tracking-[0.16em] text-muted-foreground">Base ref</div>
- <div className="truncate font-mono text-xs">{readiness.git.baseRef ?? "Not set"}</div>
+ <div className="font-mono text-xs">{readiness.git.baseRef ?? "Not set"}</div>
</div>
<div>
<div className="text-xs uppercase tracking-[0.16em] text-muted-foreground">Merged into base</div>
@@ -209,10 +209,10 @@ export function ExecutionWorkspaceCloseDialog({
{otherLinkedIssues.length > 0 ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Other linked issues</h3>
- <div className="space-y-1.5 sm:space-y-2">
+ <h3 className="text-sm font-medium">Other linked issues</h3>
+ <div className="space-y-2">
{otherLinkedIssues.map((issue) => (
- <div key={issue.id} className="rounded-xl border border-border bg-muted/20 px-3 py-2 text-xs sm:px-4 sm:py-3 sm:text-sm">
+ <div key={issue.id} className="rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<Link to={issueUrl(issue)} className="min-w-0 break-words font-medium hover:underline">
{issue.identifier ?? issue.id} · {issue.title}
@@ -227,10 +227,10 @@ export function ExecutionWorkspaceCloseDialog({
{readiness.runtimeServices.length > 0 ? (
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Attached runtime services</h3>
- <div className="space-y-1.5 sm:space-y-2">
+ <h3 className="text-sm font-medium">Attached runtime services</h3>
+ <div className="space-y-2">
{readiness.runtimeServices.map((service) => (
- <div key={service.id} className="rounded-xl border border-border bg-muted/20 px-3 py-2 text-xs sm:px-4 sm:py-3 sm:text-sm">
+ <div key={service.id} className="rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<span className="font-medium">{service.serviceName}</span>
<span className="text-xs text-muted-foreground">{service.status} · {service.lifecycle}</span>
@@ -245,10 +245,10 @@ export function ExecutionWorkspaceCloseDialog({
) : null}
<section className="space-y-2">
- <h3 className="text-xs font-medium sm:text-sm">Cleanup actions</h3>
- <div className="space-y-1.5 sm:space-y-2">
+ <h3 className="text-sm font-medium">Cleanup actions</h3>
+ <div className="space-y-2">
{readiness.plannedActions.map((action, index) => (
- <div key={`${action.kind}-${index}`} className="rounded-xl border border-border bg-muted/20 px-3 py-2 text-xs sm:px-4 sm:py-3 sm:text-sm">
+ <div key={`${action.kind}-${index}`} className="rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm">
<div className="font-medium">{action.label}</div>
<div className="mt-1 break-words text-muted-foreground">{action.description}</div>
{action.command ? (
@@ -262,20 +262,20 @@ export function ExecutionWorkspaceCloseDialog({
</section>
{currentStatus === "cleanup_failed" ? (
- <div className="rounded-xl border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm text-muted-foreground">
+ <div className="rounded-xl border border-amber-500/20 bg-amber-500/5 px-4 py-3 text-sm text-muted-foreground">
Cleanup previously failed on this workspace. Retrying close will rerun the cleanup flow and update the
workspace status if it succeeds.
</div>
) : null}
{currentStatus === "archived" ? (
- <div className="rounded-xl border border-border bg-muted/20 px-3 py-2.5 text-xs sm:px-4 sm:py-3 sm:text-sm text-muted-foreground">
+ <div className="rounded-xl border border-border bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
This workspace is already archived.
</div>
) : null}
{readiness.git?.repoRoot ? (
- <div className="overflow-hidden break-words text-xs text-muted-foreground">
+ <div className="break-words text-xs text-muted-foreground">
Repo root: <span className="font-mono break-all">{readiness.git.repoRoot}</span>
{readiness.git.workspacePath ? (
<>
diff --git a/ui/src/components/InstanceSidebar.tsx b/ui/src/components/InstanceSidebar.tsx
index b39b959c65..6a1d0add15 100644
--- a/ui/src/components/InstanceSidebar.tsx
+++ b/ui/src/components/InstanceSidebar.tsx
@@ -1,5 +1,5 @@
import { useQuery } from "@tanstack/react-query";
-import { Clock3, Cpu, FlaskConical, Puzzle, Settings, SlidersHorizontal } from "lucide-react";
+import { Clock3, Cpu, FlaskConical, Puzzle, Settings, Shield, SlidersHorizontal, UserRoundPen } from "lucide-react";
import { NavLink } from "@/lib/router";
import { pluginsApi } from "@/api/plugins";
import { queryKeys } from "@/lib/queryKeys";
@@ -23,7 +23,9 @@ export function InstanceSidebar() {
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 px-3 py-2">
<div className="flex flex-col gap-0.5">
+ <SidebarNavItem to="/instance/settings/profile" label="Profile" icon={UserRoundPen} end />
<SidebarNavItem to="/instance/settings/general" label="General" icon={SlidersHorizontal} end />
+ <SidebarNavItem to="/instance/settings/access" label="Access" icon={Shield} end />
<SidebarNavItem to="/instance/settings/heartbeats" label="Heartbeats" icon={Clock3} end />
<SidebarNavItem to="/instance/settings/experimental" label="Experimental" icon={FlaskConical} />
<SidebarNavItem to="/instance/settings/plugins" label="Plugins" icon={Puzzle} />
diff --git a/ui/src/components/IssueChatThread.test.tsx b/ui/src/components/IssueChatThread.test.tsx
index dbddfacb3d..13f237c627 100644
--- a/ui/src/components/IssueChatThread.test.tsx
+++ b/ui/src/components/IssueChatThread.test.tsx
@@ -5,7 +5,12 @@ import type { ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { IssueChatThread, canStopIssueChatRun, resolveAssistantMessageFoldedState } from "./IssueChatThread";
+import {
+ IssueChatThread,
+ canStopIssueChatRun,
+ resolveAssistantMessageFoldedState,
+ resolveIssueChatHumanAuthor,
+} from "./IssueChatThread";
const { markdownEditorFocusMock } = vi.hoisted(() => ({
markdownEditorFocusMock: vi.fn(),
@@ -661,4 +666,33 @@ describe("IssueChatThread", () => {
activeRunIds: new Set<string>(),
})).toBe(false);
});
+
+ it("uses company profile data to distinguish the current user from other humans", () => {
+ const userProfileMap = new Map([
+ ["user-1", { label: "Dotta", image: "/avatars/dotta.png" }],
+ ["user-2", { label: "Alice", image: "/avatars/alice.png" }],
+ ]);
+
+ expect(resolveIssueChatHumanAuthor({
+ authorName: "You",
+ authorUserId: "user-1",
+ currentUserId: "user-1",
+ userProfileMap,
+ })).toEqual({
+ isCurrentUser: true,
+ authorName: "Dotta",
+ avatarUrl: "/avatars/dotta.png",
+ });
+
+ expect(resolveIssueChatHumanAuthor({
+ authorName: "Alice",
+ authorUserId: "user-2",
+ currentUserId: "user-1",
+ userProfileMap,
+ })).toEqual({
+ isCurrentUser: false,
+ authorName: "Alice",
+ avatarUrl: "/avatars/alice.png",
+ });
+ });
});
diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx
index 91fda37330..096ef8f245 100644
--- a/ui/src/components/IssueChatThread.tsx
+++ b/ui/src/components/IssueChatThread.tsx
@@ -47,7 +47,7 @@ import {
import { resolveIssueChatTranscriptRuns } from "../lib/issueChatTranscriptRuns";
import type { IssueTimelineAssignee, IssueTimelineEvent } from "../lib/issue-timeline-events";
import { Button } from "@/components/ui/button";
-import { Avatar, AvatarFallback } from "@/components/ui/avatar";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Dialog,
DialogContent,
@@ -74,6 +74,7 @@ import {
shouldPreserveComposerViewport,
} from "../lib/issue-chat-scroll";
import { formatAssigneeUserLabel } from "../lib/assignees";
+import type { CompanyUserProfile } from "../lib/company-members";
import { timeAgo } from "../lib/timeAgo";
import {
describeToolInput,
@@ -96,6 +97,8 @@ interface IssueChatMessageContext {
feedbackTermsUrl: string | null;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
+ userLabelMap?: ReadonlyMap<string, string> | null;
+ userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
activeRunIds: ReadonlySet<string>;
onVote?: (
commentId: string,
@@ -217,6 +220,8 @@ interface IssueChatThreadProps {
issueStatus?: string;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
+ userLabelMap?: ReadonlyMap<string, string> | null;
+ userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
onVote?: (
commentId: string,
vote: FeedbackVoteValue,
@@ -477,12 +482,13 @@ function formatTimelineAssigneeLabel(
assignee: IssueTimelineAssignee,
agentMap?: Map<string, Agent>,
currentUserId?: string | null,
+ userLabelMap?: ReadonlyMap<string, string> | null,
) {
if (assignee.agentId) {
return agentMap?.get(assignee.agentId)?.name ?? assignee.agentId.slice(0, 8);
}
if (assignee.userId) {
- return formatAssigneeUserLabel(assignee.userId, currentUserId) ?? "Board";
+ return formatAssigneeUserLabel(assignee.userId, currentUserId, userLabelMap) ?? "Board";
}
return "Unassigned";
}
@@ -495,6 +501,26 @@ function initialsForName(name: string) {
return name.slice(0, 2).toUpperCase();
}
+export function resolveIssueChatHumanAuthor(args: {
+ authorName?: string | null;
+ authorUserId?: string | null;
+ currentUserId?: string | null;
+ userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
+}) {
+ const { authorName, authorUserId, currentUserId, userProfileMap } = args;
+ const profile = authorUserId ? userProfileMap?.get(authorUserId) ?? null : null;
+ const isCurrentUser = Boolean(authorUserId && currentUserId && authorUserId === currentUserId);
+ const resolvedAuthorName = profile?.label?.trim()
+ || authorName?.trim()
+ || (authorUserId === "local-board" ? "Board" : (isCurrentUser ? "You" : "User"));
+
+ return {
+ isCurrentUser,
+ authorName: resolvedAuthorName,
+ avatarUrl: profile?.image ?? null,
+ };
+}
+
function formatRunStatusLabel(status: string) {
switch (status) {
case "timed_out":
@@ -906,108 +932,151 @@ function IssueChatToolPart({
}
function IssueChatUserMessage() {
- const { onInterruptQueued, onCancelQueued, interruptingQueuedRunId } = useContext(IssueChatCtx);
+ const {
+ onInterruptQueued,
+ onCancelQueued,
+ interruptingQueuedRunId,
+ currentUserId,
+ userProfileMap,
+ } = useContext(IssueChatCtx);
const message = useMessage();
const custom = message.metadata.custom as Record<string, unknown>;
const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
const commentId = typeof custom.commentId === "string" ? custom.commentId : message.id;
+ const authorName = typeof custom.authorName === "string" ? custom.authorName : null;
+ const authorUserId = typeof custom.authorUserId === "string" ? custom.authorUserId : null;
const queued = custom.queueState === "queued" || custom.clientStatus === "queued";
const pending = custom.clientStatus === "pending";
const queueTargetRunId = typeof custom.queueTargetRunId === "string" ? custom.queueTargetRunId : null;
const [copied, setCopied] = useState(false);
-
- return (
- <MessagePrimitive.Root id={anchorId}>
- <div className="group flex items-start justify-end gap-2.5">
- <div className="flex min-w-0 max-w-[85%] flex-col items-end">
- <div
- className={cn(
- "min-w-0 max-w-full overflow-hidden break-all rounded-2xl px-4 py-2.5",
- queued
- ? "bg-amber-50/80 dark:bg-amber-500/10"
- : "bg-muted",
- pending && "opacity-80",
- )}
- >
- {queued ? (
- <div className="mb-1.5 flex items-center gap-2">
- <span className="inline-flex items-center rounded-full border border-amber-400/60 bg-amber-100/70 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-amber-800 dark:border-amber-400/40 dark:bg-amber-500/20 dark:text-amber-200">
- Queued
- </span>
- {queueTargetRunId && onInterruptQueued ? (
- <Button
- size="sm"
- variant="outline"
- className="h-6 border-red-300 px-2 text-[11px] text-red-700 hover:bg-red-50 hover:text-red-800 dark:border-red-500/40 dark:text-red-300 dark:hover:bg-red-500/10"
- disabled={interruptingQueuedRunId === queueTargetRunId}
- onClick={() => void onInterruptQueued(queueTargetRunId)}
- >
- {interruptingQueuedRunId === queueTargetRunId ? "Interrupting..." : "Interrupt"}
- </Button>
- ) : null}
- {onCancelQueued ? (
- <Button
- size="sm"
- variant="outline"
- className="h-6 border-amber-300 px-2 text-[11px] text-amber-900 hover:bg-amber-100/80 hover:text-amber-950 dark:border-amber-500/40 dark:text-amber-100 dark:hover:bg-amber-500/10"
- onClick={() => onCancelQueued(commentId)}
- >
- Cancel
- </Button>
- ) : null}
- </div>
+ const {
+ isCurrentUser,
+ authorName: resolvedAuthorName,
+ avatarUrl,
+ } = resolveIssueChatHumanAuthor({
+ authorName,
+ authorUserId,
+ currentUserId,
+ userProfileMap,
+ });
+ const authorAvatar = (
+ <Avatar size="sm" className="mt-1 shrink-0">
+ {avatarUrl ? <AvatarImage src={avatarUrl} alt={resolvedAuthorName} /> : null}
+ <AvatarFallback>{initialsForName(resolvedAuthorName)}</AvatarFallback>
+ </Avatar>
+ );
+ const messageBody = (
+ <div className={cn("flex min-w-0 max-w-[85%] flex-col", isCurrentUser && "items-end")}>
+ <div className={cn("mb-1 flex items-center gap-2 px-1", isCurrentUser ? "justify-end" : "justify-start")}>
+ <span className="text-sm font-medium text-foreground">{resolvedAuthorName}</span>
+ </div>
+ <div
+ className={cn(
+ "min-w-0 max-w-full overflow-hidden break-all rounded-2xl px-4 py-2.5",
+ queued
+ ? "bg-amber-50/80 dark:bg-amber-500/10"
+ : "bg-muted",
+ pending && "opacity-80",
+ )}
+ >
+ {queued ? (
+ <div className="mb-1.5 flex items-center gap-2">
+ <span className="inline-flex items-center rounded-full border border-amber-400/60 bg-amber-100/70 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-amber-800 dark:border-amber-400/40 dark:bg-amber-500/20 dark:text-amber-200">
+ Queued
+ </span>
+ {queueTargetRunId && onInterruptQueued ? (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-6 border-red-300 px-2 text-[11px] text-red-700 hover:bg-red-50 hover:text-red-800 dark:border-red-500/40 dark:text-red-300 dark:hover:bg-red-500/10"
+ disabled={interruptingQueuedRunId === queueTargetRunId}
+ onClick={() => void onInterruptQueued(queueTargetRunId)}
+ >
+ {interruptingQueuedRunId === queueTargetRunId ? "Interrupting..." : "Interrupt"}
+ </Button>
+ ) : null}
+ {onCancelQueued ? (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-6 border-amber-300 px-2 text-[11px] text-amber-900 hover:bg-amber-100/80 hover:text-amber-950 dark:border-amber-500/40 dark:text-amber-100 dark:hover:bg-amber-500/10"
+ onClick={() => onCancelQueued(commentId)}
+ >
+ Cancel
+ </Button>
) : null}
- <div className="min-w-0 max-w-full space-y-3">
- <MessagePrimitive.Parts
- components={{
- Text: ({ text }) => <IssueChatTextPart text={text} />,
- }}
- />
- </div>
</div>
+ ) : null}
+ <div className="min-w-0 max-w-full space-y-3">
+ <MessagePrimitive.Parts
+ components={{
+ Text: ({ text }) => <IssueChatTextPart text={text} />,
+ }}
+ />
+ </div>
+ </div>
- {pending ? (
- <div className="mt-1 flex justify-end px-1 text-[11px] text-muted-foreground">Sending...</div>
- ) : (
- <div className="mt-1 flex items-center justify-end gap-1.5 px-1 opacity-0 transition-opacity group-hover:opacity-100">
- <Tooltip>
- <TooltipTrigger asChild>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-[11px] text-muted-foreground hover:text-foreground hover:underline"
- >
- {message.createdAt ? commentDateLabel(message.createdAt) : ""}
- </a>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- {message.createdAt ? formatDateTime(message.createdAt) : ""}
- </TooltipContent>
- </Tooltip>
- <button
- type="button"
- className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
- title="Copy message"
- aria-label="Copy message"
- onClick={() => {
- const text = message.content
- .filter((p): p is { type: "text"; text: string } => p.type === "text")
- .map((p) => p.text)
- .join("\n\n");
- void navigator.clipboard.writeText(text).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- });
- }}
- >
- {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
- </button>
- </div>
+ {pending ? (
+ <div className={cn("mt-1 flex px-1 text-[11px] text-muted-foreground", isCurrentUser ? "justify-end" : "justify-start")}>
+ Sending...
+ </div>
+ ) : (
+ <div
+ className={cn(
+ "mt-1 flex items-center gap-1.5 px-1 opacity-0 transition-opacity group-hover:opacity-100",
+ isCurrentUser ? "justify-end" : "justify-start",
)}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <a
+ href={anchorId ? `#${anchorId}` : undefined}
+ className="text-[11px] text-muted-foreground hover:text-foreground hover:underline"
+ >
+ {message.createdAt ? commentDateLabel(message.createdAt) : ""}
+ </a>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ {message.createdAt ? formatDateTime(message.createdAt) : ""}
+ </TooltipContent>
+ </Tooltip>
+ <button
+ type="button"
+ className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
+ title="Copy message"
+ aria-label="Copy message"
+ onClick={() => {
+ const text = message.content
+ .filter((p): p is { type: "text"; text: string } => p.type === "text")
+ .map((p) => p.text)
+ .join("\n\n");
+ void navigator.clipboard.writeText(text).then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ });
+ }}
+ >
+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
+ </button>
</div>
+ )}
+ </div>
+ );
- <Avatar size="sm" className="mt-1 shrink-0">
- <AvatarFallback>You</AvatarFallback>
- </Avatar>
+ return (
+ <MessagePrimitive.Root id={anchorId}>
+ <div className={cn("group flex items-start gap-2.5", isCurrentUser && "justify-end")}>
+ {isCurrentUser ? (
+ <>
+ {messageBody}
+ {authorAvatar}
+ </>
+ ) : (
+ <>
+ {authorAvatar}
+ {messageBody}
+ </>
+ )}
</div>
</MessagePrimitive.Root>
);
@@ -1463,7 +1532,7 @@ function IssueChatFeedbackButtons({
}
function IssueChatSystemMessage() {
- const { agentMap, currentUserId } = useContext(IssueChatCtx);
+ const { agentMap, currentUserId, userLabelMap } = useContext(IssueChatCtx);
const message = useMessage();
const custom = message.metadata.custom as Record<string, unknown>;
const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
@@ -1519,11 +1588,11 @@ function IssueChatSystemMessage() {
Assignee
</span>
<span className="text-muted-foreground">
- {formatTimelineAssigneeLabel(assigneeChange.from, agentMap, currentUserId)}
+ {formatTimelineAssigneeLabel(assigneeChange.from, agentMap, currentUserId, userLabelMap)}
</span>
<ArrowRight className="h-3 w-3 text-muted-foreground" />
<span className="font-medium text-foreground">
- {formatTimelineAssigneeLabel(assigneeChange.to, agentMap, currentUserId)}
+ {formatTimelineAssigneeLabel(assigneeChange.to, agentMap, currentUserId, userLabelMap)}
</span>
</div>
) : null}
@@ -1855,6 +1924,8 @@ export function IssueChatThread({
issueStatus,
agentMap,
currentUserId,
+ userLabelMap,
+ userProfileMap,
onVote,
onAdd,
onCancelRun,
@@ -1947,6 +2018,7 @@ export function IssueChatThread({
projectId,
agentMap,
currentUserId,
+ userLabelMap,
}),
[
comments,
@@ -1961,6 +2033,7 @@ export function IssueChatThread({
projectId,
agentMap,
currentUserId,
+ userLabelMap,
],
);
const stableMessagesRef = useRef<readonly import("@assistant-ui/react").ThreadMessage[]>([]);
@@ -2028,6 +2101,8 @@ export function IssueChatThread({
feedbackTermsUrl,
agentMap,
currentUserId,
+ userLabelMap,
+ userProfileMap,
activeRunIds,
onVote,
onStopRun,
@@ -2043,6 +2118,8 @@ export function IssueChatThread({
feedbackTermsUrl,
agentMap,
currentUserId,
+ userLabelMap,
+ userProfileMap,
activeRunIds,
onVote,
onStopRun,
diff --git a/ui/src/components/IssueColumns.tsx b/ui/src/components/IssueColumns.tsx
index 516a8c4506..492ba2fba7 100644
--- a/ui/src/components/IssueColumns.tsx
+++ b/ui/src/components/IssueColumns.tsx
@@ -196,6 +196,8 @@ export function InboxIssueTrailingColumns({
workspaceId,
workspaceName,
assigneeName,
+ assigneeUserName,
+ assigneeUserAvatarUrl,
currentUserId,
parentIdentifier,
parentTitle,
@@ -209,6 +211,8 @@ export function InboxIssueTrailingColumns({
workspaceId?: string | null;
workspaceName: string | null;
assigneeName: string | null;
+ assigneeUserName?: string | null;
+ assigneeUserAvatarUrl?: string | null;
currentUserId: string | null;
parentIdentifier: string | null;
parentTitle: string | null;
@@ -216,7 +220,7 @@ export function InboxIssueTrailingColumns({
onFilterWorkspace?: (workspaceId: string) => void;
}) {
const activityText = timeAgo(issue.lastActivityAt ?? issue.lastExternalCommentAt ?? issue.updatedAt);
- const userLabel = formatAssigneeUserLabel(issue.assigneeUserId, currentUserId) ?? "User";
+ const userLabel = assigneeUserName ?? formatAssigneeUserLabel(issue.assigneeUserId, currentUserId) ?? "User";
return (
<span
@@ -243,8 +247,13 @@ export function InboxIssueTrailingColumns({
if (issue.assigneeUserId) {
return (
- <span key={column} className="min-w-0 truncate text-xs font-medium text-muted-foreground">
- {userLabel}
+ <span key={column} className="min-w-0 text-xs text-foreground">
+ <Identity
+ name={userLabel}
+ avatarUrl={assigneeUserAvatarUrl}
+ size="sm"
+ className="min-w-0"
+ />
</span>
);
}
diff --git a/ui/src/components/IssueProperties.tsx b/ui/src/components/IssueProperties.tsx
index 0deebe6376..4a83830b3c 100644
--- a/ui/src/components/IssueProperties.tsx
+++ b/ui/src/components/IssueProperties.tsx
@@ -3,12 +3,14 @@ import { pickTextColorForPillBg } from "@/lib/color-contrast";
import { Link } from "@/lib/router";
import type { Issue } from "@paperclipai/shared";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { accessApi } from "../api/access";
import { agentsApi } from "../api/agents";
import { authApi } from "../api/auth";
import { issuesApi } from "../api/issues";
import { projectsApi } from "../api/projects";
import { useCompany } from "../context/CompanyContext";
import { queryKeys } from "../lib/queryKeys";
+import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap } from "../lib/company-members";
import { useProjectOrder } from "../hooks/useProjectOrder";
import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
import { formatAssigneeUserLabel } from "../lib/assignees";
@@ -187,6 +189,11 @@ export function IssueProperties({
queryFn: () => agentsApi.list(companyId!),
enabled: !!companyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(companyId!),
+ queryFn: () => accessApi.listUserDirectory(companyId!),
+ enabled: !!companyId,
+ });
const { data: projects } = useQuery({
queryKey: queryKeys.projects.list(companyId!),
@@ -257,13 +264,21 @@ export function IssueProperties({
() => sortAgentsByRecency((agents ?? []).filter((a) => a.status !== "terminated"), recentAssigneeIds),
[agents, recentAssigneeIds],
);
+ const userLabelMap = useMemo(
+ () => buildCompanyUserLabelMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+ const otherUserOptions = useMemo(
+ () => buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId, issue.createdByUserId] }),
+ [companyMembers?.users, currentUserId, issue.createdByUserId],
+ );
const assignee = issue.assigneeAgentId
? agents?.find((a) => a.id === issue.assigneeAgentId)
: null;
const reviewerValues = stageParticipantValues(issue.executionPolicy, "review");
const approverValues = stageParticipantValues(issue.executionPolicy, "approval");
- const userLabel = (userId: string | null | undefined) => formatAssigneeUserLabel(userId, currentUserId);
+ const userLabel = (userId: string | null | undefined) => formatAssigneeUserLabel(userId, currentUserId, userLabelMap);
const assigneeUserLabel = userLabel(issue.assigneeUserId);
const creatorUserLabel = userLabel(issue.createdByUserId);
const updateExecutionPolicy = (nextReviewers: string[], nextApprovers: string[]) => {
@@ -499,6 +514,31 @@ export function IssueProperties({
{creatorUserLabel ? `Assign to ${creatorUserLabel}` : "Assign to requester"}
</button>
)}
+ {otherUserOptions
+ .filter((option) => {
+ if (!assigneeSearch.trim()) return true;
+ const q = assigneeSearch.toLowerCase();
+ return `${option.label} ${option.searchText ?? ""}`.toLowerCase().includes(q);
+ })
+ .map((option) => {
+ const userId = option.id.slice("user:".length);
+ return (
+ <button
+ key={option.id}
+ className={cn(
+ "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
+ issue.assigneeUserId === userId && "bg-accent",
+ )}
+ onClick={() => {
+ onUpdate({ assigneeAgentId: null, assigneeUserId: userId });
+ setAssigneeOpen(false);
+ }}
+ >
+ <User className="h-3 w-3 shrink-0 text-muted-foreground" />
+ {option.label}
+ </button>
+ );
+ })}
{sortedAgents
.filter((a) => {
if (!assigneeSearch.trim()) return true;
@@ -571,6 +611,24 @@ export function IssueProperties({
{creatorUserLabel ? creatorUserLabel : "Requester"}
</button>
)}
+ {otherUserOptions
+ .filter((option) => {
+ if (!search.trim()) return true;
+ return `${option.label} ${option.searchText ?? ""}`.toLowerCase().includes(search.toLowerCase());
+ })
+ .map((option) => (
+ <button
+ key={`${stageType}:${option.id}`}
+ className={cn(
+ "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
+ values.includes(option.id) && "bg-accent",
+ )}
+ onClick={() => toggleExecutionParticipant(stageType, option.id)}
+ >
+ <User className="h-3 w-3 shrink-0 text-muted-foreground" />
+ {option.label}
+ </button>
+ ))}
{sortedAgents
.filter((agent) => {
if (!search.trim()) return true;
diff --git a/ui/src/components/IssuesList.test.tsx b/ui/src/components/IssuesList.test.tsx
index 4c263f96ed..a41d1bfa4c 100644
--- a/ui/src/components/IssuesList.test.tsx
+++ b/ui/src/components/IssuesList.test.tsx
@@ -26,6 +26,11 @@ const mockAuthApi = vi.hoisted(() => ({
getSession: vi.fn(),
}));
+const mockAccessApi = vi.hoisted(() => ({
+ listMembers: vi.fn(),
+ listUserDirectory: vi.fn(),
+}));
+
const mockExecutionWorkspacesApi = vi.hoisted(() => ({
list: vi.fn(),
listSummaries: vi.fn(),
@@ -51,6 +56,10 @@ vi.mock("../api/auth", () => ({
authApi: mockAuthApi,
}));
+vi.mock("../api/access", () => ({
+ accessApi: mockAccessApi,
+}));
+
vi.mock("../api/execution-workspaces", () => ({
executionWorkspacesApi: mockExecutionWorkspacesApi,
}));
@@ -183,12 +192,16 @@ describe("IssuesList", () => {
mockIssuesApi.list.mockReset();
mockIssuesApi.listLabels.mockReset();
mockAuthApi.getSession.mockReset();
+ mockAccessApi.listMembers.mockReset();
+ mockAccessApi.listUserDirectory.mockReset();
mockExecutionWorkspacesApi.list.mockReset();
mockExecutionWorkspacesApi.listSummaries.mockReset();
mockInstanceSettingsApi.getExperimental.mockReset();
mockIssuesApi.list.mockResolvedValue([]);
mockIssuesApi.listLabels.mockResolvedValue([]);
mockAuthApi.getSession.mockResolvedValue({ user: null, session: null });
+ mockAccessApi.listMembers.mockResolvedValue({ members: [], access: {} });
+ mockAccessApi.listUserDirectory.mockResolvedValue({ users: [] });
mockExecutionWorkspacesApi.list.mockResolvedValue([]);
mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([]);
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
@@ -498,6 +511,50 @@ describe("IssuesList", () => {
});
});
+ it("shows human assignee names from company member profiles", async () => {
+ localStorage.setItem("paperclip:test-issues:company-1:issue-columns", JSON.stringify(["id", "assignee"]));
+ mockAccessApi.listUserDirectory.mockResolvedValue({
+ users: [
+ {
+ principalId: "user-2",
+ status: "active",
+ user: {
+ id: "user-2",
+ name: "Jordan Lee",
+ email: "[email protected]",
+ image: "https://example.com/jordan.png",
+ },
+ },
+ ],
+ });
+
+ const assignedIssue = createIssue({
+ id: "issue-human",
+ identifier: "PAP-12",
+ title: "Human assigned issue",
+ assigneeUserId: "user-2",
+ });
+
+ const { root } = renderWithQueryClient(
+ <IssuesList
+ issues={[assignedIssue]}
+ agents={[]}
+ projects={[]}
+ viewStateKey="paperclip:test-issues"
+ onUpdateIssue={() => undefined}
+ />,
+ container,
+ );
+
+ await waitForAssertion(() => {
+ expect(container.textContent).toContain("Jordan Lee");
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
it("preserves stored grouping across refresh when initial assignees are applied", async () => {
localStorage.setItem(
"paperclip:test-issues:company-1",
diff --git a/ui/src/components/IssuesList.tsx b/ui/src/components/IssuesList.tsx
index 45d3f188a3..283b6ba856 100644
--- a/ui/src/components/IssuesList.tsx
+++ b/ui/src/components/IssuesList.tsx
@@ -1,5 +1,6 @@
import { startTransition, useDeferredValue, useEffect, useMemo, useState, useCallback, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
+import { accessApi } from "../api/access";
import { useDialog } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { executionWorkspacesApi } from "../api/execution-workspaces";
@@ -12,6 +13,7 @@ import {
shouldBlurPageSearchOnEscape,
} from "../lib/keyboardShortcuts";
import { formatAssigneeUserLabel } from "../lib/assignees";
+import { buildCompanyUserLabelMap, buildCompanyUserProfileMap } from "../lib/company-members";
import { groupBy } from "../lib/groupBy";
import {
applyIssueFilters,
@@ -282,6 +284,11 @@ export function IssuesList({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
const { data: experimentalSettings } = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: () => instanceSettingsApi.getExperimental(),
@@ -376,6 +383,15 @@ export function IssuesList({
return agents.find((a) => a.id === id)?.name ?? null;
}, [agents]);
+ const companyUserLabelMap = useMemo(
+ () => buildCompanyUserLabelMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+ const companyUserProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+
const projectById = useMemo(() => {
const map = new Map<string, { name: string; color: string | null }>();
for (const project of projects ?? []) {
@@ -601,11 +617,11 @@ export function IssuesList({
key === "__unassigned"
? "Unassigned"
: key.startsWith("__user:")
- ? (formatAssigneeUserLabel(key.slice("__user:".length), currentUserId) ?? "User")
+ ? (formatAssigneeUserLabel(key.slice("__user:".length), currentUserId, companyUserLabelMap) ?? "User")
: (agentName(key) ?? key.slice(0, 8)),
items: groups[key]!,
}));
- }, [filtered, viewState.groupBy, agents, agentName, currentUserId, workspaceNameMap, issueTitleMap]);
+ }, [filtered, viewState.groupBy, agents, agentName, currentUserId, workspaceNameMap, issueTitleMap, companyUserLabelMap]);
useEffect(() => {
if (viewState.viewMode !== "list") return;
@@ -910,6 +926,14 @@ export function IssuesList({
const useDeferredRowRendering = !(hasChildren && isExpanded);
const issueProject = issue.projectId ? projectById.get(issue.projectId) ?? null : null;
const parentIssue = issue.parentId ? issueById.get(issue.parentId) ?? null : null;
+ const assigneeUserProfile = issue.assigneeUserId
+ ? companyUserProfileMap.get(issue.assigneeUserId) ?? null
+ : null;
+ const assigneeUserLabel = formatAssigneeUserLabel(
+ issue.assigneeUserId,
+ currentUserId,
+ companyUserLabelMap,
+ ) ?? assigneeUserProfile?.label ?? null;
const toggleCollapse = (e: { preventDefault: () => void; stopPropagation: () => void }) => {
e.preventDefault();
e.stopPropagation();
@@ -994,6 +1018,8 @@ export function IssuesList({
})}
onFilterWorkspace={filterToWorkspace}
assigneeName={agentName(issue.assigneeAgentId)}
+ assigneeUserName={assigneeUserLabel}
+ assigneeUserAvatarUrl={assigneeUserProfile?.image ?? null}
currentUserId={currentUserId}
parentIdentifier={parentIssue?.identifier ?? null}
parentTitle={parentIssue?.title ?? null}
@@ -1007,18 +1033,18 @@ export function IssuesList({
>
<PopoverTrigger asChild>
<button
- className="flex w-[180px] shrink-0 items-center rounded-md px-2 py-1 transition-colors hover:bg-accent/50"
+ className="flex w-full shrink-0 items-center overflow-hidden rounded-md px-2 py-1 transition-colors hover:bg-accent/50"
onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
>
{issue.assigneeAgentId && agentName(issue.assigneeAgentId) ? (
- <Identity name={agentName(issue.assigneeAgentId)!} size="sm" />
+ <Identity name={agentName(issue.assigneeAgentId)!} size="sm" className="min-w-0" />
) : issue.assigneeUserId ? (
- <span className="inline-flex items-center gap-1.5 text-xs">
- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30">
- <User className="h-3.5 w-3.5" />
- </span>
- {formatAssigneeUserLabel(issue.assigneeUserId, currentUserId) ?? "User"}
- </span>
+ <Identity
+ name={assigneeUserLabel ?? "User"}
+ avatarUrl={assigneeUserProfile?.image ?? null}
+ size="sm"
+ className="min-w-0"
+ />
) : (
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<span className="inline-flex h-6 w-6 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30">
diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsx
new file mode 100644
index 0000000000..9ea147a85b
--- /dev/null
+++ b/ui/src/components/Layout.test.tsx
@@ -0,0 +1,249 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Layout } from "./Layout";
+
+const mockHealthApi = vi.hoisted(() => ({
+ get: vi.fn(),
+}));
+
+const mockInstanceSettingsApi = vi.hoisted(() => ({
+ getGeneral: vi.fn(),
+}));
+
+const mockNavigate = vi.hoisted(() => vi.fn());
+const mockSetSelectedCompanyId = vi.hoisted(() => vi.fn());
+const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
+let currentPathname = "/PAP/dashboard";
+
+vi.mock("@/lib/router", () => ({
+ Outlet: () => <div>Outlet content</div>,
+ useLocation: () => ({ pathname: currentPathname, search: "", hash: "", state: null }),
+ useNavigate: () => mockNavigate,
+ useNavigationType: () => "PUSH",
+ useParams: () => ({ companyPrefix: "PAP" }),
+}));
+
+vi.mock("./CompanyRail", () => ({
+ CompanyRail: () => <div>Company rail</div>,
+}));
+
+vi.mock("./Sidebar", () => ({
+ Sidebar: () => <div>Main company nav</div>,
+}));
+
+vi.mock("./InstanceSidebar", () => ({
+ InstanceSidebar: () => <div>Instance sidebar</div>,
+}));
+
+vi.mock("./CompanySettingsSidebar", () => ({
+ CompanySettingsSidebar: () => <div>Company settings sidebar</div>,
+}));
+
+vi.mock("./BreadcrumbBar", () => ({
+ BreadcrumbBar: () => <div>Breadcrumbs</div>,
+}));
+
+vi.mock("./PropertiesPanel", () => ({
+ PropertiesPanel: () => null,
+}));
+
+vi.mock("./CommandPalette", () => ({
+ CommandPalette: () => null,
+}));
+
+vi.mock("./NewIssueDialog", () => ({
+ NewIssueDialog: () => null,
+}));
+
+vi.mock("./NewProjectDialog", () => ({
+ NewProjectDialog: () => null,
+}));
+
+vi.mock("./NewGoalDialog", () => ({
+ NewGoalDialog: () => null,
+}));
+
+vi.mock("./NewAgentDialog", () => ({
+ NewAgentDialog: () => null,
+}));
+
+vi.mock("./KeyboardShortcutsCheatsheet", () => ({
+ KeyboardShortcutsCheatsheet: () => null,
+}));
+
+vi.mock("./ToastViewport", () => ({
+ ToastViewport: () => null,
+}));
+
+vi.mock("./MobileBottomNav", () => ({
+ MobileBottomNav: () => null,
+}));
+
+vi.mock("./WorktreeBanner", () => ({
+ WorktreeBanner: () => null,
+}));
+
+vi.mock("./DevRestartBanner", () => ({
+ DevRestartBanner: () => null,
+}));
+
+vi.mock("./SidebarAccountMenu", () => ({
+ SidebarAccountMenu: () => <div>Account menu</div>,
+}));
+
+vi.mock("../context/DialogContext", () => ({
+ useDialog: () => ({
+ openNewIssue: vi.fn(),
+ openOnboarding: vi.fn(),
+ }),
+}));
+
+vi.mock("../context/PanelContext", () => ({
+ usePanel: () => ({
+ togglePanelVisible: vi.fn(),
+ }),
+}));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({
+ companies: [{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" }],
+ loading: false,
+ selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
+ selectedCompanyId: "company-1",
+ selectionSource: "manual",
+ setSelectedCompanyId: mockSetSelectedCompanyId,
+ }),
+}));
+
+vi.mock("../context/SidebarContext", () => ({
+ useSidebar: () => ({
+ sidebarOpen: true,
+ setSidebarOpen: mockSetSidebarOpen,
+ toggleSidebar: vi.fn(),
+ isMobile: false,
+ }),
+}));
+
+vi.mock("../hooks/useKeyboardShortcuts", () => ({
+ useKeyboardShortcuts: () => undefined,
+}));
+
+vi.mock("../hooks/useCompanyPageMemory", () => ({
+ useCompanyPageMemory: () => undefined,
+}));
+
+vi.mock("../api/health", () => ({
+ healthApi: mockHealthApi,
+}));
+
+vi.mock("../api/instanceSettings", () => ({
+ instanceSettingsApi: mockInstanceSettingsApi,
+}));
+
+vi.mock("../lib/company-selection", () => ({
+ shouldSyncCompanySelectionFromRoute: () => false,
+}));
+
+vi.mock("../lib/instance-settings", () => ({
+ DEFAULT_INSTANCE_SETTINGS_PATH: "/instance/settings/general",
+ normalizeRememberedInstanceSettingsPath: (value: string | null | undefined) =>
+ value ?? "/instance/settings/general",
+}));
+
+vi.mock("../lib/main-content-focus", () => ({
+ scheduleMainContentFocus: () => () => undefined,
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("Layout", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ currentPathname = "/PAP/dashboard";
+ mockHealthApi.get.mockResolvedValue({
+ status: "ok",
+ deploymentMode: "authenticated",
+ deploymentExposure: "private",
+ version: "1.2.3",
+ });
+ mockInstanceSettingsApi.getGeneral.mockResolvedValue({
+ keyboardShortcuts: false,
+ });
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("does not render the deployment explainer in the shared layout", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Layout />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(mockHealthApi.get).toHaveBeenCalled();
+ expect(container.textContent).toContain("Breadcrumbs");
+ expect(container.textContent).toContain("Outlet content");
+ expect(container.textContent).not.toContain("Authenticated private");
+ expect(container.textContent).not.toContain(
+ "Sign-in is required and this instance is intended for private-network access.",
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("renders the company settings sidebar on company settings routes", async () => {
+ currentPathname = "/PAP/company/settings/access";
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Layout />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Company settings sidebar");
+ expect(container.textContent).not.toContain("Instance sidebar");
+ expect(container.textContent).not.toContain("Main company nav");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index cd6972180c..b0281df7f0 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -1,10 +1,10 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { BookOpen, Moon, Settings, Sun } from "lucide-react";
-import { Link, Outlet, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";
+import { Outlet, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";
import { CompanyRail } from "./CompanyRail";
import { Sidebar } from "./Sidebar";
import { InstanceSidebar } from "./InstanceSidebar";
+import { CompanySettingsSidebar } from "./CompanySettingsSidebar";
import { BreadcrumbBar } from "./BreadcrumbBar";
import { PropertiesPanel } from "./PropertiesPanel";
import { CommandPalette } from "./CommandPalette";
@@ -17,12 +17,12 @@ import { ToastViewport } from "./ToastViewport";
import { MobileBottomNav } from "./MobileBottomNav";
import { WorktreeBanner } from "./WorktreeBanner";
import { DevRestartBanner } from "./DevRestartBanner";
+import { SidebarAccountMenu } from "./SidebarAccountMenu";
import { useDialog } from "../context/DialogContext";
import { GeneralSettingsProvider } from "../context/GeneralSettingsContext";
import { usePanel } from "../context/PanelContext";
import { useCompany } from "../context/CompanyContext";
import { useSidebar } from "../context/SidebarContext";
-import { useTheme } from "../context/ThemeContext";
import { useKeyboardShortcuts } from "../hooks/useKeyboardShortcuts";
import { useCompanyPageMemory } from "../hooks/useCompanyPageMemory";
import { healthApi } from "../api/health";
@@ -34,15 +34,12 @@ import {
} from "../lib/instance-settings";
import {
resetNavigationScroll,
- SIDEBAR_SCROLL_RESET_STATE,
shouldResetScrollOnNavigation,
} from "../lib/navigation-scroll";
import { queryKeys } from "../lib/queryKeys";
import { scheduleMainContentFocus } from "../lib/main-content-focus";
import { cn } from "../lib/utils";
import { NotFoundPage } from "../pages/NotFound";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
const INSTANCE_SETTINGS_MEMORY_KEY = "paperclip.lastInstanceSettingsPath";
@@ -67,12 +64,12 @@ export function Layout() {
selectionSource,
setSelectedCompanyId,
} = useCompany();
- const { theme, toggleTheme } = useTheme();
const { companyPrefix } = useParams<{ companyPrefix: string }>();
const navigate = useNavigate();
const location = useLocation();
const navigationType = useNavigationType();
const isInstanceSettingsRoute = location.pathname.startsWith("/instance/");
+ const isCompanySettingsRoute = location.pathname.includes("/company/settings");
const onboardingTriggered = useRef(false);
const lastMainScrollTop = useRef(0);
const previousPathname = useRef<string | null>(null);
@@ -80,7 +77,6 @@ export function Layout() {
const [mobileNavVisible, setMobileNavVisible] = useState(true);
const [instanceSettingsTarget, setInstanceSettingsTarget] = useState<string>(() => readRememberedInstanceSettingsPath());
const [shortcutsOpen, setShortcutsOpen] = useState(false);
- const nextTheme = theme === "dark" ? "light" : "dark";
const matchedCompany = useMemo(() => {
if (!companyPrefix) return null;
const requestedPrefix = companyPrefix.toUpperCase();
@@ -341,53 +337,19 @@ export function Layout() {
>
<div className="flex flex-1 min-h-0 overflow-hidden">
<CompanyRail />
- {isInstanceSettingsRoute ? <InstanceSidebar /> : <Sidebar />}
- </div>
- <div className="border-t border-r border-border px-3 py-2 bg-background">
- <div className="flex items-center gap-1">
- <a
- href="https://docs.paperclip.ing/"
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors text-foreground/80 hover:bg-accent/50 hover:text-foreground flex-1 min-w-0"
- >
- <BookOpen className="h-4 w-4 shrink-0" />
- <span className="truncate">Documentation</span>
- </a>
- {health?.version && (
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="px-2 text-xs text-muted-foreground shrink-0 cursor-default">v</span>
- </TooltipTrigger>
- <TooltipContent>v{health.version}</TooltipContent>
- </Tooltip>
- )}
- <Button variant="ghost" size="icon-sm" className="text-muted-foreground shrink-0" asChild>
- <Link
- to={instanceSettingsTarget}
- state={SIDEBAR_SCROLL_RESET_STATE}
- aria-label="Instance settings"
- title="Instance settings"
- onClick={() => {
- if (isMobile) setSidebarOpen(false);
- }}
- >
- <Settings className="h-4 w-4" />
- </Link>
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="text-muted-foreground shrink-0"
- onClick={toggleTheme}
- aria-label={`Switch to ${nextTheme} mode`}
- title={`Switch to ${nextTheme} mode`}
- >
- {theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
- </Button>
- </div>
+ {isInstanceSettingsRoute ? (
+ <InstanceSidebar />
+ ) : isCompanySettingsRoute ? (
+ <CompanySettingsSidebar />
+ ) : (
+ <Sidebar />
+ )}
</div>
+ <SidebarAccountMenu
+ deploymentMode={health?.deploymentMode}
+ instanceSettingsTarget={instanceSettingsTarget}
+ version={health?.version}
+ />
</div>
) : (
<div className="flex h-full flex-col shrink-0">
@@ -399,54 +361,20 @@ export function Layout() {
sidebarOpen ? "w-60" : "w-0"
)}
>
- {isInstanceSettingsRoute ? <InstanceSidebar /> : <Sidebar />}
- </div>
- </div>
- <div className="border-t border-r border-border px-3 py-2">
- <div className="flex items-center gap-1">
- <a
- href="https://docs.paperclip.ing/"
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors text-foreground/80 hover:bg-accent/50 hover:text-foreground flex-1 min-w-0"
- >
- <BookOpen className="h-4 w-4 shrink-0" />
- <span className="truncate">Documentation</span>
- </a>
- {health?.version && (
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="px-2 text-xs text-muted-foreground shrink-0 cursor-default">v</span>
- </TooltipTrigger>
- <TooltipContent>v{health.version}</TooltipContent>
- </Tooltip>
+ {isInstanceSettingsRoute ? (
+ <InstanceSidebar />
+ ) : isCompanySettingsRoute ? (
+ <CompanySettingsSidebar />
+ ) : (
+ <Sidebar />
)}
- <Button variant="ghost" size="icon-sm" className="text-muted-foreground shrink-0" asChild>
- <Link
- to={instanceSettingsTarget}
- state={SIDEBAR_SCROLL_RESET_STATE}
- aria-label="Instance settings"
- title="Instance settings"
- onClick={() => {
- if (isMobile) setSidebarOpen(false);
- }}
- >
- <Settings className="h-4 w-4" />
- </Link>
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="text-muted-foreground shrink-0"
- onClick={toggleTheme}
- aria-label={`Switch to ${nextTheme} mode`}
- title={`Switch to ${nextTheme} mode`}
- >
- {theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
- </Button>
</div>
</div>
+ <SidebarAccountMenu
+ deploymentMode={health?.deploymentMode}
+ instanceSettingsTarget={instanceSettingsTarget}
+ version={health?.version}
+ />
</div>
)}
diff --git a/ui/src/components/MarkdownBody.test.tsx b/ui/src/components/MarkdownBody.test.tsx
index c3b66c69bb..3604f52d12 100644
--- a/ui/src/components/MarkdownBody.test.tsx
+++ b/ui/src/components/MarkdownBody.test.tsx
@@ -4,7 +4,7 @@ import type { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
-import { buildAgentMentionHref, buildProjectMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
+import { buildAgentMentionHref, buildProjectMentionHref, buildSkillMentionHref, buildUserMentionHref } from "@paperclipai/shared";
import { ThemeProvider } from "../context/ThemeContext";
import { MarkdownBody } from "./MarkdownBody";
import { queryKeys } from "../lib/queryKeys";
@@ -75,17 +75,19 @@ describe("MarkdownBody", () => {
expect(html).toContain('alt="Org chart"');
});
- it("renders agent, project, and skill mentions as chips", () => {
+ it("renders user, agent, project, and skill mentions as chips", () => {
const html = renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<ThemeProvider>
<MarkdownBody>
- {`[@CodexCoder](${buildAgentMentionHref("agent-123", "code")}) [@Paperclip App](${buildProjectMentionHref("project-456", "#336699")}) [/release-changelog](${buildSkillMentionHref("skill-789", "release-changelog")})`}
+ {`[@Taylor](${buildUserMentionHref("user-123")}) [@CodexCoder](${buildAgentMentionHref("agent-123", "code")}) [@Paperclip App](${buildProjectMentionHref("project-456", "#336699")}) [/release-changelog](${buildSkillMentionHref("skill-789", "release-changelog")})`}
</MarkdownBody>
</ThemeProvider>
</QueryClientProvider>,
);
+ expect(html).toContain('href="/company/settings/access"');
+ expect(html).toContain('data-mention-kind="user"');
expect(html).toContain('href="/agents/agent-123"');
expect(html).toContain('data-mention-kind="agent"');
expect(html).toContain("--paperclip-mention-icon-mask");
diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx
index e168997b30..3ae0f51bd9 100644
--- a/ui/src/components/MarkdownBody.tsx
+++ b/ui/src/components/MarkdownBody.tsx
@@ -225,6 +225,8 @@ export function MarkdownBody({
? `/projects/${parsed.projectId}`
: parsed.kind === "skill"
? `/skills/${parsed.skillId}`
+ : parsed.kind === "user"
+ ? "/company/settings/access"
: `/agents/${parsed.agentId}`;
return (
<a
diff --git a/ui/src/components/MarkdownEditor.tsx b/ui/src/components/MarkdownEditor.tsx
index 73b7951f83..66d37e448f 100644
--- a/ui/src/components/MarkdownEditor.tsx
+++ b/ui/src/components/MarkdownEditor.tsx
@@ -31,8 +31,8 @@ import {
thematicBreakPlugin,
type RealmPlugin,
} from "@mdxeditor/editor";
-import { buildAgentMentionHref, buildProjectMentionHref } from "@paperclipai/shared";
-import { Boxes } from "lucide-react";
+import { buildAgentMentionHref, buildProjectMentionHref, buildUserMentionHref } from "@paperclipai/shared";
+import { Boxes, User } from "lucide-react";
import { AgentIcon } from "./AgentIconPicker";
import { applyMentionChipDecoration, clearMentionChipDecoration, parseMentionChipHref } from "../lib/mention-chips";
import { MentionAwareLinkNode, mentionAwareLinkNodeReplacement } from "../lib/mention-aware-link-node";
@@ -48,11 +48,12 @@ import { useEditorAutocomplete, type SkillCommandOption } from "../context/Edito
export interface MentionOption {
id: string;
name: string;
- kind?: "agent" | "project";
+ kind?: "agent" | "project" | "user";
agentId?: string;
agentIcon?: string | null;
projectId?: string;
projectColor?: string | null;
+ userId?: string;
}
/* ---- Editor props ---- */
@@ -354,6 +355,9 @@ function mentionMarkdown(option: MentionOption): string {
if (option.kind === "project" && option.projectId) {
return `[@${option.name}](${buildProjectMentionHref(option.projectId, option.projectColor ?? null)}) `;
}
+ if (option.kind === "user" && option.userId) {
+ return `[@${option.name}](${buildUserMentionHref(option.userId)}) `;
+ }
const agentId = option.agentId ?? option.id.replace(/^agent:/, "");
return `[@${option.name}](${buildAgentMentionHref(agentId, option.agentIcon ?? null)}) `;
}
@@ -400,6 +404,9 @@ function autocompleteOptionMatchesLink(option: AutocompleteOption, href: string)
if (option.kind === "project" && option.projectId) {
return parsed.kind === "project" && parsed.projectId === option.projectId;
}
+ if (option.kind === "user" && option.userId) {
+ return parsed.kind === "user" && parsed.userId === option.userId;
+ }
const agentId = option.agentId ?? option.id.replace(/^agent:/, "");
return parsed.kind === "agent" && parsed.agentId === agentId;
@@ -527,6 +534,9 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
const agentId = mention.agentId ?? mention.id.replace(/^agent:/, "");
map.set(`agent:${agentId}`, mention);
}
+ if (mention.kind === "user" && mention.userId) {
+ map.set(`user:${mention.userId}`, mention);
+ }
if (mention.kind === "project" && mention.projectId) {
map.set(`project:${mention.projectId}`, mention);
}
@@ -717,6 +727,11 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
continue;
}
+ if (parsed.kind === "user") {
+ applyMentionChipDecoration(link, parsed);
+ continue;
+ }
+
const option = mentionOptionByKey.get(`agent:${parsed.agentId}`);
applyMentionChipDecoration(link, {
...parsed,
@@ -1098,7 +1113,10 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
createPortal(
<div
className="fixed z-[9999] min-w-[180px] max-w-[calc(100vw-16px)] max-h-[200px] overflow-y-auto rounded-md border border-border bg-popover shadow-md"
- style={mentionMenuPosition ?? undefined}
+ style={{
+ top: Math.min(mentionState.viewportTop + 4, window.innerHeight - 208),
+ left: Math.max(8, Math.min(mentionState.viewportLeft, window.innerWidth - 188)),
+ }}
>
{filteredMentions.map((option, i) => (
<button
@@ -1125,6 +1143,8 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
className="inline-flex h-2 w-2 rounded-full border border-border/50"
style={{ backgroundColor: option.projectColor ?? "#64748b" }}
/>
+ ) : option.kind === "user" ? (
+ <User className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
) : (
<AgentIcon
icon={option.agentIcon}
@@ -1137,6 +1157,11 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
Project
</span>
)}
+ {option.kind === "user" && (
+ <span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground">
+ User
+ </span>
+ )}
{option.kind === "skill" && (
<span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground">
Skill
diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx
index 6e3447bb3f..70d96ff637 100644
--- a/ui/src/components/NewIssueDialog.tsx
+++ b/ui/src/components/NewIssueDialog.tsx
@@ -8,8 +8,10 @@ import { issuesApi } from "../api/issues";
import { instanceSettingsApi } from "../api/instanceSettings";
import { projectsApi } from "../api/projects";
import { agentsApi } from "../api/agents";
+import { accessApi } from "../api/access";
import { authApi } from "../api/auth";
import { assetsApi } from "../api/assets";
+import { buildCompanyUserInlineOptions, buildMarkdownMentionOptions } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import { useProjectOrder } from "../hooks/useProjectOrder";
import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
@@ -353,6 +355,11 @@ export function NewIssueDialog() {
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(effectiveCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(effectiveCompanyId!),
+ enabled: Boolean(effectiveCompanyId) && newIssueOpen,
+ });
const { data: experimentalSettings } = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: () => instanceSettingsApi.getExperimental(),
@@ -379,30 +386,12 @@ export function NewIssueDialog() {
assigneeAdapterType && ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType),
);
const mentionOptions = useMemo<MentionOption[]>(() => {
- const options: MentionOption[] = [];
- const activeAgents = [...(agents ?? [])]
- .filter((agent) => agent.status !== "terminated")
- .sort((a, b) => a.name.localeCompare(b.name));
- for (const agent of activeAgents) {
- options.push({
- id: `agent:${agent.id}`,
- name: agent.name,
- kind: "agent",
- agentId: agent.id,
- agentIcon: agent.icon,
- });
- }
- for (const project of orderedProjects) {
- options.push({
- id: `project:${project.id}`,
- name: project.name,
- kind: "project",
- projectId: project.id,
- projectColor: project.color,
- });
- }
- return options;
- }, [agents, orderedProjects]);
+ return buildMarkdownMentionOptions({
+ agents,
+ projects: orderedProjects,
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users, orderedProjects]);
const { data: assigneeAdapterModels } = useQuery({
queryKey:
@@ -868,6 +857,7 @@ export function NewIssueDialog() {
const assigneeOptions = useMemo<InlineEntityOption[]>(
() => [
...currentUserAssigneeOption(currentUserId),
+ ...buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId] }),
...sortAgentsByRecency(
(agents ?? []).filter((agent) => agent.status !== "terminated"),
recentAssigneeIds,
@@ -877,7 +867,7 @@ export function NewIssueDialog() {
searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`,
})),
],
- [agents, currentUserId, recentAssigneeIds],
+ [agents, companyMembers?.users, currentUserId, recentAssigneeIds],
);
const projectOptions = useMemo<InlineEntityOption[]>(
() =>
diff --git a/ui/src/components/NewProjectDialog.tsx b/ui/src/components/NewProjectDialog.tsx
index 367384ac8a..ad4aee14dd 100644
--- a/ui/src/components/NewProjectDialog.tsx
+++ b/ui/src/components/NewProjectDialog.tsx
@@ -2,10 +2,12 @@ import { useMemo, useRef, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useDialog } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
+import { accessApi } from "../api/access";
import { projectsApi } from "../api/projects";
import { agentsApi } from "../api/agents";
import { goalsApi } from "../api/goals";
import { assetsApi } from "../api/assets";
+import { buildMarkdownMentionOptions } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import {
Dialog,
@@ -75,22 +77,18 @@ export function NewProjectDialog() {
enabled: !!selectedCompanyId && newProjectOpen,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId && newProjectOpen,
+ });
+
const mentionOptions = useMemo<MentionOption[]>(() => {
- const options: MentionOption[] = [];
- const activeAgents = [...(agents ?? [])]
- .filter((agent) => agent.status !== "terminated")
- .sort((a, b) => a.name.localeCompare(b.name));
- for (const agent of activeAgents) {
- options.push({
- id: `agent:${agent.id}`,
- name: agent.name,
- kind: "agent",
- agentId: agent.id,
- agentIcon: agent.icon,
- });
- }
- return options;
- }, [agents]);
+ return buildMarkdownMentionOptions({
+ agents,
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users]);
const createProject = useMutation({
mutationFn: (data: Record<string, unknown>) =>
diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx
index 1427245479..1b49457649 100644
--- a/ui/src/components/Sidebar.tsx
+++ b/ui/src/components/Sidebar.tsx
@@ -24,6 +24,7 @@ import { queryKeys } from "../lib/queryKeys";
import { useInboxBadge } from "../hooks/useInboxBadge";
import { Button } from "@/components/ui/button";
import { PluginSlotOutlet } from "@/plugins/slots";
+import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
export function Sidebar() {
const { openNewIssue } = useDialog();
@@ -50,15 +51,7 @@ export function Sidebar() {
<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">
{/* Top bar: Company name (bold) + Search — aligned with top sections (no visible border) */}
<div className="flex items-center gap-1 px-3 h-12 shrink-0">
- {selectedCompany?.brandColor && (
- <div
- className="w-4 h-4 rounded-sm shrink-0 ml-1"
- style={{ backgroundColor: selectedCompany.brandColor }}
- />
- )}
- <span className="flex-1 text-sm font-bold text-foreground truncate pl-1">
- {selectedCompany?.name ?? "Select company"}
- </span>
+ <SidebarCompanyMenu />
<Button
variant="ghost"
size="icon-sm"
diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsx
new file mode 100644
index 0000000000..6c1f37c7ae
--- /dev/null
+++ b/ui/src/components/SidebarAccountMenu.test.tsx
@@ -0,0 +1,117 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SidebarAccountMenu } from "./SidebarAccountMenu";
+
+const mockAuthApi = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ signInEmail: vi.fn(),
+ signUpEmail: vi.fn(),
+ getProfile: vi.fn(),
+ updateProfile: vi.fn(),
+ signOut: vi.fn(),
+}));
+const mockToggleTheme = vi.hoisted(() => vi.fn());
+const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/auth", () => ({
+ authApi: mockAuthApi,
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+}));
+
+vi.mock("../context/SidebarContext", () => ({
+ useSidebar: () => ({
+ isMobile: false,
+ setSidebarOpen: mockSetSidebarOpen,
+ }),
+}));
+
+vi.mock("../context/ThemeContext", () => ({
+ useTheme: () => ({
+ theme: "dark",
+ toggleTheme: mockToggleTheme,
+ }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("SidebarAccountMenu", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockAuthApi.getSession.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: "https://example.com/jane.png",
+ },
+ });
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("renders the signed-in user and opens the account card menu", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <SidebarAccountMenu
+ deploymentMode="authenticated"
+ instanceSettingsTarget="/instance/settings/general"
+ version="1.2.3"
+ />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Jane Example");
+ expect(container.textContent).not.toContain("[email protected]");
+
+ const trigger = container.querySelector('button[aria-label="Open account menu"]');
+ expect(trigger).not.toBeNull();
+
+ await act(async () => {
+ trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(document.body.textContent).toContain("Edit profile");
+ expect(document.body.textContent).toContain("Documentation");
+ expect(document.body.textContent).toContain("Paperclip v1.2.3");
+ expect(document.body.textContent).toContain("[email protected]");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/SidebarAccountMenu.tsx b/ui/src/components/SidebarAccountMenu.tsx
new file mode 100644
index 0000000000..452a41ea34
--- /dev/null
+++ b/ui/src/components/SidebarAccountMenu.tsx
@@ -0,0 +1,227 @@
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ BookOpen,
+ LogOut,
+ type LucideIcon,
+ Moon,
+ Settings,
+ Sun,
+ UserRoundPen,
+} from "lucide-react";
+import type { DeploymentMode } from "@paperclipai/shared";
+import { Link } from "@/lib/router";
+import { authApi } from "@/api/auth";
+import { queryKeys } from "@/lib/queryKeys";
+import { useSidebar } from "../context/SidebarContext";
+import { useTheme } from "../context/ThemeContext";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { cn } from "../lib/utils";
+
+const PROFILE_SETTINGS_PATH = "/instance/settings/profile";
+const DOCS_URL = "https://docs.paperclip.ing/";
+
+interface SidebarAccountMenuProps {
+ deploymentMode?: DeploymentMode;
+ instanceSettingsTarget: string;
+ version?: string | null;
+}
+
+interface MenuActionProps {
+ label: string;
+ description: string;
+ icon: LucideIcon;
+ onClick?: () => void;
+ href?: string;
+ external?: boolean;
+}
+
+function deriveInitials(name: string) {
+ const parts = name.trim().split(/\s+/).filter(Boolean);
+ if (parts.length >= 2) {
+ return `${parts[0]?.[0] ?? ""}${parts[parts.length - 1]?.[0] ?? ""}`.toUpperCase();
+ }
+ return name.slice(0, 2).toUpperCase();
+}
+
+function MenuAction({ label, description, icon: Icon, onClick, href, external = false }: MenuActionProps) {
+ const className =
+ "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60";
+
+ const content = (
+ <>
+ <span className="mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground">
+ <Icon className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium text-foreground">{label}</span>
+ <span className="block text-xs text-muted-foreground">{description}</span>
+ </span>
+ </>
+ );
+
+ if (href) {
+ if (external) {
+ return (
+ <a href={href} target="_blank" rel="noreferrer" className={className} onClick={onClick}>
+ {content}
+ </a>
+ );
+ }
+
+ return (
+ <Link to={href} className={className} onClick={onClick}>
+ {content}
+ </Link>
+ );
+ }
+
+ return (
+ <button type="button" className={className} onClick={onClick}>
+ {content}
+ </button>
+ );
+}
+
+export function SidebarAccountMenu({
+ deploymentMode,
+ instanceSettingsTarget,
+ version,
+}: SidebarAccountMenuProps) {
+ const [open, setOpen] = useState(false);
+ const queryClient = useQueryClient();
+ const { isMobile, setSidebarOpen } = useSidebar();
+ const { theme, toggleTheme } = useTheme();
+ const { data: session } = useQuery({
+ queryKey: queryKeys.auth.session,
+ queryFn: () => authApi.getSession(),
+ retry: false,
+ });
+
+ const signOutMutation = useMutation({
+ mutationFn: () => authApi.signOut(),
+ onSuccess: async () => {
+ setOpen(false);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
+ },
+ });
+
+ const displayName = session?.user.name?.trim() || "Board";
+ const secondaryLabel =
+ session?.user.email?.trim() || (deploymentMode === "authenticated" ? "Signed in" : "Local workspace board");
+ const accountBadge = deploymentMode === "authenticated" ? "Account" : "Local";
+ const initials = deriveInitials(displayName);
+
+ function closeNavigationChrome() {
+ setOpen(false);
+ if (isMobile) setSidebarOpen(false);
+ }
+
+ return (
+ <div className="border-t border-r border-border bg-background px-3 py-2">
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-[13px] font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground"
+ aria-label="Open account menu"
+ >
+ <Avatar size="sm">
+ {session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}
+ <AvatarFallback>{initials}</AvatarFallback>
+ </Avatar>
+ <span className="min-w-0 flex-1 truncate">{displayName}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ side="top"
+ align="start"
+ sideOffset={10}
+ className="w-[var(--radix-popover-trigger-width)] overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl"
+ >
+ <div className="h-24 bg-[linear-gradient(135deg,hsl(var(--primary))_0%,hsl(var(--accent))_55%,hsl(var(--muted))_100%)]" />
+ <div className="-mt-8 px-4 pb-4">
+ <div className="flex items-start gap-3">
+ <div className="rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm">
+ <Avatar size="lg">
+ {session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}
+ <AvatarFallback>{initials}</AvatarFallback>
+ </Avatar>
+ </div>
+ <div className="min-w-0 flex-1 pt-1">
+ <div className="flex items-center gap-2">
+ <h2 className="truncate text-base font-semibold text-foreground">{displayName}</h2>
+ <span className="rounded-full bg-accent px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {accountBadge}
+ </span>
+ </div>
+ <p className="truncate text-sm text-muted-foreground">{secondaryLabel}</p>
+ {version ? (
+ <p className="mt-1 text-xs text-muted-foreground">Paperclip v{version}</p>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="mt-4 space-y-1">
+ <MenuAction
+ label="Edit profile"
+ description="Update your display name and avatar."
+ icon={UserRoundPen}
+ href={PROFILE_SETTINGS_PATH}
+ onClick={closeNavigationChrome}
+ />
+ <MenuAction
+ label="Instance settings"
+ description="Jump back to the last settings page you opened."
+ icon={Settings}
+ href={instanceSettingsTarget}
+ onClick={closeNavigationChrome}
+ />
+ <MenuAction
+ label="Documentation"
+ description="Open Paperclip docs in a new tab."
+ icon={BookOpen}
+ href={DOCS_URL}
+ external
+ onClick={() => setOpen(false)}
+ />
+ <MenuAction
+ label={theme === "dark" ? "Switch to light mode" : "Switch to dark mode"}
+ description="Toggle the app appearance."
+ icon={theme === "dark" ? Sun : Moon}
+ onClick={() => {
+ toggleTheme();
+ setOpen(false);
+ }}
+ />
+ {deploymentMode === "authenticated" ? (
+ <button
+ type="button"
+ className={cn(
+ "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",
+ signOutMutation.isPending && "cursor-not-allowed opacity-60",
+ )}
+ onClick={() => signOutMutation.mutate()}
+ disabled={signOutMutation.isPending}
+ >
+ <span className="mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground">
+ <LogOut className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium text-foreground">
+ {signOutMutation.isPending ? "Signing out..." : "Sign out"}
+ </span>
+ <span className="block text-xs text-muted-foreground">
+ End this browser session.
+ </span>
+ </span>
+ </button>
+ ) : null}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
diff --git a/ui/src/components/SidebarCompanyMenu.test.tsx b/ui/src/components/SidebarCompanyMenu.test.tsx
new file mode 100644
index 0000000000..a96a0d5c20
--- /dev/null
+++ b/ui/src/components/SidebarCompanyMenu.test.tsx
@@ -0,0 +1,125 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
+
+const mockAuthApi = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ signInEmail: vi.fn(),
+ signUpEmail: vi.fn(),
+ getProfile: vi.fn(),
+ updateProfile: vi.fn(),
+ signOut: vi.fn(),
+}));
+const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/auth", () => ({
+ authApi: mockAuthApi,
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompany: {
+ id: "company-1",
+ name: "Acme Labs",
+ brandColor: "#3366ff",
+ },
+ }),
+}));
+
+vi.mock("../context/SidebarContext", () => ({
+ useSidebar: () => ({
+ isMobile: false,
+ setSidebarOpen: mockSetSidebarOpen,
+ }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("SidebarCompanyMenu", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockAuthApi.getSession.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ },
+ });
+ mockAuthApi.signOut.mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("shows the requested company actions and signs out through the dropdown", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <SidebarCompanyMenu />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Acme Labs");
+
+ const trigger = container.querySelector('button[aria-label="Open Acme Labs menu"]');
+ expect(trigger).not.toBeNull();
+
+ await act(async () => {
+ trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
+ trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(document.body.textContent).toContain("Invite people to Acme Labs");
+ expect(document.body.textContent).toContain("Company settings");
+ expect(document.body.textContent).toContain("Sign out");
+
+ const signOutButton = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Sign out"));
+ expect(signOutButton).toBeTruthy();
+
+ await act(async () => {
+ signOutButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockAuthApi.signOut).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/SidebarCompanyMenu.tsx b/ui/src/components/SidebarCompanyMenu.tsx
new file mode 100644
index 0000000000..c10c0a41f6
--- /dev/null
+++ b/ui/src/components/SidebarCompanyMenu.tsx
@@ -0,0 +1,102 @@
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { ChevronDown, LogOut, Settings, UserPlus } from "lucide-react";
+import { Link } from "@/lib/router";
+import { authApi } from "@/api/auth";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useCompany } from "@/context/CompanyContext";
+import { queryKeys } from "@/lib/queryKeys";
+import { useSidebar } from "../context/SidebarContext";
+
+export function SidebarCompanyMenu() {
+ const [open, setOpen] = useState(false);
+ const queryClient = useQueryClient();
+ const { selectedCompany } = useCompany();
+ const { isMobile, setSidebarOpen } = useSidebar();
+ const { data: session } = useQuery({
+ queryKey: queryKeys.auth.session,
+ queryFn: () => authApi.getSession(),
+ retry: false,
+ });
+
+ const signOutMutation = useMutation({
+ mutationFn: () => authApi.signOut(),
+ onSuccess: async () => {
+ setOpen(false);
+ if (isMobile) setSidebarOpen(false);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
+ },
+ });
+
+ function closeNavigationChrome() {
+ setOpen(false);
+ if (isMobile) setSidebarOpen(false);
+ }
+
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ className="h-auto flex-1 justify-start gap-1 px-2 py-1.5 text-left"
+ aria-label={selectedCompany ? `Open ${selectedCompany.name} menu` : "Open company menu"}
+ disabled={!selectedCompany}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ {selectedCompany?.brandColor ? (
+ <span
+ className="size-4 shrink-0 rounded-sm"
+ style={{ backgroundColor: selectedCompany.brandColor }}
+ />
+ ) : null}
+ <span className="truncate text-sm font-bold text-foreground">
+ {selectedCompany?.name ?? "Select company"}
+ </span>
+ </span>
+ <ChevronDown className="size-4 shrink-0 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-64">
+ <DropdownMenuLabel className="truncate">
+ {selectedCompany?.name ?? "Company"}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem asChild>
+ <Link to="/company/settings/invites" onClick={closeNavigationChrome}>
+ <UserPlus className="size-4" />
+ <span className="truncate">
+ {selectedCompany ? `Invite people to ${selectedCompany.name}` : "Invite people"}
+ </span>
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild>
+ <Link to="/company/settings" onClick={closeNavigationChrome}>
+ <Settings className="size-4" />
+ <span>Company settings</span>
+ </Link>
+ </DropdownMenuItem>
+ {session?.session ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => signOutMutation.mutate()}
+ disabled={signOutMutation.isPending}
+ >
+ <LogOut className="size-4" />
+ <span>{signOutMutation.isPending ? "Signing out..." : "Sign out"}</span>
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/ui/src/components/access/CompanySettingsNav.test.tsx b/ui/src/components/access/CompanySettingsNav.test.tsx
new file mode 100644
index 0000000000..543735dfec
--- /dev/null
+++ b/ui/src/components/access/CompanySettingsNav.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CompanySettingsNav, getCompanySettingsTab } from "./CompanySettingsNav";
+
+let currentPathname = "/company/settings";
+const navigateMock = vi.hoisted(() => vi.fn());
+const pageTabBarMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/lib/router", () => ({
+ useLocation: () => ({ pathname: currentPathname, search: "", hash: "" }),
+ useNavigate: () => navigateMock,
+}));
+
+vi.mock("@/components/ui/tabs", () => ({
+ Tabs: ({ children }: { children: React.ReactNode }) => <div data-testid="tabs-root">{children}</div>,
+}));
+
+vi.mock("@/components/PageTabBar", () => ({
+ PageTabBar: (props: {
+ items: Array<{ value: string; label: string }>;
+ value?: string;
+ onValueChange?: (value: string) => void;
+ }) => {
+ pageTabBarMock(props);
+
+ return (
+ <div>
+ <div data-testid="active-tab">{props.value}</div>
+ <button type="button" onClick={() => props.onValueChange?.("invites")}>
+ switch-tab
+ </button>
+ </div>
+ );
+ },
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("CompanySettingsNav", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ currentPathname = "/company/settings";
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("maps company settings routes to the expected shared tab value", () => {
+ expect(getCompanySettingsTab("/company/settings")).toBe("general");
+ expect(getCompanySettingsTab("/PAP/company/settings")).toBe("general");
+ expect(getCompanySettingsTab("/company/settings/access")).toBe("access");
+ expect(getCompanySettingsTab("/PAP/company/settings/access")).toBe("access");
+ expect(getCompanySettingsTab("/company/settings/invites")).toBe("invites");
+ });
+
+ it("renders the active tab and navigates when a different tab is selected", async () => {
+ currentPathname = "/PAP/company/settings/access";
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<CompanySettingsNav />);
+ });
+
+ expect(container.textContent).toContain("access");
+ expect(pageTabBarMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ value: "access",
+ items: [
+ { value: "general", label: "General" },
+ { value: "access", label: "Access" },
+ { value: "invites", label: "Invites" },
+ ],
+ }),
+ );
+
+ const button = container.querySelector("button");
+ expect(button).not.toBeNull();
+
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith("/company/settings/invites");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/access/CompanySettingsNav.tsx b/ui/src/components/access/CompanySettingsNav.tsx
new file mode 100644
index 0000000000..daa34a86b5
--- /dev/null
+++ b/ui/src/components/access/CompanySettingsNav.tsx
@@ -0,0 +1,46 @@
+import { PageTabBar } from "@/components/PageTabBar";
+import { Tabs } from "@/components/ui/tabs";
+import { useLocation, useNavigate } from "@/lib/router";
+
+const items = [
+ { value: "general", label: "General", href: "/company/settings" },
+ { value: "access", label: "Access", href: "/company/settings/access" },
+ { value: "invites", label: "Invites", href: "/company/settings/invites" },
+] as const;
+
+type CompanySettingsTab = (typeof items)[number]["value"];
+
+export function getCompanySettingsTab(pathname: string): CompanySettingsTab {
+ if (pathname.includes("/company/settings/access")) {
+ return "access";
+ }
+
+ if (pathname.includes("/company/settings/invites")) {
+ return "invites";
+ }
+
+ return "general";
+}
+
+export function CompanySettingsNav() {
+ const location = useLocation();
+ const navigate = useNavigate();
+ const activeTab = getCompanySettingsTab(location.pathname);
+
+ function handleTabChange(value: string) {
+ const nextTab = items.find((item) => item.value === value);
+ if (!nextTab || nextTab.value === activeTab) return;
+ navigate(nextTab.href);
+ }
+
+ return (
+ <Tabs value={activeTab} onValueChange={handleTabChange}>
+ <PageTabBar
+ items={items.map(({ value, label }) => ({ value, label }))}
+ value={activeTab}
+ onValueChange={handleTabChange}
+ align="start"
+ />
+ </Tabs>
+ );
+}
diff --git a/ui/src/components/access/ModeBadge.tsx b/ui/src/components/access/ModeBadge.tsx
new file mode 100644
index 0000000000..8a65f38cc1
--- /dev/null
+++ b/ui/src/components/access/ModeBadge.tsx
@@ -0,0 +1,19 @@
+import type { DeploymentExposure, DeploymentMode } from "@paperclipai/shared";
+import { Badge } from "@/components/ui/badge";
+
+export function ModeBadge({
+ deploymentMode,
+ deploymentExposure,
+}: {
+ deploymentMode?: DeploymentMode;
+ deploymentExposure?: DeploymentExposure;
+}) {
+ if (!deploymentMode) return null;
+
+ const label =
+ deploymentMode === "local_trusted"
+ ? "Local trusted"
+ : `Authenticated ${deploymentExposure ?? "private"}`;
+
+ return <Badge variant="outline">{label}</Badge>;
+}
diff --git a/ui/src/components/agent-config-primitives.tsx b/ui/src/components/agent-config-primitives.tsx
index d20363991f..e072041b19 100644
--- a/ui/src/components/agent-config-primitives.tsx
+++ b/ui/src/components/agent-config-primitives.tsx
@@ -113,11 +113,23 @@ export function ToggleField({
<span className="text-xs text-muted-foreground">{label}</span>
{hint && <HintIcon text={hint} />}
</div>
- <ToggleSwitch
- checked={checked}
- onCheckedChange={onChange}
+ <button
+ data-slot="toggle"
data-testid={toggleTestId}
- />
+ type="button"
+ className={cn(
+ "relative inline-flex h-5 w-9 items-center rounded-full transition-colors",
+ checked ? "bg-green-600" : "bg-muted"
+ )}
+ onClick={() => onChange(!checked)}
+ >
+ <span
+ className={cn(
+ "inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",
+ checked ? "translate-x-4.5" : "translate-x-0.5"
+ )}
+ />
+ </button>
</div>
);
}
diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts
index 96c5d3b98c..f9a9cec13f 100644
--- a/ui/src/context/LiveUpdatesProvider.test.ts
+++ b/ui/src/context/LiveUpdatesProvider.test.ts
@@ -670,55 +670,3 @@ describe("LiveUpdatesProvider run lifecycle toasts", () => {
});
});
});
-
-describe("LiveUpdatesProvider socket helpers", () => {
- it("waits for the selected company object to catch up before connecting", () => {
- expect(__liveUpdatesTestUtils.resolveLiveCompanyId("company-1", null)).toBeNull();
- expect(__liveUpdatesTestUtils.resolveLiveCompanyId("company-1", "company-2")).toBeNull();
- expect(__liveUpdatesTestUtils.resolveLiveCompanyId("company-1", "company-1")).toBe("company-1");
- });
-
- it("defers close until onopen for sockets that are still connecting", () => {
- const socket = {
- readyState: 0,
- onopen: (() => undefined) as (() => void) | null,
- onmessage: (() => undefined) as (() => void) | null,
- onerror: (() => undefined) as (() => void) | null,
- onclose: (() => undefined) as (() => void) | null,
- close: vi.fn(),
- };
-
- __liveUpdatesTestUtils.closeSocketQuietly(socket as never, "provider_unmount");
-
- expect(socket.close).not.toHaveBeenCalled();
- expect(socket.onmessage).toBeNull();
- expect(socket.onclose).toBeNull();
- expect(socket.onopen).toBeTypeOf("function");
- expect(socket.onerror).toBeTypeOf("function");
-
- socket.onopen?.();
-
- expect(socket.close).toHaveBeenCalledWith(1000, "provider_unmount");
- expect(socket.onopen).toBeNull();
- expect(socket.onerror).toBeNull();
- });
-
- it("closes open sockets immediately without leaving handlers behind", () => {
- const socket = {
- readyState: 1,
- onopen: (() => undefined) as (() => void) | null,
- onmessage: (() => undefined) as (() => void) | null,
- onerror: (() => undefined) as (() => void) | null,
- onclose: (() => undefined) as (() => void) | null,
- close: vi.fn(),
- };
-
- __liveUpdatesTestUtils.closeSocketQuietly(socket as never, "stale_connection");
-
- expect(socket.close).toHaveBeenCalledWith(1000, "stale_connection");
- expect(socket.onopen).toBeNull();
- expect(socket.onmessage).toBeNull();
- expect(socket.onerror).toBeNull();
- expect(socket.onclose).toBeNull();
- });
-});
diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx
index a146ca66f0..95f06ace19 100644
--- a/ui/src/context/LiveUpdatesProvider.tsx
+++ b/ui/src/context/LiveUpdatesProvider.tsx
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient, type InfiniteData, type QueryClient } from "@
import type { Agent, Issue, IssueComment, LiveEvent } from "@paperclipai/shared";
import type { RunForIssue } from "../api/activity";
import type { ActiveRunForIssue, LiveRunForIssue } from "../api/heartbeats";
+import type { CompanyUserDirectoryResponse } from "../api/access";
import { issuesApi } from "../api/issues";
import { authApi } from "../api/auth";
import { useCompany } from "./CompanyContext";
@@ -52,6 +53,19 @@ function resolveAgentName(
return agent?.name ?? null;
}
+function resolveUserName(
+ queryClient: QueryClient,
+ companyId: string,
+ userId: string,
+): string | null {
+ const directory = queryClient.getQueryData<CompanyUserDirectoryResponse>(
+ queryKeys.access.companyUserDirectory(companyId),
+ );
+ if (!directory) return null;
+ const entry = directory.users.find((u) => u.principalId === userId);
+ return entry?.user?.name?.trim() || entry?.user?.email?.trim() || null;
+}
+
function truncate(text: string, max: number): string {
if (text.length <= max) return text;
return text.slice(0, max - 1) + "\u2026";
@@ -68,7 +82,7 @@ function resolveActorLabel(
}
if (actorType === "system") return "System";
if (actorType === "user" && actorId) {
- return "Board";
+ return resolveUserName(queryClient, companyId, actorId) ?? "Board";
}
return "Someone";
}
diff --git a/ui/src/hooks/useInboxBadge.ts b/ui/src/hooks/useInboxBadge.ts
index 9a092613dc..6c4083b8ea 100644
--- a/ui/src/hooks/useInboxBadge.ts
+++ b/ui/src/hooks/useInboxBadge.ts
@@ -4,6 +4,7 @@ import { accessApi } from "../api/access";
import { ApiError } from "../api/client";
import { inboxDismissalsApi } from "../api/inboxDismissals";
import { approvalsApi } from "../api/approvals";
+import { authApi } from "../api/auth";
import { dashboardApi } from "../api/dashboard";
import { heartbeatsApi } from "../api/heartbeats";
import { issuesApi } from "../api/issues";
@@ -139,6 +140,10 @@ export function useReadInboxItems() {
export function useInboxBadge(companyId: string | null | undefined) {
const { dismissed: dismissedAlerts } = useDismissedInboxAlerts();
const { dismissedAtByKey } = useInboxDismissals(companyId);
+ const { data: session } = useQuery({
+ queryKey: queryKeys.auth.session,
+ queryFn: () => authApi.getSession(),
+ });
const { data: approvals = [] } = useQuery({
queryKey: queryKeys.approvals.list(companyId!),
@@ -180,6 +185,7 @@ export function useInboxBadge(companyId: string | null | undefined) {
});
const mineIssues = useMemo(() => getRecentTouchedIssues(mineIssuesRaw), [mineIssuesRaw]);
+ const currentUserId = session?.user.id ?? session?.session.userId ?? null;
const { data: heartbeatRuns = [] } = useQuery({
queryKey: [...queryKeys.heartbeats(companyId!), "limit", INBOX_BADGE_HEARTBEAT_RUN_LIMIT],
@@ -197,7 +203,8 @@ export function useInboxBadge(companyId: string | null | undefined) {
mineIssues,
dismissedAlerts,
dismissedAtByKey,
+ currentUserId,
}),
- [approvals, joinRequests, dashboard, heartbeatRuns, mineIssues, dismissedAlerts, dismissedAtByKey],
+ [approvals, joinRequests, dashboard, heartbeatRuns, mineIssues, dismissedAlerts, dismissedAtByKey, currentUserId],
);
}
diff --git a/ui/src/lib/activity-format.ts b/ui/src/lib/activity-format.ts
index 45906bac73..98608e71c9 100644
--- a/ui/src/lib/activity-format.ts
+++ b/ui/src/lib/activity-format.ts
@@ -1,4 +1,5 @@
import type { Agent } from "@paperclipai/shared";
+import type { CompanyUserProfile } from "./company-members";
type ActivityDetails = Record<string, unknown> | null | undefined;
@@ -16,6 +17,7 @@ type ActivityIssueReference = {
interface ActivityFormatOptions {
agentMap?: Map<string, Agent>;
+ userProfileMap?: Map<string, CompanyUserProfile>;
currentUserId?: string | null;
}
@@ -118,9 +120,11 @@ function readIssueReferences(details: ActivityDetails, key: string): ActivityIss
return value.filter(isActivityIssueReference);
}
-function formatUserLabel(userId: string | null | undefined, currentUserId?: string | null): string {
+function formatUserLabel(userId: string | null | undefined, options: ActivityFormatOptions = {}): string {
if (!userId || userId === "local-board") return "Board";
- if (currentUserId && userId === currentUserId) return "You";
+ if (options.currentUserId && userId === options.currentUserId) return "You";
+ const profile = options.userProfileMap?.get(userId);
+ if (profile) return profile.label;
return `user ${userId.slice(0, 5)}`;
}
@@ -129,7 +133,7 @@ function formatParticipantLabel(participant: ActivityParticipant, options: Activ
const agentId = participant.agentId ?? "";
return options.agentMap?.get(agentId)?.name ?? "agent";
}
- return formatUserLabel(participant.userId, options.currentUserId);
+ return formatUserLabel(participant.userId, options);
}
function formatIssueReferenceLabel(reference: ActivityIssueReference): string {
@@ -167,7 +171,20 @@ function formatIssueUpdatedVerb(details: ActivityDetails): string | null {
return null;
}
-function formatIssueUpdatedAction(details: ActivityDetails): string | null {
+function formatAssigneeName(details: ActivityDetails, options: ActivityFormatOptions): string | null {
+ if (!details) return null;
+ const agentId = details.assigneeAgentId;
+ const userId = details.assigneeUserId;
+ if (typeof agentId === "string" && agentId) {
+ return options.agentMap?.get(agentId)?.name ?? "agent";
+ }
+ if (typeof userId === "string" && userId) {
+ return formatUserLabel(userId, options);
+ }
+ return null;
+}
+
+function formatIssueUpdatedAction(details: ActivityDetails, options: ActivityFormatOptions = {}): string | null {
if (!details) return null;
const previous = asRecord(details._previous) ?? {};
const parts: string[] = [];
@@ -189,7 +206,8 @@ function formatIssueUpdatedAction(details: ActivityDetails): string | null {
);
}
if (details.assigneeAgentId !== undefined || details.assigneeUserId !== undefined) {
- parts.push(details.assigneeAgentId || details.assigneeUserId ? "assigned the issue" : "unassigned the issue");
+ const assigneeName = formatAssigneeName(details, options);
+ parts.push(assigneeName ? `assigned the issue to ${assigneeName}` : "unassigned the issue");
}
if (details.title !== undefined) parts.push("updated the title");
if (details.description !== undefined) parts.push("updated the description");
@@ -266,7 +284,7 @@ export function formatIssueActivityAction(
options: ActivityFormatOptions = {},
): string {
if (action === "issue.updated") {
- const issueUpdatedAction = formatIssueUpdatedAction(details);
+ const issueUpdatedAction = formatIssueUpdatedAction(details, options);
if (issueUpdatedAction) return issueUpdatedAction;
}
diff --git a/ui/src/lib/assignees.ts b/ui/src/lib/assignees.ts
index 87a278ce57..edc4d5456f 100644
--- a/ui/src/lib/assignees.ts
+++ b/ui/src/lib/assignees.ts
@@ -74,9 +74,16 @@ export function currentUserAssigneeOption(currentUserId: string | null | undefin
export function formatAssigneeUserLabel(
userId: string | null | undefined,
currentUserId: string | null | undefined,
+ userLabels?: ReadonlyMap<string, string> | Record<string, string> | null,
): string | null {
if (!userId) return null;
if (currentUserId && userId === currentUserId) return "You";
+ if (userLabels) {
+ const label = userLabels instanceof Map
+ ? userLabels.get(userId)
+ : (userLabels as Record<string, string>)[userId];
+ if (typeof label === "string" && label.trim()) return label;
+ }
if (userId === "local-board") return "Board";
return userId.slice(0, 5);
}
diff --git a/ui/src/lib/company-members.test.ts b/ui/src/lib/company-members.test.ts
new file mode 100644
index 0000000000..2afc4fa3b8
--- /dev/null
+++ b/ui/src/lib/company-members.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import type { CompanyMember, CompanyUserDirectoryEntry } from "@/api/access";
+import {
+ buildCompanyUserInlineOptions,
+ buildCompanyUserLabelMap,
+ buildCompanyUserProfileMap,
+ buildMarkdownMentionOptions,
+} from "./company-members";
+
+const activeMember = (overrides: Partial<CompanyMember>): CompanyMember => ({
+ id: overrides.id ?? "member-1",
+ companyId: overrides.companyId ?? "company-1",
+ principalType: "user",
+ principalId: overrides.principalId ?? "user-1",
+ status: overrides.status ?? "active",
+ membershipRole: overrides.membershipRole ?? "operator",
+ createdAt: overrides.createdAt ?? "2026-01-01T00:00:00.000Z",
+ updatedAt: overrides.updatedAt ?? "2026-01-01T00:00:00.000Z",
+ user: overrides.user === undefined
+ ? { id: overrides.principalId ?? "user-1", name: "Taylor", email: "[email protected]", image: null }
+ : overrides.user,
+ grants: overrides.grants ?? [],
+});
+
+describe("company-members helpers", () => {
+ it("builds labels from company member profiles", () => {
+ const labels = buildCompanyUserLabelMap([
+ activeMember({ principalId: "user-1", user: { id: "user-1", name: "Taylor", email: "[email protected]", image: null } }),
+ activeMember({ id: "member-2", principalId: "local-board", user: null }),
+ ]);
+
+ expect(labels.get("user-1")).toBe("Taylor");
+ expect(labels.get("local-board")).toBe("Board");
+ });
+
+ it("builds user profiles with labels and avatars", () => {
+ const profiles = buildCompanyUserProfileMap([
+ activeMember({
+ principalId: "user-1",
+ user: { id: "user-1", name: "Taylor", email: "[email protected]", image: "https://example.com/taylor.png" },
+ }),
+ activeMember({ id: "member-2", principalId: "local-board", user: null }),
+ ]);
+
+ expect(profiles.get("user-1")).toEqual({
+ label: "Taylor",
+ image: "https://example.com/taylor.png",
+ });
+ expect(profiles.get("local-board")).toEqual({
+ label: "Board",
+ image: null,
+ });
+ });
+
+ it("builds inline options for active users and excludes requested ids", () => {
+ const options = buildCompanyUserInlineOptions([
+ activeMember({ principalId: "user-1", user: { id: "user-1", name: "Taylor", email: "[email protected]", image: null } }),
+ activeMember({ id: "member-2", principalId: "user-2", user: { id: "user-2", name: "Jordan", email: "[email protected]", image: null } }),
+ activeMember({ id: "member-3", principalId: "user-3", status: "suspended" }),
+ ], { excludeUserIds: ["user-1"] });
+
+ expect(options).toEqual([
+ {
+ id: "user:user-2",
+ label: "Jordan",
+ searchText: "Jordan [email protected] user-2",
+ },
+ ]);
+ });
+
+ it("includes human users in markdown mention options", () => {
+ const options = buildMarkdownMentionOptions({
+ members: [activeMember({ principalId: "user-1", user: { id: "user-1", name: "Taylor", email: "[email protected]", image: null } })],
+ agents: [{ id: "agent-1", name: "CodexCoder", status: "active", icon: "code" }],
+ projects: [{ id: "project-1", name: "Paperclip App", color: "#336699" }],
+ });
+
+ expect(options).toEqual([
+ { id: "user:user-1", name: "Taylor", kind: "user", userId: "user-1" },
+ { id: "agent:agent-1", name: "CodexCoder", kind: "agent", agentId: "agent-1", agentIcon: "code" },
+ { id: "project:project-1", name: "Paperclip App", kind: "project", projectId: "project-1", projectColor: "#336699" },
+ ]);
+ });
+
+ it("accepts read-only directory entries for assignee and mention helpers", () => {
+ const users: CompanyUserDirectoryEntry[] = [
+ {
+ principalId: "user-1",
+ status: "active",
+ user: { id: "user-1", name: "Taylor", email: "[email protected]", image: null },
+ },
+ ];
+
+ expect(buildCompanyUserInlineOptions(users)).toEqual([
+ {
+ id: "user:user-1",
+ label: "Taylor",
+ searchText: "Taylor [email protected] user-1",
+ },
+ ]);
+ expect(buildMarkdownMentionOptions({ members: users })).toEqual([
+ { id: "user:user-1", name: "Taylor", kind: "user", userId: "user-1" },
+ ]);
+ });
+});
diff --git a/ui/src/lib/company-members.ts b/ui/src/lib/company-members.ts
new file mode 100644
index 0000000000..f0f908f923
--- /dev/null
+++ b/ui/src/lib/company-members.ts
@@ -0,0 +1,116 @@
+import type { CompanyMember, CompanyUserDirectoryEntry } from "@/api/access";
+import type { InlineEntityOption } from "@/components/InlineEntitySelector";
+import type { MentionOption } from "@/components/MarkdownEditor";
+import type { Agent, Project } from "@paperclipai/shared";
+
+export interface CompanyUserProfile {
+ label: string;
+ image: string | null;
+}
+
+type CompanyUserRecord = Pick<CompanyMember, "principalId" | "status" | "user">
+ | CompanyUserDirectoryEntry;
+
+function fallbackUserLabel(userId: string): string {
+ if (userId === "local-board") return "Board";
+ return userId.slice(0, 5);
+}
+
+function baseMemberLabel(member: Pick<CompanyUserRecord, "principalId" | "user">): string {
+ const name = member.user?.name?.trim();
+ if (name) return name;
+ const email = member.user?.email?.trim();
+ if (email) return email;
+ return fallbackUserLabel(member.principalId);
+}
+
+function activeUniqueMembers(members: CompanyUserRecord[] | null | undefined) {
+ const byId = new Map<string, CompanyUserRecord>();
+ for (const member of members ?? []) {
+ if (member.status !== "active") continue;
+ if (!byId.has(member.principalId)) {
+ byId.set(member.principalId, member);
+ }
+ }
+ return [...byId.values()].sort((left, right) => baseMemberLabel(left).localeCompare(baseMemberLabel(right)));
+}
+
+export function buildCompanyUserLabelMap(members: CompanyUserRecord[] | null | undefined): Map<string, string> {
+ const labels = new Map<string, string>();
+ for (const member of members ?? []) {
+ labels.set(member.principalId, baseMemberLabel(member));
+ }
+ return labels;
+}
+
+export function buildCompanyUserProfileMap(
+ members: CompanyUserRecord[] | null | undefined,
+): Map<string, CompanyUserProfile> {
+ const profiles = new Map<string, CompanyUserProfile>();
+ for (const member of members ?? []) {
+ profiles.set(member.principalId, {
+ label: baseMemberLabel(member),
+ image: member.user?.image ?? null,
+ });
+ }
+ return profiles;
+}
+
+export function buildCompanyUserInlineOptions(
+ members: CompanyUserRecord[] | null | undefined,
+ options?: { excludeUserIds?: Iterable<string | null | undefined> },
+): InlineEntityOption[] {
+ const exclude = new Set(
+ [...(options?.excludeUserIds ?? [])].filter((value): value is string => Boolean(value)),
+ );
+
+ return activeUniqueMembers(members)
+ .filter((member) => !exclude.has(member.principalId))
+ .map((member) => ({
+ id: `user:${member.principalId}`,
+ label: baseMemberLabel(member),
+ searchText: [member.user?.name, member.user?.email, member.principalId].filter(Boolean).join(" "),
+ }));
+}
+
+export function buildCompanyUserMentionOptions(
+ members: CompanyUserRecord[] | null | undefined,
+): MentionOption[] {
+ return activeUniqueMembers(members).map((member) => ({
+ id: `user:${member.principalId}`,
+ name: baseMemberLabel(member),
+ kind: "user",
+ userId: member.principalId,
+ }));
+}
+
+export function buildMarkdownMentionOptions(args: {
+ agents?: Array<Pick<Agent, "id" | "name" | "status" | "icon">> | null | undefined;
+ projects?: Array<Pick<Project, "id" | "name" | "color">> | null | undefined;
+ members?: CompanyUserRecord[] | null | undefined;
+}): MentionOption[] {
+ const options: MentionOption[] = [
+ ...buildCompanyUserMentionOptions(args.members),
+ ...[...(args.agents ?? [])]
+ .filter((agent) => agent.status !== "terminated")
+ .sort((left, right) => left.name.localeCompare(right.name))
+ .map((agent) => ({
+ id: `agent:${agent.id}`,
+ name: agent.name,
+ kind: "agent" as const,
+ agentId: agent.id,
+ agentIcon: agent.icon,
+ })),
+ ...[...(args.projects ?? [])]
+ .sort((left, right) => left.name.localeCompare(right.name))
+ .map((project) => ({
+ id: `project:${project.id}`,
+ name: project.name,
+ kind: "project" as const,
+ projectId: project.id,
+ projectColor: project.color,
+ })),
+ ];
+
+ return options;
+}
diff --git a/ui/src/lib/company-routes.test.ts b/ui/src/lib/company-routes.test.ts
index 866b4a6255..d6dc266837 100644
--- a/ui/src/lib/company-routes.test.ts
+++ b/ui/src/lib/company-routes.test.ts
@@ -9,47 +9,15 @@ import {
describe("company routes", () => {
it("treats execution workspace paths as board routes that need a company prefix", () => {
expect(isBoardPathWithoutPrefix("/execution-workspaces/workspace-123")).toBe(true);
- expect(isBoardPathWithoutPrefix("/execution-workspaces/workspace-123/issues")).toBe(true);
expect(extractCompanyPrefixFromPath("/execution-workspaces/workspace-123")).toBeNull();
expect(applyCompanyPrefix("/execution-workspaces/workspace-123", "PAP")).toBe(
"/PAP/execution-workspaces/workspace-123",
);
- expect(applyCompanyPrefix("/execution-workspaces/workspace-123/issues", "PAP")).toBe(
- "/PAP/execution-workspaces/workspace-123/issues",
- );
});
it("normalizes prefixed execution workspace paths back to company-relative paths", () => {
expect(toCompanyRelativePath("/PAP/execution-workspaces/workspace-123")).toBe(
"/execution-workspaces/workspace-123",
);
- expect(toCompanyRelativePath("/PAP/execution-workspaces/workspace-123/configuration")).toBe(
- "/execution-workspaces/workspace-123/configuration",
- );
- });
-
- /**
- * Regression tests for https://github.com/paperclipai/paperclip/issues/2910
- *
- * The Export and Import links on the Company Settings page used plain
- * `<a href="/company/export">` anchors which bypass the router's Link
- * wrapper. Without the wrapper, the company prefix is never applied and
- * the links resolve to `/company/export` instead of `/:prefix/company/export`,
- * producing a "Company not found" error.
- *
- * The fix replaces the `<a>` elements with the prefix-aware `<Link>` from
- * `@/lib/router`. These tests assert that the underlying `applyCompanyPrefix`
- * utility (used by that Link) correctly rewrites the export/import paths.
- */
- it("applies company prefix to /company/export", () => {
- expect(applyCompanyPrefix("/company/export", "PAP")).toBe("/PAP/company/export");
- });
-
- it("applies company prefix to /company/import", () => {
- expect(applyCompanyPrefix("/company/import", "PAP")).toBe("/PAP/company/import");
- });
-
- it("does not double-apply the prefix if already present", () => {
- expect(applyCompanyPrefix("/PAP/company/export", "PAP")).toBe("/PAP/company/export");
});
});
diff --git a/ui/src/lib/inbox.test.ts b/ui/src/lib/inbox.test.ts
index 834c262c89..23c6973016 100644
--- a/ui/src/lib/inbox.test.ts
+++ b/ui/src/lib/inbox.test.ts
@@ -46,6 +46,7 @@ import {
saveInboxIssueColumns,
saveInboxWorkItemGroupBy,
saveLastInboxTab,
+ shouldShowCompanyAlerts,
shouldResetInboxWorkspaceGrouping,
shouldShowInboxSection,
type InboxWorkItem,
@@ -298,7 +299,10 @@ describe("inbox helpers", () => {
it("counts the same inbox sources the badge uses", () => {
const result = computeInboxBadgeData({
- approvals: [makeApproval("pending"), makeApproval("approved")],
+ approvals: [
+ { ...makeApproval("pending"), requestedByUserId: "user-1" },
+ { ...makeApproval("approved"), requestedByUserId: "user-2" },
+ ],
joinRequests: [makeJoinRequest("join-1")],
dashboard,
heartbeatRuns: [
@@ -309,10 +313,11 @@ describe("inbox helpers", () => {
mineIssues: [makeIssue("1", true)],
dismissedAlerts: new Set<string>(),
dismissedAtByKey: new Map<string, number>(),
+ currentUserId: "user-1",
});
expect(result).toEqual({
- inbox: 6,
+ inbox: 5,
approvals: 1,
failedRuns: 2,
joinRequests: 1,
@@ -330,6 +335,7 @@ describe("inbox helpers", () => {
mineIssues: [],
dismissedAlerts: new Set<string>(["alert:budget", "alert:agent-errors"]),
dismissedAtByKey: new Map<string, number>([["run:run-1", new Date("2026-03-11T00:00:00.000Z").getTime()]]),
+ currentUserId: "user-1",
});
expect(result).toEqual({
@@ -351,10 +357,12 @@ describe("inbox helpers", () => {
mineIssues: [makeIssue("1", false), makeIssue("2", false), makeIssue("3", true)],
dismissedAlerts: new Set<string>(),
dismissedAtByKey: new Map(),
+ currentUserId: "user-1",
});
expect(result.mineIssues).toBe(1);
- expect(result.inbox).toBe(3);
+ expect(result.inbox).toBe(1);
+ expect(result.alerts).toBe(2);
});
it("resurfaces non-issue items when they change after dismissal", () => {
@@ -393,21 +401,25 @@ describe("inbox helpers", () => {
expect(issues).toHaveLength(2);
});
- it("shows recent approvals in updated order and unread approvals as actionable only", () => {
+ it("shows only my approvals on mine, while recent and unread stay company-wide", () => {
const approvals = [
- makeApprovalWithTimestamps("approval-approved", "approved", "2026-03-11T02:00:00.000Z"),
- makeApprovalWithTimestamps("approval-pending", "pending", "2026-03-11T01:00:00.000Z"),
- makeApprovalWithTimestamps(
- "approval-revision",
- "revision_requested",
- "2026-03-11T03:00:00.000Z",
- ),
+ {
+ ...makeApprovalWithTimestamps("approval-approved", "approved", "2026-03-11T02:00:00.000Z"),
+ requestedByUserId: "user-1",
+ },
+ {
+ ...makeApprovalWithTimestamps("approval-pending", "pending", "2026-03-11T01:00:00.000Z"),
+ requestedByUserId: "user-2",
+ },
+ {
+ ...makeApprovalWithTimestamps("approval-revision", "revision_requested", "2026-03-11T03:00:00.000Z"),
+ decidedByUserId: "user-1",
+ },
];
- expect(getApprovalsForTab(approvals, "mine", "all").map((approval) => approval.id)).toEqual([
+ expect(getApprovalsForTab(approvals, "mine", "all", "user-1").map((approval) => approval.id)).toEqual([
"approval-revision",
"approval-approved",
- "approval-pending",
]);
expect(getApprovalsForTab(approvals, "recent", "all").map((approval) => approval.id)).toEqual([
"approval-revision",
@@ -423,6 +435,44 @@ describe("inbox helpers", () => {
]);
});
+ it("keeps unrelated approvals out of a new user's badge and mine tab", () => {
+ const approvals = [
+ { ...makeApproval("pending"), requestedByUserId: "user-2" },
+ { ...makeApproval("revision_requested"), decidedByUserId: "user-3" },
+ ];
+
+ expect(getApprovalsForTab(approvals, "mine", "all", "user-1")).toEqual([]);
+
+ const result = computeInboxBadgeData({
+ approvals,
+ joinRequests: [],
+ dashboard,
+ heartbeatRuns: [],
+ mineIssues: [],
+ dismissedAlerts: new Set<string>(),
+ dismissedAtByKey: new Map(),
+ currentUserId: "user-1",
+ });
+
+ expect(result.approvals).toBe(0);
+ });
+
+ it("does not count company-wide alerts in the personal inbox badge", () => {
+ const result = computeInboxBadgeData({
+ approvals: [],
+ joinRequests: [],
+ dashboard,
+ heartbeatRuns: [],
+ mineIssues: [],
+ dismissedAlerts: new Set<string>(),
+ dismissedAtByKey: new Map(),
+ currentUserId: "user-1",
+ });
+
+ expect(result.alerts).toBe(2);
+ expect(result.inbox).toBe(0);
+ });
+
it("mixes approvals into the inbox feed by most recent activity", () => {
const newerIssue = makeIssue("1", true);
newerIssue.lastActivityAt = new Date("2026-03-11T04:00:00.000Z");
@@ -614,6 +664,13 @@ describe("inbox helpers", () => {
).toBe(false);
});
+ it("shows company alerts only on the all tab", () => {
+ expect(shouldShowCompanyAlerts("mine")).toBe(false);
+ expect(shouldShowCompanyAlerts("recent")).toBe(false);
+ expect(shouldShowCompanyAlerts("unread")).toBe(false);
+ expect(shouldShowCompanyAlerts("all")).toBe(true);
+ });
+
it("limits recent touched issues before unread badge counting", () => {
const issues = Array.from({ length: RECENT_ISSUES_LIMIT + 5 }, (_, index) => {
const issue = makeIssue(String(index + 1), index < 3);
diff --git a/ui/src/lib/inbox.ts b/ui/src/lib/inbox.ts
index 6b66f66f2d..86d34e1b13 100644
--- a/ui/src/lib/inbox.ts
+++ b/ui/src/lib/inbox.ts
@@ -625,6 +625,10 @@ export function isMineInboxTab(tab: InboxTab): boolean {
return tab === "mine";
}
+export function shouldShowCompanyAlerts(tab: InboxTab): boolean {
+ return tab === "all";
+}
+
export function resolveInboxSelectionIndex(
previousIndex: number,
itemCount: number,
@@ -695,12 +699,20 @@ export function getApprovalsForTab(
approvals: Approval[],
tab: InboxTab,
filter: InboxApprovalFilter,
+ currentUserId?: string | null,
): Approval[] {
const sortedApprovals = [...approvals].sort(
(a, b) => normalizeTimestamp(b.updatedAt) - normalizeTimestamp(a.updatedAt),
);
- if (tab === "mine" || tab === "recent") return sortedApprovals;
+ if (tab === "mine") {
+ if (!currentUserId) return [];
+ return sortedApprovals.filter(
+ (approval) =>
+ approval.requestedByUserId === currentUserId || approval.decidedByUserId === currentUserId,
+ );
+ }
+ if (tab === "recent") return sortedApprovals;
if (tab === "unread") {
return sortedApprovals.filter((approval) => ACTIONABLE_APPROVAL_STATUSES.has(approval.status));
}
@@ -1005,6 +1017,7 @@ export function computeInboxBadgeData({
mineIssues,
dismissedAlerts,
dismissedAtByKey,
+ currentUserId,
}: {
approvals: Approval[];
joinRequests: JoinRequest[];
@@ -1013,9 +1026,12 @@ export function computeInboxBadgeData({
mineIssues: Issue[];
dismissedAlerts: Set<string>;
dismissedAtByKey: ReadonlyMap<string, number>;
+ currentUserId?: string | null;
}): InboxBadgeData {
const actionableApprovals = approvals.filter(
(approval) =>
+ !!currentUserId &&
+ (approval.requestedByUserId === currentUserId || approval.decidedByUserId === currentUserId) &&
ACTIONABLE_APPROVAL_STATUSES.has(approval.status) &&
!isInboxEntityDismissed(dismissedAtByKey, `approval:${approval.id}`, approval.updatedAt),
).length;
@@ -1040,7 +1056,8 @@ export function computeInboxBadgeData({
const alerts = Number(showAggregateAgentError) + Number(showBudgetAlert);
return {
- inbox: actionableApprovals + visibleJoinRequests + failedRuns + visibleMineIssues + alerts,
+ // The inbox badge reflects personal/actionable work, not company-wide health alerts.
+ inbox: actionableApprovals + visibleJoinRequests + failedRuns + visibleMineIssues,
approvals: actionableApprovals,
failedRuns,
joinRequests: visibleJoinRequests,
diff --git a/ui/src/lib/invite-memory.ts b/ui/src/lib/invite-memory.ts
new file mode 100644
index 0000000000..5156d2dd91
--- /dev/null
+++ b/ui/src/lib/invite-memory.ts
@@ -0,0 +1,36 @@
+const PENDING_INVITE_STORAGE_KEY = "paperclip:pending-invite-token";
+
+function canUseStorage() {
+ return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
+}
+
+export function rememberPendingInviteToken(token: string) {
+ const normalized = token.trim();
+ if (!normalized || !canUseStorage()) return;
+ try {
+ window.localStorage.setItem(PENDING_INVITE_STORAGE_KEY, normalized);
+ } catch {
+ // Ignore storage failures and keep the invite flow usable.
+ }
+}
+
+export function clearPendingInviteToken(expectedToken?: string) {
+ if (!canUseStorage()) return;
+ try {
+ const current = window.localStorage.getItem(PENDING_INVITE_STORAGE_KEY);
+ if (expectedToken && current !== expectedToken.trim()) return;
+ window.localStorage.removeItem(PENDING_INVITE_STORAGE_KEY);
+ } catch {
+ // Ignore storage failures.
+ }
+}
+
+export function getRememberedInvitePath() {
+ if (!canUseStorage()) return null;
+ try {
+ const token = window.localStorage.getItem(PENDING_INVITE_STORAGE_KEY)?.trim();
+ return token ? `/invite/${token}` : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/ui/src/lib/issue-chat-messages.test.ts b/ui/src/lib/issue-chat-messages.test.ts
index c79759f4a7..7bd6472355 100644
--- a/ui/src/lib/issue-chat-messages.test.ts
+++ b/ui/src/lib/issue-chat-messages.test.ts
@@ -234,6 +234,27 @@ describe("buildAssistantPartsFromTranscript", () => {
});
describe("buildIssueChatMessages", () => {
+ it("uses the company user label for current-user comments instead of collapsing to You", () => {
+ const messages = buildIssueChatMessages({
+ comments: [createComment({ authorUserId: "user-1" })],
+ timelineEvents: [],
+ linkedRuns: [],
+ liveRuns: [],
+ currentUserId: "user-1",
+ userLabelMap: new Map([["user-1", "Dotta"]]),
+ });
+
+ expect(messages[0]).toMatchObject({
+ role: "user",
+ metadata: {
+ custom: {
+ authorName: "Dotta",
+ authorUserId: "user-1",
+ },
+ },
+ });
+ });
+
it("orders events before comments and appends active live runs as running assistant messages", () => {
const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "CodexCoder")]]);
const comments = [
diff --git a/ui/src/lib/issue-chat-messages.ts b/ui/src/lib/issue-chat-messages.ts
index 8b6869fa45..5b52498716 100644
--- a/ui/src/lib/issue-chat-messages.ts
+++ b/ui/src/lib/issue-chat-messages.ts
@@ -270,11 +270,16 @@ function authorNameForComment(
comment: IssueChatComment,
agentMap?: Map<string, Agent>,
currentUserId?: string | null,
+ userLabelMap?: ReadonlyMap<string, string> | null,
) {
if (comment.authorAgentId) {
return agentMap?.get(comment.authorAgentId)?.name ?? comment.authorAgentId.slice(0, 8);
}
- return formatAssigneeUserLabel(comment.authorUserId ?? null, currentUserId) ?? "You";
+ const authorUserId = comment.authorUserId ?? null;
+ if (!authorUserId) return "You";
+ const userLabel = userLabelMap?.get(authorUserId)?.trim();
+ if (userLabel) return userLabel;
+ return formatAssigneeUserLabel(authorUserId, currentUserId, userLabelMap) ?? "You";
}
function formatStatusLabel(status: string) {
@@ -285,12 +290,13 @@ function createCommentMessage(args: {
comment: IssueChatComment;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
+ userLabelMap?: ReadonlyMap<string, string> | null;
companyId?: string | null;
projectId?: string | null;
}): ThreadMessage {
- const { comment, agentMap, currentUserId, companyId, projectId } = args;
+ const { comment, agentMap, currentUserId, userLabelMap, companyId, projectId } = args;
const createdAt = toDate(comment.createdAt);
- const authorName = authorNameForComment(comment, agentMap, currentUserId);
+ const authorName = authorNameForComment(comment, agentMap, currentUserId, userLabelMap);
const custom = {
kind: "comment",
commentId: comment.id,
@@ -335,13 +341,14 @@ function createTimelineEventMessage(args: {
event: IssueTimelineEvent;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
+ userLabelMap?: ReadonlyMap<string, string> | null;
}) {
- const { event, agentMap, currentUserId } = args;
+ const { event, agentMap, currentUserId, userLabelMap } = args;
const actorName = event.actorType === "agent"
? (agentMap?.get(event.actorId)?.name ?? event.actorId.slice(0, 8))
: event.actorType === "system"
? "System"
- : (formatAssigneeUserLabel(event.actorId, currentUserId) ?? "Board");
+ : (formatAssigneeUserLabel(event.actorId, currentUserId, userLabelMap) ?? "Board");
const lines: string[] = [`${actorName} updated this issue`];
if (event.statusChange) {
@@ -352,10 +359,10 @@ function createTimelineEventMessage(args: {
if (event.assigneeChange) {
const from = event.assigneeChange.from.agentId
? (agentMap?.get(event.assigneeChange.from.agentId)?.name ?? event.assigneeChange.from.agentId.slice(0, 8))
- : (formatAssigneeUserLabel(event.assigneeChange.from.userId, currentUserId) ?? "Unassigned");
+ : (formatAssigneeUserLabel(event.assigneeChange.from.userId, currentUserId, userLabelMap) ?? "Unassigned");
const to = event.assigneeChange.to.agentId
? (agentMap?.get(event.assigneeChange.to.agentId)?.name ?? event.assigneeChange.to.agentId.slice(0, 8))
- : (formatAssigneeUserLabel(event.assigneeChange.to.userId, currentUserId) ?? "Unassigned");
+ : (formatAssigneeUserLabel(event.assigneeChange.to.userId, currentUserId, userLabelMap) ?? "Unassigned");
lines.push(`Assignee: ${from} -> ${to}`);
}
@@ -743,6 +750,7 @@ export function buildIssueChatMessages(args: {
projectId?: string | null;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
+ userLabelMap?: ReadonlyMap<string, string> | null;
}) {
const {
comments,
@@ -758,6 +766,7 @@ export function buildIssueChatMessages(args: {
projectId,
agentMap,
currentUserId,
+ userLabelMap,
} = args;
const orderedMessages: MessageWithOrder[] = [];
@@ -766,7 +775,7 @@ export function buildIssueChatMessages(args: {
orderedMessages.push({
createdAtMs: toTimestamp(comment.createdAt),
order: 1,
- message: createCommentMessage({ comment, agentMap, currentUserId, companyId, projectId }),
+ message: createCommentMessage({ comment, agentMap, currentUserId, userLabelMap, companyId, projectId }),
});
}
@@ -774,7 +783,7 @@ export function buildIssueChatMessages(args: {
orderedMessages.push({
createdAtMs: toTimestamp(event.createdAt),
order: 0,
- message: createTimelineEventMessage({ event, agentMap, currentUserId }),
+ message: createTimelineEventMessage({ event, agentMap, currentUserId, userLabelMap }),
});
}
diff --git a/ui/src/lib/mention-chips.ts b/ui/src/lib/mention-chips.ts
index 7fecbb8922..b641224e47 100644
--- a/ui/src/lib/mention-chips.ts
+++ b/ui/src/lib/mention-chips.ts
@@ -1,5 +1,5 @@
import type { CSSProperties } from "react";
-import { parseAgentMentionHref, parseProjectMentionHref, parseSkillMentionHref } from "@paperclipai/shared";
+import { parseAgentMentionHref, parseProjectMentionHref, parseSkillMentionHref, parseUserMentionHref } from "@paperclipai/shared";
import { getAgentIcon } from "./agent-icons";
import { hexToRgb, pickTextColorForPillBg } from "./color-contrast";
@@ -14,6 +14,10 @@ export type ParsedMentionChip =
projectId: string;
color: string | null;
}
+ | {
+ kind: "user";
+ userId: string;
+ }
| {
kind: "skill";
skillId: string;
@@ -41,6 +45,14 @@ export function parseMentionChipHref(href: string): ParsedMentionChip | null {
};
}
+ const user = parseUserMentionHref(href);
+ if (user) {
+ return {
+ kind: "user",
+ userId: user.userId,
+ };
+ }
+
const skill = parseSkillMentionHref(href);
if (skill) {
return {
@@ -100,6 +112,7 @@ export function clearMentionChipDecoration(element: HTMLElement) {
"paperclip-mention-chip",
"paperclip-mention-chip--agent",
"paperclip-mention-chip--project",
+ "paperclip-mention-chip--user",
"paperclip-mention-chip--skill",
"paperclip-project-mention-chip",
);
diff --git a/ui/src/lib/project-workspaces-tab.ts b/ui/src/lib/project-workspaces-tab.ts
index f4e5c5c376..df0d9bb35d 100644
--- a/ui/src/lib/project-workspaces-tab.ts
+++ b/ui/src/lib/project-workspaces-tab.ts
@@ -78,37 +78,35 @@ export function buildProjectWorkspaceSummaries(input: {
})) continue;
const existing = summaries.get(`execution:${executionWorkspace.id}`);
- const nextIssues = existing?.issues ?? [];
- nextIssues.push(issue);
+ const nextIssues = [...(existing?.issues ?? []), issue].sort(
+ (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
+ );
- if (!existing) {
- summaries.set(`execution:${executionWorkspace.id}`, {
- key: `execution:${executionWorkspace.id}`,
- kind: "execution_workspace",
- workspaceId: executionWorkspace.id,
- workspaceName: executionWorkspace.name,
- cwd: executionWorkspace.cwd ?? null,
- branchName: executionWorkspace.branchName ?? executionWorkspace.baseRef ?? null,
- lastUpdatedAt: maxDate(
- executionWorkspace.lastUsedAt,
- executionWorkspace.updatedAt,
- issue.updatedAt,
- ),
- projectWorkspaceId: executionWorkspace.projectWorkspaceId ?? issue.projectWorkspaceId ?? null,
- executionWorkspaceId: executionWorkspace.id,
- executionWorkspaceStatus: executionWorkspace.status,
- serviceCount: executionWorkspace.runtimeServices?.length ?? 0,
- runningServiceCount: executionWorkspace.runtimeServices?.filter((service) => service.status === "running").length ?? 0,
- primaryServiceUrl: executionWorkspace.runtimeServices?.find((service) => service.url)?.url ?? null,
- hasRuntimeConfig: Boolean(
- executionWorkspace.config?.workspaceRuntime
- ?? projectWorkspacesById.get(executionWorkspace.projectWorkspaceId ?? issue.projectWorkspaceId ?? "")?.runtimeConfig?.workspaceRuntime,
- ),
- issues: nextIssues,
- });
- } else {
- existing.lastUpdatedAt = maxDate(existing.lastUpdatedAt, issue.updatedAt);
- }
+ summaries.set(`execution:${executionWorkspace.id}`, {
+ key: `execution:${executionWorkspace.id}`,
+ kind: "execution_workspace",
+ workspaceId: executionWorkspace.id,
+ workspaceName: executionWorkspace.name,
+ cwd: executionWorkspace.cwd ?? null,
+ branchName: executionWorkspace.branchName ?? executionWorkspace.baseRef ?? null,
+ lastUpdatedAt: maxDate(
+ existing?.lastUpdatedAt,
+ executionWorkspace.lastUsedAt,
+ executionWorkspace.updatedAt,
+ issue.updatedAt,
+ ),
+ projectWorkspaceId: executionWorkspace.projectWorkspaceId ?? issue.projectWorkspaceId ?? null,
+ executionWorkspaceId: executionWorkspace.id,
+ executionWorkspaceStatus: executionWorkspace.status,
+ serviceCount: executionWorkspace.runtimeServices?.length ?? 0,
+ runningServiceCount: executionWorkspace.runtimeServices?.filter((service) => service.status === "running").length ?? 0,
+ primaryServiceUrl: executionWorkspace.runtimeServices?.find((service) => service.url)?.url ?? null,
+ hasRuntimeConfig: Boolean(
+ executionWorkspace.config?.workspaceRuntime
+ ?? projectWorkspacesById.get(executionWorkspace.projectWorkspaceId ?? issue.projectWorkspaceId ?? "")?.runtimeConfig?.workspaceRuntime,
+ ),
+ issues: nextIssues,
+ });
continue;
}
@@ -117,30 +115,27 @@ export function buildProjectWorkspaceSummaries(input: {
if (!projectWorkspace) continue;
const existing = summaries.get(`project:${projectWorkspace.id}`);
- const nextIssues = existing?.issues ?? [];
- nextIssues.push(issue);
+ const nextIssues = [...(existing?.issues ?? []), issue].sort(
+ (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
+ );
- if (!existing) {
- summaries.set(`project:${projectWorkspace.id}`, {
- key: `project:${projectWorkspace.id}`,
- kind: "project_workspace",
- workspaceId: projectWorkspace.id,
- workspaceName: projectWorkspace.name,
- cwd: projectWorkspace.cwd ?? null,
- branchName: projectWorkspace.repoRef ?? projectWorkspace.defaultRef ?? null,
- lastUpdatedAt: maxDate(projectWorkspace.updatedAt, issue.updatedAt),
- projectWorkspaceId: projectWorkspace.id,
- executionWorkspaceId: null,
- executionWorkspaceStatus: null,
- serviceCount: projectWorkspace.runtimeServices?.length ?? 0,
- runningServiceCount: projectWorkspace.runtimeServices?.filter((service) => service.status === "running").length ?? 0,
- primaryServiceUrl: projectWorkspace.runtimeServices?.find((service) => service.url)?.url ?? null,
- hasRuntimeConfig: Boolean(projectWorkspace.runtimeConfig?.workspaceRuntime),
- issues: nextIssues,
- });
- } else {
- existing.lastUpdatedAt = maxDate(existing.lastUpdatedAt, issue.updatedAt);
- }
+ summaries.set(`project:${projectWorkspace.id}`, {
+ key: `project:${projectWorkspace.id}`,
+ kind: "project_workspace",
+ workspaceId: projectWorkspace.id,
+ workspaceName: projectWorkspace.name,
+ cwd: projectWorkspace.cwd ?? null,
+ branchName: projectWorkspace.repoRef ?? projectWorkspace.defaultRef ?? null,
+ lastUpdatedAt: maxDate(existing?.lastUpdatedAt, projectWorkspace.updatedAt, issue.updatedAt),
+ projectWorkspaceId: projectWorkspace.id,
+ executionWorkspaceId: null,
+ executionWorkspaceStatus: null,
+ serviceCount: projectWorkspace.runtimeServices?.length ?? 0,
+ runningServiceCount: projectWorkspace.runtimeServices?.filter((service) => service.status === "running").length ?? 0,
+ primaryServiceUrl: projectWorkspace.runtimeServices?.find((service) => service.url)?.url ?? null,
+ hasRuntimeConfig: Boolean(projectWorkspace.runtimeConfig?.workspaceRuntime),
+ issues: nextIssues,
+ });
}
for (const projectWorkspace of input.project.workspaces) {
@@ -170,17 +165,8 @@ export function buildProjectWorkspaceSummaries(input: {
});
}
- const result = [...summaries.values()];
- // Sort issues within each summary once (instead of on every insertion)
- const issueTime = (issue: Issue) => new Date(issue.updatedAt).getTime();
- for (const summary of result) {
- if (summary.issues.length > 1) {
- summary.issues.sort((a, b) => issueTime(b) - issueTime(a));
- }
- }
- result.sort((a, b) => {
+ return [...summaries.values()].sort((a, b) => {
const diff = b.lastUpdatedAt.getTime() - a.lastUpdatedAt.getTime();
return diff !== 0 ? diff : a.workspaceName.localeCompare(b.workspaceName);
});
- return result;
}
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index 6c67cbd0a1..57c4abb522 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -90,9 +90,16 @@ export const queryKeys = {
issues: (approvalId: string) => ["approvals", "issues", approvalId] as const,
},
access: {
+ invites: (companyId: string, state: string = "all", limit: number = 20) =>
+ ["access", "invites", "paginated-v1", companyId, state, limit] as const,
joinRequests: (companyId: string, status: string = "pending_approval") =>
["access", "join-requests", companyId, status] as const,
+ companyMembers: (companyId: string) => ["access", "company-members", companyId] as const,
+ companyUserDirectory: (companyId: string) => ["access", "company-user-directory", companyId] as const,
+ adminUsers: (query: string) => ["access", "admin-users", query] as const,
+ userCompanyAccess: (userId: string) => ["access", "user-company-access", userId] as const,
invite: (token: string) => ["access", "invite", token] as const,
+ currentBoardAccess: ["access", "current-board-access"] as const,
},
auth: {
session: ["auth", "session"] as const,
diff --git a/ui/src/pages/Activity.tsx b/ui/src/pages/Activity.tsx
index cfb347bba3..685b7974cb 100644
--- a/ui/src/pages/Activity.tsx
+++ b/ui/src/pages/Activity.tsx
@@ -1,10 +1,12 @@
import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { activityApi } from "../api/activity";
+import { accessApi } from "../api/access";
import { agentsApi } from "../api/agents";
import { issuesApi } from "../api/issues";
import { projectsApi } from "../api/projects";
import { goalsApi } from "../api/goals";
+import { buildCompanyUserProfileMap } from "../lib/company-members";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
@@ -60,6 +62,17 @@ export function Activity() {
enabled: !!selectedCompanyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const userProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+
const agentMap = useMemo(() => {
const map = new Map<string, Agent>();
for (const a of agents ?? []) map.set(a.id, a);
@@ -129,6 +142,7 @@ export function Activity() {
key={event.id}
event={event}
agentMap={agentMap}
+ userProfileMap={userProfileMap}
entityNameMap={entityNameMap}
entityTitleMap={entityTitleMap}
/>
diff --git a/ui/src/pages/Auth.tsx b/ui/src/pages/Auth.tsx
index 97e95d58f9..56e67fc1c5 100644
--- a/ui/src/pages/Auth.tsx
+++ b/ui/src/pages/Auth.tsx
@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useSearchParams } from "@/lib/router";
import { authApi } from "../api/auth";
import { queryKeys } from "../lib/queryKeys";
+import { getRememberedInvitePath } from "../lib/invite-memory";
import { Button } from "@/components/ui/button";
import { AsciiArtAnimation } from "@/components/AsciiArtAnimation";
import { Sparkles } from "lucide-react";
@@ -19,7 +20,10 @@ export function AuthPage() {
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
- const nextPath = useMemo(() => searchParams.get("next") || "/", [searchParams]);
+ const nextPath = useMemo(
+ () => searchParams.get("next") || getRememberedInvitePath() || "/",
+ [searchParams],
+ );
const { data: session, isLoading: isSessionLoading } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
diff --git a/ui/src/pages/CompanyAccess.test.tsx b/ui/src/pages/CompanyAccess.test.tsx
new file mode 100644
index 0000000000..4d6af17cf0
--- /dev/null
+++ b/ui/src/pages/CompanyAccess.test.tsx
@@ -0,0 +1,219 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CompanyAccess } from "./CompanyAccess";
+
+const listMembersMock = vi.hoisted(() => vi.fn());
+const listJoinRequestsMock = vi.hoisted(() => vi.fn());
+const updateMemberAccessMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/access", () => ({
+ accessApi: {
+ listMembers: (companyId: string) => listMembersMock(companyId),
+ listJoinRequests: (companyId: string, status: string) => listJoinRequestsMock(companyId, status),
+ updateMember: vi.fn(),
+ updateMemberPermissions: vi.fn(),
+ updateMemberAccess: (companyId: string, memberId: string, input: unknown) =>
+ updateMemberAccessMock(companyId, memberId, input),
+ approveJoinRequest: vi.fn(),
+ rejectJoinRequest: vi.fn(),
+ },
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompanyId: "company-1",
+ selectedCompany: { id: "company-1", name: "Paperclip" },
+ }),
+}));
+
+vi.mock("@/context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
+}));
+
+vi.mock("@/context/ToastContext", () => ({
+ useToast: () => ({ pushToast: vi.fn() }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("CompanyAccess", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ listMembersMock.mockResolvedValue({
+ members: [
+ {
+ id: "member-1",
+ companyId: "company-1",
+ principalType: "user",
+ principalId: "user-1",
+ status: "active",
+ membershipRole: "owner",
+ createdAt: "2026-04-10T00:00:00.000Z",
+ updatedAt: "2026-04-10T00:00:00.000Z",
+ user: {
+ id: "user-1",
+ email: "[email protected]",
+ name: "Codex Coder",
+ image: null,
+ },
+ grants: [],
+ },
+ ],
+ access: {
+ currentUserRole: "owner",
+ canManageMembers: true,
+ canInviteUsers: true,
+ canApproveJoinRequests: true,
+ },
+ });
+ listJoinRequestsMock.mockResolvedValue([
+ {
+ id: "join-1",
+ requestType: "human",
+ createdAt: "2026-04-10T00:00:00.000Z",
+ requesterUser: {
+ id: "user-2",
+ email: "[email protected]",
+ name: "Board User",
+ image: null,
+ },
+ requestEmailSnapshot: "[email protected]",
+ requestingUserId: "user-2",
+ invite: {
+ allowedJoinTypes: "human",
+ humanRole: "operator",
+ },
+ },
+ {
+ id: "join-2",
+ requestType: "agent",
+ createdAt: "2026-04-10T00:00:00.000Z",
+ agentName: "Codex Worker",
+ adapterType: "codex_local",
+ capabilities: "Implements code changes",
+ invite: {
+ allowedJoinTypes: "agent",
+ humanRole: null,
+ },
+ },
+ ]);
+ updateMemberAccessMock.mockResolvedValue({});
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("keeps the page human-focused and explains implicit versus explicit grants", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <CompanyAccess />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Manage company user memberships");
+ expect(container.textContent).toContain("Humans");
+ expect(container.textContent).toContain("Pending human joins");
+ expect(container.textContent).toContain("User account");
+ expect(container.textContent).not.toContain("Agents");
+ expect(container.textContent).not.toContain("Pending agent joins");
+ expect(container.textContent).not.toContain("Open join request queue");
+ expect(container.textContent).not.toContain("Manage invites");
+ expect(container.textContent).not.toContain("Active user accounts");
+ expect(container.textContent).not.toContain("Suspended user accounts");
+ expect(container.textContent).not.toContain("Pending user joins");
+
+ const editButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Edit",
+ );
+ expect(editButton).toBeTruthy();
+
+ await act(async () => {
+ editButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(document.body.textContent).toContain("Implicit grants from role");
+ expect(document.body.textContent).toContain("Owner currently includes these permissions automatically.");
+ expect(document.body.textContent).toContain(
+ "Included implicitly by the Owner role. Add an explicit grant only if it should stay after the role changes.",
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("saves member role, status, and grants in one request", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <CompanyAccess />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ const editButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Edit",
+ );
+ expect(editButton).toBeTruthy();
+
+ await act(async () => {
+ editButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ const saveButton = Array.from(document.body.querySelectorAll("button")).find(
+ (button) => button.textContent === "Save access",
+ );
+ expect(saveButton).toBeTruthy();
+
+ await act(async () => {
+ saveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(updateMemberAccessMock).toHaveBeenCalledWith("company-1", "member-1", {
+ membershipRole: "owner",
+ status: "active",
+ grants: [],
+ });
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/CompanyAccess.tsx b/ui/src/pages/CompanyAccess.tsx
new file mode 100644
index 0000000000..9c65e45e16
--- /dev/null
+++ b/ui/src/pages/CompanyAccess.tsx
@@ -0,0 +1,476 @@
+import { useEffect, useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS, PERMISSION_KEYS, type PermissionKey } from "@paperclipai/shared";
+import { ShieldCheck, Users } from "lucide-react";
+import { accessApi, type CompanyMember } from "@/api/access";
+import { ApiError } from "@/api/client";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Badge } from "@/components/ui/badge";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "@/context/CompanyContext";
+import { useToast } from "@/context/ToastContext";
+import { queryKeys } from "@/lib/queryKeys";
+
+const permissionLabels: Record<PermissionKey, string> = {
+ "agents:create": "Create agents",
+ "users:invite": "Invite humans and agents",
+ "users:manage_permissions": "Manage members and grants",
+ "tasks:assign": "Assign tasks",
+ "tasks:assign_scope": "Assign scoped tasks",
+ "joins:approve": "Approve join requests",
+};
+
+function formatGrantSummary(member: CompanyMember) {
+ if (member.grants.length === 0) return "No explicit grants";
+ return member.grants.map((grant) => permissionLabels[grant.permissionKey]).join(", ");
+}
+
+const implicitRoleGrantMap: Record<NonNullable<CompanyMember["membershipRole"]>, PermissionKey[]> = {
+ owner: ["agents:create", "users:invite", "users:manage_permissions", "tasks:assign", "joins:approve"],
+ admin: ["agents:create", "users:invite", "tasks:assign", "joins:approve"],
+ operator: ["tasks:assign"],
+ viewer: [],
+};
+
+function getImplicitGrantKeys(role: CompanyMember["membershipRole"]) {
+ return role ? implicitRoleGrantMap[role] : [];
+}
+
+export function CompanyAccess() {
+ const { selectedCompany, selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { pushToast } = useToast();
+ const queryClient = useQueryClient();
+ const [editingMemberId, setEditingMemberId] = useState<string | null>(null);
+ const [draftRole, setDraftRole] = useState<CompanyMember["membershipRole"]>(null);
+ const [draftStatus, setDraftStatus] = useState<CompanyMember["status"]>("active");
+ const [draftGrants, setDraftGrants] = useState<Set<PermissionKey>>(new Set());
+
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: selectedCompany?.name ?? "Company", href: "/dashboard" },
+ { label: "Settings", href: "/company/settings" },
+ { label: "Access" },
+ ]);
+ }, [selectedCompany?.name, setBreadcrumbs]);
+
+ const membersQuery = useQuery({
+ queryKey: queryKeys.access.companyMembers(selectedCompanyId ?? ""),
+ queryFn: () => accessApi.listMembers(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const joinRequestsQuery = useQuery({
+ queryKey: queryKeys.access.joinRequests(selectedCompanyId ?? "", "pending_approval"),
+ queryFn: () => accessApi.listJoinRequests(selectedCompanyId!, "pending_approval"),
+ enabled: !!selectedCompanyId && !!membersQuery.data?.access.canApproveJoinRequests,
+ });
+
+ const refreshAccessData = async () => {
+ if (!selectedCompanyId) return;
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.companyMembers(selectedCompanyId) });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId) });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId, "pending_approval") });
+ };
+
+ const updateMemberMutation = useMutation({
+ mutationFn: async (input: { memberId: string; membershipRole: CompanyMember["membershipRole"]; status: CompanyMember["status"]; grants: PermissionKey[] }) => {
+ return accessApi.updateMemberAccess(selectedCompanyId!, input.memberId, {
+ membershipRole: input.membershipRole,
+ status: input.status,
+ grants: input.grants.map((permissionKey) => ({ permissionKey })),
+ });
+ },
+ onSuccess: async () => {
+ setEditingMemberId(null);
+ await refreshAccessData();
+ pushToast({
+ title: "Member updated",
+ tone: "success",
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ title: "Failed to update member",
+ body: error instanceof Error ? error.message : "Unknown error",
+ tone: "error",
+ });
+ },
+ });
+
+ const approveJoinRequestMutation = useMutation({
+ mutationFn: (requestId: string) => accessApi.approveJoinRequest(selectedCompanyId!, requestId),
+ onSuccess: async () => {
+ await refreshAccessData();
+ pushToast({
+ title: "Join request approved",
+ tone: "success",
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ title: "Failed to approve join request",
+ body: error instanceof Error ? error.message : "Unknown error",
+ tone: "error",
+ });
+ },
+ });
+
+ const rejectJoinRequestMutation = useMutation({
+ mutationFn: (requestId: string) => accessApi.rejectJoinRequest(selectedCompanyId!, requestId),
+ onSuccess: async () => {
+ await refreshAccessData();
+ pushToast({
+ title: "Join request rejected",
+ tone: "success",
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ title: "Failed to reject join request",
+ body: error instanceof Error ? error.message : "Unknown error",
+ tone: "error",
+ });
+ },
+ });
+
+ const editingMember = useMemo(
+ () => membersQuery.data?.members.find((member) => member.id === editingMemberId) ?? null,
+ [editingMemberId, membersQuery.data?.members],
+ );
+
+ useEffect(() => {
+ if (!editingMember) return;
+ setDraftRole(editingMember.membershipRole);
+ setDraftStatus(editingMember.status);
+ setDraftGrants(new Set(editingMember.grants.map((grant) => grant.permissionKey)));
+ }, [editingMember]);
+
+ if (!selectedCompanyId) {
+ return <div className="text-sm text-muted-foreground">Select a company to manage access.</div>;
+ }
+
+ if (membersQuery.isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading company access…</div>;
+ }
+
+ if (membersQuery.error) {
+ const message =
+ membersQuery.error instanceof ApiError && membersQuery.error.status === 403
+ ? "You do not have permission to manage company members."
+ : membersQuery.error instanceof Error
+ ? membersQuery.error.message
+ : "Failed to load company members.";
+ return <div className="text-sm text-destructive">{message}</div>;
+ }
+
+ const members = membersQuery.data?.members ?? [];
+ const access = membersQuery.data?.access;
+ const pendingHumanJoinRequests =
+ joinRequestsQuery.data?.filter((request) => request.requestType === "human") ?? [];
+ const joinRequestActionPending =
+ approveJoinRequestMutation.isPending || rejectJoinRequestMutation.isPending;
+ const implicitGrantKeys = getImplicitGrantKeys(draftRole);
+ const implicitGrantSet = new Set(implicitGrantKeys);
+
+ return (
+ <div className="max-w-6xl space-y-8">
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <ShieldCheck className="h-5 w-5 text-muted-foreground" />
+ <h1 className="text-lg font-semibold">Company Access</h1>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ Manage company user memberships, membership status, and explicit permission grants for {selectedCompany?.name}.
+ </p>
+ </div>
+
+ {access && !access.currentUserRole && (
+ <div className="rounded-xl border border-amber-500/40 px-4 py-3 text-sm text-amber-200">
+ This account can manage access here through instance-admin privileges, but it does not currently hold an active company membership.
+ </div>
+ )}
+
+ <section className="space-y-4">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <Users className="h-4 w-4 text-muted-foreground" />
+ <h2 className="text-base font-semibold">Humans</h2>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ Manage human company memberships, status, and grants here.
+ </p>
+ </div>
+
+ {access?.canApproveJoinRequests && pendingHumanJoinRequests.length > 0 ? (
+ <div className="space-y-3 rounded-xl border border-border px-4 py-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div>
+ <h3 className="text-sm font-semibold">Pending human joins</h3>
+ <p className="text-sm text-muted-foreground">
+ Review human join requests before they become active company members.
+ </p>
+ </div>
+ <Badge variant="outline">{pendingHumanJoinRequests.length} pending</Badge>
+ </div>
+ <div className="space-y-3">
+ {pendingHumanJoinRequests.map((request) => (
+ <PendingJoinRequestCard
+ key={request.id}
+ title={
+ request.requesterUser?.name ||
+ request.requestEmailSnapshot ||
+ request.requestingUserId ||
+ "Unknown human requester"
+ }
+ subtitle={
+ request.requesterUser?.email ||
+ request.requestEmailSnapshot ||
+ request.requestingUserId ||
+ "No email available"
+ }
+ context={
+ request.invite
+ ? `${request.invite.allowedJoinTypes} join invite${request.invite.humanRole ? ` • default role ${request.invite.humanRole}` : ""}`
+ : "Invite metadata unavailable"
+ }
+ detail={`Submitted ${new Date(request.createdAt).toLocaleString()}`}
+ approveLabel="Approve human"
+ rejectLabel="Reject human"
+ disabled={joinRequestActionPending}
+ onApprove={() => approveJoinRequestMutation.mutate(request.id)}
+ onReject={() => rejectJoinRequestMutation.mutate(request.id)}
+ />
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ <div className="overflow-hidden rounded-xl border border-border">
+ <div className="grid grid-cols-[minmax(0,1.5fr)_120px_120px_minmax(0,1.2fr)_120px] gap-3 border-b border-border px-4 py-3 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ <div>User account</div>
+ <div>Role</div>
+ <div>Status</div>
+ <div>Grants</div>
+ <div className="text-right">Action</div>
+ </div>
+ {members.length === 0 ? (
+ <div className="px-4 py-8 text-sm text-muted-foreground">No user memberships found for this company yet.</div>
+ ) : (
+ members.map((member) => (
+ <div
+ key={member.id}
+ className="grid grid-cols-[minmax(0,1.5fr)_120px_120px_minmax(0,1.2fr)_120px] gap-3 border-b border-border px-4 py-3 last:border-b-0"
+ >
+ <div className="min-w-0">
+ <div className="truncate font-medium">{member.user?.name?.trim() || member.user?.email || member.principalId}</div>
+ <div className="truncate text-xs text-muted-foreground">{member.user?.email || member.principalId}</div>
+ </div>
+ <div className="text-sm">
+ {member.membershipRole
+ ? HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS[member.membershipRole]
+ : "Unset"}
+ </div>
+ <div>
+ <Badge variant={member.status === "active" ? "secondary" : member.status === "suspended" ? "destructive" : "outline"}>
+ {member.status.replace("_", " ")}
+ </Badge>
+ </div>
+ <div className="min-w-0 text-sm text-muted-foreground">{formatGrantSummary(member)}</div>
+ <div className="text-right">
+ <Button size="sm" variant="outline" onClick={() => setEditingMemberId(member.id)}>
+ Edit
+ </Button>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </section>
+
+ <Dialog open={!!editingMember} onOpenChange={(open) => !open && setEditingMemberId(null)}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>Edit member</DialogTitle>
+ <DialogDescription>
+ Update company role, membership status, and explicit grants for {editingMember?.user?.name || editingMember?.user?.email || editingMember?.principalId}.
+ </DialogDescription>
+ </DialogHeader>
+ {editingMember && (
+ <div className="space-y-5">
+ <div className="grid gap-4 md:grid-cols-2">
+ <label className="space-y-2 text-sm">
+ <span className="font-medium">Company role</span>
+ <select
+ className="w-full rounded-md border border-border bg-background px-3 py-2"
+ value={draftRole ?? ""}
+ onChange={(event) =>
+ setDraftRole((event.target.value || null) as CompanyMember["membershipRole"])
+ }
+ >
+ <option value="">Unset</option>
+ {Object.entries(HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS).map(([value, label]) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="space-y-2 text-sm">
+ <span className="font-medium">Membership status</span>
+ <select
+ className="w-full rounded-md border border-border bg-background px-3 py-2"
+ value={draftStatus}
+ onChange={(event) =>
+ setDraftStatus(event.target.value as CompanyMember["status"])
+ }
+ >
+ <option value="active">Active</option>
+ <option value="pending">Pending</option>
+ <option value="suspended">Suspended</option>
+ </select>
+ </label>
+ </div>
+
+ <div className="space-y-3">
+ <div>
+ <h3 className="text-sm font-medium">Grants</h3>
+ <p className="text-sm text-muted-foreground">
+ Roles provide implicit grants automatically. Explicit grants below are only for overrides and extra access that should persist even if the role changes.
+ </p>
+ </div>
+ <div className="rounded-lg border border-border px-3 py-3">
+ <div className="text-sm font-medium">Implicit grants from role</div>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {draftRole
+ ? `${HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS[draftRole]} currently includes these permissions automatically.`
+ : "No role is selected, so this member has no implicit grants right now."}
+ </p>
+ {implicitGrantKeys.length > 0 ? (
+ <div className="mt-3 flex flex-wrap gap-2">
+ {implicitGrantKeys.map((permissionKey) => (
+ <Badge key={permissionKey} variant="outline">
+ {permissionLabels[permissionKey]}
+ </Badge>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ <div className="grid gap-3 md:grid-cols-2">
+ {PERMISSION_KEYS.map((permissionKey) => (
+ <label
+ key={permissionKey}
+ className="flex items-start gap-3 rounded-lg border border-border px-3 py-2"
+ >
+ <Checkbox
+ checked={draftGrants.has(permissionKey)}
+ onCheckedChange={(checked) => {
+ setDraftGrants((current) => {
+ const next = new Set(current);
+ if (checked) next.add(permissionKey);
+ else next.delete(permissionKey);
+ return next;
+ });
+ }}
+ />
+ <span className="space-y-1">
+ <span className="block text-sm font-medium">{permissionLabels[permissionKey]}</span>
+ <span className="block text-xs text-muted-foreground">{permissionKey}</span>
+ {implicitGrantSet.has(permissionKey) ? (
+ <span className="block text-xs text-muted-foreground">
+ Included implicitly by the {draftRole ? HUMAN_COMPANY_MEMBERSHIP_ROLE_LABELS[draftRole] : "selected"} role. Add an explicit grant only if it should stay after the role changes.
+ </span>
+ ) : null}
+ {draftGrants.has(permissionKey) ? (
+ <span className="block text-xs text-muted-foreground">
+ Stored explicitly for this member.
+ </span>
+ ) : null}
+ </span>
+ </label>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setEditingMemberId(null)}>
+ Cancel
+ </Button>
+ <Button
+ onClick={() => {
+ if (!editingMember) return;
+ updateMemberMutation.mutate({
+ memberId: editingMember.id,
+ membershipRole: draftRole,
+ status: draftStatus,
+ grants: [...draftGrants],
+ });
+ }}
+ disabled={updateMemberMutation.isPending}
+ >
+ {updateMemberMutation.isPending ? "Saving…" : "Save access"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+function PendingJoinRequestCard({
+ title,
+ subtitle,
+ context,
+ detail,
+ detailSecondary,
+ approveLabel,
+ rejectLabel,
+ disabled,
+ onApprove,
+ onReject,
+}: {
+ title: string;
+ subtitle: string;
+ context: string;
+ detail: string;
+ detailSecondary?: string;
+ approveLabel: string;
+ rejectLabel: string;
+ disabled: boolean;
+ onApprove: () => void;
+ onReject: () => void;
+}) {
+ return (
+ <div className="rounded-xl border border-border px-4 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="space-y-2">
+ <div>
+ <div className="font-medium">{title}</div>
+ <div className="text-sm text-muted-foreground">{subtitle}</div>
+ </div>
+ <div className="text-sm text-muted-foreground">{context}</div>
+ <div className="text-sm text-muted-foreground">{detail}</div>
+ {detailSecondary ? <div className="text-sm text-muted-foreground">{detailSecondary}</div> : null}
+ </div>
+ <div className="flex gap-2">
+ <Button type="button" variant="outline" onClick={onReject} disabled={disabled}>
+ {rejectLabel}
+ </Button>
+ <Button type="button" onClick={onApprove} disabled={disabled}>
+ {approveLabel}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/CompanyInvites.test.tsx b/ui/src/pages/CompanyInvites.test.tsx
new file mode 100644
index 0000000000..03937030a7
--- /dev/null
+++ b/ui/src/pages/CompanyInvites.test.tsx
@@ -0,0 +1,267 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CompanyInvites } from "./CompanyInvites";
+import { queryKeys } from "@/lib/queryKeys";
+
+const listInvitesMock = vi.hoisted(() => vi.fn());
+const createCompanyInviteMock = vi.hoisted(() => vi.fn());
+const revokeInviteMock = vi.hoisted(() => vi.fn());
+const pushToastMock = vi.hoisted(() => vi.fn());
+const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
+const clipboardWriteTextMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/access", () => ({
+ accessApi: {
+ listInvites: (companyId: string, options?: unknown) => listInvitesMock(companyId, options),
+ createCompanyInvite: (companyId: string, input: unknown) =>
+ createCompanyInviteMock(companyId, input),
+ revokeInvite: (inviteId: string) => revokeInviteMock(inviteId),
+ },
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompanyId: "company-1",
+ selectedCompany: { id: "company-1", name: "Paperclip", issuePrefix: "PAP" },
+ }),
+}));
+
+vi.mock("@/context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),
+}));
+
+vi.mock("@/context/ToastContext", () => ({
+ useToast: () => ({ pushToast: pushToastMock }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("CompanyInvites", () => {
+ let container: HTMLDivElement;
+ const inviteHistory = Array.from({ length: 25 }, (_, index) => {
+ const inviteNumber = 25 - index;
+ const isActive = inviteNumber === 25;
+ return {
+ id: `invite-${inviteNumber}`,
+ companyId: "company-1",
+ inviteType: "company_join",
+ tokenHash: `hash-${inviteNumber}`,
+ allowedJoinTypes: "human",
+ defaultsPayload: null,
+ expiresAt: "2026-04-20T00:00:00.000Z",
+ invitedByUserId: "user-1",
+ revokedAt: null,
+ acceptedAt: isActive ? null : "2026-04-11T00:00:00.000Z",
+ createdAt: `2026-04-${String(inviteNumber).padStart(2, "0")}T00:00:00.000Z`,
+ updatedAt: `2026-04-${String(inviteNumber).padStart(2, "0")}T00:00:00.000Z`,
+ companyName: "Paperclip",
+ humanRole: isActive ? "operator" : "viewer",
+ inviteMessage: null,
+ state: isActive ? "active" : "accepted",
+ invitedByUser: {
+ id: "user-1",
+ name: `Board User ${inviteNumber}`,
+ email: `board${inviteNumber}@paperclip.local`,
+ image: null,
+ },
+ relatedJoinRequestId: isActive ? "join-1" : null,
+ };
+ });
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ listInvitesMock.mockImplementation((_companyId: string, options?: { limit?: number; offset?: number }) => {
+ const limit = options?.limit ?? 20;
+ const offset = options?.offset ?? 0;
+ const invites = inviteHistory.slice(offset, offset + limit);
+ const nextOffset = offset + invites.length < inviteHistory.length ? offset + invites.length : null;
+ return Promise.resolve({ invites, nextOffset });
+ });
+
+ createCompanyInviteMock.mockResolvedValue({
+ inviteUrl: "https://paperclip.local/invite/new-token",
+ onboardingTextUrl: null,
+ onboardingTextPath: null,
+ humanRole: "viewer",
+ allowedJoinTypes: "human",
+ });
+
+ revokeInviteMock.mockResolvedValue(undefined);
+
+ Object.defineProperty(globalThis.navigator, "clipboard", {
+ configurable: true,
+ value: { writeText: clipboardWriteTextMock },
+ });
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("renders a human-only invite flow and keeps invite history in a table", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <CompanyInvites />
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Company Invites");
+ expect(container.textContent).toContain("Create invite");
+ expect(container.textContent).toContain("Invite history");
+ expect(container.textContent).toContain("Board User 25");
+ expect(container.textContent).toContain("Board User 21");
+ expect(container.textContent).not.toContain("Board User 20");
+ expect(container.textContent).toContain("Review request");
+ expect(container.textContent).toContain("View more");
+ expect(container.textContent).not.toContain("Human or agent");
+ expect(container.textContent).not.toContain("Invite message");
+ expect(container.textContent).not.toContain("Latest generated invite");
+ expect(container.textContent).not.toContain("Active invites");
+ expect(container.textContent).not.toContain("Consumed invites");
+ expect(container.textContent).not.toContain("Expired invites");
+ expect(container.textContent).not.toContain("OpenClaw shortcut");
+
+ expect(container.textContent).toContain("Choose a role");
+ expect(container.textContent).toContain("Each invite link is single-use.");
+ expect(container.textContent).toContain("Can create agents, invite users, assign tasks, and approve join requests.");
+ expect(container.textContent).toContain("Everything in Admin, plus managing members and permission grants.");
+ expect(listInvitesMock).toHaveBeenCalledWith("company-1", { limit: 5, offset: 0 });
+
+ const viewMoreButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "View more",
+ );
+
+ await act(async () => {
+ viewMoreButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(listInvitesMock).toHaveBeenCalledWith("company-1", { limit: 5, offset: 5 });
+ expect(container.textContent).toContain("Board User 20");
+ expect(container.textContent).toContain("Board User 16");
+ expect(container.textContent).toContain("View more");
+
+ await act(async () => {
+ const viewerRadio = container.querySelector('input[type="radio"][value="viewer"]') as HTMLInputElement | null;
+ viewerRadio?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ viewerRadio?.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ const buttons = Array.from(container.querySelectorAll("button"));
+ const createButton = buttons.find((button) => button.textContent === "Create invite");
+ const revokeButton = buttons.find((button) => button.textContent === "Revoke");
+
+ expect(createButton).toBeTruthy();
+ expect(revokeButton).toBeTruthy();
+
+ await act(async () => {
+ createButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(createCompanyInviteMock).toHaveBeenCalledWith("company-1", {
+ allowedJoinTypes: "human",
+ humanRole: "viewer",
+ agentMessage: null,
+ });
+ expect(clipboardWriteTextMock).toHaveBeenCalledWith("https://paperclip.local/invite/new-token");
+ expect(container.textContent).toContain("Latest invite link");
+ expect(container.textContent).toContain("This URL includes the current Paperclip domain returned by the server.");
+ expect(container.textContent).toContain("https://paperclip.local/invite/new-token");
+ expect(container.textContent).toContain("Open invite");
+ expect(pushToastMock).toHaveBeenCalledWith({
+ title: "Invite created",
+ body: "Invite ready below and copied to clipboard.",
+ tone: "success",
+ });
+
+ const inviteFieldButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("https://paperclip.local/invite/new-token"),
+ );
+
+ await act(async () => {
+ inviteFieldButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(clipboardWriteTextMock).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain("Copied");
+
+ await act(async () => {
+ revokeButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(revokeInviteMock).toHaveBeenCalledWith("invite-25");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("ignores legacy cached invite arrays and refetches paginated history", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ queryClient.setQueryData(["access", "invites", "company-1", "all"], inviteHistory.slice(0, 2));
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <CompanyInvites />
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("Board User 25");
+ expect(container.textContent).not.toContain("Board User 20");
+ expect(listInvitesMock).toHaveBeenCalledWith("company-1", { limit: 5, offset: 0 });
+ expect(queryClient.getQueryData(queryKeys.access.invites("company-1", "all", 5))).toMatchObject({
+ pages: [
+ {
+ invites: expect.any(Array),
+ nextOffset: 5,
+ },
+ ],
+ });
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/CompanyInvites.tsx b/ui/src/pages/CompanyInvites.tsx
new file mode 100644
index 0000000000..0d52bf314d
--- /dev/null
+++ b/ui/src/pages/CompanyInvites.tsx
@@ -0,0 +1,374 @@
+import { useEffect, useMemo, useState } from "react";
+import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { Check, ExternalLink, MailPlus } from "lucide-react";
+import { accessApi } from "@/api/access";
+import { ApiError } from "@/api/client";
+import { Button } from "@/components/ui/button";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "@/context/CompanyContext";
+import { useToast } from "@/context/ToastContext";
+import { Link } from "@/lib/router";
+import { queryKeys } from "@/lib/queryKeys";
+
+const inviteRoleOptions = [
+ {
+ value: "viewer",
+ label: "Viewer",
+ description: "Can view company work and follow along without operational permissions.",
+ gets: "No built-in grants.",
+ },
+ {
+ value: "operator",
+ label: "Operator",
+ description: "Recommended for people who need to help run work without managing access.",
+ gets: "Can assign tasks.",
+ },
+ {
+ value: "admin",
+ label: "Admin",
+ description: "Recommended for operators who need to invite people, create agents, and approve joins.",
+ gets: "Can create agents, invite users, assign tasks, and approve join requests.",
+ },
+ {
+ value: "owner",
+ label: "Owner",
+ description: "Full company access, including membership and permission management.",
+ gets: "Everything in Admin, plus managing members and permission grants.",
+ },
+] as const;
+
+const INVITE_HISTORY_PAGE_SIZE = 5;
+
+function isInviteHistoryRow(value: unknown): value is Awaited<ReturnType<typeof accessApi.listInvites>>["invites"][number] {
+ if (!value || typeof value !== "object") return false;
+ return "id" in value && "state" in value && "createdAt" in value;
+}
+
+export function CompanyInvites() {
+ const { selectedCompany, selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { pushToast } = useToast();
+ const queryClient = useQueryClient();
+ const [humanRole, setHumanRole] = useState<"owner" | "admin" | "operator" | "viewer">("operator");
+ const [latestInviteUrl, setLatestInviteUrl] = useState<string | null>(null);
+ const [latestInviteCopied, setLatestInviteCopied] = useState(false);
+
+ useEffect(() => {
+ if (!latestInviteCopied) return;
+ const timeout = window.setTimeout(() => {
+ setLatestInviteCopied(false);
+ }, 1600);
+ return () => window.clearTimeout(timeout);
+ }, [latestInviteCopied]);
+
+ async function copyInviteUrl(url: string) {
+ try {
+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(url);
+ return true;
+ }
+ } catch {
+ // Fall through to the unavailable message below.
+ }
+
+ pushToast({
+ title: "Clipboard unavailable",
+ body: "Copy the invite URL manually from the field below.",
+ tone: "warn",
+ });
+ return false;
+ }
+
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: selectedCompany?.name ?? "Company", href: "/dashboard" },
+ { label: "Settings", href: "/company/settings" },
+ { label: "Invites" },
+ ]);
+ }, [selectedCompany?.name, setBreadcrumbs]);
+
+ const inviteHistoryQueryKey = queryKeys.access.invites(selectedCompanyId ?? "", "all", INVITE_HISTORY_PAGE_SIZE);
+ const invitesQuery = useInfiniteQuery({
+ queryKey: inviteHistoryQueryKey,
+ queryFn: ({ pageParam }) =>
+ accessApi.listInvites(selectedCompanyId!, {
+ limit: INVITE_HISTORY_PAGE_SIZE,
+ offset: pageParam,
+ }),
+ enabled: !!selectedCompanyId,
+ initialPageParam: 0,
+ getNextPageParam: (lastPage) => lastPage.nextOffset ?? undefined,
+ });
+ const inviteHistory = useMemo(
+ () =>
+ invitesQuery.data?.pages.flatMap((page) =>
+ Array.isArray(page?.invites) ? page.invites.filter(isInviteHistoryRow) : [],
+ ) ?? [],
+ [invitesQuery.data?.pages],
+ );
+
+ const createInviteMutation = useMutation({
+ mutationFn: () =>
+ accessApi.createCompanyInvite(selectedCompanyId!, {
+ allowedJoinTypes: "human",
+ humanRole,
+ agentMessage: null,
+ }),
+ onSuccess: async (invite) => {
+ setLatestInviteUrl(invite.inviteUrl);
+ setLatestInviteCopied(false);
+ const copied = await copyInviteUrl(invite.inviteUrl);
+
+ await queryClient.invalidateQueries({ queryKey: inviteHistoryQueryKey });
+ pushToast({
+ title: "Invite created",
+ body: copied ? "Invite ready below and copied to clipboard." : "Invite ready below.",
+ tone: "success",
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ title: "Failed to create invite",
+ body: error instanceof Error ? error.message : "Unknown error",
+ tone: "error",
+ });
+ },
+ });
+
+ const revokeMutation = useMutation({
+ mutationFn: (inviteId: string) => accessApi.revokeInvite(inviteId),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: inviteHistoryQueryKey });
+ pushToast({ title: "Invite revoked", tone: "success" });
+ },
+ onError: (error) => {
+ pushToast({
+ title: "Failed to revoke invite",
+ body: error instanceof Error ? error.message : "Unknown error",
+ tone: "error",
+ });
+ },
+ });
+
+ if (!selectedCompanyId) {
+ return <div className="text-sm text-muted-foreground">Select a company to manage invites.</div>;
+ }
+
+ if (invitesQuery.isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading invites…</div>;
+ }
+
+ if (invitesQuery.error) {
+ const message =
+ invitesQuery.error instanceof ApiError && invitesQuery.error.status === 403
+ ? "You do not have permission to manage company invites."
+ : invitesQuery.error instanceof Error
+ ? invitesQuery.error.message
+ : "Failed to load invites.";
+ return <div className="text-sm text-destructive">{message}</div>;
+ }
+
+ return (
+ <div className="max-w-5xl space-y-8">
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <MailPlus className="h-5 w-5 text-muted-foreground" />
+ <h1 className="text-lg font-semibold">Company Invites</h1>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ Create human invite links for company access. New invite links are copied to your clipboard when they are generated.
+ </p>
+ </div>
+
+ <section className="space-y-4 rounded-xl border border-border p-5">
+ <div className="space-y-1">
+ <h2 className="text-sm font-semibold">Create invite</h2>
+ <p className="text-sm text-muted-foreground">
+ Generate a human invite link and choose the default access it should request.
+ </p>
+ </div>
+
+ <fieldset className="space-y-3">
+ <legend className="text-sm font-medium">Choose a role</legend>
+ <div className="rounded-xl border border-border">
+ {inviteRoleOptions.map((option, index) => {
+ const checked = humanRole === option.value;
+ return (
+ <label
+ key={option.value}
+ className={`flex cursor-pointer gap-3 px-4 py-4 ${index > 0 ? "border-t border-border" : ""}`}
+ >
+ <input
+ type="radio"
+ name="invite-role"
+ value={option.value}
+ checked={checked}
+ onChange={() => setHumanRole(option.value)}
+ className="mt-1 h-4 w-4 border-border text-foreground"
+ />
+ <span className="min-w-0 space-y-1">
+ <span className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium">{option.label}</span>
+ {option.value === "operator" ? (
+ <span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ Default
+ </span>
+ ) : null}
+ </span>
+ <span className="block max-w-2xl text-sm text-muted-foreground">{option.description}</span>
+ <span className="block text-sm text-foreground">{option.gets}</span>
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ </fieldset>
+
+ <div className="rounded-lg border border-border px-4 py-3 text-sm text-muted-foreground">
+ Each invite link is single-use. The first successful use consumes the link and creates or reuses the matching join request before approval.
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button onClick={() => createInviteMutation.mutate()} disabled={createInviteMutation.isPending}>
+ {createInviteMutation.isPending ? "Creating…" : "Create invite"}
+ </Button>
+ <span className="text-sm text-muted-foreground">Invite history below keeps the audit trail.</span>
+ </div>
+
+ {latestInviteUrl ? (
+ <div className="space-y-3 rounded-lg border border-border px-4 py-4">
+ <div className="space-y-1">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-sm font-medium">Latest invite link</div>
+ {latestInviteCopied ? (
+ <div className="inline-flex items-center gap-1 text-xs font-medium text-foreground">
+ <Check className="h-3.5 w-3.5" />
+ Copied
+ </div>
+ ) : null}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ This URL includes the current Paperclip domain returned by the server.
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={async () => {
+ const copied = await copyInviteUrl(latestInviteUrl);
+ setLatestInviteCopied(copied);
+ }}
+ className="w-full rounded-md border border-border bg-muted/60 px-3 py-2 text-left text-sm break-all transition-colors hover:bg-background"
+ >
+ {latestInviteUrl}
+ </button>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" asChild>
+ <a href={latestInviteUrl} target="_blank" rel="noreferrer">
+ <ExternalLink className="h-4 w-4" />
+ Open invite
+ </a>
+ </Button>
+ </div>
+ </div>
+ ) : null}
+ </section>
+
+ <section className="rounded-xl border border-border">
+ <div className="flex flex-wrap items-center justify-between gap-4 px-5 py-4">
+ <div className="space-y-1">
+ <h2 className="text-sm font-semibold">Invite history</h2>
+ <p className="text-sm text-muted-foreground">
+ Review invite status, role, inviter, and any linked join request.
+ </p>
+ </div>
+ <Link to="/inbox/requests" className="text-sm underline underline-offset-4">
+ Open join request queue
+ </Link>
+ </div>
+
+ {inviteHistory.length === 0 ? (
+ <div className="border-t border-border px-5 py-8 text-sm text-muted-foreground">
+ No invites have been created for this company yet.
+ </div>
+ ) : (
+ <div className="border-t border-border">
+ <div className="overflow-x-auto">
+ <table className="min-w-full text-left text-sm">
+ <thead>
+ <tr className="border-b border-border">
+ <th className="px-5 py-3 font-medium text-muted-foreground">State</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Role</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Invited by</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Created</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Join request</th>
+ <th className="px-5 py-3 text-right font-medium text-muted-foreground">Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ {inviteHistory.map((invite) => (
+ <tr key={invite.id} className="border-b border-border last:border-b-0">
+ <td className="px-5 py-3 align-top">
+ <span className="inline-flex rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ {formatInviteState(invite.state)}
+ </span>
+ </td>
+ <td className="px-5 py-3 align-top">{invite.humanRole ?? "—"}</td>
+ <td className="px-5 py-3 align-top">
+ <div>{invite.invitedByUser?.name || invite.invitedByUser?.email || "Unknown inviter"}</div>
+ {invite.invitedByUser?.email && invite.invitedByUser.name ? (
+ <div className="text-xs text-muted-foreground">{invite.invitedByUser.email}</div>
+ ) : null}
+ </td>
+ <td className="px-5 py-3 align-top text-muted-foreground">
+ {new Date(invite.createdAt).toLocaleString()}
+ </td>
+ <td className="px-5 py-3 align-top">
+ {invite.relatedJoinRequestId ? (
+ <Link to="/inbox/requests" className="underline underline-offset-4">
+ Review request
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </td>
+ <td className="px-5 py-3 text-right align-top">
+ {invite.state === "active" ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => revokeMutation.mutate(invite.id)}
+ disabled={revokeMutation.isPending}
+ >
+ Revoke
+ </Button>
+ ) : (
+ <span className="text-xs text-muted-foreground">Inactive</span>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ {invitesQuery.hasNextPage ? (
+ <div className="flex justify-center border-t border-border px-5 py-4">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => invitesQuery.fetchNextPage()}
+ disabled={invitesQuery.isFetchingNextPage}
+ >
+ {invitesQuery.isFetchingNextPage ? "Loading more…" : "View more"}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ )}
+ </section>
+ </div>
+ );
+}
+
+function formatInviteState(state: "active" | "accepted" | "expired" | "revoked") {
+ return state.charAt(0).toUpperCase() + state.slice(1);
+}
diff --git a/ui/src/pages/Dashboard.tsx b/ui/src/pages/Dashboard.tsx
index 0f6ccb12e1..273fc35d9b 100644
--- a/ui/src/pages/Dashboard.tsx
+++ b/ui/src/pages/Dashboard.tsx
@@ -3,10 +3,12 @@ import { Link } from "@/lib/router";
import { useQuery } from "@tanstack/react-query";
import { dashboardApi } from "../api/dashboard";
import { activityApi } from "../api/activity";
+import { accessApi } from "../api/access";
import { issuesApi } from "../api/issues";
import { agentsApi } from "../api/agents";
import { projectsApi } from "../api/projects";
import { heartbeatsApi } from "../api/heartbeats";
+import { buildCompanyUserProfileMap } from "../lib/company-members";
import { useCompany } from "../context/CompanyContext";
import { useDialog } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
@@ -82,6 +84,17 @@ export function Dashboard() {
enabled: !!selectedCompanyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const userProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+
const recentIssues = issues ? getRecentIssues(issues) : [];
const recentActivity = useMemo(() => (activity ?? []).slice(0, 10), [activity]);
@@ -320,6 +333,7 @@ export function Dashboard() {
key={event.id}
event={event}
agentMap={agentMap}
+ userProfileMap={userProfileMap}
entityNameMap={entityNameMap}
entityTitleMap={entityTitleMap}
className={animatedActivityIds.has(event.id) ? "activity-row-enter" : undefined}
diff --git a/ui/src/pages/Inbox.test.tsx b/ui/src/pages/Inbox.test.tsx
index cc1300d489..77e7de9540 100644
--- a/ui/src/pages/Inbox.test.tsx
+++ b/ui/src/pages/Inbox.test.tsx
@@ -5,7 +5,14 @@ import type { ComponentProps } from "react";
import { createRoot } from "react-dom/client";
import type { Issue } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { FailedRunInboxRow, InboxGroupHeader, InboxIssueMetaLeading, InboxIssueTrailingColumns } from "./Inbox";
+import type { CompanyJoinRequest } from "../api/access";
+import {
+ FailedRunInboxRow,
+ InboxGroupHeader,
+ InboxIssueMetaLeading,
+ InboxIssueTrailingColumns,
+ formatJoinRequestInboxLabel,
+} from "./Inbox";
vi.mock("@/lib/router", () => ({
Link: ({ children, className, ...props }: ComponentProps<"a">) => (
@@ -62,6 +69,44 @@ function createIssue(overrides: Partial<Issue> = {}): Issue {
};
}
+function createJoinRequest(
+ overrides: Partial<CompanyJoinRequest> = {},
+): CompanyJoinRequest {
+ return {
+ id: "join-1",
+ inviteId: "invite-1",
+ companyId: "company-1",
+ requestType: "human",
+ status: "pending_approval",
+ requestIp: "127.0.0.1",
+ requestingUserId: "user-1",
+ requestEmailSnapshot: "[email protected]",
+ agentName: null,
+ adapterType: null,
+ capabilities: null,
+ agentDefaultsPayload: null,
+ claimSecretExpiresAt: null,
+ claimSecretConsumedAt: null,
+ createdAgentId: null,
+ approvedByUserId: null,
+ approvedAt: null,
+ rejectedByUserId: null,
+ rejectedAt: null,
+ createdAt: new Date("2026-03-11T00:00:00.000Z"),
+ updatedAt: new Date("2026-03-11T00:00:00.000Z"),
+ requesterUser: {
+ id: "user-1",
+ name: "Jordan Example",
+ email: "[email protected]",
+ image: null,
+ },
+ approvedByUser: null,
+ rejectedByUser: null,
+ invite: null,
+ ...overrides,
+ };
+}
+
describe("FailedRunInboxRow", () => {
let container: HTMLDivElement;
@@ -246,6 +291,26 @@ describe("InboxIssueTrailingColumns", () => {
});
});
+describe("formatJoinRequestInboxLabel", () => {
+ it("shows the human requester's name and email when available", () => {
+ expect(formatJoinRequestInboxLabel(createJoinRequest())).toBe(
+ "Jordan Example ([email protected])",
+ );
+ });
+
+ it("falls back to the email snapshot when the requester profile is missing", () => {
+ expect(
+ formatJoinRequestInboxLabel(
+ createJoinRequest({
+ requesterUser: null,
+ requestEmailSnapshot: "[email protected]",
+ requestingUserId: null,
+ }),
+ ),
+ ).toBe("[email protected]");
+ });
+});
+
describe("InboxGroupHeader", () => {
let container: HTMLDivElement;
diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx
index 5134bd9b1a..f58d9688a2 100644
--- a/ui/src/pages/Inbox.tsx
+++ b/ui/src/pages/Inbox.tsx
@@ -24,6 +24,7 @@ import {
type IssueFilterState,
} from "../lib/issue-filters";
import { formatAssigneeUserLabel } from "../lib/assignees";
+import { buildCompanyUserLabelMap, buildCompanyUserProfileMap } from "../lib/company-members";
import {
armIssueDetailInboxQuickArchive,
createIssueDetailLocationState,
@@ -134,6 +135,7 @@ import {
type InboxIssueColumn,
type InboxKeyboardNavEntry,
saveLastInboxTab,
+ shouldShowCompanyAlerts,
shouldShowInboxSection,
type InboxGroupedSection,
type InboxTab,
@@ -184,6 +186,39 @@ function readIssueIdFromRun(run: HeartbeatRun): string | null {
return null;
}
+function nonEmptyLabel(value: string | null | undefined): string | null {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed : null;
+}
+
+export function formatJoinRequestInboxLabel(
+ joinRequest: Pick<
+ JoinRequest,
+ "requestType" | "agentName" | "requestEmailSnapshot" | "requestingUserId"
+ > & {
+ requesterUser?: {
+ name: string | null;
+ email: string | null;
+ } | null;
+ },
+) {
+ if (joinRequest.requestType !== "human") {
+ return `Agent join request${joinRequest.agentName ? `: ${joinRequest.agentName}` : ""}`;
+ }
+
+ const requesterName = nonEmptyLabel(joinRequest.requesterUser?.name);
+ const requesterEmail =
+ nonEmptyLabel(joinRequest.requesterUser?.email) ??
+ nonEmptyLabel(joinRequest.requestEmailSnapshot);
+ const requesterId = nonEmptyLabel(joinRequest.requestingUserId);
+
+ if (requesterName && requesterEmail) return `${requesterName} (${requesterEmail})`;
+ if (requesterEmail) return requesterEmail;
+ if (requesterName) return requesterName;
+ if (requesterId) return requesterId;
+ return "Human join request";
+}
+
type NonIssueUnreadState = "visible" | "fading" | "hidden" | null;
@@ -510,10 +545,7 @@ function JoinRequestInboxRow({
selected?: boolean;
className?: string;
}) {
- const label =
- joinRequest.requestType === "human"
- ? "Human join request"
- : `Agent join request${joinRequest.agentName ? `: ${joinRequest.agentName}` : ""}`;
+ const label = formatJoinRequestInboxLabel(joinRequest);
const showUnreadSlot = unreadState !== null;
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
@@ -787,8 +819,22 @@ export function Inbox() {
enabled: !!selectedCompanyId,
refetchInterval: 5000,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
+ const companyUserLabelMap = useMemo(
+ () => buildCompanyUserLabelMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+ const companyUserProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+
const mineIssues = useMemo(() => getRecentTouchedIssues(mineIssuesRaw), [mineIssuesRaw]);
const touchedIssues = useMemo(() => getRecentTouchedIssues(touchedIssuesRaw), [touchedIssuesRaw]);
const visibleMineIssues = useMemo(
@@ -960,14 +1006,14 @@ export function Inbox() {
}, [liveRuns]);
const approvalsToRender = useMemo(() => {
- let filtered = getApprovalsForTab(approvals ?? [], tab, allApprovalFilter);
+ let filtered = getApprovalsForTab(approvals ?? [], tab, allApprovalFilter, currentUserId);
if (tab === "mine") {
filtered = filtered.filter(
(a) => !isInboxEntityDismissed(dismissedAtByKey, `approval:${a.id}`, a.updatedAt),
);
}
return filtered;
- }, [approvals, tab, allApprovalFilter, dismissedAtByKey]);
+ }, [approvals, tab, allApprovalFilter, currentUserId, dismissedAtByKey]);
const showJoinRequestsCategory =
allCategoryFilter === "everything" || allCategoryFilter === "join_requests";
const showTouchedCategory =
@@ -1745,12 +1791,15 @@ export function Inbox() {
}
const hasRunFailures = failedRuns.length > 0;
+ const showCompanyAlerts = shouldShowCompanyAlerts(tab) && showAlertsCategory;
const showAggregateAgentError =
+ showCompanyAlerts &&
!!dashboard &&
dashboard.agents.error > 0 &&
!hasRunFailures &&
!dismissedAlerts.has("alert:agent-errors");
const showBudgetAlert =
+ showCompanyAlerts &&
!!dashboard &&
dashboard.costs.monthBudgetCents > 0 &&
dashboard.costs.monthUtilizationPercent >= 80 &&
@@ -1760,10 +1809,10 @@ export function Inbox() {
const showAlertsSection = shouldShowInboxSection({
tab,
hasItems: hasAlerts,
- showOnMine: hasAlerts,
- showOnRecent: hasAlerts,
- showOnUnread: hasAlerts,
- showOnAll: showAlertsCategory && hasAlerts,
+ showOnMine: false,
+ showOnRecent: false,
+ showOnUnread: false,
+ showOnAll: hasAlerts,
});
const visibleSections = [
@@ -2064,6 +2113,9 @@ export function Inbox() {
const isFading = fadingOutIssues.has(issue.id);
const isArchiving = archivingIssueIds.has(issue.id);
const project = issue.projectId ? projectById.get(issue.projectId) ?? null : null;
+ const assigneeUserProfile = issue.assigneeUserId
+ ? companyUserProfileMap.get(issue.assigneeUserId) ?? null
+ : null;
return (
<IssueRow
key={`issue:${issue.id}`}
@@ -2140,6 +2192,12 @@ export function Inbox() {
defaultProjectWorkspaceIdByProjectId,
})}
assigneeName={agentName(issue.assigneeAgentId)}
+ assigneeUserName={
+ formatAssigneeUserLabel(issue.assigneeUserId, currentUserId, companyUserLabelMap)
+ ?? assigneeUserProfile?.label
+ ?? null
+ }
+ assigneeUserAvatarUrl={assigneeUserProfile?.image ?? null}
currentUserId={currentUserId}
parentIdentifier={issue.parentId ? (issueById.get(issue.parentId)?.identifier ?? null) : null}
parentTitle={issue.parentId ? (issueById.get(issue.parentId)?.title ?? null) : null}
diff --git a/ui/src/pages/InstanceAccess.tsx b/ui/src/pages/InstanceAccess.tsx
new file mode 100644
index 0000000000..d40ea814e9
--- /dev/null
+++ b/ui/src/pages/InstanceAccess.tsx
@@ -0,0 +1,245 @@
+import { useEffect, useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Shield, ShieldCheck } from "lucide-react";
+import { accessApi } from "@/api/access";
+import { ApiError } from "@/api/client";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "@/context/CompanyContext";
+import { useToast } from "@/context/ToastContext";
+import { queryKeys } from "@/lib/queryKeys";
+
+export function InstanceAccess() {
+ const { companies } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { pushToast } = useToast();
+ const queryClient = useQueryClient();
+ const [search, setSearch] = useState("");
+ const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
+ const [selectedCompanyIds, setSelectedCompanyIds] = useState<Set<string>>(new Set());
+
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: "Instance Settings", href: "/instance/settings/general" },
+ { label: "Access" },
+ ]);
+ }, [setBreadcrumbs]);
+
+ const usersQuery = useQuery({
+ queryKey: queryKeys.access.adminUsers(search),
+ queryFn: () => accessApi.searchAdminUsers(search),
+ });
+
+ const selectedUser = useMemo(
+ () => usersQuery.data?.find((user) => user.id === selectedUserId) ?? null,
+ [selectedUserId, usersQuery.data],
+ );
+
+ const userAccessQuery = useQuery({
+ queryKey: queryKeys.access.userCompanyAccess(selectedUserId ?? ""),
+ queryFn: () => accessApi.getUserCompanyAccess(selectedUserId!),
+ enabled: !!selectedUserId,
+ });
+
+ useEffect(() => {
+ if (!selectedUserId && usersQuery.data?.[0]) {
+ setSelectedUserId(usersQuery.data[0].id);
+ }
+ }, [selectedUserId, usersQuery.data]);
+
+ useEffect(() => {
+ if (!userAccessQuery.data) return;
+ setSelectedCompanyIds(
+ new Set(userAccessQuery.data.companyAccess.map((membership) => membership.companyId)),
+ );
+ }, [userAccessQuery.data]);
+
+ const updateCompanyAccessMutation = useMutation({
+ mutationFn: () => accessApi.setUserCompanyAccess(selectedUserId!, [...selectedCompanyIds]),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.userCompanyAccess(selectedUserId!) });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.adminUsers(search) });
+ pushToast({ title: "Company access updated", tone: "success" });
+ },
+ });
+
+ const setAdminMutation = useMutation({
+ mutationFn: async (makeAdmin: boolean) => {
+ if (!selectedUserId) throw new Error("No user selected");
+ if (makeAdmin) return accessApi.promoteInstanceAdmin(selectedUserId);
+ return accessApi.demoteInstanceAdmin(selectedUserId);
+ },
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.adminUsers(search) });
+ if (selectedUserId) {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.userCompanyAccess(selectedUserId) });
+ }
+ pushToast({ title: "Instance role updated", tone: "success" });
+ },
+ });
+
+ if (usersQuery.isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading instance users…</div>;
+ }
+
+ if (usersQuery.error) {
+ const message =
+ usersQuery.error instanceof ApiError && usersQuery.error.status === 403
+ ? "Instance admin access is required to manage users."
+ : usersQuery.error instanceof Error
+ ? usersQuery.error.message
+ : "Failed to load users.";
+ return <div className="text-sm text-destructive">{message}</div>;
+ }
+
+ return (
+ <div className="max-w-6xl space-y-6">
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <Shield className="h-5 w-5 text-muted-foreground" />
+ <h1 className="text-lg font-semibold">Instance Access</h1>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ Search users, manage instance-admin status, and control which companies they can access.
+ </p>
+ </div>
+
+ <div className="grid gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
+ <section className="space-y-4 rounded-xl border border-border bg-card p-4">
+ <label className="block space-y-2 text-sm">
+ <span className="font-medium">Search users</span>
+ <input
+ className="w-full rounded-md border border-border bg-background px-3 py-2"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder="Search by name or email"
+ />
+ </label>
+ <div className="space-y-2">
+ {(usersQuery.data ?? []).map((user) => (
+ <button
+ key={user.id}
+ type="button"
+ onClick={() => setSelectedUserId(user.id)}
+ className={`w-full rounded-lg border px-3 py-3 text-left transition-colors ${
+ user.id === selectedUserId
+ ? "border-foreground bg-accent"
+ : "border-border hover:bg-accent/40"
+ }`}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <div className="truncate font-medium">{user.name || user.email || user.id}</div>
+ <div className="truncate text-sm text-muted-foreground">{user.email || user.id}</div>
+ </div>
+ {user.isInstanceAdmin ? (
+ <ShieldCheck className="h-4 w-4 text-emerald-600" />
+ ) : null}
+ </div>
+ <div className="mt-2 text-xs text-muted-foreground">
+ {user.activeCompanyMembershipCount} active company memberships
+ </div>
+ </button>
+ ))}
+ </div>
+ </section>
+
+ <section className="space-y-4 rounded-xl border border-border bg-card p-5">
+ {!selectedUserId ? (
+ <div className="text-sm text-muted-foreground">Select a user to inspect instance access.</div>
+ ) : userAccessQuery.isLoading ? (
+ <div className="text-sm text-muted-foreground">Loading user access…</div>
+ ) : userAccessQuery.error ? (
+ <div className="text-sm text-destructive">
+ {userAccessQuery.error instanceof Error ? userAccessQuery.error.message : "Failed to load user access."}
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div>
+ <div className="text-lg font-semibold">
+ {selectedUser?.name || selectedUser?.email || selectedUserId}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ {selectedUser?.email || selectedUserId}
+ </div>
+ </div>
+ <Button
+ variant={selectedUser?.isInstanceAdmin ? "outline" : "default"}
+ onClick={() => setAdminMutation.mutate(!(selectedUser?.isInstanceAdmin ?? false))}
+ disabled={setAdminMutation.isPending}
+ >
+ {selectedUser?.isInstanceAdmin ? "Remove instance admin" : "Promote to instance admin"}
+ </Button>
+ </div>
+
+ <div className="space-y-3">
+ <div>
+ <h2 className="text-sm font-semibold">Company access</h2>
+ <p className="text-sm text-muted-foreground">
+ Toggle company membership for this user. New access defaults to an active operator membership.
+ </p>
+ </div>
+ <div className="grid gap-3 md:grid-cols-2">
+ {companies.map((company) => (
+ <label
+ key={company.id}
+ className="flex items-start gap-3 rounded-lg border border-border px-3 py-3"
+ >
+ <Checkbox
+ checked={selectedCompanyIds.has(company.id)}
+ onCheckedChange={(checked) => {
+ setSelectedCompanyIds((current) => {
+ const next = new Set(current);
+ if (checked) next.add(company.id);
+ else next.delete(company.id);
+ return next;
+ });
+ }}
+ />
+ <span className="space-y-1">
+ <span className="block text-sm font-medium">{company.name}</span>
+ <span className="block text-xs text-muted-foreground">{company.issuePrefix}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ <div className="flex justify-end">
+ <Button
+ onClick={() => updateCompanyAccessMutation.mutate()}
+ disabled={updateCompanyAccessMutation.isPending}
+ >
+ {updateCompanyAccessMutation.isPending ? "Saving…" : "Save company access"}
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <h2 className="text-sm font-semibold">Current memberships</h2>
+ <div className="space-y-2">
+ {(userAccessQuery.data?.companyAccess ?? []).map((membership) => (
+ <div
+ key={membership.id}
+ className="flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm"
+ >
+ <div>
+ <div className="font-medium">{membership.companyName || membership.companyId}</div>
+ <div className="text-muted-foreground">
+ {membership.membershipRole || "unset"} • {membership.status}
+ </div>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {new Date(membership.updatedAt).toLocaleDateString()}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </section>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/InstanceGeneralSettings.tsx b/ui/src/pages/InstanceGeneralSettings.tsx
index 04c3638d52..b33ce040b3 100644
--- a/ui/src/pages/InstanceGeneralSettings.tsx
+++ b/ui/src/pages/InstanceGeneralSettings.tsx
@@ -9,7 +9,9 @@ import {
} from "@paperclipai/shared";
import { LogOut, SlidersHorizontal } from "lucide-react";
import { authApi } from "@/api/auth";
+import { healthApi } from "@/api/health";
import { instanceSettingsApi } from "@/api/instanceSettings";
+import { ModeBadge } from "@/components/access/ModeBadge";
import { Button } from "../components/ui/button";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
@@ -44,6 +46,11 @@ export function InstanceGeneralSettings() {
queryKey: queryKeys.instance.generalSettings,
queryFn: () => instanceSettingsApi.getGeneral(),
});
+ const healthQuery = useQuery({
+ queryKey: queryKeys.health,
+ queryFn: () => healthApi.get(),
+ retry: false,
+ });
const updateGeneralMutation = useMutation({
mutationFn: instanceSettingsApi.updateGeneral,
@@ -93,6 +100,39 @@ export function InstanceGeneralSettings() {
</div>
)}
+ <section className="rounded-xl border border-border bg-card p-5">
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <h2 className="text-sm font-semibold">Deployment and auth</h2>
+ <ModeBadge
+ deploymentMode={healthQuery.data?.deploymentMode}
+ deploymentExposure={healthQuery.data?.deploymentExposure}
+ />
+ </div>
+ <div className="text-sm text-muted-foreground">
+ {healthQuery.data?.deploymentMode === "local_trusted"
+ ? "Local trusted mode is optimized for a local operator. Browser requests run as local board context and no sign-in is required."
+ : healthQuery.data?.deploymentExposure === "public"
+ ? "Authenticated public mode requires sign-in for board access and is intended for public URLs."
+ : "Authenticated private mode requires sign-in and is intended for LAN, VPN, or other private-network deployments."}
+ </div>
+ <div className="grid gap-3 md:grid-cols-3">
+ <StatusBox
+ label="Auth readiness"
+ value={healthQuery.data?.authReady ? "Ready" : "Not ready"}
+ />
+ <StatusBox
+ label="Bootstrap status"
+ value={healthQuery.data?.bootstrapStatus === "bootstrap_pending" ? "Setup required" : "Ready"}
+ />
+ <StatusBox
+ label="Bootstrap invite"
+ value={healthQuery.data?.bootstrapInviteActive ? "Active" : "None"}
+ />
+ </div>
+ </div>
+ </section>
+
<section className="rounded-xl border border-border bg-card p-5">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1.5">
@@ -330,3 +370,12 @@ export function InstanceGeneralSettings() {
</div>
);
}
+
+function StatusBox({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="rounded-lg border border-border bg-background px-3 py-3">
+ <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{label}</div>
+ <div className="mt-2 text-sm font-medium">{value}</div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/InviteLanding.test.tsx b/ui/src/pages/InviteLanding.test.tsx
new file mode 100644
index 0000000000..0fe56c2dc2
--- /dev/null
+++ b/ui/src/pages/InviteLanding.test.tsx
@@ -0,0 +1,657 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { InviteLandingPage } from "./InviteLanding";
+
+const getInviteMock = vi.hoisted(() => vi.fn());
+const acceptInviteMock = vi.hoisted(() => vi.fn());
+const getSessionMock = vi.hoisted(() => vi.fn());
+const signInEmailMock = vi.hoisted(() => vi.fn());
+const signUpEmailMock = vi.hoisted(() => vi.fn());
+const healthGetMock = vi.hoisted(() => vi.fn());
+const listCompaniesMock = vi.hoisted(() => vi.fn());
+const setSelectedCompanyIdMock = vi.hoisted(() => vi.fn());
+
+vi.mock("../api/access", () => ({
+ accessApi: {
+ getInvite: (token: string) => getInviteMock(token),
+ acceptInvite: (token: string, input: unknown) => acceptInviteMock(token, input),
+ },
+}));
+
+vi.mock("../api/auth", () => ({
+ authApi: {
+ getSession: () => getSessionMock(),
+ signInEmail: (input: unknown) => signInEmailMock(input),
+ signUpEmail: (input: unknown) => signUpEmailMock(input),
+ },
+}));
+
+vi.mock("../api/health", () => ({
+ healthApi: {
+ get: () => healthGetMock(),
+ },
+}));
+
+vi.mock("../api/companies", () => ({
+ companiesApi: {
+ list: () => listCompaniesMock(),
+ },
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompany: null,
+ selectedCompanyId: null,
+ companies: [],
+ selectionSource: "manual",
+ loading: false,
+ error: null,
+ setSelectedCompanyId: setSelectedCompanyIdMock,
+ reloadCompanies: vi.fn(),
+ createCompany: vi.fn(),
+ }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("InviteLandingPage", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ localStorage.clear();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
+ configurable: true,
+ value: vi.fn(() => ({
+ fillStyle: "",
+ fillRect: vi.fn(),
+ beginPath: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ })),
+ });
+ Object.defineProperty(HTMLCanvasElement.prototype, "toDataURL", {
+ configurable: true,
+ value: vi.fn(() => "data:image/png;base64,stub"),
+ });
+
+ getInviteMock.mockResolvedValue({
+ id: "invite-1",
+ companyId: "company-1",
+ companyName: "Acme Robotics",
+ companyLogoUrl: "/api/invites/pcp_invite_test/logo",
+ companyBrandColor: "#114488",
+ inviteType: "company_join",
+ allowedJoinTypes: "both",
+ humanRole: "operator",
+ expiresAt: "2027-03-07T00:10:00.000Z",
+ inviteMessage: "Welcome aboard.",
+ });
+ acceptInviteMock.mockReset();
+ healthGetMock.mockResolvedValue({
+ status: "ok",
+ deploymentMode: "authenticated",
+ });
+ listCompaniesMock.mockResolvedValue([]);
+ getSessionMock.mockResolvedValue(null);
+ signInEmailMock.mockResolvedValue(undefined);
+ signUpEmailMock.mockResolvedValue(undefined);
+ setSelectedCompanyIdMock.mockReset();
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("defaults invite auth to account creation and guides existing users back to sign in", async () => {
+ signUpEmailMock.mockRejectedValue(
+ Object.assign(new Error("User already exists. Use another email."), {
+ code: "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL",
+ status: 422,
+ }),
+ );
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).toContain("You've been invited to join Paperclip");
+ expect(container.textContent).toContain("Join Acme Robotics");
+ expect(container.textContent).toContain("Create account");
+ expect(container.textContent).toContain("I already have an account");
+ expect(container.textContent).toContain("Message from inviter");
+ expect(container.querySelector('[data-testid="invite-inline-auth"]')).not.toBeNull();
+ expect(localStorage.getItem("paperclip:pending-invite-token")).toBe("pcp_invite_test");
+ const inviteLogo = container.querySelector('img[alt="Acme Robotics logo"]');
+ expect(inviteLogo).not.toBeNull();
+ expect(inviteLogo?.className).toContain("object-contain");
+ expect(container.querySelector('input[name="name"]')).not.toBeNull();
+
+ const nameInput = container.querySelector('input[name="name"]') as HTMLInputElement | null;
+ const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement | null;
+ const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement | null;
+ expect(nameInput).not.toBeNull();
+ expect(emailInput).not.toBeNull();
+ expect(passwordInput).not.toBeNull();
+ const inputValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ expect(inputValueSetter).toBeTypeOf("function");
+
+ await act(async () => {
+ inputValueSetter!.call(nameInput, "Jane Example");
+ nameInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ nameInput!.dispatchEvent(new Event("change", { bubbles: true }));
+ inputValueSetter!.call(emailInput, "[email protected]");
+ emailInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ emailInput!.dispatchEvent(new Event("change", { bubbles: true }));
+ inputValueSetter!.call(passwordInput, "supersecret");
+ passwordInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ passwordInput!.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ const authForm = container.querySelector('[data-testid="invite-inline-auth"]') as HTMLFormElement | null;
+ expect(authForm).not.toBeNull();
+
+ await act(async () => {
+ authForm?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(signUpEmailMock).toHaveBeenCalledWith({
+ name: "Jane Example",
+ email: "[email protected]",
+ password: "supersecret",
+ });
+ expect(container.textContent).toContain("An account already exists for [email protected]. Sign in below to continue with this invite.");
+ expect(container.querySelector('input[name="name"]')).toBeNull();
+ expect(container.textContent).toContain("Sign in to continue");
+ expect(localStorage.getItem("paperclip:pending-invite-token")).toBe("pcp_invite_test");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("turns invalid sign-in responses into a clear invite-specific message", async () => {
+ signInEmailMock.mockRejectedValue(
+ Object.assign(new Error("Invalid email or password"), {
+ code: "INVALID_EMAIL_OR_PASSWORD",
+ status: 401,
+ }),
+ );
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ const inputValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ expect(inputValueSetter).toBeTypeOf("function");
+
+ const existingAccountButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "I already have an account",
+ );
+ expect(existingAccountButton).not.toBeNull();
+
+ await act(async () => {
+ existingAccountButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement | null;
+ const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement | null;
+ expect(emailInput).not.toBeNull();
+ expect(passwordInput).not.toBeNull();
+
+ await act(async () => {
+ inputValueSetter!.call(emailInput, "[email protected]");
+ emailInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ emailInput!.dispatchEvent(new Event("change", { bubbles: true }));
+ inputValueSetter!.call(passwordInput, "wrongpass");
+ passwordInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ passwordInput!.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ const authForm = container.querySelector('[data-testid="invite-inline-auth"]') as HTMLFormElement | null;
+ expect(authForm).not.toBeNull();
+
+ await act(async () => {
+ authForm?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(signInEmailMock).toHaveBeenCalledWith({
+ email: "[email protected]",
+ password: "wrongpass",
+ });
+ expect(container.textContent).toContain(
+ "That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here.",
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("auto-accepts the invite after account creation and redirects into the company", async () => {
+ getSessionMock.mockResolvedValueOnce(null);
+ getSessionMock.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: null,
+ },
+ });
+ acceptInviteMock.mockResolvedValue({
+ id: "join-1",
+ companyId: "company-1",
+ requestType: "human",
+ status: "approved",
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ const inputValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ expect(inputValueSetter).toBeTypeOf("function");
+
+ const nameInput = container.querySelector('input[name="name"]') as HTMLInputElement | null;
+ const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement | null;
+ const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement | null;
+ expect(nameInput).not.toBeNull();
+ expect(emailInput).not.toBeNull();
+ expect(passwordInput).not.toBeNull();
+
+ await act(async () => {
+ inputValueSetter!.call(nameInput, "Jane Example");
+ nameInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ inputValueSetter!.call(emailInput, "[email protected]");
+ emailInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ inputValueSetter!.call(passwordInput, "supersecret");
+ passwordInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ const authForm = container.querySelector('[data-testid="invite-inline-auth"]') as HTMLFormElement | null;
+ expect(authForm).not.toBeNull();
+
+ await act(async () => {
+ authForm?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(signUpEmailMock).toHaveBeenCalledWith({
+ name: "Jane Example",
+ email: "[email protected]",
+ password: "supersecret",
+ });
+ expect(acceptInviteMock).toHaveBeenCalledWith("pcp_invite_test", { requestType: "human" });
+ expect(setSelectedCompanyIdMock).toHaveBeenCalledWith("company-1", { source: "manual" });
+ expect(localStorage.getItem("paperclip:pending-invite-token")).toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("shows the pending approval page with the company icon and linked access instructions", async () => {
+ acceptInviteMock.mockResolvedValue({
+ id: "join-1",
+ companyId: "company-1",
+ requestType: "human",
+ status: "pending_approval",
+ });
+ getSessionMock.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: null,
+ },
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(acceptInviteMock).toHaveBeenCalledWith("pcp_invite_test", { requestType: "human" });
+ expect(container.textContent).toContain("Request to join Acme Robotics");
+ expect(container.textContent).toContain("A company admin must approve your request to join.");
+ expect(container.textContent).toContain(
+ "Ask them to visit Company Settings → Access to approve your request.",
+ );
+ expect(container.querySelector('img[alt="Acme Robotics logo"]')).not.toBeNull();
+ expect(container.textContent).not.toContain("http://localhost/company/settings/access");
+
+ const approvalLinks = Array.from(container.querySelectorAll("a")).filter(
+ (link) => link.textContent === "Company Settings → Access",
+ );
+ expect(approvalLinks).toHaveLength(2);
+ const expectedApprovalUrl = `${window.location.origin}/company/settings/access`;
+ for (const link of approvalLinks) {
+ expect(link.getAttribute("href")).toBe(expectedApprovalUrl);
+ }
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("keeps the waiting-for-approval state on refresh for an accepted invite", async () => {
+ getInviteMock.mockResolvedValue({
+ id: "invite-1",
+ companyId: "company-1",
+ companyName: "Acme Robotics",
+ companyLogoUrl: "/api/invites/pcp_invite_test/logo",
+ companyBrandColor: "#114488",
+ inviteType: "company_join",
+ allowedJoinTypes: "both",
+ humanRole: "operator",
+ expiresAt: "2027-03-07T00:10:00.000Z",
+ inviteMessage: "Welcome aboard.",
+ joinRequestStatus: "pending_approval",
+ joinRequestType: "human",
+ });
+ getSessionMock.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: null,
+ },
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(acceptInviteMock).not.toHaveBeenCalled();
+ expect(container.querySelector('[data-testid="invite-pending-approval"]')).not.toBeNull();
+ expect(container.textContent).toContain("Your request is still awaiting approval.");
+ expect(container.textContent).toContain(
+ "Ask them to visit Company Settings → Access to approve your request.",
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("redirects straight to the company after sign-in when the user already has access", async () => {
+ getSessionMock.mockResolvedValueOnce(null);
+ getSessionMock.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: null,
+ },
+ });
+ listCompaniesMock.mockResolvedValue([{ id: "company-1", name: "Acme Robotics" }]);
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ const inputValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ expect(inputValueSetter).toBeTypeOf("function");
+
+ const existingAccountButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "I already have an account",
+ );
+ expect(existingAccountButton).not.toBeNull();
+
+ await act(async () => {
+ existingAccountButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ const emailInput = container.querySelector('input[name="email"]') as HTMLInputElement | null;
+ const passwordInput = container.querySelector('input[name="password"]') as HTMLInputElement | null;
+ expect(emailInput).not.toBeNull();
+ expect(passwordInput).not.toBeNull();
+
+ await act(async () => {
+ inputValueSetter!.call(emailInput, "[email protected]");
+ emailInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ inputValueSetter!.call(passwordInput, "supersecret");
+ passwordInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ const authForm = container.querySelector('[data-testid="invite-inline-auth"]') as HTMLFormElement | null;
+ expect(authForm).not.toBeNull();
+
+ await act(async () => {
+ authForm?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(signInEmailMock).toHaveBeenCalledWith({
+ email: "[email protected]",
+ password: "supersecret",
+ });
+ expect(acceptInviteMock).not.toHaveBeenCalled();
+ expect(setSelectedCompanyIdMock).toHaveBeenCalledWith("company-1", { source: "manual" });
+ expect(localStorage.getItem("paperclip:pending-invite-token")).toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("falls back to the generated company icon when the invite logo fails to load", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ const logo = container.querySelector('img[alt="Acme Robotics logo"]') as HTMLImageElement | null;
+ expect(logo).not.toBeNull();
+
+ await act(async () => {
+ logo?.dispatchEvent(new Event("error"));
+ });
+ await flushReact();
+
+ expect(container.querySelector('img[alt="Acme Robotics logo"]')).toBeNull();
+ expect(container.querySelector('img[aria-hidden="true"]')).not.toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("waits for the membership check before showing invite acceptance to signed-in users", async () => {
+ let resolveCompanies: ((value: Array<{ id: string; name: string }>) => void) | null = null;
+ acceptInviteMock.mockResolvedValue({
+ id: "join-1",
+ companyId: "company-1",
+ requestType: "human",
+ status: "pending_approval",
+ });
+ listCompaniesMock.mockImplementation(
+ () =>
+ new Promise<Array<{ id: string; name: string }>>((resolve) => {
+ resolveCompanies = resolve;
+ }),
+ );
+ getSessionMock.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: null,
+ },
+ });
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/invite/pcp_invite_test"]}>
+ <QueryClientProvider client={queryClient}>
+ <Routes>
+ <Route path="/invite/:token" element={<InviteLandingPage />} />
+ </Routes>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+ });
+ await flushReact();
+
+ expect(container.textContent).toContain("Checking your access...");
+ expect(container.textContent).not.toContain("Accept company invite");
+ expect(acceptInviteMock).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveCompanies?.([]);
+ });
+ await flushReact();
+ await flushReact();
+ await flushReact();
+
+ expect(acceptInviteMock).toHaveBeenCalledWith("pcp_invite_test", { requestType: "human" });
+ expect(container.textContent).toContain("Request to join Acme Robotics");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/InviteLanding.tsx b/ui/src/pages/InviteLanding.tsx
index c2b0fe027d..7dcef629b3 100644
--- a/ui/src/pages/InviteLanding.tsx
+++ b/ui/src/pages/InviteLanding.tsx
@@ -1,24 +1,32 @@
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Link, useParams } from "@/lib/router";
+import { AGENT_ADAPTER_TYPES } from "@paperclipai/shared";
+import type { AgentAdapterType, JoinRequest } from "@paperclipai/shared";
+import { Button } from "@/components/ui/button";
+import { CompanyPatternIcon } from "@/components/CompanyPatternIcon";
+import { useCompany } from "@/context/CompanyContext";
+import { Link, useNavigate, useParams } from "@/lib/router";
import { accessApi } from "../api/access";
import { authApi } from "../api/auth";
+import { companiesApi } from "../api/companies";
import { healthApi } from "../api/health";
-import { queryKeys } from "../lib/queryKeys";
-import { Button } from "@/components/ui/button";
-import { AGENT_ADAPTER_TYPES } from "@paperclipai/shared";
-import type { AgentAdapterType, JoinRequest } from "@paperclipai/shared";
-
-type JoinType = "human" | "agent";
-const joinAdapterOptions: AgentAdapterType[] = [...AGENT_ADAPTER_TYPES];
-
import { getAdapterLabel } from "../adapters/adapter-display-registry";
+import { clearPendingInviteToken, rememberPendingInviteToken } from "../lib/invite-memory";
+import { queryKeys } from "../lib/queryKeys";
+import { formatDate } from "../lib/utils";
-const ENABLED_INVITE_ADAPTERS = new Set(["claude_local", "codex_local", "gemini_local", "opencode_local", "pi_local", "cursor"]);
+type AuthMode = "sign_in" | "sign_up";
+type AuthFeedback = { tone: "error" | "info"; message: string };
-function dateTime(value: string) {
- return new Date(value).toLocaleString();
-}
+const joinAdapterOptions: AgentAdapterType[] = [...AGENT_ADAPTER_TYPES];
+const ENABLED_INVITE_ADAPTERS = new Set([
+ "claude_local",
+ "codex_local",
+ "gemini_local",
+ "opencode_local",
+ "pi_local",
+ "cursor",
+]);
function readNestedString(value: unknown, path: string[]): string | null {
let current: unknown = value;
@@ -29,16 +37,198 @@ function readNestedString(value: unknown, path: string[]): string | null {
return typeof current === "string" && current.trim().length > 0 ? current : null;
}
+const fieldClassName =
+ "w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500";
+const panelClassName = "border border-zinc-800 bg-zinc-950/95 p-6";
+const modeButtonBaseClassName =
+ "flex-1 border px-3 py-2 text-sm transition-colors";
+
+function formatHumanRole(role: string | null | undefined) {
+ if (!role) return null;
+ return role.charAt(0).toUpperCase() + role.slice(1);
+}
+
+function getAuthErrorCode(error: unknown) {
+ if (!error || typeof error !== "object") return null;
+ const code = (error as { code?: unknown }).code;
+ return typeof code === "string" && code.trim().length > 0 ? code : null;
+}
+
+function getAuthErrorMessage(error: unknown) {
+ if (!(error instanceof Error)) return null;
+ const message = error.message.trim();
+ return message.length > 0 ? message : null;
+}
+
+function mapInviteAuthFeedback(
+ error: unknown,
+ authMode: AuthMode,
+ email: string,
+): AuthFeedback {
+ const code = getAuthErrorCode(error);
+ const message = getAuthErrorMessage(error);
+ const emailLabel = email.trim().length > 0 ? email.trim() : "that email";
+
+ if (code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") {
+ return {
+ tone: "info",
+ message: `An account already exists for ${emailLabel}. Sign in below to continue with this invite.`,
+ };
+ }
+
+ if (code === "INVALID_EMAIL_OR_PASSWORD") {
+ return {
+ tone: "error",
+ message:
+ "That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here.",
+ };
+ }
+
+ if (authMode === "sign_in" && message === "Request failed: 401") {
+ return {
+ tone: "error",
+ message:
+ "That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here.",
+ };
+ }
+
+ if (authMode === "sign_up" && message === "Request failed: 422") {
+ return {
+ tone: "info",
+ message: `An account may already exist for ${emailLabel}. Try signing in instead.`,
+ };
+ }
+
+ return {
+ tone: "error",
+ message: message ?? "Authentication failed",
+ };
+}
+
+function isBootstrapAcceptancePayload(payload: unknown) {
+ return Boolean(
+ payload &&
+ typeof payload === "object" &&
+ "bootstrapAccepted" in (payload as Record<string, unknown>),
+ );
+}
+
+function isApprovedHumanJoinPayload(payload: unknown, showsAgentForm: boolean) {
+ if (!payload || typeof payload !== "object" || showsAgentForm) return false;
+ const status = (payload as { status?: unknown }).status;
+ return status === "approved";
+}
+
+type AwaitingJoinApprovalPanelProps = {
+ companyDisplayName: string;
+ companyLogoUrl: string | null;
+ companyBrandColor: string | null;
+ invitedByUserName: string | null;
+ claimSecret?: string | null;
+ claimApiKeyPath?: string | null;
+ onboardingTextUrl?: string | null;
+};
+
+function InviteCompanyLogo({
+ companyDisplayName,
+ companyLogoUrl,
+ companyBrandColor,
+ className,
+}: {
+ companyDisplayName: string;
+ companyLogoUrl: string | null;
+ companyBrandColor: string | null;
+ className?: string;
+}) {
+ return (
+ <CompanyPatternIcon
+ companyName={companyDisplayName}
+ logoUrl={companyLogoUrl}
+ brandColor={companyBrandColor}
+ logoFit="contain"
+ className={className}
+ />
+ );
+}
+
+function AwaitingJoinApprovalPanel({
+ companyDisplayName,
+ companyLogoUrl,
+ companyBrandColor,
+ invitedByUserName,
+ claimSecret = null,
+ claimApiKeyPath = null,
+ onboardingTextUrl = null,
+}: AwaitingJoinApprovalPanelProps) {
+ const approvalUrl = `${window.location.origin}/company/settings/access`;
+ const approverLabel = invitedByUserName ?? "A company admin";
+
+ return (
+ <div className="min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100">
+ <div className="mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6" data-testid="invite-pending-approval">
+ <div className="flex items-center gap-3">
+ <InviteCompanyLogo
+ companyDisplayName={companyDisplayName}
+ companyLogoUrl={companyLogoUrl}
+ companyBrandColor={companyBrandColor}
+ className="h-12 w-12 border border-zinc-800 rounded-none"
+ />
+ <h1 className="text-lg font-semibold">Request to join {companyDisplayName}</h1>
+ </div>
+ <div className="mt-4 space-y-3">
+ <p className="text-sm text-zinc-400">
+ Your request is still awaiting approval. {approverLabel} must approve your request to join.
+ </p>
+ <div className="border border-zinc-800 p-3">
+ <p className="text-xs text-zinc-500 mb-1">Approval page</p>
+ <a
+ href={approvalUrl}
+ className="text-sm text-zinc-200 underline underline-offset-2 hover:text-zinc-100"
+ >
+ Company Settings → Access
+ </a>
+ </div>
+ <p className="text-sm text-zinc-400">
+ Ask them to visit <a href={approvalUrl} className="text-zinc-200 underline underline-offset-2 hover:text-zinc-100">Company Settings → Access</a> to approve your request.
+ </p>
+ <p className="text-xs text-zinc-500">
+ Refresh this page after you've been approved — you'll be redirected automatically.
+ </p>
+ </div>
+ {claimSecret && claimApiKeyPath ? (
+ <div className="mt-4 space-y-1 border border-zinc-800 p-3 text-xs text-zinc-400">
+ <div className="text-zinc-200">Claim secret</div>
+ <div className="font-mono break-all">{claimSecret}</div>
+ <div className="font-mono break-all">POST {claimApiKeyPath}</div>
+ </div>
+ ) : null}
+ {onboardingTextUrl ? (
+ <div className="mt-4 text-xs text-zinc-400">
+ Onboarding: <span className="font-mono break-all">{onboardingTextUrl}</span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
export function InviteLandingPage() {
const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { setSelectedCompanyId } = useCompany();
const params = useParams();
const token = (params.token ?? "").trim();
- const [joinType, setJoinType] = useState<JoinType>("human");
+ const [authMode, setAuthMode] = useState<AuthMode>("sign_up");
+ const [name, setName] = useState("");
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
const [agentName, setAgentName] = useState("");
const [adapterType, setAdapterType] = useState<AgentAdapterType>("claude_local");
const [capabilities, setCapabilities] = useState("");
const [result, setResult] = useState<{ kind: "bootstrap" | "join"; payload: unknown } | null>(null);
const [error, setError] = useState<string | null>(null);
+ const [authFeedback, setAuthFeedback] = useState<AuthFeedback | null>(null);
+ const [autoAcceptStarted, setAutoAcceptStarted] = useState(false);
const healthQuery = useQuery({
queryKey: queryKeys.health,
@@ -57,33 +247,85 @@ export function InviteLandingPage() {
retry: false,
});
- const invite = inviteQuery.data;
- const companyName = invite?.companyName?.trim() || null;
- const allowedJoinTypes = invite?.allowedJoinTypes ?? "both";
- const availableJoinTypes = useMemo(() => {
- if (invite?.inviteType === "bootstrap_ceo") return ["human"] as JoinType[];
- if (allowedJoinTypes === "both") return ["human", "agent"] as JoinType[];
- return [allowedJoinTypes] as JoinType[];
- }, [invite?.inviteType, allowedJoinTypes]);
+ const companiesQuery = useQuery({
+ queryKey: queryKeys.companies.all,
+ queryFn: () => companiesApi.list(),
+ enabled: !!sessionQuery.data && !!inviteQuery.data?.companyId,
+ retry: false,
+ });
+
+ useEffect(() => {
+ if (token) rememberPendingInviteToken(token);
+ }, [token]);
+
+ useEffect(() => {
+ setAutoAcceptStarted(false);
+ }, [token]);
useEffect(() => {
- if (!availableJoinTypes.includes(joinType)) {
- setJoinType(availableJoinTypes[0] ?? "human");
+ if (!companiesQuery.data || !inviteQuery.data?.companyId) return;
+ const isMember = companiesQuery.data.some(
+ (c) => c.id === inviteQuery.data!.companyId
+ );
+ if (isMember) {
+ clearPendingInviteToken(token);
+ navigate("/", { replace: true });
}
- }, [availableJoinTypes, joinType]);
+ }, [companiesQuery.data, inviteQuery.data, token, navigate]);
- const requiresAuthForHuman =
- joinType === "human" &&
+ const invite = inviteQuery.data;
+ const isCheckingExistingMembership =
+ Boolean(sessionQuery.data) &&
+ Boolean(invite?.companyId) &&
+ companiesQuery.isLoading;
+ const isCurrentMember =
+ Boolean(invite?.companyId) &&
+ Boolean(
+ companiesQuery.data?.some((company) => company.id === invite?.companyId),
+ );
+ const companyName = invite?.companyName?.trim() || null;
+ const companyDisplayName = companyName || "this Paperclip company";
+ const companyLogoUrl = invite?.companyLogoUrl?.trim() || null;
+ const companyBrandColor = invite?.companyBrandColor?.trim() || null;
+ const invitedByUserName = invite?.invitedByUserName?.trim() || null;
+ const inviteMessage = invite?.inviteMessage?.trim() || null;
+ const requestedHumanRole = formatHumanRole(invite?.humanRole);
+ const inviteJoinRequestStatus = invite?.joinRequestStatus ?? null;
+ const inviteJoinRequestType = invite?.joinRequestType ?? null;
+ const requiresHumanAccount =
healthQuery.data?.deploymentMode === "authenticated" &&
- !sessionQuery.data;
+ !sessionQuery.data &&
+ invite?.allowedJoinTypes !== "agent";
+ const showsAgentForm = invite?.inviteType !== "bootstrap_ceo" && invite?.allowedJoinTypes === "agent";
+ const shouldAutoAcceptHumanInvite =
+ Boolean(sessionQuery.data) &&
+ !showsAgentForm &&
+ invite?.inviteType !== "bootstrap_ceo" &&
+ !inviteJoinRequestStatus &&
+ !isCheckingExistingMembership &&
+ !isCurrentMember &&
+ !result &&
+ error === null;
+ const sessionLabel =
+ sessionQuery.data?.user.name?.trim() ||
+ sessionQuery.data?.user.email?.trim() ||
+ "this account";
+
+ const authCanSubmit =
+ email.trim().length > 0 &&
+ password.trim().length > 0 &&
+ (authMode === "sign_in" || (name.trim().length > 0 && password.trim().length >= 8));
const acceptMutation = useMutation({
mutationFn: async () => {
if (!invite) throw new Error("Invite not found");
- if (invite.inviteType === "bootstrap_ceo") {
- return accessApi.acceptInvite(token, { requestType: "human" });
+ if (isCheckingExistingMembership) {
+ throw new Error("Checking your company access. Try again in a moment.");
+ }
+ if (isCurrentMember) {
+ throw new Error("This account already belongs to the company.");
}
- if (joinType === "human") {
+ if (invite.inviteType === "bootstrap_ceo" || invite.allowedJoinTypes !== "agent") {
return accessApi.acceptInvite(token, { requestType: "human" });
}
return accessApi.acceptInvite(token, {
@@ -95,17 +337,87 @@ export function InviteLandingPage() {
},
onSuccess: async (payload) => {
setError(null);
+ clearPendingInviteToken(token);
+ const asBootstrap = isBootstrapAcceptancePayload(payload);
+ setResult({ kind: asBootstrap ? "bootstrap" : "join", payload });
await queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
await queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
- const asBootstrap =
- payload && typeof payload === "object" && "bootstrapAccepted" in (payload as Record<string, unknown>);
- setResult({ kind: asBootstrap ? "bootstrap" : "join", payload });
+ if (invite?.companyId && isApprovedHumanJoinPayload(payload, showsAgentForm)) {
+ setSelectedCompanyId(invite.companyId, { source: "manual" });
+ navigate("/", { replace: true });
+ }
},
onError: (err) => {
setError(err instanceof Error ? err.message : "Failed to accept invite");
},
});
+ useEffect(() => {
+ if (!shouldAutoAcceptHumanInvite || autoAcceptStarted || acceptMutation.isPending) return;
+ setAutoAcceptStarted(true);
+ setError(null);
+ acceptMutation.mutate();
+ }, [acceptMutation, autoAcceptStarted, shouldAutoAcceptHumanInvite]);
+
+ const authMutation = useMutation({
+ mutationFn: async () => {
+ if (authMode === "sign_in") {
+ await authApi.signInEmail({ email: email.trim(), password });
+ return;
+ }
+ await authApi.signUpEmail({
+ name: name.trim(),
+ email: email.trim(),
+ password,
+ });
+ },
+ onSuccess: async () => {
+ setAuthFeedback(null);
+ rememberPendingInviteToken(token);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
+ const companies = await queryClient.fetchQuery({
+ queryKey: queryKeys.companies.all,
+ queryFn: () => companiesApi.list(),
+ retry: false,
+ });
+
+ if (invite?.companyId && companies.some((company) => company.id === invite.companyId)) {
+ clearPendingInviteToken(token);
+ setSelectedCompanyId(invite.companyId, { source: "manual" });
+ navigate("/", { replace: true });
+ return;
+ }
+
+ if (!invite || invite.inviteType !== "bootstrap_ceo") {
+ return;
+ }
+
+ try {
+ const payload = await acceptMutation.mutateAsync();
+ if (isBootstrapAcceptancePayload(payload)) {
+ navigate("/", { replace: true });
+ }
+ } catch {
+ return;
+ }
+ },
+ onError: (err) => {
+ const nextFeedback = mapInviteAuthFeedback(err, authMode, email);
+ if (getAuthErrorCode(err) === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") {
+ setAuthMode("sign_in");
+ setPassword("");
+ }
+ setAuthFeedback(nextFeedback);
+ },
+ });
+
+ const joinButtonLabel = useMemo(() => {
+ if (!invite) return "Continue";
+ if (invite.inviteType === "bootstrap_ceo") return "Accept invite";
+ if (showsAgentForm) return "Submit request";
+ return sessionQuery.data ? "Accept invite" : "Continue";
+ }, [invite, sessionQuery.data, showsAgentForm]);
+
if (!token) {
return <div className="mx-auto max-w-xl py-10 text-sm text-destructive">Invalid invite token.</div>;
}
@@ -114,10 +426,14 @@ export function InviteLandingPage() {
return <div className="mx-auto max-w-xl py-10 text-sm text-muted-foreground">Loading invite...</div>;
}
+ if (isCheckingExistingMembership) {
+ return <div className="mx-auto max-w-xl py-10 text-sm text-muted-foreground">Checking your access...</div>;
+ }
+
if (inviteQuery.error || !invite) {
return (
<div className="mx-auto max-w-xl py-10">
- <div className="rounded-lg border border-border bg-card p-6">
+ <div className="border border-border bg-card p-6" data-testid="invite-error">
<h1 className="text-lg font-semibold">Invite not available</h1>
<p className="mt-2 text-sm text-muted-foreground">
This invite may be expired, revoked, or already used.
@@ -127,17 +443,50 @@ export function InviteLandingPage() {
);
}
- if (result?.kind === "bootstrap") {
+ if (
+ inviteJoinRequestStatus === "approved" &&
+ inviteJoinRequestType === "human" &&
+ isCurrentMember
+ ) {
+ return <div className="mx-auto max-w-xl py-10 text-sm text-muted-foreground">Opening company...</div>;
+ }
+
+ if (inviteJoinRequestStatus === "pending_approval") {
+ return (
+ <AwaitingJoinApprovalPanel
+ companyDisplayName={companyDisplayName}
+ companyLogoUrl={companyLogoUrl}
+ companyBrandColor={companyBrandColor}
+ invitedByUserName={invitedByUserName}
+ />
+ );
+ }
+
+ if (inviteJoinRequestStatus) {
return (
<div className="mx-auto max-w-xl py-10">
- <div className="rounded-lg border border-border bg-card p-6">
- <h1 className="text-lg font-semibold">Bootstrap complete</h1>
+ <div className="border border-border bg-card p-6" data-testid="invite-error">
+ <h1 className="text-lg font-semibold">Invite not available</h1>
<p className="mt-2 text-sm text-muted-foreground">
- The first instance admin is now configured. You can continue to the board.
+ {inviteJoinRequestStatus === "rejected"
+ ? "This join request was not approved."
+ : "This invite has already been used."}
</p>
- <Button asChild className="mt-4">
- <Link to="/">Open board</Link>
- </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (result?.kind === "bootstrap") {
+ return (
+ <div className="min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100">
+ <div className="mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6">
+ <h1 className="text-lg font-semibold">Bootstrap complete</h1>
+ <div className="mt-4">
+ <Button asChild className="rounded-none">
+ <Link to="/">Open board</Link>
+ </Button>
+ </div>
</div>
</div>
);
@@ -148,171 +497,330 @@ export function InviteLandingPage() {
claimSecret?: string;
claimApiKeyPath?: string;
onboarding?: Record<string, unknown>;
- diagnostics?: Array<{
- code: string;
- level: "info" | "warn";
- message: string;
- hint?: string;
- }>;
};
const claimSecret = typeof payload.claimSecret === "string" ? payload.claimSecret : null;
const claimApiKeyPath = typeof payload.claimApiKeyPath === "string" ? payload.claimApiKeyPath : null;
- const onboardingSkillUrl = readNestedString(payload.onboarding, ["skill", "url"]);
- const onboardingSkillPath = readNestedString(payload.onboarding, ["skill", "path"]);
- const onboardingInstallPath = readNestedString(payload.onboarding, ["skill", "installPath"]);
const onboardingTextUrl = readNestedString(payload.onboarding, ["textInstructions", "url"]);
- const onboardingTextPath = readNestedString(payload.onboarding, ["textInstructions", "path"]);
- const diagnostics = Array.isArray(payload.diagnostics) ? payload.diagnostics : [];
+ const joinedNow = !showsAgentForm && payload.status === "approved";
+
return (
- <div className="mx-auto max-w-xl py-10">
- <div className="rounded-lg border border-border bg-card p-6">
- <h1 className="text-lg font-semibold">Join request submitted</h1>
- <p className="mt-2 text-sm text-muted-foreground">
- Your request is pending admin approval. You will not have access until approved.
- </p>
- <div className="mt-4 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
- Request ID: <span className="font-mono">{payload.id}</span>
- </div>
- {claimSecret && claimApiKeyPath && (
- <div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
- <p className="font-medium text-foreground">One-time claim secret (save now)</p>
- <p className="font-mono break-all">{claimSecret}</p>
- <p className="font-mono break-all">POST {claimApiKeyPath}</p>
- </div>
- )}
- {(onboardingSkillUrl || onboardingSkillPath || onboardingInstallPath) && (
- <div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
- <p className="font-medium text-foreground">Paperclip skill bootstrap</p>
- {onboardingSkillUrl && <p className="font-mono break-all">GET {onboardingSkillUrl}</p>}
- {!onboardingSkillUrl && onboardingSkillPath && <p className="font-mono break-all">GET {onboardingSkillPath}</p>}
- {onboardingInstallPath && <p className="font-mono break-all">Install to {onboardingInstallPath}</p>}
- </div>
- )}
- {(onboardingTextUrl || onboardingTextPath) && (
- <div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
- <p className="font-medium text-foreground">Agent-readable onboarding text</p>
- {onboardingTextUrl && <p className="font-mono break-all">GET {onboardingTextUrl}</p>}
- {!onboardingTextUrl && onboardingTextPath && <p className="font-mono break-all">GET {onboardingTextPath}</p>}
+ joinedNow ? (
+ <div className="min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100">
+ <div className="mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6">
+ <div className="flex items-center gap-3">
+ <InviteCompanyLogo
+ companyDisplayName={companyDisplayName}
+ companyLogoUrl={companyLogoUrl}
+ companyBrandColor={companyBrandColor}
+ className="h-12 w-12 border border-zinc-800 rounded-none"
+ />
+ <h1 className="text-lg font-semibold">You joined the company</h1>
</div>
- )}
- {diagnostics.length > 0 && (
- <div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
- <p className="font-medium text-foreground">Connectivity diagnostics</p>
- {diagnostics.map((diag, idx) => (
- <div key={`${diag.code}:${idx}`} className="space-y-0.5">
- <p className={diag.level === "warn" ? "text-amber-600 dark:text-amber-400" : undefined}>
- [{diag.level}] {diag.message}
- </p>
- {diag.hint && <p className="font-mono break-all">{diag.hint}</p>}
- </div>
- ))}
+ <div className="mt-4">
+ <Button asChild className="w-full rounded-none">
+ <Link to="/">Open board</Link>
+ </Button>
</div>
- )}
+ </div>
</div>
- </div>
+ ) : (
+ <AwaitingJoinApprovalPanel
+ companyDisplayName={companyDisplayName}
+ companyLogoUrl={companyLogoUrl}
+ companyBrandColor={companyBrandColor}
+ invitedByUserName={invitedByUserName}
+ claimSecret={claimSecret}
+ claimApiKeyPath={claimApiKeyPath}
+ onboardingTextUrl={onboardingTextUrl}
+ />
+ )
);
}
return (
- <div className="mx-auto max-w-xl py-10">
- <div className="rounded-lg border border-border bg-card p-6">
- <h1 className="text-xl font-semibold">
- {invite.inviteType === "bootstrap_ceo"
- ? "Bootstrap your Paperclip instance"
- : companyName
- ? `Join ${companyName}`
- : "Join this Paperclip company"}
- </h1>
- <p className="mt-2 text-sm text-muted-foreground">
- {invite.inviteType !== "bootstrap_ceo" && companyName
- ? `You were invited to join ${companyName}. `
- : null}
- Invite expires {dateTime(invite.expiresAt)}.
- </p>
-
- {invite.inviteType !== "bootstrap_ceo" && (
- <div className="mt-5 flex gap-2">
- {availableJoinTypes.map((type) => (
- <button
- key={type}
- type="button"
- onClick={() => setJoinType(type)}
- className={`rounded-md border px-3 py-1.5 text-sm ${
- joinType === type
- ? "border-foreground bg-foreground text-background"
- : "border-border bg-background text-foreground"
- }`}
- >
- Join as {type}
- </button>
- ))}
- </div>
- )}
-
- {joinType === "agent" && invite.inviteType !== "bootstrap_ceo" && (
- <div className="mt-4 space-y-3">
- <label className="block text-sm">
- <span className="mb-1 block text-muted-foreground">Agent name</span>
- <input
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
- value={agentName}
- onChange={(event) => setAgentName(event.target.value)}
+ <div className="min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100">
+ <div className="mx-auto max-w-5xl">
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1.15fr)_minmax(360px,0.85fr)]">
+ <section className={`${panelClassName} space-y-6`}>
+ <div className="flex items-start gap-4">
+ <InviteCompanyLogo
+ companyDisplayName={companyDisplayName}
+ companyLogoUrl={companyLogoUrl}
+ companyBrandColor={companyBrandColor}
+ className="h-16 w-16 rounded-none border border-zinc-800"
/>
- </label>
- <label className="block text-sm">
- <span className="mb-1 block text-muted-foreground">Adapter type</span>
- <select
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
- value={adapterType}
- onChange={(event) => setAdapterType(event.target.value as AgentAdapterType)}
- >
- {joinAdapterOptions.map((type) => (
- <option key={type} value={type} disabled={!ENABLED_INVITE_ADAPTERS.has(type)}>
- {getAdapterLabel(type)}{!ENABLED_INVITE_ADAPTERS.has(type) ? " (Coming soon)" : ""}
- </option>
- ))}
- </select>
- </label>
- <label className="block text-sm">
- <span className="mb-1 block text-muted-foreground">Capabilities (optional)</span>
- <textarea
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
- rows={4}
- value={capabilities}
- onChange={(event) => setCapabilities(event.target.value)}
- />
- </label>
- </div>
- )}
-
- {requiresAuthForHuman && (
- <div className="mt-4 rounded-md border border-border bg-muted/30 p-3 text-sm">
- Sign in or create an account before submitting a human join request.
- <div className="mt-2">
- <Button asChild size="sm" variant="outline">
- <Link to={`/auth?next=${encodeURIComponent(`/invite/${token}`)}`}>Sign in / Create account</Link>
- </Button>
+ <div className="min-w-0">
+ <p className="text-xs uppercase tracking-[0.24em] text-zinc-500">
+ You&apos;ve been invited to join Paperclip
+ </p>
+ <h1 className="mt-2 text-2xl font-semibold">
+ {invite.inviteType === "bootstrap_ceo" ? "Set up Paperclip" : `Join ${companyDisplayName}`}
+ </h1>
+ <p className="mt-2 max-w-2xl text-sm leading-6 text-zinc-300">
+ {showsAgentForm
+ ? "Review the invite details, then submit the agent information below to start the join request."
+ : requiresHumanAccount
+ ? "Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email."
+ : "Your account is ready. Review the invite details, then accept it to continue."}
+ </p>
+ </div>
</div>
- </div>
- )}
-
- {error && <p className="mt-3 text-sm text-destructive">{error}</p>}
-
- <Button
- className="mt-5"
- disabled={
- acceptMutation.isPending ||
- (joinType === "agent" && invite.inviteType !== "bootstrap_ceo" && agentName.trim().length === 0) ||
- requiresAuthForHuman
- }
- onClick={() => acceptMutation.mutate()}
- >
- {acceptMutation.isPending
- ? "Submitting…"
- : invite.inviteType === "bootstrap_ceo"
- ? "Accept bootstrap invite"
- : "Submit join request"}
- </Button>
+
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="border border-zinc-800 p-3">
+ <div className="text-xs uppercase tracking-[0.2em] text-zinc-500">Company</div>
+ <div className="mt-1 text-sm text-zinc-100">{companyDisplayName}</div>
+ </div>
+ <div className="border border-zinc-800 p-3">
+ <div className="text-xs uppercase tracking-[0.2em] text-zinc-500">Invited by</div>
+ <div className="mt-1 text-sm text-zinc-100">{invitedByUserName ?? "Paperclip board"}</div>
+ </div>
+ <div className="border border-zinc-800 p-3">
+ <div className="text-xs uppercase tracking-[0.2em] text-zinc-500">Requested access</div>
+ <div className="mt-1 text-sm text-zinc-100">
+ {showsAgentForm ? "Agent join request" : requestedHumanRole ?? "Company access"}
+ </div>
+ </div>
+ <div className="border border-zinc-800 p-3">
+ <div className="text-xs uppercase tracking-[0.2em] text-zinc-500">Invite expires</div>
+ <div className="mt-1 text-sm text-zinc-100">{formatDate(invite.expiresAt)}</div>
+ </div>
+ </div>
+
+ {inviteMessage ? (
+ <div className="border border-amber-500/40 bg-amber-500/10 p-4">
+ <div className="text-xs uppercase tracking-[0.2em] text-amber-200/80">Message from inviter</div>
+ <p className="mt-2 text-sm leading-6 text-amber-50">{inviteMessage}</p>
+ </div>
+ ) : null}
+
+ {sessionQuery.data ? (
+ <div className="border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50">
+ Signed in as <span className="font-medium">{sessionLabel}</span>.
+ </div>
+ ) : null}
+ </section>
+
+ <section className={`${panelClassName} h-fit`}>
+ {showsAgentForm ? (
+ <div className="space-y-4">
+ <div>
+ <h2 className="text-lg font-semibold">Submit agent details</h2>
+ <p className="mt-1 text-sm text-zinc-400">
+ This invite will create an approval request for a new agent in {companyDisplayName}.
+ </p>
+ </div>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Agent name</span>
+ <input
+ className={fieldClassName}
+ value={agentName}
+ onChange={(event) => setAgentName(event.target.value)}
+ />
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Adapter type</span>
+ <select
+ className={fieldClassName}
+ value={adapterType}
+ onChange={(event) => setAdapterType(event.target.value as AgentAdapterType)}
+ >
+ {joinAdapterOptions.map((type) => (
+ <option key={type} value={type} disabled={!ENABLED_INVITE_ADAPTERS.has(type)}>
+ {getAdapterLabel(type)}{!ENABLED_INVITE_ADAPTERS.has(type) ? " (Coming soon)" : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Capabilities</span>
+ <textarea
+ className={fieldClassName}
+ rows={4}
+ value={capabilities}
+ onChange={(event) => setCapabilities(event.target.value)}
+ />
+ </label>
+ {error ? <p className="text-xs text-red-400">{error}</p> : null}
+ <Button
+ className="w-full rounded-none"
+ disabled={acceptMutation.isPending || agentName.trim().length === 0}
+ onClick={() => acceptMutation.mutate()}
+ >
+ {acceptMutation.isPending ? "Working..." : joinButtonLabel}
+ </Button>
+ </div>
+ ) : requiresHumanAccount ? (
+ <div className="space-y-5">
+ <div>
+ <h2 className="text-lg font-semibold">
+ {authMode === "sign_up" ? "Create your account" : "Sign in to continue"}
+ </h2>
+ <p className="mt-1 text-sm text-zinc-400">
+ {authMode === "sign_up"
+ ? `Start with a Paperclip account. After that, you'll come right back here to accept the invite for ${companyDisplayName}.`
+ : "Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."}
+ </p>
+ </div>
+
+ <div className="flex gap-2">
+ <button
+ type="button"
+ className={`${modeButtonBaseClassName} ${
+ authMode === "sign_up"
+ ? "border-zinc-100 bg-zinc-100 text-zinc-950"
+ : "border-zinc-800 text-zinc-300 hover:border-zinc-600"
+ }`}
+ onClick={() => {
+ setAuthFeedback(null);
+ setAuthMode("sign_up");
+ }}
+ >
+ Create account
+ </button>
+ <button
+ type="button"
+ className={`${modeButtonBaseClassName} ${
+ authMode === "sign_in"
+ ? "border-zinc-100 bg-zinc-100 text-zinc-950"
+ : "border-zinc-800 text-zinc-300 hover:border-zinc-600"
+ }`}
+ onClick={() => {
+ setAuthFeedback(null);
+ setAuthMode("sign_in");
+ }}
+ >
+ I already have an account
+ </button>
+ </div>
+
+ <form
+ className="space-y-4"
+ method="post"
+ action={authMode === "sign_up" ? "/api/auth/sign-up/email" : "/api/auth/sign-in/email"}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (authMutation.isPending) return;
+ if (!authCanSubmit) {
+ setAuthFeedback({ tone: "error", message: "Please fill in all required fields." });
+ return;
+ }
+ authMutation.mutate();
+ }}
+ data-testid="invite-inline-auth"
+ >
+ {authMode === "sign_up" ? (
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Name</span>
+ <input
+ name="name"
+ className={fieldClassName}
+ value={name}
+ onChange={(event) => {
+ setName(event.target.value);
+ setAuthFeedback(null);
+ }}
+ autoComplete="name"
+ autoFocus
+ />
+ </label>
+ ) : null}
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Email</span>
+ <input
+ name="email"
+ type="email"
+ className={fieldClassName}
+ value={email}
+ onChange={(event) => {
+ setEmail(event.target.value);
+ setAuthFeedback(null);
+ }}
+ autoComplete="email"
+ autoFocus={authMode === "sign_in"}
+ />
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Password</span>
+ <input
+ name="password"
+ type="password"
+ className={fieldClassName}
+ value={password}
+ onChange={(event) => {
+ setPassword(event.target.value);
+ setAuthFeedback(null);
+ }}
+ autoComplete={authMode === "sign_in" ? "current-password" : "new-password"}
+ />
+ </label>
+ {authFeedback ? (
+ <p
+ className={`text-xs ${
+ authFeedback.tone === "info" ? "text-amber-300" : "text-red-400"
+ }`}
+ >
+ {authFeedback.message}
+ </p>
+ ) : null}
+ <Button
+ type="submit"
+ className="w-full rounded-none"
+ disabled={authMutation.isPending}
+ aria-disabled={!authCanSubmit || authMutation.isPending}
+ >
+ {authMutation.isPending
+ ? "Working..."
+ : authMode === "sign_in"
+ ? "Sign in and continue"
+ : "Create account and continue"}
+ </Button>
+ </form>
+
+ <p className="text-xs leading-5 text-zinc-500">
+ {authMode === "sign_up"
+ ? "Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user."
+ : "No account yet? Switch back to create account so you can accept the invite with a new login."}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <div>
+ <h2 className="text-lg font-semibold">
+ {shouldAutoAcceptHumanInvite
+ ? "Submitting join request"
+ : invite.inviteType === "bootstrap_ceo"
+ ? "Accept bootstrap invite"
+ : "Accept company invite"}
+ </h2>
+ <p className="mt-1 text-sm text-zinc-400">
+ {shouldAutoAcceptHumanInvite
+ ? `Submitting your join request for ${companyDisplayName}.`
+ : isCurrentMember
+ ? `This account already belongs to ${companyDisplayName}.`
+ : `This will ${
+ invite.inviteType === "bootstrap_ceo" ? "finish setting up Paperclip" : `submit or complete your join request for ${companyDisplayName}`
+ }.`}
+ </p>
+ </div>
+ {error ? <p className="text-xs text-red-400">{error}</p> : null}
+ {shouldAutoAcceptHumanInvite ? (
+ <div className="text-sm text-zinc-400">
+ {acceptMutation.isPending ? "Submitting request..." : "Finishing sign-in..."}
+ </div>
+ ) : (
+ <Button
+ className="w-full rounded-none"
+ disabled={acceptMutation.isPending || isCurrentMember}
+ onClick={() => acceptMutation.mutate()}
+ >
+ {acceptMutation.isPending ? "Working..." : joinButtonLabel}
+ </Button>
+ )}
+ </div>
+ )}
+ </section>
+ </div>
</div>
</div>
);
diff --git a/ui/src/pages/InviteUxLab.test.tsx b/ui/src/pages/InviteUxLab.test.tsx
new file mode 100644
index 0000000000..0eb7e8d85e
--- /dev/null
+++ b/ui/src/pages/InviteUxLab.test.tsx
@@ -0,0 +1,52 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { InviteUxLab } from "./InviteUxLab";
+
+vi.mock("@/components/CompanyPatternIcon", () => ({
+ CompanyPatternIcon: ({ companyName }: { companyName: string }) => (
+ <div aria-label={`${companyName} logo`}>{companyName}</div>
+ ),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("InviteUxLab", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("renders the invite/signup review sections", async () => {
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<InviteUxLab />);
+ });
+
+ expect(container.textContent).toContain("Invite and signup UX review surface");
+ expect(container.textContent).toContain("/tests/ux/invites");
+ expect(container.textContent).toContain("Landing state coverage");
+ expect(container.textContent).toContain("Split-screen invite flows");
+ expect(container.textContent).toContain("Approval and completion screens");
+ expect(container.textContent).toContain("Auth page states");
+ expect(container.textContent).toContain("Company invite management");
+ expect(container.textContent).toContain("Create your account");
+ expect(container.textContent).toContain("Invite history");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/InviteUxLab.tsx b/ui/src/pages/InviteUxLab.tsx
new file mode 100644
index 0000000000..941a487551
--- /dev/null
+++ b/ui/src/pages/InviteUxLab.tsx
@@ -0,0 +1,927 @@
+import type { ReactNode } from "react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { CompanyPatternIcon } from "@/components/CompanyPatternIcon";
+import { cn } from "@/lib/utils";
+import {
+ ArrowRight,
+ Check,
+ Clock3,
+ ExternalLink,
+ FlaskConical,
+ KeyRound,
+ Link2,
+ Loader2,
+ MailPlus,
+ ShieldCheck,
+ UserPlus,
+ Users,
+} from "lucide-react";
+
+const inviteRoleOptions = [
+ {
+ value: "viewer",
+ label: "Viewer",
+ description: "Can view company work and follow along without operational permissions.",
+ gets: "No built-in grants.",
+ },
+ {
+ value: "operator",
+ label: "Operator",
+ description: "Recommended for people who need to help run work without managing access.",
+ gets: "Can assign tasks.",
+ },
+ {
+ value: "admin",
+ label: "Admin",
+ description: "Recommended for operators who need to invite people, create agents, and approve joins.",
+ gets: "Can create agents, invite users, assign tasks, and approve join requests.",
+ },
+ {
+ value: "owner",
+ label: "Owner",
+ description: "Full company access, including membership and permission management.",
+ gets: "Everything in Admin, plus managing members and permission grants.",
+ },
+] as const;
+
+const inviteHistory = [
+ {
+ id: "invite-active",
+ state: "Active",
+ humanRole: "operator",
+ invitedBy: "Board User 25",
+ email: "[email protected]",
+ createdAt: "Apr 25, 2026, 9:00 AM",
+ action: "Revoke",
+ relatedLabel: "Review request",
+ },
+ {
+ id: "invite-accepted",
+ state: "Accepted",
+ humanRole: "viewer",
+ invitedBy: "Board User 24",
+ email: "[email protected]",
+ createdAt: "Apr 24, 2026, 8:15 AM",
+ action: "Inactive",
+ relatedLabel: "—",
+ },
+ {
+ id: "invite-revoked",
+ state: "Revoked",
+ humanRole: "admin",
+ invitedBy: "Board User 20",
+ email: "[email protected]",
+ createdAt: "Apr 20, 2026, 2:45 PM",
+ action: "Inactive",
+ relatedLabel: "—",
+ },
+ {
+ id: "invite-expired",
+ state: "Expired",
+ humanRole: "owner",
+ invitedBy: "Board User 19",
+ email: "[email protected]",
+ createdAt: "Apr 19, 2026, 7:10 PM",
+ action: "Inactive",
+ relatedLabel: "—",
+ },
+] as const;
+
+const fieldClassName =
+ "w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500";
+const panelClassName = "border border-zinc-800 bg-zinc-950/95 p-6";
+
+function LabSection({
+ eyebrow,
+ title,
+ description,
+ accentClassName,
+ children,
+}: {
+ eyebrow: string;
+ title: string;
+ description: string;
+ accentClassName?: string;
+ children: ReactNode;
+}) {
+ return (
+ <section
+ className={cn(
+ "rounded-[28px] border border-border/70 bg-background/80 p-4 shadow-[0_24px_60px_rgba(15,23,42,0.08)] sm:p-5",
+ accentClassName,
+ )}
+ >
+ <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground">
+ {eyebrow}
+ </div>
+ <h2 className="mt-1 text-xl font-semibold tracking-tight">{title}</h2>
+ <p className="mt-2 max-w-3xl text-sm text-muted-foreground">{description}</p>
+ </div>
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function StatusCard({
+ icon,
+ title,
+ body,
+ tone = "default",
+}: {
+ icon: ReactNode;
+ title: string;
+ body: string;
+ tone?: "default" | "warn" | "success" | "error";
+}) {
+ const toneClassName = {
+ default: "border-border/70 bg-background/85",
+ warn: "border-amber-400/40 bg-amber-500/[0.08]",
+ success: "border-emerald-400/40 bg-emerald-500/[0.08]",
+ error: "border-rose-400/40 bg-rose-500/[0.08]",
+ }[tone];
+
+ return (
+ <Card className={cn("rounded-[24px] shadow-none", toneClassName)}>
+ <CardHeader className="space-y-3">
+ <div className="flex h-10 w-10 items-center justify-center rounded-full border border-current/10 bg-background/70 text-muted-foreground">
+ {icon}
+ </div>
+ <div>
+ <CardTitle className="text-base">{title}</CardTitle>
+ <CardDescription className="mt-2 text-sm leading-6">{body}</CardDescription>
+ </div>
+ </CardHeader>
+ </Card>
+ );
+}
+
+function InviteLandingShell({
+ left,
+ right,
+}: {
+ left: ReactNode;
+ right: ReactNode;
+}) {
+ return (
+ <div className="overflow-hidden rounded-[28px] border border-zinc-800 bg-zinc-950 shadow-[0_30px_80px_rgba(2,6,23,0.55)]">
+ <div className="grid gap-px bg-zinc-800 lg:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]">
+ <section className={cn(panelClassName, "space-y-6 bg-zinc-950")}>{left}</section>
+ <section className={cn(panelClassName, "h-full bg-zinc-950")}>{right}</section>
+ </div>
+ </div>
+ );
+}
+
+function InviteSummaryPanel({
+ title,
+ description,
+ inviteMessage,
+ requestedAccess,
+ signedInLabel,
+}: {
+ title: string;
+ description: string;
+ inviteMessage?: string;
+ requestedAccess: string;
+ signedInLabel?: string;
+}) {
+ return (
+ <>
+ <div className="flex items-start gap-4">
+ <CompanyPatternIcon
+ companyName="Acme Robotics"
+ logoUrl="/api/invites/pcp_invite_test/logo"
+ brandColor="#114488"
+ className="h-16 w-16 rounded-none border border-zinc-800"
+ />
+ <div className="min-w-0">
+ <p className="text-xs uppercase tracking-[0.24em] text-zinc-500">You&apos;ve been invited to join Paperclip</p>
+ <h3 className="mt-2 text-2xl font-semibold text-zinc-100">{title}</h3>
+ <p className="mt-2 max-w-2xl text-sm leading-6 text-zinc-300">{description}</p>
+ </div>
+ </div>
+
+ <div className="grid gap-3 sm:grid-cols-2">
+ <MetaCard label="Company" value="Acme Robotics" />
+ <MetaCard label="Invited by" value="Board User" />
+ <MetaCard label="Requested access" value={requestedAccess} />
+ <MetaCard label="Invite expires" value="Mar 7, 2027" />
+ </div>
+
+ {inviteMessage ? (
+ <div className="border border-amber-500/40 bg-amber-500/10 p-4">
+ <div className="text-xs uppercase tracking-[0.2em] text-amber-200/80">Message from inviter</div>
+ <p className="mt-2 text-sm leading-6 text-amber-50">{inviteMessage}</p>
+ </div>
+ ) : null}
+
+ {signedInLabel ? (
+ <div className="border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50">
+ Signed in as <span className="font-medium">{signedInLabel}</span>.
+ </div>
+ ) : null}
+ </>
+ );
+}
+
+function MetaCard({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="border border-zinc-800 p-3">
+ <div className="text-xs uppercase tracking-[0.2em] text-zinc-500">{label}</div>
+ <div className="mt-1 text-sm text-zinc-100">{value}</div>
+ </div>
+ );
+}
+
+function InlineAuthPreview({
+ mode,
+ feedback,
+ working,
+}: {
+ mode: "sign_up" | "sign_in";
+ feedback?: { tone: "info" | "error"; text: string };
+ working?: boolean;
+}) {
+ return (
+ <div className="space-y-5">
+ <div>
+ <h3 className="text-lg font-semibold text-zinc-100">
+ {mode === "sign_up" ? "Create your account" : "Sign in to continue"}
+ </h3>
+ <p className="mt-1 text-sm text-zinc-400">
+ {mode === "sign_up"
+ ? "Start with a Paperclip account. After that, you'll come right back here to accept the invite for Acme Robotics."
+ : "Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."}
+ </p>
+ </div>
+
+ <div className="flex gap-2">
+ <button
+ type="button"
+ className={cn(
+ "flex-1 border px-3 py-2 text-sm transition-colors",
+ mode === "sign_up"
+ ? "border-zinc-100 bg-zinc-100 text-zinc-950"
+ : "border-zinc-800 text-zinc-300 hover:border-zinc-600",
+ )}
+ >
+ Create account
+ </button>
+ <button
+ type="button"
+ className={cn(
+ "flex-1 border px-3 py-2 text-sm transition-colors",
+ mode === "sign_in"
+ ? "border-zinc-100 bg-zinc-100 text-zinc-950"
+ : "border-zinc-800 text-zinc-300 hover:border-zinc-600",
+ )}
+ >
+ I already have an account
+ </button>
+ </div>
+
+ <form className="space-y-4">
+ {mode === "sign_up" ? (
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Name</span>
+ <input name="name" className={fieldClassName} defaultValue="Jane Example" readOnly />
+ </label>
+ ) : null}
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Email</span>
+ <input name="email" type="email" className={fieldClassName} defaultValue="[email protected]" readOnly />
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Password</span>
+ <input name="password" type="password" className={fieldClassName} defaultValue="supersecret" readOnly />
+ </label>
+ {feedback ? (
+ <p className={cn("text-xs", feedback.tone === "info" ? "text-amber-300" : "text-red-400")}>
+ {feedback.text}
+ </p>
+ ) : null}
+ <Button type="button" className="w-full rounded-none" disabled={working}>
+ {working ? "Working..." : mode === "sign_in" ? "Sign in and continue" : "Create account and continue"}
+ </Button>
+ </form>
+
+ <p className="text-xs leading-5 text-zinc-500">
+ {mode === "sign_up"
+ ? "Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user."
+ : "No account yet? Switch back to create account so you can accept the invite with a new login."}
+ </p>
+ </div>
+ );
+}
+
+function AgentRequestPreview() {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-semibold text-zinc-100">Submit agent details</h3>
+ <p className="mt-1 text-sm text-zinc-400">
+ This invite will create an approval request for a new agent in Acme Robotics.
+ </p>
+ </div>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Agent name</span>
+ <input className={fieldClassName} defaultValue="Acme Ops Agent" readOnly />
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Adapter type</span>
+ <select className={fieldClassName} defaultValue="codex_local" disabled>
+ <option value="codex_local">Codex</option>
+ <option value="claude_local">Claude Code</option>
+ <option value="cursor">Cursor</option>
+ </select>
+ </label>
+ <label className="block text-sm">
+ <span className="mb-1 block text-zinc-400">Capabilities</span>
+ <textarea
+ className={fieldClassName}
+ rows={4}
+ defaultValue="Reviews invites, triages requests, and keeps the board queue moving."
+ readOnly
+ />
+ </label>
+ <Button type="button" className="w-full rounded-none">
+ Submit request
+ </Button>
+ </div>
+ );
+}
+
+function AcceptInvitePreview({
+ autoAccept,
+ isCurrentMember,
+ error,
+}: {
+ autoAccept?: boolean;
+ isCurrentMember?: boolean;
+ error?: string;
+}) {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-semibold text-zinc-100">Accept company invite</h3>
+ <p className="mt-1 text-sm text-zinc-400">
+ {autoAccept
+ ? "Submitting your join request for Acme Robotics."
+ : isCurrentMember
+ ? "This account already belongs to Acme Robotics."
+ : "This will submit or complete your join request for Acme Robotics."}
+ </p>
+ </div>
+ {error ? <p className="text-xs text-red-400">{error}</p> : null}
+ {autoAccept ? (
+ <div className="text-sm text-zinc-400">Submitting request...</div>
+ ) : (
+ <Button type="button" className="w-full rounded-none" disabled={isCurrentMember}>
+ Accept invite
+ </Button>
+ )}
+ </div>
+ );
+}
+
+function InviteResultPreview({
+ title,
+ description,
+ claimSecret,
+ onboardingTextUrl,
+ joinedNow = false,
+}: {
+ title: string;
+ description: string;
+ claimSecret?: string;
+ onboardingTextUrl?: string;
+ joinedNow?: boolean;
+}) {
+ return (
+ <div className="mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6 text-zinc-100">
+ <div className="flex items-center gap-3">
+ <CompanyPatternIcon
+ companyName="Acme Robotics"
+ logoUrl="/api/invites/pcp_invite_test/logo"
+ brandColor="#114488"
+ className="h-12 w-12 rounded-none border border-zinc-800"
+ />
+ <h3 className="text-lg font-semibold">{title}</h3>
+ </div>
+ <div className="mt-4 space-y-3">
+ <p className="text-sm text-zinc-400">{description}</p>
+ {joinedNow ? (
+ <Button type="button" className="w-full rounded-none">
+ Open board
+ </Button>
+ ) : (
+ <>
+ <div className="border border-zinc-800 p-3">
+ <p className="mb-1 text-xs text-zinc-500">Approval page</p>
+ <a className="text-sm text-zinc-200 underline underline-offset-2" href="/company/settings/access">
+ Company Settings → Access
+ </a>
+ </div>
+ <p className="text-xs text-zinc-500">
+ Refresh this page after you&apos;ve been approved — you&apos;ll be redirected automatically.
+ </p>
+ </>
+ )}
+ {claimSecret ? (
+ <div className="space-y-1 border border-zinc-800 p-3 text-xs text-zinc-400">
+ <div className="text-zinc-200">Claim secret</div>
+ <div className="font-mono break-all">{claimSecret}</div>
+ <div className="font-mono break-all">POST /api/agents/claim-api-key</div>
+ </div>
+ ) : null}
+ {onboardingTextUrl ? (
+ <div className="text-xs text-zinc-400">
+ Onboarding: <span className="font-mono break-all">{onboardingTextUrl}</span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function AuthScreenPreview({ mode, error }: { mode: "sign_in" | "sign_up"; error?: string }) {
+ return (
+ <div className="overflow-hidden rounded-[28px] border border-border/70 bg-background shadow-[0_24px_60px_rgba(15,23,42,0.08)]">
+ <div className="grid gap-px bg-border/60 md:grid-cols-2">
+ <div className="flex min-h-[420px] flex-col justify-center bg-background px-8 py-10">
+ <div className="mx-auto w-full max-w-md">
+ <div className="mb-8 flex items-center gap-2">
+ <FlaskConical className="h-4 w-4 text-muted-foreground" />
+ <span className="text-sm font-medium">Paperclip</span>
+ </div>
+ <h3 className="text-xl font-semibold">
+ {mode === "sign_in" ? "Sign in to Paperclip" : "Create your Paperclip account"}
+ </h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {mode === "sign_in"
+ ? "Use your email and password to access this instance."
+ : "Create an account for this instance. Email confirmation is not required in v1."}
+ </p>
+ <div className="mt-6 space-y-4">
+ {mode === "sign_up" ? (
+ <label className="block">
+ <span className="mb-1 block text-xs text-muted-foreground">Name</span>
+ <input
+ className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm"
+ defaultValue="Jane Example"
+ readOnly
+ />
+ </label>
+ ) : null}
+ <label className="block">
+ <span className="mb-1 block text-xs text-muted-foreground">Email</span>
+ <input
+ className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm"
+ defaultValue="[email protected]"
+ readOnly
+ />
+ </label>
+ <label className="block">
+ <span className="mb-1 block text-xs text-muted-foreground">Password</span>
+ <input
+ className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm"
+ defaultValue="supersecret"
+ readOnly
+ />
+ </label>
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ <Button type="button" className="w-full">
+ {mode === "sign_in" ? "Sign In" : "Create Account"}
+ </Button>
+ </div>
+ <div className="mt-5 text-sm text-muted-foreground">
+ {mode === "sign_in" ? "Need an account?" : "Already have an account?"}{" "}
+ <span className="font-medium text-foreground underline underline-offset-2">
+ {mode === "sign_in" ? "Create one" : "Sign in"}
+ </span>
+ </div>
+ </div>
+ </div>
+ <div className="hidden min-h-[420px] items-center justify-center bg-[radial-gradient(circle_at_top,rgba(8,145,178,0.18),transparent_48%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,1))] px-8 py-10 md:flex">
+ <div className="max-w-sm space-y-4 text-zinc-200">
+ <div className="inline-flex items-center gap-2 rounded-full border border-cyan-400/30 bg-cyan-500/[0.08] px-3 py-1 text-[10px] uppercase tracking-[0.22em] text-cyan-200">
+ Auth preview
+ </div>
+ <div className="text-2xl font-semibold">Side-by-side signup styling review</div>
+ <p className="text-sm leading-6 text-zinc-400">
+ This frame mirrors the production auth surface so spacing, label density, button treatments, and desktop composition are easy to compare.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function CompanyInvitesPreview() {
+ return (
+ <div className="grid gap-5 xl:grid-cols-[minmax(0,0.92fr)_minmax(0,1.08fr)]">
+ <Card className="rounded-[28px] shadow-none">
+ <CardHeader className="space-y-3">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <MailPlus className="h-4 w-4" />
+ Company Invites
+ </div>
+ <div>
+ <CardTitle>Create invite</CardTitle>
+ <CardDescription className="mt-2">
+ Generate a human invite link and choose the default access it should request.
+ </CardDescription>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <fieldset className="space-y-3">
+ <legend className="text-sm font-medium">Choose a role</legend>
+ <div className="rounded-2xl border border-border">
+ {inviteRoleOptions.map((option, index) => (
+ <label
+ key={option.value}
+ className={cn("flex cursor-default gap-3 px-4 py-4", index > 0 && "border-t border-border")}
+ >
+ <input
+ type="radio"
+ readOnly
+ checked={option.value === "operator"}
+ className="mt-1 h-4 w-4 border-border text-foreground"
+ />
+ <span className="min-w-0 space-y-1">
+ <span className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium">{option.label}</span>
+ {option.value === "operator" ? (
+ <span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ Default
+ </span>
+ ) : null}
+ </span>
+ <span className="block max-w-2xl text-sm text-muted-foreground">{option.description}</span>
+ <span className="block text-sm text-foreground">{option.gets}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ </fieldset>
+
+ <div className="rounded-xl border border-border px-4 py-3 text-sm text-muted-foreground">
+ Each invite link is single-use. The first successful use consumes the link and creates or reuses the matching join request before approval.
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button type="button">Create invite</Button>
+ <span className="text-sm text-muted-foreground">Invite history below keeps the audit trail.</span>
+ </div>
+
+ <div className="space-y-3 rounded-2xl border border-border px-4 py-4">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <div className="text-sm font-medium">Latest invite link</div>
+ <div className="text-sm text-muted-foreground">
+ This URL includes the current Paperclip domain returned by the server.
+ </div>
+ </div>
+ <div className="inline-flex items-center gap-1 text-xs font-medium text-foreground">
+ <Check className="h-3.5 w-3.5" />
+ Copied
+ </div>
+ </div>
+ <button
+ type="button"
+ className="w-full rounded-md border border-border bg-muted/60 px-3 py-2 text-left text-sm break-all"
+ >
+ https://paperclip.local/invite/new-token
+ </button>
+ <div className="flex flex-wrap gap-2">
+ <Button type="button" size="sm" variant="outline">
+ <ExternalLink className="h-4 w-4" />
+ Open invite
+ </Button>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card className="rounded-[28px] shadow-none">
+ <CardHeader className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <CardTitle>Invite history</CardTitle>
+ <CardDescription className="mt-2">
+ Review invite status, role, inviter, and any linked join request.
+ </CardDescription>
+ </div>
+ <a href="/inbox/requests" className="text-sm underline underline-offset-4">
+ Open join request queue
+ </a>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="overflow-x-auto rounded-2xl border border-border">
+ <table className="min-w-full text-left text-sm">
+ <thead>
+ <tr className="border-b border-border">
+ <th className="px-5 py-3 font-medium text-muted-foreground">State</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Role</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Invited by</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Created</th>
+ <th className="px-5 py-3 font-medium text-muted-foreground">Join request</th>
+ <th className="px-5 py-3 text-right font-medium text-muted-foreground">Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ {inviteHistory.map((invite) => (
+ <tr key={invite.id} className="border-b border-border last:border-b-0">
+ <td className="px-5 py-3 align-top">
+ <span className="inline-flex rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ {invite.state}
+ </span>
+ </td>
+ <td className="px-5 py-3 align-top">{invite.humanRole}</td>
+ <td className="px-5 py-3 align-top">
+ <div>{invite.invitedBy}</div>
+ <div className="text-xs text-muted-foreground">{invite.email}</div>
+ </td>
+ <td className="px-5 py-3 align-top text-muted-foreground">{invite.createdAt}</td>
+ <td className="px-5 py-3 align-top">
+ {invite.relatedLabel === "Review request" ? (
+ <a href="/inbox/requests" className="underline underline-offset-4">
+ {invite.relatedLabel}
+ </a>
+ ) : (
+ <span className="text-muted-foreground">{invite.relatedLabel}</span>
+ )}
+ </td>
+ <td className="px-5 py-3 text-right align-top">
+ {invite.action === "Revoke" ? (
+ <Button type="button" size="sm" variant="outline">
+ Revoke
+ </Button>
+ ) : (
+ <span className="text-xs text-muted-foreground">Inactive</span>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ <div className="grid gap-3 md:grid-cols-2">
+ <div className="rounded-2xl border border-border p-4">
+ <div className="text-sm font-medium">Empty history state</div>
+ <div className="mt-2 text-sm text-muted-foreground">
+ No invites have been created for this company yet.
+ </div>
+ </div>
+ <div className="rounded-2xl border border-rose-400/40 bg-rose-500/[0.07] p-4">
+ <div className="text-sm font-medium text-foreground">Permission error</div>
+ <div className="mt-2 text-sm text-muted-foreground">
+ You do not have permission to manage company invites.
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+export function InviteUxLab() {
+ return (
+ <div className="space-y-6">
+ <div className="overflow-hidden rounded-[32px] border border-border/70 bg-[linear-gradient(135deg,rgba(8,145,178,0.10),transparent_28%),linear-gradient(180deg,rgba(245,158,11,0.10),transparent_44%),var(--background)] shadow-[0_30px_80px_rgba(15,23,42,0.10)]">
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1.2fr)_320px]">
+ <div className="p-6 sm:p-7">
+ <div className="inline-flex items-center gap-2 rounded-full border border-cyan-500/25 bg-cyan-500/[0.08] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.24em] text-cyan-700 dark:text-cyan-300">
+ <FlaskConical className="h-3.5 w-3.5" />
+ Invite UX Lab
+ </div>
+ <h1 className="mt-4 text-3xl font-semibold tracking-tight">Invite and signup UX review surface</h1>
+ <p className="mt-3 max-w-3xl text-sm leading-6 text-muted-foreground">
+ This page collects the current invite landing, signup, approval-result, and company invite-management states in one place so styling changes can be reviewed without recreating each backend condition by hand.
+ </p>
+
+ <div className="mt-5 flex flex-wrap items-center gap-2">
+ <Badge variant="outline" className="rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]">
+ /tests/ux/invites
+ </Badge>
+ <Badge variant="outline" className="rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]">
+ signup + invite states
+ </Badge>
+ <Badge variant="outline" className="rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]">
+ fixture-backed preview
+ </Badge>
+ </div>
+ </div>
+
+ <aside className="border-t border-border/60 bg-background/70 p-6 lg:border-l lg:border-t-0">
+ <div className="mb-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground">
+ Covered states
+ </div>
+ <div className="space-y-3">
+ {[
+ "Invite loading, access-check, missing-token, and unavailable states",
+ "Inline account creation and sign-in variants, including feedback/error copy",
+ "Human accept, agent request, and auto-accept transitions",
+ "Pending approval, joined-now, claim secret, and onboarding result screens",
+ "Company invite creation, copied-link, history, empty, and permission-error states",
+ ].map((highlight) => (
+ <div
+ key={highlight}
+ className="rounded-2xl border border-border/70 bg-background/85 px-4 py-3 text-sm text-muted-foreground"
+ >
+ {highlight}
+ </div>
+ ))}
+ </div>
+ </aside>
+ </div>
+ </div>
+
+ <LabSection
+ eyebrow="Top-level states"
+ title="Landing state coverage"
+ description="Small cards for the fast-return invite states that do not render the full split-screen layout."
+ accentClassName="bg-[linear-gradient(180deg,rgba(59,130,246,0.05),transparent_30%),var(--background)]"
+ >
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
+ <StatusCard
+ icon={<Loader2 className="h-4 w-4 animate-spin" />}
+ title="Loading invite"
+ body="Shown while invite summary, deployment mode, or auth session data is still loading."
+ />
+ <StatusCard
+ icon={<Clock3 className="h-4 w-4" />}
+ title="Checking your access"
+ body="Shown after sign-in while the app verifies whether the current user already belongs to the invited company."
+ />
+ <StatusCard
+ icon={<KeyRound className="h-4 w-4" />}
+ title="Invalid invite token"
+ body="The token is missing entirely, so the page short-circuits before any invite lookup."
+ tone="error"
+ />
+ <StatusCard
+ icon={<Link2 className="h-4 w-4" />}
+ title="Invite not available"
+ body="Used for expired, revoked, already-consumed, or otherwise missing invites."
+ tone="warn"
+ />
+ <StatusCard
+ icon={<ShieldCheck className="h-4 w-4" />}
+ title="Bootstrap complete"
+ body="Result screen for bootstrap CEO invites after setup has been accepted successfully."
+ tone="success"
+ />
+ <StatusCard
+ icon={<ArrowRight className="h-4 w-4" />}
+ title="Auto-accept in progress"
+ body="Signed-in human users skip the extra button click and move straight into join submission."
+ />
+ <StatusCard
+ icon={<Users className="h-4 w-4" />}
+ title="Already a member"
+ body="Acceptance stays disabled and the page redirects into the company once membership is confirmed."
+ />
+ <StatusCard
+ icon={<UserPlus className="h-4 w-4" />}
+ title="Invite result surfaces"
+ body="Both pending-approval and joined-now confirmations are included below with claim and onboarding extras."
+ tone="success"
+ />
+ </div>
+ </LabSection>
+
+ <LabSection
+ eyebrow="Invite landing"
+ title="Split-screen invite flows"
+ description="These frames mirror the production invite surface closely enough to review spacing, hierarchy, and control states while keeping data fixture-driven."
+ accentClassName="bg-[linear-gradient(180deg,rgba(234,179,8,0.06),transparent_28%),var(--background)]"
+ >
+ <div className="space-y-5">
+ <InviteLandingShell
+ left={
+ <InviteSummaryPanel
+ title="Join Acme Robotics"
+ description="Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email."
+ inviteMessage="Welcome aboard."
+ requestedAccess="Operator"
+ />
+ }
+ right={<InlineAuthPreview mode="sign_up" />}
+ />
+
+ <InviteLandingShell
+ left={
+ <InviteSummaryPanel
+ title="Join Acme Robotics"
+ description="Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email."
+ inviteMessage="Welcome aboard."
+ requestedAccess="Operator"
+ />
+ }
+ right={
+ <InlineAuthPreview
+ mode="sign_in"
+ feedback={{
+ tone: "info",
+ text: "An account already exists for [email protected]. Sign in below to continue with this invite.",
+ }}
+ />
+ }
+ />
+
+ <InviteLandingShell
+ left={
+ <InviteSummaryPanel
+ title="Join Acme Robotics"
+ description="Your account is ready. Review the invite details, then accept it to continue."
+ inviteMessage="Welcome aboard."
+ requestedAccess="Operator"
+ signedInLabel="Jane Example"
+ />
+ }
+ right={<AcceptInvitePreview autoAccept />}
+ />
+
+ <InviteLandingShell
+ left={
+ <InviteSummaryPanel
+ title="Join Acme Robotics"
+ description="Review the invite details, then submit the agent information below to start the join request."
+ requestedAccess="Agent join request"
+ />
+ }
+ right={<AgentRequestPreview />}
+ />
+
+ <InviteLandingShell
+ left={
+ <InviteSummaryPanel
+ title="Join Acme Robotics"
+ description="Your account is ready. Review the invite details, then accept it to continue."
+ requestedAccess="Operator"
+ signedInLabel="Jane Example"
+ />
+ }
+ right={<AcceptInvitePreview error="This account already belongs to the company." isCurrentMember />}
+ />
+ </div>
+ </LabSection>
+
+ <LabSection
+ eyebrow="Result states"
+ title="Approval and completion screens"
+ description="These are the post-submit states returned from invite acceptance, including optional claim and onboarding metadata."
+ accentClassName="bg-[linear-gradient(180deg,rgba(16,185,129,0.06),transparent_30%),var(--background)]"
+ >
+ <div className="grid gap-5 xl:grid-cols-3">
+ <InviteResultPreview
+ title="Request to join Acme Robotics"
+ description="Board User must approve your request to join."
+ claimSecret="pcp_claim_secret_demo"
+ onboardingTextUrl="/api/invites/pcp_invite_test/onboarding.txt"
+ />
+ <InviteResultPreview
+ title="You joined the company"
+ description="Your account already matched the approved invite, so the board can be opened immediately."
+ joinedNow
+ />
+ <InviteResultPreview
+ title="Request to join Acme Robotics"
+ description="Ask them to visit Company Settings → Access to approve your request."
+ />
+ </div>
+ </LabSection>
+
+ <LabSection
+ eyebrow="Standalone auth"
+ title="Auth page states"
+ description="The general `/auth` page uses a different composition from invite landing. These previews keep both sign-in and sign-up variants visible."
+ accentClassName="bg-[linear-gradient(180deg,rgba(168,85,247,0.06),transparent_28%),var(--background)]"
+ >
+ <div className="space-y-5">
+ <AuthScreenPreview mode="sign_in" error="Invalid email or password" />
+ <AuthScreenPreview mode="sign_up" />
+ </div>
+ </LabSection>
+
+ <LabSection
+ eyebrow="Company settings"
+ title="Company invite management"
+ description="This section captures the board-side invite creation flow, copied-link state, audit table, and the edge states that are otherwise tedious to stage."
+ accentClassName="bg-[linear-gradient(180deg,rgba(244,114,182,0.06),transparent_28%),var(--background)]"
+ >
+ <CompanyInvitesPreview />
+ </LabSection>
+ </div>
+ );
+}
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index 7edea69730..4ee14f7660 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -7,6 +7,7 @@ import { approvalsApi } from "../api/approvals";
import { activityApi, type RunForIssue } from "../api/activity";
import { heartbeatsApi, type ActiveRunForIssue, type LiveRunForIssue } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
+import { accessApi } from "../api/access";
import { agentsApi } from "../api/agents";
import { authApi } from "../api/auth";
import { projectsApi } from "../api/projects";
@@ -17,6 +18,7 @@ import { useSidebar } from "../context/SidebarContext";
import { useToastActions } from "../context/ToastContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { assigneeValueFromSelection, suggestedCommentAssigneeValue } from "../lib/assignees";
+import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap, buildCompanyUserProfileMap, buildMarkdownMentionOptions } from "../lib/company-members";
import { extractIssueTimelineEvents } from "../lib/issue-timeline-events";
import { queryKeys } from "../lib/queryKeys";
import { keepPreviousDataForSameQueryTail } from "../lib/query-placeholder-data";
@@ -250,14 +252,17 @@ function mergeOptimisticFeedbackVote(
];
}
-function ActorIdentity({ evt, agentMap }: { evt: ActivityEvent; agentMap: Map<string, Agent> }) {
+function ActorIdentity({ evt, agentMap, userProfileMap }: { evt: ActivityEvent; agentMap: Map<string, Agent>; userProfileMap?: Map<string, import("../lib/company-members").CompanyUserProfile> }) {
const id = evt.actorId;
if (evt.actorType === "agent") {
const agent = agentMap.get(id);
return <Identity name={agent?.name ?? id.slice(0, 8)} size="sm" />;
}
if (evt.actorType === "system") return <Identity name="System" size="sm" />;
- if (evt.actorType === "user") return <Identity name="Board" size="sm" />;
+ if (evt.actorType === "user") {
+ const profile = userProfileMap?.get(id);
+ return <Identity name={profile?.label ?? "Board"} avatarUrl={profile?.image} size="sm" />;
+ }
return <Identity name={id || "Unknown"} size="sm" />;
}
@@ -502,6 +507,8 @@ type IssueDetailChatTabProps = {
feedbackTermsUrl: string | null;
agentMap: Map<string, Agent>;
currentUserId: string | null;
+ userLabelMap: ReadonlyMap<string, string> | null;
+ userProfileMap: ReadonlyMap<string, import("../lib/company-members").CompanyUserProfile> | null;
draftKey: string;
reassignOptions: Array<{ id: string; label: string; searchText?: string }>;
currentAssigneeValue: string;
@@ -538,6 +545,8 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
feedbackTermsUrl,
agentMap,
currentUserId,
+ userLabelMap,
+ userProfileMap,
draftKey,
reassignOptions,
currentAssigneeValue,
@@ -682,6 +691,8 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
issueStatus={issueStatus}
agentMap={agentMap}
currentUserId={currentUserId}
+ userLabelMap={userLabelMap}
+ userProfileMap={userProfileMap}
draftKey={draftKey}
enableReassign
reassignOptions={reassignOptions}
@@ -713,6 +724,7 @@ type IssueDetailActivityTabProps = {
issueId: string;
agentMap: Map<string, Agent>;
currentUserId: string | null;
+ userProfileMap: Map<string, import("../lib/company-members").CompanyUserProfile>;
pendingApprovalAction: { approvalId: string; action: "approve" | "reject" } | null;
onApprovalAction: (approvalId: string, action: "approve" | "reject") => void;
};
@@ -721,6 +733,7 @@ function IssueDetailActivityTab({
issueId,
agentMap,
currentUserId,
+ userProfileMap,
pendingApprovalAction,
onApprovalAction,
}: IssueDetailActivityTabProps) {
@@ -837,8 +850,8 @@ function IssueDetailActivityTab({
<div className="space-y-1.5">
{activity.slice(0, 20).map((evt) => (
<div key={evt.id} className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <ActorIdentity evt={evt} agentMap={agentMap} />
- <span>{formatIssueActivityAction(evt.action, evt.details, { agentMap, currentUserId })}</span>
+ <ActorIdentity evt={evt} agentMap={agentMap} userProfileMap={userProfileMap} />
+ <span>{formatIssueActivityAction(evt.action, evt.details, { agentMap, userProfileMap, currentUserId })}</span>
<span className="ml-auto shrink-0">{relativeTime(evt.createdAt)}</span>
</div>
))}
@@ -976,6 +989,11 @@ export function IssueDetail() {
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
@@ -1027,31 +1045,21 @@ export function IssueDetail() {
for (const a of agents ?? []) map.set(a.id, a);
return map;
}, [agents]);
+ const userProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
+ const userLabelMap = useMemo(
+ () => buildCompanyUserLabelMap(companyMembers?.users),
+ [companyMembers?.users],
+ );
const mentionOptions = useMemo<MentionOption[]>(() => {
- const options: MentionOption[] = [];
- const activeAgents = [...(agents ?? [])]
- .filter((agent) => agent.status !== "terminated")
- .sort((a, b) => a.name.localeCompare(b.name));
- for (const agent of activeAgents) {
- options.push({
- id: `agent:${agent.id}`,
- name: agent.name,
- kind: "agent",
- agentId: agent.id,
- agentIcon: agent.icon,
- });
- }
- for (const project of orderedProjects) {
- options.push({
- id: `project:${project.id}`,
- name: project.name,
- kind: "project",
- projectId: project.id,
- projectColor: project.color,
- });
- }
- return options;
- }, [agents, orderedProjects]);
+ return buildMarkdownMentionOptions({
+ agents,
+ projects: orderedProjects,
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users, orderedProjects]);
const resolvedProject = useMemo(
() => (issue?.projectId ? orderedProjects.find((project) => project.id === issue.projectId) ?? issue.project ?? null : null),
@@ -1085,6 +1093,7 @@ export function IssueDetail() {
const commentReassignOptions = useMemo(() => {
const options: Array<{ id: string; label: string; searchText?: string }> = [];
+ options.push(...buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId] }));
const activeAgents = [...(agents ?? [])]
.filter((agent) => agent.status !== "terminated")
.sort((a, b) => a.name.localeCompare(b.name));
@@ -1095,7 +1104,7 @@ export function IssueDetail() {
options.push({ id: `user:${currentUserId}`, label: "Me" });
}
return options;
- }, [agents, currentUserId]);
+ }, [agents, companyMembers?.users, currentUserId]);
const actualAssigneeValue = useMemo(
() => assigneeValueFromSelection(issue ?? {}),
@@ -2628,6 +2637,8 @@ export function IssueDetail() {
feedbackTermsUrl={FEEDBACK_TERMS_URL}
agentMap={agentMap}
currentUserId={currentUserId}
+ userLabelMap={userLabelMap}
+ userProfileMap={userProfileMap}
draftKey={`paperclip:issue-comment-draft:${issue.id}`}
reassignOptions={commentReassignOptions}
currentAssigneeValue={actualAssigneeValue}
@@ -2652,6 +2663,7 @@ export function IssueDetail() {
issueId={issue.id}
agentMap={agentMap}
currentUserId={currentUserId}
+ userProfileMap={userProfileMap}
pendingApprovalAction={pendingApprovalAction}
onApprovalAction={(approvalId, action) => {
approvalDecision.mutate({ approvalId, action });
diff --git a/ui/src/pages/JoinRequestQueue.tsx b/ui/src/pages/JoinRequestQueue.tsx
new file mode 100644
index 0000000000..29662d9a16
--- /dev/null
+++ b/ui/src/pages/JoinRequestQueue.tsx
@@ -0,0 +1,194 @@
+import { useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { UserPlus2 } from "lucide-react";
+import { accessApi } from "@/api/access";
+import { ApiError } from "@/api/client";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "@/context/CompanyContext";
+import { useToast } from "@/context/ToastContext";
+import { queryKeys } from "@/lib/queryKeys";
+
+export function JoinRequestQueue() {
+ const { selectedCompany, selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { pushToast } = useToast();
+ const queryClient = useQueryClient();
+ const [status, setStatus] = useState<"pending_approval" | "approved" | "rejected">("pending_approval");
+ const [requestType, setRequestType] = useState<"all" | "human" | "agent">("all");
+
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: selectedCompany?.name ?? "Company", href: "/dashboard" },
+ { label: "Inbox", href: "/inbox" },
+ { label: "Join Requests" },
+ ]);
+ }, [selectedCompany?.name, setBreadcrumbs]);
+
+ const requestsQuery = useQuery({
+ queryKey: queryKeys.access.joinRequests(selectedCompanyId ?? "", `${status}:${requestType}`),
+ queryFn: () =>
+ accessApi.listJoinRequests(
+ selectedCompanyId!,
+ status,
+ requestType === "all" ? undefined : requestType,
+ ),
+ enabled: !!selectedCompanyId,
+ });
+
+ const approveMutation = useMutation({
+ mutationFn: (requestId: string) => accessApi.approveJoinRequest(selectedCompanyId!, requestId),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId!, `${status}:${requestType}`) });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.companyMembers(selectedCompanyId!) });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!) });
+ pushToast({ title: "Join request approved", tone: "success" });
+ },
+ });
+
+ const rejectMutation = useMutation({
+ mutationFn: (requestId: string) => accessApi.rejectJoinRequest(selectedCompanyId!, requestId),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId!, `${status}:${requestType}`) });
+ pushToast({ title: "Join request rejected", tone: "success" });
+ },
+ });
+
+ if (!selectedCompanyId) {
+ return <div className="text-sm text-muted-foreground">Select a company to review join requests.</div>;
+ }
+
+ if (requestsQuery.isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading join requests…</div>;
+ }
+
+ if (requestsQuery.error) {
+ const message =
+ requestsQuery.error instanceof ApiError && requestsQuery.error.status === 403
+ ? "You do not have permission to review join requests for this company."
+ : requestsQuery.error instanceof Error
+ ? requestsQuery.error.message
+ : "Failed to load join requests.";
+ return <div className="text-sm text-destructive">{message}</div>;
+ }
+
+ return (
+ <div className="max-w-6xl space-y-6">
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <UserPlus2 className="h-5 w-5 text-muted-foreground" />
+ <h1 className="text-lg font-semibold">Join Request Queue</h1>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap gap-3 rounded-xl border border-border bg-card p-4">
+ <label className="space-y-2 text-sm">
+ <span className="font-medium">Status</span>
+ <select
+ className="rounded-md border border-border bg-background px-3 py-2"
+ value={status}
+ onChange={(event) =>
+ setStatus(event.target.value as "pending_approval" | "approved" | "rejected")
+ }
+ >
+ <option value="pending_approval">Pending approval</option>
+ <option value="approved">Approved</option>
+ <option value="rejected">Rejected</option>
+ </select>
+ </label>
+ <label className="space-y-2 text-sm">
+ <span className="font-medium">Request type</span>
+ <select
+ className="rounded-md border border-border bg-background px-3 py-2"
+ value={requestType}
+ onChange={(event) =>
+ setRequestType(event.target.value as "all" | "human" | "agent")
+ }
+ >
+ <option value="all">All</option>
+ <option value="human">Human</option>
+ <option value="agent">Agent</option>
+ </select>
+ </label>
+ </div>
+
+ <div className="space-y-4">
+ {(requestsQuery.data ?? []).length === 0 ? (
+ <div className="rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground">
+ No join requests match the current filters.
+ </div>
+ ) : (
+ requestsQuery.data!.map((request) => (
+ <div key={request.id} className="rounded-xl border border-border bg-card p-4">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge variant={request.status === "pending_approval" ? "secondary" : request.status === "approved" ? "outline" : "destructive"}>
+ {request.status.replace("_", " ")}
+ </Badge>
+ <Badge variant="outline">{request.requestType}</Badge>
+ {request.adapterType ? <Badge variant="outline">{request.adapterType}</Badge> : null}
+ </div>
+ <div>
+ <div className="text-base font-medium">
+ {request.requestType === "human"
+ ? request.requesterUser?.name || request.requestEmailSnapshot || request.requestingUserId || "Unknown human requester"
+ : request.agentName || "Unknown agent requester"}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ {request.requestType === "human"
+ ? request.requesterUser?.email || request.requestEmailSnapshot || request.requestingUserId
+ : request.capabilities || request.requestIp}
+ </div>
+ </div>
+ </div>
+
+ {request.status === "pending_approval" ? (
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => rejectMutation.mutate(request.id)}
+ disabled={rejectMutation.isPending}
+ >
+ Reject
+ </Button>
+ <Button
+ onClick={() => approveMutation.mutate(request.id)}
+ disabled={approveMutation.isPending}
+ >
+ Approve
+ </Button>
+ </div>
+ ) : null}
+ </div>
+
+ <div className="mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2">
+ <div className="rounded-lg border border-border bg-background px-3 py-2">
+ <div className="text-xs font-medium uppercase tracking-wide">Invite context</div>
+ <div className="mt-2">
+ {request.invite
+ ? `${request.invite.allowedJoinTypes} join invite${request.invite.humanRole ? ` • default role ${request.invite.humanRole}` : ""}`
+ : "Invite metadata unavailable"}
+ </div>
+ {request.invite?.inviteMessage ? (
+ <div className="mt-2 text-foreground">{request.invite.inviteMessage}</div>
+ ) : null}
+ </div>
+ <div className="rounded-lg border border-border bg-background px-3 py-2">
+ <div className="text-xs font-medium uppercase tracking-wide">Request details</div>
+ <div className="mt-2">Submitted {new Date(request.createdAt).toLocaleString()}</div>
+ <div>Source IP {request.requestIp}</div>
+ {request.requestType === "agent" && request.capabilities ? <div>{request.capabilities}</div> : null}
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/ProfileSettings.test.tsx b/ui/src/pages/ProfileSettings.test.tsx
new file mode 100644
index 0000000000..72a9425936
--- /dev/null
+++ b/ui/src/pages/ProfileSettings.test.tsx
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ProfileSettings } from "./ProfileSettings";
+
+const mockAuthApi = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ signInEmail: vi.fn(),
+ signUpEmail: vi.fn(),
+ getProfile: vi.fn(),
+ updateProfile: vi.fn(),
+ signOut: vi.fn(),
+}));
+
+const mockAssetsApi = vi.hoisted(() => ({
+ uploadImage: vi.fn(),
+ uploadCompanyLogo: vi.fn(),
+}));
+
+const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/auth", () => ({
+ authApi: mockAuthApi,
+}));
+
+vi.mock("@/api/assets", () => ({
+ assetsApi: mockAssetsApi,
+}));
+
+vi.mock("../context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({
+ setBreadcrumbs: mockSetBreadcrumbs,
+ }),
+}));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompanyId: "company-1",
+ selectedCompany: { id: "company-1", name: "Paperclip", issuePrefix: "PAP" },
+ }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+describe("ProfileSettings", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ mockAuthApi.getSession.mockResolvedValue({
+ session: { id: "session-1", userId: "user-1" },
+ user: {
+ id: "user-1",
+ name: "Jane Example",
+ email: "[email protected]",
+ image: "https://example.com/jane.png",
+ },
+ });
+ mockAssetsApi.uploadImage.mockResolvedValue({
+ assetId: "asset-1",
+ contentPath: "/api/assets/asset-1/content",
+ });
+ mockAuthApi.updateProfile.mockImplementation(async (input: { name: string; image: string | null }) => ({
+ id: "user-1",
+ name: input.name,
+ email: "[email protected]",
+ image: input.image,
+ }));
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("uploads a clicked avatar into Paperclip storage and persists the returned asset path", async () => {
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <ProfileSettings />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(container.textContent).not.toContain("Avatar image URL");
+
+ const avatarInput = container.querySelector('input[type="file"]') as HTMLInputElement | null;
+ expect(avatarInput).not.toBeNull();
+
+ const file = new File(["avatar"], "avatar.png", { type: "image/png" });
+ Object.defineProperty(avatarInput, "files", {
+ configurable: true,
+ value: [file],
+ });
+
+ await act(async () => {
+ avatarInput?.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(mockAssetsApi.uploadImage).toHaveBeenCalledWith("company-1", file, "profiles/user-1");
+ expect(mockAuthApi.updateProfile).toHaveBeenCalledWith({
+ name: "Jane Example",
+ image: "/api/assets/asset-1/content",
+ });
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/ProfileSettings.tsx b/ui/src/pages/ProfileSettings.tsx
new file mode 100644
index 0000000000..a60c0b7acf
--- /dev/null
+++ b/ui/src/pages/ProfileSettings.tsx
@@ -0,0 +1,273 @@
+import { useEffect, useId, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Camera, LoaderCircle, Save, Trash2, UserRoundPen } from "lucide-react";
+import type { AuthSession, CurrentUserProfile, UpdateCurrentUserProfile } from "@paperclipai/shared";
+import { authApi } from "@/api/auth";
+import { assetsApi } from "@/api/assets";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useCompany } from "../context/CompanyContext";
+import { queryKeys } from "../lib/queryKeys";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+function deriveInitials(name: string) {
+ const parts = name.trim().split(/\s+/).filter(Boolean);
+ if (parts.length >= 2) return `${parts[0]?.[0] ?? ""}${parts[parts.length - 1]?.[0] ?? ""}`.toUpperCase();
+ return name.slice(0, 2).toUpperCase();
+}
+
+export function ProfileSettings() {
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { selectedCompanyId, selectedCompany } = useCompany();
+ const queryClient = useQueryClient();
+ const avatarInputId = useId();
+ const avatarInputRef = useRef<HTMLInputElement | null>(null);
+ const [name, setName] = useState("");
+ const [image, setImage] = useState("");
+ const [actionError, setActionError] = useState<string | null>(null);
+ const sessionQuery = useQuery({
+ queryKey: queryKeys.auth.session,
+ queryFn: () => authApi.getSession(),
+ retry: false,
+ });
+
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: "Instance Settings" },
+ { label: "Profile" },
+ ]);
+ }, [setBreadcrumbs]);
+
+ useEffect(() => {
+ const session = sessionQuery.data;
+ if (!session) return;
+ setName(session.user.name ?? "");
+ setImage(session.user.image ?? "");
+ }, [sessionQuery.data]);
+
+ function syncSessionProfile(profile: CurrentUserProfile) {
+ queryClient.setQueryData<AuthSession | null>(queryKeys.auth.session, (current) => {
+ if (!current) return current;
+ return {
+ ...current,
+ user: {
+ ...current.user,
+ ...profile,
+ },
+ };
+ });
+ }
+
+ async function persistProfile(input: UpdateCurrentUserProfile) {
+ const profile = await authApi.updateProfile(input);
+ syncSessionProfile(profile);
+ return profile;
+ }
+
+ function resolveProfileName() {
+ return name.trim() || sessionQuery.data?.user.name || "Board";
+ }
+
+ const updateMutation = useMutation({
+ mutationFn: (input: UpdateCurrentUserProfile) => persistProfile(input),
+ onSuccess: (profile) => {
+ setActionError(null);
+ setName(profile.name ?? "");
+ setImage(profile.image ?? "");
+ },
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to update profile.");
+ },
+ });
+
+ const uploadAvatarMutation = useMutation({
+ mutationFn: async (file: File) => {
+ if (!selectedCompanyId) {
+ throw new Error("Select a company before uploading a profile avatar.");
+ }
+
+ const asset = await assetsApi.uploadImage(
+ selectedCompanyId,
+ file,
+ `profiles/${sessionQuery.data?.user.id ?? "board-user"}`,
+ );
+ return persistProfile({ name: resolveProfileName(), image: asset.contentPath });
+ },
+ onSuccess: (profile) => {
+ setActionError(null);
+ setName(profile.name ?? "");
+ setImage(profile.image ?? "");
+ },
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to upload avatar.");
+ },
+ });
+
+ const removeAvatarMutation = useMutation({
+ mutationFn: () => persistProfile({ name: resolveProfileName(), image: null }),
+ onSuccess: (profile) => {
+ setActionError(null);
+ setName(profile.name ?? "");
+ setImage(profile.image ?? "");
+ },
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to remove avatar.");
+ },
+ });
+
+ if (sessionQuery.isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading profile...</div>;
+ }
+
+ if (sessionQuery.error || !sessionQuery.data) {
+ return (
+ <div className="text-sm text-destructive">
+ {sessionQuery.error instanceof Error ? sessionQuery.error.message : "Failed to load profile."}
+ </div>
+ );
+ }
+
+ const currentName = name.trim() || sessionQuery.data.user.name || "Board";
+ const currentImage = image.trim() || null;
+ const initials = deriveInitials(currentName);
+ const isSavingProfile = updateMutation.isPending || uploadAvatarMutation.isPending || removeAvatarMutation.isPending;
+ const uploadHint = selectedCompany
+ ? `Stored in Paperclip file storage for ${selectedCompany.name}.`
+ : "Select a company to upload an avatar into Paperclip storage.";
+
+ return (
+ <div className="max-w-4xl space-y-6">
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <UserRoundPen className="h-5 w-5 text-muted-foreground" />
+ <h1 className="text-lg font-semibold">Profile</h1>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Control how your account appears in the sidebar and other board surfaces.
+ </p>
+ </div>
+
+ {actionError ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ {actionError}
+ </div>
+ ) : null}
+
+ <section className="space-y-8">
+ <div className="relative overflow-hidden rounded-[28px] border border-border/70 bg-card shadow-sm">
+ <div className="absolute inset-x-0 top-0 h-32 bg-[linear-gradient(135deg,hsl(var(--primary))_0%,hsl(var(--accent))_58%,color-mix(in_oklab,hsl(var(--background))_76%,white_24%)_100%)]" />
+ <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.22),transparent_34%),radial-gradient(circle_at_bottom_left,rgba(255,255,255,0.08),transparent_36%)]" />
+ <div className="relative p-6 pt-10">
+ <div className="flex flex-wrap items-end gap-5 rounded-[24px] border border-border/70 bg-background/92 p-5 shadow-[0_18px_44px_-28px_rgba(0,0,0,0.45)] backdrop-blur-sm">
+ <div className="space-y-3">
+ <label
+ htmlFor={avatarInputId}
+ className="group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background"
+ >
+ <input
+ ref={avatarInputRef}
+ id={avatarInputId}
+ type="file"
+ accept="image/*"
+ className="sr-only"
+ disabled={!selectedCompanyId || isSavingProfile}
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ uploadAvatarMutation.mutate(file);
+ event.target.value = "";
+ }}
+ />
+ <span className="absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14" />
+ <span className="absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm">
+ {uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
+ </span>
+ <Avatar size="lg" className="data-[size=lg]:size-24 ring-4 ring-background shadow-xl">
+ {currentImage ? <AvatarImage src={currentImage} alt={currentName} /> : null}
+ <AvatarFallback>{initials}</AvatarFallback>
+ </Avatar>
+ </label>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => avatarInputRef.current?.click()}
+ disabled={!selectedCompanyId || isSavingProfile}
+ >
+ {uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
+ {currentImage ? "Change photo" : "Upload photo"}
+ </Button>
+ {currentImage ? (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => removeAvatarMutation.mutate()}
+ disabled={isSavingProfile}
+ >
+ {removeAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
+ Remove
+ </Button>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="min-w-0 flex-1 space-y-2 pb-1">
+ <div>
+ <h2 className="truncate text-2xl font-semibold text-foreground">{currentName}</h2>
+ <p className="truncate text-sm text-muted-foreground">{sessionQuery.data.user.email ?? "No email"}</p>
+ </div>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ Click the avatar to upload a new image. {uploadHint}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <form
+ className="grid gap-6 md:grid-cols-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ updateMutation.mutate({ name: resolveProfileName(), image: image.trim() || null });
+ }}
+ >
+ <div className="space-y-2">
+ <Label htmlFor="profile-name">Display name</Label>
+ <Input
+ id="profile-name"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ maxLength={120}
+ placeholder="Board"
+ />
+ <p className="text-xs text-muted-foreground">
+ Shown in the sidebar account footer and comment author surfaces.
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="profile-email">Email</Label>
+ <Input
+ id="profile-email"
+ value={sessionQuery.data.user.email ?? ""}
+ readOnly
+ disabled
+ />
+ <p className="text-xs text-muted-foreground">
+ Email is managed by your auth session and is read-only here.
+ </p>
+ </div>
+
+ <div className="md:col-span-2 flex justify-end">
+ <Button type="submit" disabled={isSavingProfile || !name.trim()}>
+ {updateMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Save className="size-4" />}
+ {updateMutation.isPending ? "Saving..." : "Save profile"}
+ </Button>
+ </div>
+ </form>
+ </section>
+ </div>
+ );
+}
diff --git a/ui/src/pages/ProjectDetail.tsx b/ui/src/pages/ProjectDetail.tsx
index b88fcbd4fb..f5b0976bfb 100644
--- a/ui/src/pages/ProjectDetail.tsx
+++ b/ui/src/pages/ProjectDetail.tsx
@@ -363,7 +363,6 @@ export function ProjectDetail() {
const experimentalSettingsQuery = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: () => instanceSettingsApi.getExperimental(),
- retry: false,
});
const {
slots: pluginDetailSlots,
diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx
index d86dceefca..0262cc94a4 100644
--- a/ui/src/pages/Routines.tsx
+++ b/ui/src/pages/Routines.tsx
@@ -807,20 +807,11 @@ export function Routines() {
bordered={false}
contentClassName="min-h-[160px] text-sm text-muted-foreground"
onSubmit={() => {
- if (!createRoutine.isPending && draft.title.trim()) {
+ if (!createRoutine.isPending && draft.title.trim() && draft.projectId && draft.assigneeAgentId) {
createRoutine.mutate();
}
}}
/>
- <div className="mt-3 space-y-3">
- <RoutineVariablesHint />
- <RoutineVariablesEditor
- title={draft.title}
- description={draft.description}
- value={draft.variables}
- onChange={(variables) => setDraft((current) => ({ ...current, variables }))}
- />
- </div>
</div>
<div className="border-t border-border/60 px-5 py-3">