Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions contracts/agent-procedures.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,19 @@
"type": "array",
"items": {
"type": "string"
},
"default": []
},
"emails": {
"type": "array",
"items": {
"type": "string",
"format": "email"
}
}
},
"required": [
"actionId",
"userIds"
"actionId"
]
}
},
Expand Down
183 changes: 183 additions & 0 deletions src/server/api/routers/__tests__/action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1886,6 +1886,189 @@ describe("action router (mocked)", () => {
});
});

// ────────────────────────────────────────────────────────────────────
// Assignees by email, and clearing them (CLI / MCP / agents)
//
// Callers outside the UI know a colleague's email, not their CUID. An email
// must reach no further than an id: it resolves to a user, then the same
// containment check runs, and an unregistered address fails exactly like a
// registered one that is not assignable here.
// ────────────────────────────────────────────────────────────────────
describe("assignees by email and clear", () => {
const callerId = "caller-1";
const workspaceId = "w1";
const actionId = "a1";
const jamesId = "user-james";

/** A project-less action in `workspaceId`; `members` are the users with
* a WorkspaceUser row in `workspaceId` (any other workspace is ignored). */
function stubAction(members: string[]) {
dbMock.action.findUnique.mockResolvedValue({
id: actionId, name: "Follow up", projectId: null, project: null,
teamId: null, team: null, workspaceId,
} as never);
dbMock.action.findFirst.mockResolvedValue({ id: actionId } as never);
type MembershipArgs = { where?: { userId_workspaceId?: { userId?: string; workspaceId?: string } } };
dbMock.workspaceUser.findUnique.mockImplementation(((args: MembershipArgs) => {
const key = args?.where?.userId_workspaceId;
return Promise.resolve(
key?.workspaceId === workspaceId && key.userId && members.includes(key.userId)
? { userId: key.userId, workspaceId, role: "member", joinedAt: new Date() }
: null,
);
}) as unknown as typeof dbMock.workspaceUser.findUnique);
dbMock.teamUser.findFirst.mockResolvedValue(null as never);
dbMock.team.findFirst.mockResolvedValue(null as never);
dbMock.externalAgent.findMany.mockResolvedValue([] as never);
}

it("assigns a workspace member by email, case-insensitively", async () => {
stubAction([jamesId]);
dbMock.user.findMany.mockResolvedValue([{ id: jamesId, email: "james@example.com" }] as never);
dbMock.actionAssignee.findMany.mockResolvedValue([]);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await caller.action.assign({ actionId, emails: ["James@Example.com"] });

expect(dbMock.actionAssignee.createMany).toHaveBeenCalledWith({
data: [{ actionId, userId: jamesId }],
skipDuplicates: true,
});
});

it("refuses a registered user who is not a member of the action's workspace", async () => {
stubAction([]);
dbMock.user.findMany.mockResolvedValue([{ id: jamesId, email: "james@example.com" }] as never);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await expect(
caller.action.assign({ actionId, emails: ["james@example.com"] }),
).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(dbMock.actionAssignee.createMany).not.toHaveBeenCalled();
});

it("refuses a member of another workspace (cross-workspace), by id", async () => {
stubAction([]);
// A member of w2 only: the containment lookup is keyed on w1.
const otherWorkspaceUser = "user-in-w2";

const caller = createMockCaller({ userId: callerId, db: dbMock });
await expect(
caller.action.assign({ actionId, userIds: [otherWorkspaceUser] }),
).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(dbMock.workspaceUser.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: { userId_workspaceId: { userId: otherWorkspaceUser, workspaceId } },
}),
);
expect(dbMock.actionAssignee.createMany).not.toHaveBeenCalled();
});

it("answers an unregistered email exactly like a non-member, so it is no oracle", async () => {
stubAction([]);
const caller = createMockCaller({ userId: callerId, db: dbMock });

dbMock.user.findMany.mockResolvedValue([] as never);
const unknown = await caller.action
.assign({ actionId, emails: ["nobody@example.com"] })
.catch((e: unknown) => e as { code: string; message: string });

dbMock.user.findMany.mockResolvedValue([{ id: jamesId, email: "james@example.com" }] as never);
const nonMember = await caller.action
.assign({ actionId, emails: ["james@example.com"] })
.catch((e: unknown) => e as { code: string; message: string });

expect(unknown).toMatchObject({ code: "NOT_FOUND" });
expect(unknown.message).toBe(nonMember.message);
});

it("refuses an assign naming nobody", async () => {
const caller = createMockCaller({ userId: callerId, db: dbMock });
await expect(caller.action.assign({ actionId })).rejects.toMatchObject({ code: "BAD_REQUEST" });
});

