[codex] Bundle local branch fixes from PAP-10032 (#6604)

## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies.
> - This branch accumulated multiple already-tested control-plane,
adapter runtime, invite, workspace, plugin, and UI quality fixes on the
primary Paperclip checkout.
> - `origin/master` advanced while those commits were still local, so
the branch needed to be preserved and reconciled before review.
> - Splitting the branch commit-by-commit against the new base produced
overlapping conflicts with recently merged upstream PRs.
> - This pull request keeps the remaining branch as one standalone PR
because the final diff is 38 files after removing screenshot artifacts,
under Greptile's 100-file cap, and can be merged independently after
review.
> - The benefit is that none of the local work is lost, the branch is
now based on current `origin/master`, and reviewers can evaluate the
reconciled changes in one place.

## What Changed

- Merged the local accumulated branch with current `origin/master` and
resolved the invite-flow overlaps from the newer upstream companies
query helper.
- Preserved the local fixes for invite existing-member behavior, invite
link copy fallback, reusable workspace selection, worktree auth, static
SPA fallback, markdown wrapping, plugin slot registration, cloud
upstream UX/server polish, project sorting, and related tests.
- Removed screenshot artifacts from the PR per review request.
- Kept the PR under the requested file limit: 38 files changed, with no
`pnpm-lock.yaml` or `.github/workflows/*` changes.

## Verification

- `NODE_ENV=test pnpm exec vitest run
ui/src/pages/CompanyInvites.test.tsx ui/src/pages/InviteLanding.test.tsx
ui/src/pages/Projects.test.tsx ui/src/plugins/slots.test.ts
ui/src/components/MarkdownBody.test.tsx
server/src/__tests__/invite-accept-existing-member.test.ts
server/src/__tests__/static-index-html.test.ts
server/src/__tests__/execution-workspaces-service.test.ts
server/src/__tests__/better-auth.test.ts
server/src/__tests__/worktree-config.test.ts`
- `NODE_ENV=test pnpm --filter @paperclipai/ui typecheck`
- `NODE_ENV=test pnpm --filter @paperclipai/server typecheck`
- Confirmed `git diff --name-only origin/master...HEAD | wc -l` is `38`.
- Confirmed no PR diff entries match `pnpm-lock.yaml`,
`.github/workflows/*`, or `screenshots/*`.

## Risks

- Medium review risk because this is a bundled rescue PR rather than
several narrow feature PRs.
- Invite flow and company cache behavior overlapped with newer upstream
changes; the merge resolution intentionally keeps the shared
`companiesListQueryOptions` helper while preserving local
existing-member invite behavior.
- Visual review evidence is no longer attached in-repo because
screenshots were removed from this PR per review request.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, GPT-5-based coding agent, with repository tool access,
terminal execution, and git/GitHub CLI operations.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] UI screenshots were intentionally removed from this PR per review
request
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: CodexCoder <codexcoder@paperclip.local>
This commit is contained in:
Dotta
2026-05-25 07:25:26 -05:00
committed by GitHub
parent 96f0279e08
commit ece8a51e22
38 changed files with 1715 additions and 134 deletions
+44 -2
View File
@@ -44,6 +44,47 @@ describe("Better Auth cookie scoping", () => {
cookiePrefix: "paperclip-pap-worktree",
useSecureCookies: false,
});
expect(getCookies({
advanced: buildBetterAuthAdvancedOptions({ disableSecureCookies: true }),
} as BetterAuthOptions).sessionToken.name).toBe("paperclip-pap-worktree.session_token");
});
it("disables secure cookies for authenticated private auto-origin dev servers", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: undefined,
})).toBe(true);
});
it("keeps secure cookies for authenticated public auto-origin servers", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "public",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: undefined,
})).toBe(false);
});
it("uses an explicit public URL when deciding whether secure cookies are required", () => {
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "private",
authBaseUrlMode: "auto",
authPublicBaseUrl: undefined,
publicUrl: "https://paperclip.example.test",
})).toBe(false);
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
deploymentExposure: "public",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "http://paperclip.local.test:3100",
publicUrl: undefined,
})).toBe(true);
});
it("disables secure cookies when no canonical public auth URL is configured", () => {
@@ -71,13 +112,14 @@ describe("Better Auth cookie scoping", () => {
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(false);
});
it("lets PAPERCLIP_PUBLIC_URL override the auth base URL for cookie security", () => {
process.env.PAPERCLIP_PUBLIC_URL = "http://paperclip-dev:46259";
it("uses the caller-resolved public URL for cookie security", () => {
process.env.PAPERCLIP_PUBLIC_URL = "https://ignored.example.test";
expect(shouldDisableSecureAuthCookies({
deploymentMode: "authenticated",
authBaseUrlMode: "explicit",
authPublicBaseUrl: "https://paperclip.example.test",
publicUrl: "http://paperclip-dev:46259",
} as Parameters<typeof shouldDisableSecureAuthCookies>[0])).toBe(true);
});
@@ -63,6 +63,42 @@ describe("dev-runner worktree env bootstrap", () => {
expect(env.PAPERCLIP_OPTIONAL).toBe("");
});
it("repairs stale migrated config paths before loading worktree env", () => {
const root = createTempRoot("paperclip-dev-runner-worktree-migrated-env-");
const localConfigPath = path.join(root, ".paperclip", "config.json");
const worktreesDir = path.join(root, ".paperclip-worktrees");
fs.mkdirSync(path.dirname(localConfigPath), { recursive: true });
fs.writeFileSync(path.join(root, ".git"), "gitdir: /tmp/paperclip/.git/worktrees/feature\n", "utf8");
fs.writeFileSync(localConfigPath, "{}\n", "utf8");
fs.writeFileSync(
resolveWorktreeEnvFilePath(root),
[
"PAPERCLIP_HOME=/old/home/.paperclip-worktrees",
"PAPERCLIP_INSTANCE_ID=feature-worktree",
"PAPERCLIP_CONFIG=/old/home/paperclip/.paperclip/worktrees/feature/.paperclip/config.json",
"PAPERCLIP_CONTEXT=/old/home/.paperclip-worktrees/context.json",
"PAPERCLIP_IN_WORKTREE=true",
"PAPERCLIP_WORKTREE_NAME=feature-worktree",
"",
].join("\n"),
"utf8",
);
const env: NodeJS.ProcessEnv = {
PAPERCLIP_WORKTREES_DIR: worktreesDir,
};
const result = bootstrapDevRunnerWorktreeEnv(root, env);
expect(result).toEqual({
envPath: resolveWorktreeEnvFilePath(root),
missingEnv: false,
});
expect(env.PAPERCLIP_HOME).toBe(worktreesDir);
expect(env.PAPERCLIP_CONFIG).toBe(localConfigPath);
expect(env.PAPERCLIP_CONTEXT).toBe(path.join(worktreesDir, "context.json"));
expect(env.PAPERCLIP_INSTANCE_ID).toBe("feature-worktree");
});
it("reports uninitialized linked worktrees so dev runner can fail fast", () => {
const root = createTempRoot("paperclip-dev-runner-worktree-missing-");
fs.writeFileSync(path.join(root, ".git"), "gitdir: /tmp/paperclip/.git/worktrees/feature\n", "utf8");
@@ -343,6 +343,83 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
expect(readExecutionWorkspaceConfig(byId.get(untouchedWorkspaceId) ?? null)).toBeNull();
});
it("limits reusable summaries to open non-shared execution workspaces", async () => {
const companyId = randomUUID();
const projectId = randomUUID();
const openWorkspaceId = randomUUID();
const sharedWorkspaceId = randomUUID();
const closedWorkspaceId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: "PAP",
requireBoardApprovalForNewAgents: false,
});
await db.insert(projects).values({
id: projectId,
companyId,
name: "Reusable workspaces",
status: "in_progress",
executionWorkspacePolicy: {
enabled: true,
},
});
await db.insert(executionWorkspaces).values([
{
id: openWorkspaceId,
companyId,
projectId,
mode: "isolated_workspace",
strategyType: "git_worktree",
name: "Open isolated workspace",
status: "idle",
providerType: "git_worktree",
cwd: "/tmp/open-workspace",
branchName: "paperclip/open",
},
{
id: sharedWorkspaceId,
companyId,
projectId,
mode: "shared_workspace",
strategyType: "project_primary",
name: "Shared session",
status: "active",
providerType: "local_fs",
cwd: "/tmp/project-primary",
},
{
id: closedWorkspaceId,
companyId,
projectId,
mode: "isolated_workspace",
strategyType: "git_worktree",
name: "Closed isolated workspace",
status: "active",
providerType: "git_worktree",
cwd: "/tmp/closed-workspace",
closedAt: new Date("2026-05-23T20:00:00.000Z"),
},
]);
const summaries = await svc.listSummaries(companyId, {
projectId,
reuseEligible: true,
});
expect(summaries).toEqual([
expect.objectContaining({
id: openWorkspaceId,
name: "Open isolated workspace",
mode: "isolated_workspace",
status: "idle",
cwd: "/tmp/open-workspace",
branchName: "paperclip/open",
}),
]);
});
it("warns about dirty and unmerged git worktrees and reports cleanup actions", async () => {
const repoRoot = await createTempRepo();
tempDirs.add(repoRoot);
@@ -4,12 +4,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { accessRoutes } from "../routes/access.js";
import { errorHandler } from "../middleware/index.js";
const accessServiceMock = vi.hoisted(() => ({
isInstanceAdmin: vi.fn(),
canUser: vi.fn(),
hasPermission: vi.fn(),
ensureMembership: vi.fn(),
setPrincipalGrants: vi.fn(),
}));
const logActivityMock = vi.hoisted(() => vi.fn());
vi.mock("../services/index.js", () => ({
accessService: () => ({
isInstanceAdmin: vi.fn(),
canUser: vi.fn(),
hasPermission: vi.fn(),
}),
accessService: () => accessServiceMock,
agentService: () => ({
getById: vi.fn(),
}),
@@ -20,10 +25,36 @@ vi.mock("../services/index.js", () => ({
revokeBoardApiKey: vi.fn(),
}),
deduplicateAgentName: vi.fn(),
logActivity: vi.fn(),
logActivity: logActivityMock,
notifyHireApproved: vi.fn(),
}));
type QueryHooks = {
onSet?: (value: unknown) => void;
onValues?: (value: unknown) => void;
};
function createQuery(rows: unknown[], hooks: QueryHooks = {}) {
const query = {
from: vi.fn(() => query),
where: vi.fn(() => query),
orderBy: vi.fn(() => query),
set: vi.fn((value: unknown) => {
hooks.onSet?.(value);
return query;
}),
values: vi.fn((value: unknown) => {
hooks.onValues?.(value);
return query;
}),
returning: vi.fn(() => query),
then(resolve: (value: unknown[]) => unknown, reject?: (reason: unknown) => unknown) {
return Promise.resolve(rows).then(resolve, reject);
},
};
return query;
}
function createDbStub() {
const updateMock = vi.fn();
const invite = {
@@ -75,22 +106,26 @@ function createDbStub() {
}
function createApp(db: Record<string, unknown>) {
return createAppWithActor(db, {
type: "board",
source: "session",
userId: "user-1",
companyIds: ["company-1"],
memberships: [
{
companyId: "company-1",
membershipRole: "owner",
status: "active",
},
],
});
}
function createAppWithActor(db: Record<string, unknown>, actor: 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",
},
],
};
(req as any).actor = actor;
next();
});
app.use(
@@ -106,6 +141,162 @@ function createApp(db: Record<string, unknown>) {
return app;
}
function createDirectHumanInviteDbStub() {
const insertedValues: unknown[] = [];
const updateValues: unknown[] = [];
const invite = {
id: "invite-1",
companyId: "company-1",
inviteType: "company_join",
allowedJoinTypes: "human",
tokenHash: "hash",
defaultsPayload: { human: { role: "owner" } },
expiresAt: new Date("2027-03-10T00:00:00.000Z"),
invitedByUserId: "inviter-user",
revokedAt: null,
acceptedAt: null,
createdAt: new Date("2026-03-07T00:00:00.000Z"),
updatedAt: new Date("2026-03-07T00:00:00.000Z"),
};
const createdJoinRequest = {
id: "join-1",
inviteId: "invite-1",
companyId: "company-1",
requestType: "human",
status: "pending_approval",
requestIp: "::ffff:127.0.0.1",
requestingUserId: "invitee-user",
requestEmailSnapshot: "invitee@example.com",
agentName: null,
adapterType: null,
capabilities: null,
agentDefaultsPayload: null,
claimSecretHash: null,
claimSecretExpiresAt: null,
claimSecretConsumedAt: null,
createdAgentId: null,
approvedByUserId: null,
approvedAt: null,
rejectedByUserId: null,
rejectedAt: null,
createdAt: new Date("2026-03-07T00:01:00.000Z"),
updatedAt: new Date("2026-03-07T00:01:00.000Z"),
};
const approvedJoinRequest = {
...createdJoinRequest,
status: "approved",
approvedByUserId: "inviter-user",
approvedAt: new Date("2026-03-07T00:02:00.000Z"),
updatedAt: new Date("2026-03-07T00:02:00.000Z"),
};
const selectResponses = [
[invite],
[{ email: "invitee@example.com" }],
[],
];
const updateResponses = [[], [approvedJoinRequest]];
const insertResponses = [[createdJoinRequest]];
const db = {
select() {
return createQuery(selectResponses.shift() ?? []);
},
update() {
return createQuery(updateResponses.shift() ?? [], {
onSet: (value) => updateValues.push(value),
});
},
insert() {
return createQuery(insertResponses.shift() ?? [], {
onValues: (value) => insertedValues.push(value),
});
},
transaction(callback: (tx: unknown) => unknown) {
return callback(db);
},
};
return { db, insertedValues, updateValues };
}
function createAcceptedHumanInviteReplayDbStub() {
const updateValues: unknown[] = [];
const invite = {
id: "invite-1",
companyId: "company-1",
inviteType: "company_join",
allowedJoinTypes: "human",
tokenHash: "hash",
defaultsPayload: { human: { role: "operator" } },
expiresAt: new Date("2027-03-10T00:00:00.000Z"),
invitedByUserId: "inviter-user",
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 pendingJoinRequest = {
id: "join-1",
inviteId: "invite-1",
companyId: "company-1",
requestType: "human",
status: "pending_approval",
requestIp: "::ffff:127.0.0.1",
requestingUserId: "invitee-user",
requestEmailSnapshot: "invitee@example.com",
agentName: null,
adapterType: null,
capabilities: null,
agentDefaultsPayload: null,
claimSecretHash: null,
claimSecretExpiresAt: null,
claimSecretConsumedAt: null,
createdAgentId: null,
approvedByUserId: null,
approvedAt: null,
rejectedByUserId: null,
rejectedAt: null,
createdAt: new Date("2026-03-07T00:01:00.000Z"),
updatedAt: new Date("2026-03-07T00:01:00.000Z"),
};
const replayedJoinRequest = {
...pendingJoinRequest,
requestIp: "::ffff:127.0.0.1",
updatedAt: new Date("2026-03-07T00:06:00.000Z"),
};
const approvedJoinRequest = {
...replayedJoinRequest,
status: "approved",
approvedByUserId: "inviter-user",
approvedAt: new Date("2026-03-07T00:07:00.000Z"),
updatedAt: new Date("2026-03-07T00:07:00.000Z"),
};
const selectResponses = [
[invite],
[pendingJoinRequest],
[{ email: "invitee@example.com" }],
[pendingJoinRequest],
];
const updateResponses = [[replayedJoinRequest], [approvedJoinRequest]];
const db = {
select() {
return createQuery(selectResponses.shift() ?? []);
},
update() {
return createQuery(updateResponses.shift() ?? [], {
onSet: (value) => updateValues.push(value),
});
},
insert: vi.fn(),
transaction(callback: (tx: unknown) => unknown) {
return callback(db);
},
};
return { db, updateValues };
}
describe("POST /invites/:token/accept", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -123,4 +314,126 @@ describe("POST /invites/:token/accept", () => {
expect(res.body.error).toBe("You already belong to this company");
expect(updateMock).not.toHaveBeenCalled();
});
it("grants company access immediately for a human invite", async () => {
const { db, insertedValues, updateValues } = createDirectHumanInviteDbStub();
const app = createAppWithActor(db, {
type: "board",
source: "session",
userId: "invitee-user",
companyIds: [],
memberships: [],
});
const res = await request(app)
.post("/api/invites/pcp_invite_test/accept")
.send({ requestType: "human" });
expect(res.status).toBe(202);
expect(res.body.status).toBe("approved");
expect(insertedValues).toEqual([
expect.objectContaining({
inviteId: "invite-1",
companyId: "company-1",
requestType: "human",
status: "pending_approval",
requestingUserId: "invitee-user",
requestEmailSnapshot: "invitee@example.com",
}),
]);
expect(updateValues).toEqual(
expect.arrayContaining([
expect.objectContaining({
acceptedAt: expect.any(Date),
}),
expect.objectContaining({
status: "approved",
approvedByUserId: "inviter-user",
approvedAt: expect.any(Date),
}),
]),
);
expect(accessServiceMock.ensureMembership).toHaveBeenCalledWith(
"company-1",
"user",
"invitee-user",
"owner",
"active",
);
expect(accessServiceMock.setPrincipalGrants).toHaveBeenCalledWith(
"company-1",
"user",
"invitee-user",
expect.arrayContaining([
expect.objectContaining({ permissionKey: "users:invite" }),
expect.objectContaining({ permissionKey: "users:manage_permissions" }),
]),
"inviter-user",
);
expect(logActivityMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "join.approved",
entityId: "join-1",
details: expect.objectContaining({ source: "human_invite_accept" }),
}),
);
});
it("replays a consumed human invite for the same user and repairs company access", async () => {
const { db, updateValues } = createAcceptedHumanInviteReplayDbStub();
const app = createAppWithActor(db, {
type: "board",
source: "session",
userId: "invitee-user",
companyIds: [],
memberships: [],
});
const res = await request(app)
.post("/api/invites/pcp_invite_test/accept")
.send({ requestType: "human" });
expect(res.status).toBe(202);
expect(res.body.status).toBe("approved");
expect(updateValues).toEqual(
expect.arrayContaining([
expect.objectContaining({
requestIp: expect.any(String),
updatedAt: expect.any(Date),
}),
expect.objectContaining({
status: "approved",
approvedByUserId: "inviter-user",
approvedAt: expect.any(Date),
}),
]),
);
expect(updateValues).not.toEqual(
expect.arrayContaining([expect.objectContaining({ acceptedAt: expect.any(Date) })]),
);
expect(accessServiceMock.ensureMembership).toHaveBeenCalledWith(
"company-1",
"user",
"invitee-user",
"operator",
"active",
);
expect(logActivityMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "join.request_replayed",
entityId: "join-1",
details: expect.objectContaining({ inviteReplay: true }),
}),
);
expect(logActivityMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "join.approved",
entityId: "join-1",
details: expect.objectContaining({ source: "human_invite_accept" }),
}),
);
});
});
@@ -0,0 +1,49 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import express from "express";
import request from "supertest";
import { afterEach, describe, expect, it } from "vitest";
import { readBrandedStaticIndexHtml } from "../static-index-html.js";
describe("static SPA fallback HTML", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("serves the current index.html instead of reusing stale asset hashes", async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-static-index-"));
tempDirs.push(tempDir);
const indexPath = path.join(tempDir, "index.html");
const app = express();
app.get(/.*/, (_req, res) => {
res
.status(200)
.set("Content-Type", "text/html")
.set("Cache-Control", "no-cache")
.end(readBrandedStaticIndexHtml(tempDir));
});
fs.writeFileSync(
indexPath,
'<html><body><script type="module" src="/assets/index-old.js"></script></body></html>',
"utf8",
);
await expect(request(app).get("/PAP/issues/PAP-9939")).resolves.toMatchObject({
text: expect.stringContaining("/assets/index-old.js"),
});
fs.writeFileSync(
indexPath,
'<html><body><script type="module" src="/assets/index-new.js"></script></body></html>',
"utf8",
);
const res = await request(app).get("/PAP/issues/PAP-9939");
expect(res.text).toContain("/assets/index-new.js");
expect(res.text).not.toContain("/assets/index-old.js");
});
});
@@ -210,6 +210,56 @@ describe("worktree config repair", () => {
expect(repairedConfig.database.embeddedPostgresPort).toBe(54331);
});
it("ignores stale migrated env paths when the dev runner resolved the local config", async () => {
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-worktree-migrated-env-"));
const worktreeRoot = path.join(tempRoot, "PAP-9940-what-can-we-learn");
const paperclipDir = path.join(worktreeRoot, ".paperclip");
const configPath = path.join(paperclipDir, "config.json");
const envPath = path.join(paperclipDir, ".env");
const oldHome = "/old/home/.paperclip-worktrees";
const isolatedHome = path.join(tempRoot, ".paperclip-worktrees");
await fs.mkdir(paperclipDir, { recursive: true });
await fs.writeFile(configPath, JSON.stringify(buildLegacyConfig(oldHome), null, 2) + "\n", "utf8");
await fs.writeFile(
envPath,
[
"# Paperclip environment variables",
"PAPERCLIP_HOME=/old/home/.paperclip-worktrees",
"PAPERCLIP_INSTANCE_ID=pap-9940-what-can-we-learn",
"PAPERCLIP_CONFIG=/old/home/paperclip/.paperclip/worktrees/PAP-9940-what-can-we-learn/.paperclip/config.json",
"PAPERCLIP_CONTEXT=/old/home/.paperclip-worktrees/context.json",
"PAPERCLIP_IN_WORKTREE=true",
"PAPERCLIP_WORKTREE_NAME=PAP-9940-what-can-we-learn",
"",
].join("\n"),
"utf8",
);
process.chdir(worktreeRoot);
process.env.PAPERCLIP_IN_WORKTREE = "true";
process.env.PAPERCLIP_CONFIG = configPath;
process.env.PAPERCLIP_WORKTREES_DIR = isolatedHome;
delete process.env.PAPERCLIP_HOME;
delete process.env.PAPERCLIP_INSTANCE_ID;
delete process.env.PAPERCLIP_CONTEXT;
const result = maybeRepairLegacyWorktreeConfigAndEnvFiles();
const repairedConfig = JSON.parse(await fs.readFile(configPath, "utf8"));
const repairedEnv = await fs.readFile(envPath, "utf8");
const instanceRoot = path.join(isolatedHome, "instances", "pap-9940-what-can-we-learn");
expect(result).toEqual({
repairedConfig: true,
repairedEnv: true,
});
expect(repairedConfig.database.embeddedPostgresDataDir).toBe(path.join(instanceRoot, "db"));
expect(repairedConfig.secrets.localEncrypted.keyFilePath).toBe(path.join(instanceRoot, "secrets", "master.key"));
expect(repairedEnv).toContain(`PAPERCLIP_HOME=${JSON.stringify(isolatedHome)}`);
expect(repairedEnv).toContain(`PAPERCLIP_CONFIG=${JSON.stringify(configPath)}`);
expect(repairedEnv).not.toContain("/old/home");
});
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");
@@ -508,6 +558,8 @@ describe("worktree config repair", () => {
process.env.PAPERCLIP_HOME = isolatedHome;
process.env.PAPERCLIP_INSTANCE_ID = "pap-878-create-a-mine-tab-in-inbox";
process.env.PAPERCLIP_CONFIG = configPath;
delete process.env.PORT;
delete process.env.DATABASE_URL;
maybePersistWorktreeRuntimePorts({
serverPort: 3103,
@@ -590,6 +642,8 @@ describe("worktree config repair", () => {
process.env.PAPERCLIP_HOME = isolatedHome;
process.env.PAPERCLIP_INSTANCE_ID = "pap-125-public-base-url";
process.env.PAPERCLIP_CONFIG = configPath;
delete process.env.PORT;
delete process.env.DATABASE_URL;
maybePersistWorktreeRuntimePorts({
serverPort: 3103,
+2 -2
View File
@@ -41,6 +41,7 @@ import { accessRoutes } from "./routes/access.js";
import { pluginRoutes } from "./routes/plugins.js";
import { adapterRoutes } from "./routes/adapters.js";
import { pluginUiStaticRoutes } from "./routes/plugin-ui-static.js";
import { readBrandedStaticIndexHtml } from "./static-index-html.js";
import { applyUiBranding } from "./ui-branding.js";
import { logger } from "./middleware/logger.js";
import { DEFAULT_LOCAL_PLUGIN_DIR, pluginLoader } from "./services/plugin-loader.js";
@@ -328,7 +329,6 @@ export async function createApp(
];
const uiDist = candidates.find((p) => fs.existsSync(path.join(p, "index.html")));
if (uiDist) {
const indexHtml = applyUiBranding(fs.readFileSync(path.join(uiDist, "index.html"), "utf-8"));
// Hashed asset files (Vite emits them under /assets/<name>.<hash>.<ext>)
// never change once built, so they can be cached aggressively.
app.use(
@@ -368,7 +368,7 @@ export async function createApp(
.status(200)
.set("Content-Type", "text/html")
.set("Cache-Control", "no-cache")
.end(indexHtml);
.end(readBrandedStaticIndexHtml(uiDist));
});
} else {
console.warn("[paperclip] UI dist not found; running in API-only mode");
+27 -7
View File
@@ -44,13 +44,26 @@ export function buildBetterAuthAdvancedOptions(input: { disableSecureCookies: bo
};
}
export function shouldDisableSecureAuthCookies(config: Config): boolean {
const configuredPublicUrl = (
process.env.PAPERCLIP_PUBLIC_URL?.trim() ||
(config.authBaseUrlMode === "explicit" ? config.authPublicBaseUrl?.trim() : "")
export function shouldDisableSecureAuthCookies(input: {
deploymentMode: Config["deploymentMode"];
deploymentExposure?: Config["deploymentExposure"];
authBaseUrlMode: Config["authBaseUrlMode"];
authPublicBaseUrl: string | undefined;
publicUrl?: string | undefined;
}): boolean {
const publicUrl = (
input.publicUrl?.trim() ||
(input.authBaseUrlMode === "explicit" ? input.authPublicBaseUrl?.trim() : "")
);
if (publicUrl) return publicUrl.startsWith("http://");
return (
input.deploymentMode === "authenticated" &&
(
(input.deploymentExposure === "private" && input.authBaseUrlMode === "auto") ||
input.deploymentExposure === undefined
)
);
if (!configuredPublicUrl) return true;
return configuredPublicUrl.startsWith("http://");
}
function headersFromNodeHeaders(rawHeaders: IncomingHttpHeaders): Headers {
@@ -101,6 +114,7 @@ export function deriveAuthTrustedOrigins(config: Config, opts?: { listenPort?: n
export function createBetterAuthInstance(db: Db, config: Config, trustedOrigins: string[]): BetterAuthInstance {
const baseUrl = config.authBaseUrlMode === "explicit" ? config.authPublicBaseUrl : undefined;
const publicUrl = process.env.PAPERCLIP_PUBLIC_URL?.trim() || baseUrl;
const secret = process.env.BETTER_AUTH_SECRET ?? process.env.PAPERCLIP_AGENT_JWT_SECRET;
if (!secret) {
throw new Error(
@@ -108,7 +122,13 @@ export function createBetterAuthInstance(db: Db, config: Config, trustedOrigins:
"For local development, set BETTER_AUTH_SECRET=paperclip-dev-secret in your .env file.",
);
}
const disableSecureCookies = shouldDisableSecureAuthCookies(config);
const disableSecureCookies = shouldDisableSecureAuthCookies({
deploymentMode: config.deploymentMode,
deploymentExposure: config.deploymentExposure,
authBaseUrlMode: config.authBaseUrlMode,
authPublicBaseUrl: config.authPublicBaseUrl,
publicUrl,
});
const authConfig = {
baseURL: baseUrl,
+45 -1
View File
@@ -1,4 +1,5 @@
import { existsSync, lstatSync, readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
function parseEnvFile(contents: string): Record<string, string> {
@@ -55,6 +56,45 @@ export function resolveWorktreeEnvFilePath(rootDir: string): string {
return path.resolve(rootDir, ".paperclip", ".env");
}
function expandHomePrefix(value: string): string {
if (value === "~") return os.homedir();
if (value.startsWith("~/")) return path.resolve(os.homedir(), value.slice(2));
return value;
}
function resolveHomeAwarePath(value: string): string {
return path.resolve(expandHomePrefix(value));
}
function resolveDefaultWorktreeHome(env: NodeJS.ProcessEnv): string {
return path.resolve(expandHomePrefix(env.PAPERCLIP_WORKTREES_DIR?.trim() || "~/.paperclip-worktrees"));
}
function repairStaleMigratedWorktreeEnvEntries(
rootDir: string,
entries: Record<string, string>,
env: NodeJS.ProcessEnv,
): Record<string, string> {
const localConfigPath = path.resolve(rootDir, ".paperclip", "config.json");
const configuredPath = entries.PAPERCLIP_CONFIG?.trim();
if (!configuredPath) return entries;
const resolvedConfiguredPath = resolveHomeAwarePath(configuredPath);
const staleConfigPath =
resolvedConfiguredPath !== localConfigPath &&
!existsSync(resolvedConfiguredPath) &&
existsSync(localConfigPath);
if (!staleConfigPath) return entries;
const homeDir = resolveDefaultWorktreeHome(env);
return {
...entries,
PAPERCLIP_HOME: homeDir,
PAPERCLIP_CONFIG: localConfigPath,
PAPERCLIP_CONTEXT: path.resolve(homeDir, "context.json"),
};
}
export function bootstrapDevRunnerWorktreeEnv(
rootDir: string,
env: NodeJS.ProcessEnv = process.env,
@@ -74,7 +114,11 @@ export function bootstrapDevRunnerWorktreeEnv(
};
}
const entries = parseEnvFile(readFileSync(envPath, "utf8"));
const entries = repairStaleMigratedWorktreeEnvEntries(
rootDir,
parseEnvFile(readFileSync(envPath, "utf8")),
env,
);
for (const [key, value] of Object.entries(entries)) {
if (typeof env[key] === "string" && env[key]!.trim().length > 0) continue;
env[key] = value;
+105 -4
View File
@@ -2721,6 +2721,83 @@ export function accessRoutes(
return { token, created, normalizedAgentMessage };
}
async function approveHumanJoinRequestFromInvite(input: {
req: Request;
invite: typeof invites.$inferSelect;
joinRequest: typeof joinRequests.$inferSelect;
companyId: string;
}) {
if (input.joinRequest.requestType !== "human") {
throw badRequest("Only human join requests can be approved through a human invite");
}
if (!input.joinRequest.requestingUserId) {
throw conflict("Join request missing user identity");
}
const membershipRole = resolveHumanInviteRole(
input.invite.defaultsPayload as Record<string, unknown> | null,
);
await access.ensureMembership(
input.companyId,
"user",
input.joinRequest.requestingUserId,
membershipRole,
"active",
);
const grants = humanJoinGrantsFromDefaults(
input.invite.defaultsPayload as Record<string, unknown> | null,
membershipRole,
);
await access.setPrincipalGrants(
input.companyId,
"user",
input.joinRequest.requestingUserId,
grants,
input.invite.invitedByUserId ?? null,
);
if (input.joinRequest.status === "approved") {
return input.joinRequest;
}
const approvedAt = new Date();
const approvedByUserId =
input.invite.invitedByUserId ?? (isLocalImplicit(input.req) ? "local-board" : null);
const approved = await db
.update(joinRequests)
.set({
status: "approved",
approvedByUserId,
approvedAt,
updatedAt: approvedAt,
})
.where(eq(joinRequests.id, input.joinRequest.id))
.returning()
.then((rows) => rows[0] ?? null);
await logActivity(db, {
companyId: input.companyId,
actorType: "user",
actorId: approvedByUserId ?? "board",
action: "join.approved",
entityType: "join_request",
entityId: input.joinRequest.id,
details: {
requestType: "human",
inviteId: input.invite.id,
source: "human_invite_accept",
},
});
return approved ?? {
...input.joinRequest,
status: "approved",
approvedByUserId,
approvedAt,
updatedAt: approvedAt,
};
}
async function getInviteCompanyBranding(
companyId: string | null,
inviteToken: string | null = null,
@@ -3255,9 +3332,26 @@ export function accessRoutes(
}
}
const actorEmail =
requestType === "human" ? await resolveActorEmail(db, req) : null;
const actorRequestingUserId =
requestType === "human"
? req.actor.userId ?? "local-board"
: null;
const canReplayHumanInviteAccept =
inviteAlreadyAccepted &&
requestType === "human" &&
existingJoinRequestForInvite?.requestType === "human" &&
Boolean(
findReusableHumanJoinRequest([existingJoinRequestForInvite], {
requestingUserId: actorRequestingUserId,
requestEmailSnapshot: actorEmail,
})
);
const adapterType = req.body.adapterType ?? null;
if (
inviteAlreadyAccepted &&
!canReplayHumanInviteAccept &&
!canReplayOpenClawGatewayInviteAccept({
requestType,
adapterType,
@@ -3336,8 +3430,6 @@ export function accessRoutes(
? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
: null;
const actorEmail =
requestType === "human" ? await resolveActorEmail(db, req) : null;
const existingHumanJoinRequest =
requestType === "human"
? findReusableHumanJoinRequest(
@@ -3352,12 +3444,12 @@ export function accessRoutes(
)
.orderBy(desc(joinRequests.createdAt)),
{
requestingUserId: req.actor.userId ?? "local-board",
requestingUserId: actorRequestingUserId,
requestEmailSnapshot: actorEmail
}
)
: null;
const created = !inviteAlreadyAccepted
let created = !inviteAlreadyAccepted
? existingHumanJoinRequest
? await db.transaction(async (tx) => {
await tx
@@ -3566,6 +3658,15 @@ export function accessRoutes(
}
});
if (requestType === "human") {
created = await approveHumanJoinRequestFromInvite({
req,
invite,
joinRequest: created,
companyId,
});
}
const response = toJoinRequestResponse(created);
if (claimSecret) {
const companyBranding = await getInviteCompanyBranding(invite.companyId);
+11
View File
@@ -103,6 +103,7 @@ type UpstreamTransferManifest = {
idempotencyKey: string;
generatedAt: string;
entityCount: number;
perEntityTypeCounts: Record<string, number>;
entities: UpstreamTransferEntityRecord[];
chunks: Array<Omit<LocalUpstreamExportChunk, "payload"> & { manifestHash: NormalizedSha256 }>;
warnings: UpstreamTransferWarning[];
@@ -914,6 +915,7 @@ function buildLocalUpstreamExportBundle(input: {
idempotencyKey: input.idempotencyKey,
generatedAt: new Date(0).toISOString(),
entityCount: entities.length,
perEntityTypeCounts: countEntityTypesForManifest(entities),
entities: entities.map((entity) => entity.record),
chunks: chunksWithoutManifestHash.map(({ payload: _payload, ...chunk }) => chunk),
warnings: input.warnings ?? [],
@@ -931,6 +933,15 @@ function buildLocalUpstreamExportBundle(input: {
};
}
function countEntityTypesForManifest(entities: LocalUpstreamExportEntity[]): Record<string, number> {
const counts: Record<string, number> = {};
for (const entity of entities) {
const entityType = entity.record.key.sourceEntityType;
counts[entityType] = (counts[entityType] ?? 0) + 1;
}
return counts;
}
function buildLocalChunks(entities: LocalUpstreamExportEntity[], maxEntitiesPerChunk: number): LocalUpstreamExportChunk[] {
if (!Number.isInteger(maxEntitiesPerChunk) || maxEntitiesPerChunk < 1) {
throw new Error("maxEntitiesPerChunk must be a positive integer");
+14 -2
View File
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { and, desc, eq, inArray } from "drizzle-orm";
import { and, desc, eq, inArray, isNull } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { executionWorkspaces, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import type {
@@ -344,12 +344,18 @@ function toExecutionWorkspace(
};
}
function toExecutionWorkspaceSummary(row: Pick<ExecutionWorkspaceRow, "id" | "name" | "mode" | "projectWorkspaceId">): ExecutionWorkspaceSummary {
function toExecutionWorkspaceSummary(
row: Pick<ExecutionWorkspaceRow, "id" | "name" | "mode" | "status" | "cwd" | "branchName" | "projectWorkspaceId" | "lastUsedAt">,
): ExecutionWorkspaceSummary {
return {
id: row.id,
name: row.name,
mode: row.mode as ExecutionWorkspaceSummary["mode"],
status: row.status as ExecutionWorkspaceSummary["status"],
cwd: row.cwd ?? null,
branchName: row.branchName ?? null,
projectWorkspaceId: row.projectWorkspaceId ?? null,
lastUsedAt: row.lastUsedAt,
};
}
@@ -412,6 +418,8 @@ export function executionWorkspaceService(db: Db) {
}
if (filters?.reuseEligible) {
conditions.push(inArray(executionWorkspaces.status, ["active", "idle", "in_review"]));
conditions.push(isNull(executionWorkspaces.closedAt));
conditions.push(inArray(executionWorkspaces.mode, ["isolated_workspace", "operator_branch", "adapter_managed", "cloud_sandbox"]));
}
return conditions;
}
@@ -452,7 +460,11 @@ export function executionWorkspaceService(db: Db) {
id: executionWorkspaces.id,
name: executionWorkspaces.name,
mode: executionWorkspaces.mode,
status: executionWorkspaces.status,
cwd: executionWorkspaces.cwd,
branchName: executionWorkspaces.branchName,
projectWorkspaceId: executionWorkspaces.projectWorkspaceId,
lastUsedAt: executionWorkspaces.lastUsedAt,
})
.from(executionWorkspaces)
.where(and(...conditions))
+3 -1
View File
@@ -559,7 +559,9 @@ export function createPluginWorkerHandle(
(message as { paperclipInvocationId?: unknown }).paperclipInvocationId,
);
if (!invocationId) {
return activeInvocations.size > 0 ? { invalidInvocationScope: true } : {};
const hasActiveInvocation = activeInvocations.size > 0 ||
Array.from(pendingRequests.values()).some((pending) => pending.invocationId);
return hasActiveInvocation ? { invalidInvocationScope: true } : {};
}
const entry = activeInvocations.get(invocationId);
if (!entry) return { invalidInvocationScope: true };
+7
View File
@@ -0,0 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { applyUiBranding } from "./ui-branding.js";
export function readBrandedStaticIndexHtml(uiDist: string): string {
return applyUiBranding(fs.readFileSync(path.join(uiDist, "index.html"), "utf-8"));
}
+9 -3
View File
@@ -115,17 +115,23 @@ function resolveWorktreeRuntimeContext(
const configPath = resolvePaperclipConfigPath(overrideConfigPath);
const envPath = resolvePaperclipEnvPath(configPath);
const persistedEnv = readEnvEntries(envPath);
const persistedConfigPath = nonEmpty(persistedEnv.PAPERCLIP_CONFIG);
const persistedConfigLooksStale =
persistedConfigPath !== null &&
path.resolve(expandHomePrefix(persistedConfigPath)) !== path.resolve(configPath) &&
!fs.existsSync(resolveHomeAwarePath(persistedConfigPath));
const stablePersistedEnv = persistedConfigLooksStale ? {} : persistedEnv;
const worktreeRoot = path.resolve(path.dirname(configPath), "..");
const worktreeName =
nonEmpty(persistedEnv.PAPERCLIP_WORKTREE_NAME) ??
nonEmpty(stablePersistedEnv.PAPERCLIP_WORKTREE_NAME) ??
nonEmpty(env.PAPERCLIP_WORKTREE_NAME) ??
path.basename(worktreeRoot);
const instanceId =
nonEmpty(persistedEnv.PAPERCLIP_INSTANCE_ID) ??
nonEmpty(stablePersistedEnv.PAPERCLIP_INSTANCE_ID) ??
nonEmpty(env.PAPERCLIP_INSTANCE_ID) ??
sanitizeWorktreeInstanceId(worktreeName);
const homeDir = resolveHomeAwarePath(
nonEmpty(persistedEnv.PAPERCLIP_HOME) ??
nonEmpty(stablePersistedEnv.PAPERCLIP_HOME) ??
nonEmpty(env.PAPERCLIP_HOME) ??
nonEmpty(env.PAPERCLIP_WORKTREES_DIR) ??
"~/.paperclip-worktrees",