mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Several setup screens offer "Set it up with your agent": a prompt the person pastes into their own agent (Claude Code, Codex) to do the setup on their computer. AWS role setup is the newest > - Once the prompt is copied, the setup page goes quiet: the person cannot see what their agent is doing or when it is done, and has to switch windows to find out > - The agent already runs commands, so it can report its progress back if we give it a safe place to send it > - This pull request adds a live checklist the agent fills in: the page creates it, the prompt gives the agent curl commands with a token, and the page shows every update as it happens > - The benefit is a setup that shows its own progress, and a reusable piece any "Set it up with your agent" screen can use ## Linked Issues or Issue Description Refs #22233 (the AWS setup screen this extends). **Subsystem affected** Connections (agent-guided setup), live updates, a new public agent API, UI. **Problem or motivation** After a person copies a setup prompt into their own agent, Paperclip shows nothing until they come back and paste a result. There is no way for the agent to say what it is doing. **Proposed solution** A setup checklist a person's own agent writes to, shown live on the setup page. The agent's requests need no Paperclip sign-in, so they carry a narrow, expiring bearer token. Paperclip Cloud needs no front-door change: it already forwards `/api` requests that carry an `Authorization` header to the workspace without Cloud identity (its machine-request lane), and these always do. **Alternatives considered** - Polling the page instead of live events: slower and adds load to every open setup page. The page uses the existing live-event channel, with a 20-second backup refresh while the agent works. - Putting the token in the URL: URLs end up in logs. The token goes in the `Authorization` header. - Letting the agent set the role ARN itself: the person still pastes it (as decided for #22233). The agent's finish summary shows the ARN to copy. ## What Changed - `packages/db`: new `agent_setup_progress` table (company-scoped, purpose and subject, token hash, items, status, summary, update count, expiry). Migration `0501` is idempotent. - `packages/shared`: `agent-setup-progress` types, limits and validators; new live event type `agent_setup_progress.updated`. - `server`: - `agentSetupProgressService`: create (random `pcsp_` token, only its SHA-256 kept), read, and the agent's set-checklist, update-item and finish. Tokens are compared in constant time; a write is refused after expiry (6 hours) or 300 updates, and concurrent writes are guarded by the update counter. Finishing `done` ticks off open steps. - Routes: board-only `POST /api/companies/{companyId}/agent-setup-progress` and `GET /api/agent-setup-progress/{id}`; agent routes `PUT …/checklist`, `POST …/items/{key}` and `POST …/finish` mounted with the other public routes. Activity entries for created, started and finished. - Each agent write publishes `agent_setup_progress.updated`; the live-events socket forwards it with only the checklist ID. - OpenAPI entries for all five routes. - `ui`: - Reusable `ui/src/components/AgentSetupProgress.tsx`: `useAgentSetupProgress` (creates one checklist per setup and follows it), `agentSetupProgressInstructions` (the prompt section with the agent's curl commands) and `AgentSetupProgressPanel` (waiting, working, done and failed states, using the task status glyphs). - `LiveUpdatesProvider` refreshes the checklist on its live event. - AWS role step: one step (no numbering) with the prompt, the live checklist and the Role ARN field. The prompt starts with the progress instructions and asks the agent to put the role ARN in its finish summary. - Docs: `docs/api/agent-setup-progress.md` (API and how to add it to another page) and the AWS setup section. - Storybook: AWS step in waiting, working, done and failed states, and the panel on its own. ## Verification - `server/src/__tests__/agent-setup-progress.test.ts` (real routes, embedded Postgres): set, update and finish with the prompt's token; only the hash is stored; four live events carry the checklist ID; activity entries. Refusals: missing token, wrong token, another checklist's token (401), bad key (400), unknown item (404), update limit (429), expired (410). Company boundary: another company's member gets 403 on read and create. - `live-events-toast.test.ts`: the socket delivers the event with only `{ progressId }`. It failed before the socket fix (red/green), which an end-to-end run found. - `AgentSetupProgress.test.tsx`: the prompt section's exact commands; the hook creates one checklist and the panel follows waiting → working → done on live refreshes. - `AwsRoleSetup.test.tsx`: the step creates the checklist for its connection, waits for the agent, and the prompt leads with progress reporting. - Totals: shared 1362, server (new, OpenAPI, live events, AWS) 101, UI (components, connections, apps, live updates) 1469. Typecheck clean for db, shared, server and UI (except Storybook's generated catalog, not built in this worktree). - End to end on a local instance: Playwright opened the real AWS setup step, read the prompt, sent the agent's requests with its token, and the page showed each update within 1.5 seconds (inside the 20-second backup refresh, so from live events) through "Your agent set up AWS" with the role ARN summary. No page errors. - Not run yet: Paperclip Cloud staging (after deploy) and an agent running the prompt on its own. ## Risks - New anonymous routes. The token is the only credential: 32 random bytes, stored as a hash, scoped to one checklist, six hours, 300 updates. Text from the agent is shown as plain text (no links or markup), so the worst a leaked token can do is change one checklist's wording until it expires. - One new table and migration (idempotent). - Live delivery is per server process, like every other live event; the 20-second refresh covers a missed event. > 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 - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, Storybook and Playwright screenshots, the in-app browser against a local dev server). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
398 lines
22 KiB
TypeScript
398 lines
22 KiB
TypeScript
import { createServer } from "node:http";
|
|
import { once } from "node:events";
|
|
import { getTableName, type SQL } from "drizzle-orm";
|
|
import { PgDialect } from "drizzle-orm/pg-core";
|
|
import { activityToastIdentity } from "../realtime/activity-toast-identity.js";
|
|
import { WebSocket } from "ws";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js";
|
|
import { publishLiveEvent } from "../services/live-events.js";
|
|
import { taskToastEligible } from "../realtime/task-toast-eligibility.js";
|
|
import { idleWorkSnapshot } from "../services/task-admission.js";
|
|
|
|
vi.mock("../realtime/task-toast-eligibility.js", () => ({ taskToastEligible: vi.fn(async () => false) }));
|
|
|
|
vi.mock("../services/authorization.js", () => ({
|
|
authorizationService: () => ({ decide: async ({ resource }: { resource: { issueId: string } }) => ({ allowed: resource.issueId !== "hidden" }) }),
|
|
}));
|
|
vi.mock("../services/heartbeat-run-privacy.js", () => ({
|
|
getHeartbeatRunReadDecisions: async (_db: unknown, _access: unknown, _actor: unknown, runs: { issueId?: string }[]) =>
|
|
runs.map(run => run.issueId !== "hidden"),
|
|
}));
|
|
vi.mock("../services/case-access.js", () => ({
|
|
canActorReadCase: async (_db: unknown, _actor: unknown, record: { id: string }) => record.id !== "hidden-case",
|
|
}));
|
|
function database(onPredicate: (kind: "where" | "join", condition: SQL) => void = () => {}) {
|
|
return { select: (fields: Record<string, unknown> = {}) => {
|
|
let table = "";
|
|
const query = {
|
|
from: (value: Parameters<typeof getTableName>[0]) => { table = getTableName(value); return query; },
|
|
innerJoin: (_table: unknown, condition: SQL) => { onPredicate("join", condition); return query; },
|
|
where: (condition: SQL) => { onPredicate("where", condition); return query; },
|
|
orderBy: () => query,
|
|
then: (resolve: (rows: unknown[]) => unknown) => Promise.resolve(table === "instance_settings"
|
|
? [{ id: "settings", general: { censorUsernameInLogs: false }, experimental: {} }] : []).then(resolve),
|
|
limit: async () => {
|
|
if (table === "issues") return [{ id: "task", identifier: "PAP-1234", title: "Fix task notifications" }];
|
|
if (table === "company_memberships") return fields.name ? [{ name: "Alex Example", image: "/alex.png" }] : [{ id: "membership" }];
|
|
if (table === "issue_comments") return [{ body: "Ready for review" }];
|
|
if (table === "agents") return [{ name: "Coder", appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "bubblegum-sky" } }];
|
|
return [];
|
|
},
|
|
};
|
|
return query;
|
|
} };
|
|
}
|
|
describe("authenticated activity notifications", () => {
|
|
it("retains live delivery idle work until the identifier read settles after the last socket closes", async () => {
|
|
const baseline = idleWorkSnapshot().active;
|
|
let release!: () => void, entered!: () => void;
|
|
const pending = new Promise<void>(resolve => { release = resolve; });
|
|
const started = new Promise<void>(resolve => { entered = resolve; });
|
|
const db = database(), select = db.select;
|
|
db.select = (fields = {}) => {
|
|
const query = select(fields);
|
|
if (fields.identifier) {
|
|
const limit = query.limit;
|
|
query.limit = async () => { entered(); await pending; return limit(); };
|
|
}
|
|
return query;
|
|
};
|
|
const server = createServer();
|
|
const wss = setupLiveEventsWebSocketServer(server, db as never, { deploymentMode: "local_trusted" });
|
|
const closed = new Promise<void>(resolve => wss.on("connection", socket => socket.on("close", resolve)));
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(baseline));
|
|
// System activity has no actor lookup: this gate is the new identifier SQL.
|
|
publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.updated", entityType: "issue", entityId: "visible", actorType: "system",
|
|
} });
|
|
await started;
|
|
socket.terminate();
|
|
await closed;
|
|
expect(wss.clients.size).toBe(0);
|
|
expect(idleWorkSnapshot().active).toBe(baseline + 1);
|
|
release();
|
|
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(baseline));
|
|
} finally {
|
|
release();
|
|
socket.terminate();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(baseline));
|
|
}
|
|
});
|
|
|
|
it.each(["local_trusted", "authenticated"] as const)("keeps authorized notifications when optional identifier reads fail (%s)", async deploymentMode => {
|
|
const db = database();
|
|
const select = db.select;
|
|
const identifierRead = vi.fn();
|
|
db.select = (fields = {}) => {
|
|
if (fields.identifier) {
|
|
identifierRead();
|
|
if (identifierRead.mock.calls.length <= 3) throw new Error("Identifier lookup unavailable");
|
|
}
|
|
return select(fields);
|
|
};
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, db as never, { deploymentMode,
|
|
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const messages: Array<{ payload: Record<string, unknown> }> = [];
|
|
const delivered = new Promise<void>(resolve => socket.on("message", data => {
|
|
const event = JSON.parse(data.toString());
|
|
messages.push(event);
|
|
if (event.payload.entityId === "after-failure") resolve();
|
|
}));
|
|
const activity = (entityId: string, actorType: string) => publishLiveEvent({
|
|
companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.updated", entityType: "issue", entityId, actorType,
|
|
actorId: actorType === "user" ? "viewer" : actorType === "agent" ? "agent" : null,
|
|
issueIdentifier: "SPOOF-1", details: { secret: "private task details" },
|
|
},
|
|
});
|
|
if (deploymentMode === "authenticated") activity("hidden", "system");
|
|
for (const actorType of ["system", "agent", "user"]) {
|
|
activity("visible", actorType);
|
|
}
|
|
activity("after-failure", "system");
|
|
await delivered;
|
|
expect(messages).toHaveLength(4);
|
|
expect(identifierRead).toHaveBeenCalledTimes(4);
|
|
for (const [index, actorType] of ["system", "agent", "user"].entries()) {
|
|
const event = messages[index];
|
|
expect(event.payload).toMatchObject({ entityId: "visible", actorType, issueIdentifier: null });
|
|
if (actorType === "agent") expect(event.payload.actorName).toBe("Coder");
|
|
if (actorType === "user") expect(event.payload.actorName).toBe("Alex Example");
|
|
if (deploymentMode === "authenticated") expect(event.payload).not.toHaveProperty("details");
|
|
// Routine updates are not task identity changes.
|
|
expect(event.payload.taskIdentityChanged).toBe(false);
|
|
}
|
|
expect(messages[3].payload.issueIdentifier).toBe("PAP-1234");
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
}
|
|
});
|
|
|
|
it.each(["authenticated", "local_trusted"] as const)("delivers useful task content through the real socket (%s)", async deploymentMode => {
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode,
|
|
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const messages: Array<{ payload: Record<string, unknown> }> = [];
|
|
socket.on("message", data => messages.push(JSON.parse(data.toString())));
|
|
const activity = (entityId: string, action: string, details: Record<string, unknown>) => publishLiveEvent({
|
|
companyId: "company", type: "activity.logged", payload: {
|
|
action, entityType: "issue", entityId, actorType: "system", issueTitle: "Spoofed title", details,
|
|
notificationDetails: { bodySnippet: "Spoofed preview" },
|
|
},
|
|
});
|
|
const changes = { status: { from: "in_progress", to: "done" }, description: { from: "private old", to: "private new" } };
|
|
if (deploymentMode === "authenticated") activity("hidden", "issue.comment_added", { bodySnippet: "Hidden comment" });
|
|
let delivery = once(socket, "message");
|
|
activity("visible", "issue.updated", { source: "comment", changes, secret: "private token" });
|
|
await delivery;
|
|
delivery = once(socket, "message");
|
|
activity("visible", "issue.comment_added", { commentId: "comment-1", bodySnippet: "Ready for review", changes, secret: "private token" });
|
|
await delivery;
|
|
expect(messages).toHaveLength(2);
|
|
expect(messages[0].payload).toMatchObject({ issueTitle: "Fix task notifications", notificationDetails: {
|
|
source: "comment", status: "done", statusFrom: "in_progress", descriptionChanged: true,
|
|
} });
|
|
expect(messages[1].payload).toMatchObject({ issueTitle: "Fix task notifications", notificationDetails: {
|
|
commentId: "comment-1", bodySnippet: "Ready for review", status: "done", statusFrom: "in_progress", descriptionChanged: true,
|
|
} });
|
|
if (deploymentMode === "authenticated") {
|
|
expect(messages[1].payload).not.toHaveProperty("details");
|
|
expect(JSON.stringify(messages)).not.toMatch(/private token|private old|private new|Spoofed|Hidden comment/);
|
|
}
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
}
|
|
});
|
|
|
|
it("preserves only an authorized handoff task identity for empty case-panel refresh", async () => {
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated",
|
|
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const messages: Array<{ payload: Record<string, unknown> }> = [];
|
|
socket.on("message", data => messages.push(JSON.parse(data.toString())));
|
|
const activity = (entityId: string, issueId: string, action = "case.handoff_applied") => publishLiveEvent({
|
|
companyId: "company", type: "activity.logged", payload: {
|
|
action, entityType: "case", entityId, issueId,
|
|
details: { instructions: "private handoff instructions", phase: "verification" },
|
|
},
|
|
});
|
|
activity("hidden-case", "visible");
|
|
activity("visible-case", "hidden");
|
|
const first = once(socket, "message");
|
|
activity("visible-case", "visible");
|
|
await first;
|
|
expect(messages).toHaveLength(1);
|
|
expect(messages[0].payload).toEqual({ action: "case.handoff_applied", entityType: "case", entityId: "visible-case", issueId: "visible", actorType: null, actorId: null });
|
|
const second = once(socket, "message");
|
|
activity("visible-case", "visible", "case.updated");
|
|
await second;
|
|
expect(messages[1].payload).toEqual({ action: "case.updated", entityType: "case", entityId: "visible-case", actorType: null, actorId: null });
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
}
|
|
});
|
|
|
|
it("delivers an agent setup progress update to the page with only the checklist id", async () => {
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated",
|
|
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const message = once(socket, "message");
|
|
publishLiveEvent({ companyId: "company", type: "agent_setup_progress.updated", payload: { progressId: "progress-1", token: "never-sent" } });
|
|
const [data] = await message;
|
|
const event = JSON.parse(data.toString());
|
|
expect(event).toMatchObject({ type: "agent_setup_progress.updated", payload: { progressId: "progress-1" } });
|
|
expect(event.payload).toEqual({ progressId: "progress-1" });
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
}
|
|
});
|
|
|
|
it("uses the persisted local-board user identity for local task eligibility", async () => {
|
|
vi.mocked(taskToastEligible).mockImplementation(async (_db, _event, userId) => userId === "local-board");
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "local_trusted" });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const delivery = once(socket, "message");
|
|
publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.updated", entityType: "issue", entityId: "visible", actorType: "agent", actorId: "agent",
|
|
} });
|
|
const [data] = await delivery;
|
|
expect(JSON.parse(data.toString()).toastEligible).toBe(true);
|
|
expect(JSON.parse(data.toString()).payload.issueIdentifier).toBe("PAP-1234");
|
|
expect(taskToastEligible).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), "local-board");
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
vi.mocked(taskToastEligible).mockReset().mockResolvedValue(false);
|
|
}
|
|
});
|
|
|
|
it("projects eligibility per viewer and keeps authorized updates on lookup failure", async () => {
|
|
vi.mocked(taskToastEligible).mockImplementation(async (_db, event, userId) => {
|
|
if (event.payload.entityId === "lookup-failure") throw new Error("Relevance unavailable");
|
|
return userId === "alice";
|
|
});
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, {
|
|
deploymentMode: "authenticated",
|
|
resolveCloudActor: async (req) => ({ userId: String(req.headers["x-test-viewer"]), companyIds: ["company"] }),
|
|
});
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const url = `ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`;
|
|
const alice = new WebSocket(url, { headers: { "x-test-viewer": "alice" } });
|
|
const bob = new WebSocket(url, { headers: { "x-test-viewer": "bob" } });
|
|
try {
|
|
await Promise.all([once(alice, "open"), once(bob, "open")]);
|
|
for (const entityId of ["visible", "lookup-failure"]) {
|
|
const deliveries = Promise.all([once(alice, "message"), once(bob, "message")]);
|
|
const original = publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.comment_added", entityType: "issue", entityId, actorType: "agent", actorId: "agent",
|
|
} });
|
|
const [a, b] = (await deliveries).map(([data]) => JSON.parse(data.toString()));
|
|
expect(a.toastEligible).toBe(entityId === "visible");
|
|
expect(b.toastEligible).toBe(false);
|
|
expect(a.payload.entityId).toBe(entityId);
|
|
expect(b.payload.entityId).toBe(entityId);
|
|
expect(a.payload.issueIdentifier).toBe("PAP-1234");
|
|
expect(b.payload.issueIdentifier).toBe("PAP-1234");
|
|
expect(original).not.toHaveProperty("toastEligible");
|
|
}
|
|
} finally {
|
|
alice.terminate(); bob.terminate();
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
vi.mocked(taskToastEligible).mockReset().mockResolvedValue(false);
|
|
}
|
|
});
|
|
|
|
it.each(["authenticated", "local_trusted"] as const)("keeps task and actor identity for %s without exposing hidden tasks or copying private details", async (deploymentMode) => {
|
|
const server = createServer();
|
|
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode,
|
|
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
|
server.listen(0, "127.0.0.1");
|
|
await once(server, "listening");
|
|
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
|
try {
|
|
await once(socket, "open");
|
|
const messages: Array<{ payload: Record<string, unknown> }> = [];
|
|
socket.on("message", (data) => messages.push(JSON.parse(data.toString())));
|
|
const activity = (entityId: string, actorType = "user") => publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.created", entityType: "issue", entityId, actorType, actorId: actorType === "user" ? "viewer" : "agent",
|
|
issueIdentifier: "SPOOF-1", issueTitle: "Untrusted title",
|
|
details: { bodySnippet: "private comment", secret: "not for the socket" },
|
|
} });
|
|
if (deploymentMode === "authenticated") activity("hidden");
|
|
const first = once(socket, "message");
|
|
activity("visible");
|
|
await first;
|
|
expect(messages).toHaveLength(1);
|
|
expect(messages[0].payload).toMatchObject({ action: "issue.created", entityType: "issue", entityId: "visible", issueIdentifier: "PAP-1234", issueTitle: "Fix task notifications", notificationDetails: {}, actorType: "user", actorId: "viewer", actorName: "Alex Example", actorImage: "/alex.png" });
|
|
if (deploymentMode === "authenticated") expect(messages[0].payload).not.toHaveProperty("details");
|
|
const second = once(socket, "message");
|
|
activity("visible", "agent");
|
|
await second;
|
|
expect(messages[1].payload).toMatchObject({ issueIdentifier: "PAP-1234", actorName: "Coder", actorType: "agent", actorId: "agent", actorAppearance: { paletteId: "bubblegum-sky" } });
|
|
if (deploymentMode === "authenticated") expect(messages[1].payload).not.toHaveProperty("details");
|
|
expect(messages[0].payload.taskIdentityChanged).toBe(true);
|
|
const third = once(socket, "message");
|
|
publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {
|
|
action: "issue.updated", entityType: "issue", entityId: "visible", actorType: "user", actorId: "viewer",
|
|
details: { title: "Secret new title", hiddenAt: null },
|
|
} });
|
|
await third;
|
|
expect(messages[2].payload.taskIdentityChanged).toBe(true);
|
|
expect(messages[2].payload.notificationDetails).toEqual({ titleChanged: true });
|
|
if (deploymentMode === "authenticated") expect(JSON.stringify(messages[2].payload)).not.toContain("Secret new title");
|
|
} finally {
|
|
socket.terminate();
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
}
|
|
});
|
|
});
|
|
|
|
|
|
describe("activity profile query boundaries", () => {
|
|
it("reads the task identifier within its company even when there is no actor", async () => {
|
|
const predicates: { sql: string; params: unknown[] }[] = [];
|
|
const db = database((_kind, condition) => {
|
|
const { sql, params } = new PgDialect().sqlToQuery(condition);
|
|
predicates.push({ sql, params });
|
|
});
|
|
expect(await activityToastIdentity(db as never, "company-A", {
|
|
action: "issue.updated", entityType: "issue", entityId: "task-A", actorType: "system",
|
|
})).toMatchObject({ issueIdentifier: "PAP-1234" });
|
|
expect(predicates[0]).toEqual({ sql: '("issues"."company_id" = $1 and "issues"."id" = $2)', params: ["company-A", "task-A"] });
|
|
expect(predicates).toHaveLength(4);
|
|
expect(predicates[1].params).toEqual(["company-A", "task-A"]);
|
|
expect(predicates[2].params).toEqual(["company-A", "task-A"]);
|
|
expect(predicates[3]).toEqual({ sql: '"instance_settings"."singleton_key" = $1', params: ["default"] });
|
|
});
|
|
|
|
it("requires the exact company, human actor, and active membership before reading a person profile", async () => {
|
|
const predicates: { kind: string; sql: string; params: unknown[] }[] = [];
|
|
const db = database((kind, condition) => {
|
|
const { sql, params } = new PgDialect().sqlToQuery(condition);
|
|
predicates.push({ kind, sql, params });
|
|
});
|
|
await activityToastIdentity(db as never, "company-A", {
|
|
action: "issue.created", actorType: "user", actorId: "person-A",
|
|
});
|
|
expect(predicates).toEqual([
|
|
{ kind: "join", sql: '"user"."id" = "company_memberships"."principal_id"', params: [] },
|
|
{ kind: "where", sql: '("company_memberships"."company_id" = $1 and "company_memberships"."principal_type" = $2 and "company_memberships"."principal_id" = $3 and "company_memberships"."status" = $4)',
|
|
params: ["company-A", "user", "person-A", "active"] },
|
|
]);
|
|
});
|
|
|
|
it("requires both the exact company and agent ID before reading an agent profile", async () => {
|
|
const predicates: { kind: string; sql: string; params: unknown[] }[] = [];
|
|
const db = database((kind, condition) => {
|
|
const { sql, params } = new PgDialect().sqlToQuery(condition);
|
|
predicates.push({ kind, sql, params });
|
|
});
|
|
await activityToastIdentity(db as never, "company-A", {
|
|
action: "issue.created", actorType: "agent", actorId: "agent-A",
|
|
});
|
|
expect(predicates).toEqual([
|
|
{ kind: "where", sql: '("agents"."company_id" = $1 and "agents"."id" = $2)',
|
|
params: ["company-A", "agent-A"] },
|
|
]);
|
|
});
|
|
});
|