it("unassign all removes every current assignee", async () => {
stubAction([]);
dbMock.actionAssignee.findMany.mockResolvedValue([
{ userId: "u1", user: { email: "a@example.com" } },
{ userId: "u2", user: { email: null } },
] as never);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await caller.action.unassign({ actionId, all: true });

expect(dbMock.actionAssignee.deleteMany).toHaveBeenCalledWith({
where: { actionId, userId: { in: ["u1", "u2"] } },
});
});

it("unassign by email matches current assignees only", async () => {
stubAction([]);
dbMock.actionAssignee.findMany.mockResolvedValue([
{ userId: "u1", user: { email: "a@example.com" } },
{ userId: "u2", user: { email: "b@example.com" } },
] as never);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await caller.action.unassign({ actionId, emails: ["B@example.com", "stranger@example.com"] });

expect(dbMock.user.findMany).not.toHaveBeenCalled();
expect(dbMock.actionAssignee.deleteMany).toHaveBeenCalledWith({
where: { actionId, userId: { in: ["u2"] } },
});
});

it("create with an unregistered assignee email writes nothing", async () => {
stubAction([callerId]);
dbMock.user.findMany.mockResolvedValue([] as never);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await expect(
caller.action.create({ name: "Follow up", workspaceId, assigneeEmails: ["nobody@example.com"] }),
).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(dbMock.action.create).not.toHaveBeenCalled();
});

it("create checks workspace access before any assignee email, so it is no oracle", async () => {
// The caller is not in the workspace. A registered and an unregistered
// email must both get the same authorisation error.
stubAction([]);
const caller = createMockCaller({ userId: callerId, db: dbMock });

dbMock.user.findMany.mockResolvedValue([] as never);
const unknown = await caller.action
.create({ name: "Probe", workspaceId, assigneeEmails: ["nobody@example.com"] })
.catch((e: unknown) => e as { code: string; message: string });

dbMock.user.findMany.mockResolvedValue([{ id: jamesId, email: "james@example.com" }] as never);
const known = await caller.action
.create({ name: "Probe", workspaceId, assigneeEmails: ["james@example.com"] })
.catch((e: unknown) => e as { code: string; message: string });

expect(unknown).toMatchObject({ code: "FORBIDDEN" });
expect(known).toMatchObject({ code: unknown.code, message: unknown.message });
expect(dbMock.action.create).not.toHaveBeenCalled();
});

it("create resolves assignee emails and attaches them in the create", async () => {
stubAction([callerId, jamesId]);
dbMock.user.findMany.mockResolvedValue([{ id: jamesId, email: "james@example.com" }] as never);
dbMock.action.create.mockResolvedValue(
{ id: "a2", name: "Follow up", workspaceId, project: null, assignees: [] } as never,
);
dbMock.action.findUniqueOrThrow.mockResolvedValue(
{ id: "a2", name: "Follow up", workspaceId, project: null, assignees: [{ userId: jamesId }] } as never,
);

const caller = createMockCaller({ userId: callerId, db: dbMock });
await caller.action.create({ name: "Follow up", workspaceId, assigneeEmails: ["james@example.com"] });

expect(dbMock.actionAssignee.createMany).toHaveBeenCalledWith(
expect.objectContaining({ data: [{ actionId: "a2", userId: jamesId }] }),
);
});
});

// ────────────────────────────────────────────────────────────────────
// create / update — workspace write authorisation
//
Expand Down
105 changes: 85 additions & 20 deletions src/server/api/routers/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import {
applyActionUpdate,
assertAssignableUsers,
assertCanWriteToWorkspace,
resolveAssigneeEmails,
assigneeIdsForEmails,
blockedByInclude,
createAction,
isActionSource,
Expand Down Expand Up @@ -474,10 +476,30 @@ export const actionRouter = createTRPCRouter({
// The shared write shape plus the optional attachments: the app sends
// tags, assignees and sprint with the create and gets them in one
// transaction; an external caller may still create and then attach.
.input(actionWriteSchema.merge(actionCreateAttachmentsSchema))
.input(
actionWriteSchema.merge(actionCreateAttachmentsSchema).extend({
/**
* Assignees by email, for callers that know a colleague's address but
* not their id (the CLI, MCP, agents). Resolved to ids and merged with
* `assigneeIds`; the same containment check then applies to both.
*/
assigneeEmails: z.array(z.string().email()).optional(),
}),
)
.mutation(async ({ ctx, input }) => {
// Emails become ids without throwing: `createAction` authorises the
// caller before its containment check, and an unknown email must fail
// there, after authorisation, like any non-assignable user. Refusing it
// here would leak whether an address has an account.
const { assigneeEmails, ...createInput } = input;
const emailAssigneeIds = assigneeEmails?.length
? await assigneeIdsForEmails(ctx.db, assigneeEmails)
: [];
const created = await createAction(actionWriteDeps(ctx), {
...input,
...createInput,
...(emailAssigneeIds.length > 0
? { assigneeIds: Array.from(new Set([...(createInput.assigneeIds ?? []), ...emailAssigneeIds])) }
: {}),
// The *who* is createdById (for an agent, its shadow user; ADR-0049),
// the *how* is source, named from the verified principal.
source: actionSourceForPrincipal(await resolvePrincipal(ctx)),
Expand Down Expand Up @@ -1478,16 +1500,26 @@ export const actionRouter = createTRPCRouter({
};
}),

// Assign users to an action
/**
* Add assignees to an action. Additive and idempotent: users already
* assigned stay, and nobody is removed (`unassign` removes). Pass users by
* id, by email, or both; every one must be assignable in the action's
* project, team or workspace (`assertAssignableUsers`), or the whole call
* is NOT_FOUND and nothing changes.
*/
assign: protectedProcedure
.input(z.object({
actionId: z.string(),
userIds: z.array(z.string()),
userIds: z.array(z.string()).default([]),
/** Resolved case-insensitively to user ids, then checked like `userIds`. */
emails: z.array(z.string().email()).optional(),
}).refine((i) => i.userIds.length > 0 || (i.emails?.length ?? 0) > 0, {
message: "Pass at least one of userIds or emails",
}))
.mutation(async ({ ctx, input }) => {
.mutation(async ({ ctx, input: rawInput }) => {
// Verify the action exists and user has permission to modify it
const action = await ctx.db.action.findUnique({
where: { id: input.actionId },
where: { id: rawInput.actionId },
select: { id: true, projectId: true, teamId: true, workspaceId: true },
});

Expand All @@ -1498,7 +1530,7 @@ export const actionRouter = createTRPCRouter({
// Check if user has permission to modify this action (creator, assignee, or project editor)
const hasPermission = await ctx.db.action.findFirst({
where: {
id: input.actionId,
id: rawInput.actionId,
...buildActionEditWhere(ctx.session.user.id),
},
select: { id: true },
Expand All @@ -1508,19 +1540,23 @@ export const actionRouter = createTRPCRouter({
throw new Error("You don't have permission to modify this action");
}

const scope = {
projectId: action.projectId,
teamId: action.teamId,
workspaceId: action.workspaceId,
};
const emailUserIds = rawInput.emails?.length
? await resolveAssigneeEmails(ctx.db, scope, rawInput.emails)
: [];
const input = {
actionId: rawInput.actionId,
userIds: Array.from(new Set([...rawInput.userIds, ...emailUserIds])),
};

// Same containment rule `createAction` applies to assignees attached on
// create, so attaching later cannot reach further than attaching at
// creation. Rejects with NOT_FOUND and never names the rejected user.
await assertAssignableUsers(
ctx.db,
ctx.session.user.id,
{
projectId: action.projectId,
teamId: action.teamId,
workspaceId: action.workspaceId,
},
input.userIds,
);
await assertAssignableUsers(ctx.db, ctx.session.user.id, scope, input.userIds);

// Snapshot existing assignees so we can compute the diff for activity logging.
const priorAssignees = await ctx.db.actionAssignee.findMany({
Expand Down Expand Up @@ -1604,13 +1640,42 @@ export const actionRouter = createTRPCRouter({
return { ...updated, agentRunsQueued: runs.length };
}),

// Unassign users from an action
/**
* Remove assignees from an action, by id, by email, or `all: true` to clear
* every assignee. Users who are not assigned are ignored. An email is only
* matched against the action's current assignees, so an unknown address is
* a no-op rather than an error that would reveal whether it is registered.
*/
unassign: protectedProcedure
.input(z.object({
actionId: z.string(),
userIds: z.array(z.string()),
userIds: z.array(z.string()).default([]),
emails: z.array(z.string().email()).optional(),
/** Remove every current assignee. */
all: z.boolean().optional(),
}).refine((i) => i.all === true || i.userIds.length > 0 || (i.emails?.length ?? 0) > 0, {
message: "Pass userIds, emails, or all: true",
}))
.mutation(async ({ ctx, input }) => {
.mutation(async ({ ctx, input: rawInput }) => {
// `all` and emails resolve against the current assignees only.
const needsLookup = rawInput.all === true || (rawInput.emails?.length ?? 0) > 0;
const current = needsLookup
? await ctx.db.actionAssignee.findMany({
where: { actionId: rawInput.actionId },
select: { userId: true, user: { select: { email: true } } },
})
: [];
const wantedEmails = new Set((rawInput.emails ?? []).map((e) => e.trim().toLowerCase()));
const resolvedIds = rawInput.all
? current.map((a) => a.userId)
: current
.filter((a) => a.user.email && wantedEmails.has(a.user.email.toLowerCase()))
.map((a) => a.userId);
const input = {
actionId: rawInput.actionId,
userIds: Array.from(new Set([...rawInput.userIds, ...resolvedIds])),
};

// Check if user is removing themselves (self-removal should always be allowed)
const isSelfRemoval = input.userIds.length === 1 && input.userIds[0] === ctx.session.user.id;

Expand Down
Loading
Loading