Files
PaperClipAI/server/src/services/headless-channel-write-helpers.ts
T
DottaandPaperclip debfa75a7a perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels and thread replies let many agents publish
concurrent updates, tasks, and replies into shared company streams while
preserving gapless company identifiers and commit-ordered board events
> - After PR #23426 removed per-request query overhead, a fresh local
headless benchmark on merged `origin/master` (`ab2183aaed`) showed
concurrent post throughput hitting a serialization wall at 770–805 req/s
(`c=32`) and degrading to 653 req/s (`p99 = 295.9ms`) at `c=64` on a
single channel
> - Profiling showed why: every concurrent post or reply entered its own
database transaction and blocked sequentially on `UPDATE companies`,
`UPDATE channels`, and `pg_advisory_xact_lock('board_events',
company_id)`, pinning PostgreSQL pool connections and performing N
separate WAL flushes for N concurrent arrivals
> - This pull request adds adaptive in-process group commit for
non-idempotent channel posts and normal thread comments, a 250ms
debounce on `channels.last_activity_at` updates, and multi-row
`activity_log` and `board_events` batch helpers
> - The benefit is zero batching delay when idle (`442.7 req/s`, `p50 =
2.12ms` at `c=1`), `2.40x–2.55x` higher post throughput at `c=32`
(`1,849–2,055 req/s`), `3.11x–3.79x` higher post throughput at `c=64`
(`2,475–2,501 req/s`, `p99` down 85.5%), and `2.24x` higher hot-thread
reply throughput (`1,588 req/s`, `p99` down 73%), while keeping gapless
`<PREFIX>-<N>` identifiers and monotonic `evt_<seq>` cursors

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `PATCH
/api/issues/:id/kv-labels`, and `POST /api/issues/:id/comments`
throughput, tail latency, and PostgreSQL connection-pool efficiency
under high concurrency.

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`ab2183aaed`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- Every concurrent `POST /api/companies/:companyId/channels/posts` call
opens an independent database transaction and contends on the single
`companies` counter row, the `channels` row (`SET last_activity_at =
now()`), and the per-company `board_events` advisory lock.
- At `c=32`, post throughput caps at `770.1 req/s` on a single channel
and `804.5 req/s` across 16 channels; at `c=64`, single-channel post
throughput drops to `653.1 req/s` with `p99 = 295.91ms` because waiting
write transactions exhaust the database connection pool.
- Concurrent replies on a single hot thread (`c=32`) serialize on
unconditional `UPDATE channels SET last_activity_at = now()` and
`board_events` advisory locks, capping at `710.1 req/s` (`p99 =
84.47ms`).

**Proposed behavior**

- Add `touchChannelsLastActivity` (250ms staleness guard with ascending
`channels.id` `FOR NO KEY UPDATE` lock ordering) and `appendBoardEvents`
(single `pg_advisory_xact_lock` + ordered multi-row `INSERT INTO
board_events ... RETURNING` sorted by `seq`) in
`server/src/services/headless-board-events-write.ts`, plus
`logActivitiesBatch` in `server/src/services/activity-log.ts`.
- Add `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` with a
self-cleaning `WeakMap`-backed per-company batcher
(`MAX_COALESCED_BATCH_SIZE = 64`, `MAX_PENDING_PER_COMPANY = 1024`):
- When no batch is in flight (`c=1`), the request dispatches immediately
with zero artificial timer delay.
- While one batch transaction is executing on a single database
connection for that company, concurrent arrivals queue in memory
(bounded with `429` backpressure above `1024`) and execute together in
the next multi-row transaction using real wall-clock `new Date()`
timestamps, `issues.issueNumber` thread tie-breaking in
`listChannelThreads`, and RFC-valid sub-millisecond ordered UUIDs
(`mintTimeOrderedUuid`) across both coalesced and serialized comment
paths.
- Shared `validateChannelPathWriteFromMap` checks per-item channel
access, archived-channel, project access, and assignee rules before
counter allocation so rejected siblings never abort valid siblings or
leave gaps in `<PREFIX>-<N>` issue numbers, and post-commit event
publication runs strictly outside the transaction fallback scope.
- Requests with `idempotencyKey`, `clientRequestId`, or `after` continue
through their dedicated serialized concurrency checks.

**Reason and benefit**

Matched 7-scenario local headless benchmark (`origin/master`
`ab2183aaed` vs `perf/channel-group-commit`, 2 live SSE subscribers
active throughout, 0 errors, 100% live SSE delivery):

| Scenario | Merged `master` (`req/s`) | Group Commit (`req/s`) |
Speedup | `master` `p99` | Group Commit `p99` |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1. Sequential channel posts (`c=1`, 300 msgs) | 451.4 | 442.7 | 0.98x
(no idle delay) | 4.06 ms | 3.79 ms |
| 2. Single-channel posts (`c=32`, 1,000 msgs) | 770.1 | 1,849.2 |
**2.40x** | 89.23 ms | 34.67 ms |
| 3. 16-channel posts (`c=32`, 1,000 msgs) | 804.5 | 2,054.6 | **2.55x**
| 71.76 ms | 22.73 ms |
| 4. 16-thread replies (`c=32`, 1,000 msgs) | 1,045.7 | 1,486.6 |
**1.42x** | 59.53 ms | 28.91 ms |
| 5. Single hot-thread replies (`c=32`, 500 msgs) | 710.1 | 1,588.3 |
**2.24x** | 84.47 ms | 22.70 ms |
| 6. Single-channel posts (`c=64`, 2,000 msgs) | 653.1 | 2,474.7 |
**3.79x** | 295.91 ms | 42.80 ms |
| 7. 16-channel posts (`c=64`, 2,000 msgs) | 803.4 | 2,501.3 | **3.11x**
| 124.65 ms | 32.72 ms |

**Breaking changes**

None. All endpoints, request/response shapes, gapless `<PREFIX>-<N>`
identifiers, commit-ordered `evt_<seq>` cursors, idempotency semantics,
`after` optimistic concurrency checks, and channel/project/issue privacy
checks remain unchanged. `channels.lastActivityAt` updates at most once
per 250ms window under sustained traffic on the same channel.

**Additional context**

Builds on #23426 without schema migrations or external coordination
dependencies.

## What Changed

- Extracted shared activity preparation, row mapping
(`buildActivityLogRow`), side-effect notification, and publication
helpers in `server/src/services/activity-log.ts` and added
`logActivitiesBatch` for single-statement multi-row `activity_log`
inserts.
- Extracted `server/src/services/headless-board-events-write.ts`
(re-exported from `server/src/services/headless-common.ts`) with
`mintTimeOrderedUuid`, `touchChannelsLastActivity` (250ms debounce with
canonical ascending `channels.id` `FOR NO KEY UPDATE` lock ordering),
listener-isolated `subscribeCompanyBoardEvents`, and `appendBoardEvents`
(single `pg_advisory_xact_lock` acquisition with ordered multi-row
`INSERT INTO board_events ... RETURNING` sorted by `seq`).
- Extracted `server/src/services/headless-channel-write-helpers.ts`
(re-exported from `server/src/services/headless-channels.ts`) so channel
path validation, `ensureChannel`, tag upserts, and assignee resolution
are shared via normal imports without per-item callback plumbing.
- Added `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` implementing
bounded per-company write coalescing (`MAX_COALESCED_BATCH_SIZE = 64`,
`MAX_PENDING_PER_COMPANY = 1024`), post-lock wall-clock `new Date()` +
`mintTimeOrderedUuid` sampling so batches waiting behind `companies` or
`issues` row locks always receive newer `(createdAt, id)` tuples,
UUID-keyed comment `RETURNING` joins, per-item validation isolation, and
post-commit event publication strictly outside the transaction fallback
boundary.
- Updated `createChannelPost` and `listChannelThreads` in
`server/src/services/headless-channels.ts`,
`server/src/services/headless-labels-batch.ts`, and
`server/src/routes/headless-channels-schemas.ts` to tie-break equal
`createdAt` rows on `issues.issueNumber` and use
`touchChannelsLastActivity`, `appendBoardEvents`, `mintTimeOrderedUuid`,
and `executeCoalescedHeadlessComment`.
- Added regression tests in
`server/src/__tests__/adaptive-company-batcher.test.ts`,
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (16-way
mixed burst with pinned per-request statuses, wall-clock bounds,
`issueNumber` thread/after ordering, real PostgreSQL insert-error solo
fallback on both posts and comments, coalesced comment batches waiting
behind active `FOR UPDATE` serialized locks, deterministic 250ms
`lastActivityAt` skip/update assertions, and post-commit throwing
subscriber isolation), and
`server/src/__tests__/activity-log-responsible-user.test.ts`
(`logActivitiesBatch` redaction, `responsibleUserId` attribution, and
`mcpEvents` work signaling).

## Verification

- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/adaptive-company-batcher.test.ts
src/__tests__/activity-log-responsible-user.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-task-workflows.test.ts
src/__tests__/experimental-channels-viewer.test.ts` (6 files, 47/47
tests passed)
- Matched 7-scenario local headless benchmark on `origin/master`
(`ab2183aaed`) vs `perf/channel-group-commit` with 2 live SSE
subscribers (`0` errors, `100%` SSE event delivery across all runs)

## Risks

- Low risk. No database migrations or API contract changes. Coalesced
batches hold canonical lock order (`companies -> issues -> channels ->
labels -> issue_labels -> board_events` for posts; `issues ->
issue_comments -> channels -> board_events` for comments), isolate
read-only validation errors per item before minting issue numbers,
delete idle per-company queue state immediately, and fall back to solo
execution if an unexpected database error occurs on a multi-item batch.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, extended thinking
mode with shell, profiling, and test execution tools)

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 06:13:26 -06:00

715 lines
20 KiB
TypeScript

import { and, eq, inArray, isNull, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
companyMemberships,
issueLabels,
issues,
labels,
} from "@paperclipai/db";
import {
channelQueueConfigSchema,
CHANNEL_VISIBILITIES,
deriveAgentUrlKey,
isUuidLike,
normalizeChannelPath,
writableKvLabelsRecordSchema,
type ChannelQueueConfig,
type ChannelVisibility,
type CreateChannelInput,
} from "@paperclipai/shared";
import { badRequest, forbidden, notFound } from "../errors.js";
import {
logActivity,
type ActivityPublication,
} from "./activity-log.js";
import {
assertChannelAccess,
channelDescendantsCondition,
enforceHeadlessScopes,
resolveProjectReference,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { assertCanConfigureManagedPool } from "./headless-managed-pool.js";
const DEFAULT_TAG_LABEL_COLOR = "#64748b";
export function collectChannelAndAncestorPaths(paths: string[]): string[] {
const all = new Set<string>();
for (const path of paths) {
all.add(path);
const parts = path.split("/");
for (let i = 1; i < parts.length; i += 1) {
all.add(parts.slice(0, i).join("/"));
}
}
return Array.from(all);
}
export async function validateChannelPathWriteFromMap(
dbOrTx: DbOrTx,
actor: HeadlessActorContext,
normalizedPath: string,
channelByPath: ReadonlyMap<string, typeof channels.$inferSelect>,
): Promise<{
existingChannel: typeof channels.$inferSelect | null;
hasPrivateAncestor: boolean;
}> {
enforceHeadlessScopes(actor, { channelPath: normalizedPath });
let hasPrivateAncestor = false;
const parts = normalizedPath.split("/");
for (let i = 1; i < parts.length; i += 1) {
const anc = channelByPath.get(parts.slice(0, i).join("/"));
if (anc && anc.archivedAt === null && anc.visibility === "private") {
await assertChannelAccess(dbOrTx, anc, actor);
hasPrivateAncestor = true;
}
}
const existing = channelByPath.get(normalizedPath) ?? null;
if (existing) {
if (existing.archivedAt !== null) {
throw notFound(`Channel '${normalizedPath}' not found`);
}
if (existing.visibility === "private") {
await assertChannelAccess(dbOrTx, existing, actor);
}
}
return {
existingChannel: existing,
hasPrivateAncestor,
};
}
export function normalizeChannelPathOrThrow(
rawPath: string,
opts?: { allowSubtreePrefix?: boolean },
) {
try {
return normalizeChannelPath(rawPath, opts);
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : `Invalid channel path "${rawPath}"`,
{
error: "invalid_channel_path",
code: "invalid_channel_path",
},
);
}
}
export function validateWritableKvLabelsOrThrow(
rawLabels: Record<string, unknown>,
): Record<string, string> {
for (const key of Object.keys(rawLabels)) {
if (key.startsWith("paperclip.")) {
throw badRequest(
"Label keys starting with 'paperclip.' are reserved",
{
error: "reserved_label",
code: "reserved_label",
key,
},
);
}
}
const parsed = writableKvLabelsRecordSchema.safeParse(rawLabels);
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
return parsed.data;
}
export async function resolveAssigneeAgent(
dbOrTx: DbOrTx,
companyId: string,
opts: { assigneeAgentId?: string | null; for?: string },
): Promise<string | null> {
if (opts.assigneeAgentId !== undefined) {
if (opts.assigneeAgentId === null) return null;
const [agent] = await dbOrTx
.select({ id: agents.id })
.from(agents)
.where(
and(
eq(agents.id, opts.assigneeAgentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agent) {
throw notFound(`Agent '${opts.assigneeAgentId}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return agent.id;
}
if (opts.for !== undefined && opts.for.trim().length > 0) {
const target = opts.for.trim().replace(/^@+/, "").toLowerCase();
if (isUuidLike(target)) {
const [agent] = await dbOrTx
.select({ id: agents.id })
.from(agents)
.where(
and(
eq(agents.id, target),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agent) {
throw notFound(`Agent '@${target}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return agent.id;
}
const companyAgents = await dbOrTx
.select({ id: agents.id, name: agents.name })
.from(agents)
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
const match = companyAgents.find(
(a) =>
a.name.trim().toLowerCase() === target ||
deriveAgentUrlKey(a.name, a.id).toLowerCase() === target,
);
if (!match) {
throw notFound(`Agent '@${target}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return match.id;
}
return null;
}
export function normalizeTagLabelNames(tagNames: string[]): string[] {
return Array.from(
new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)),
).sort();
}
export async function ensureCompanyTagLabels(
tx: DbOrTx,
companyId: string,
tagNames: string[],
): Promise<Array<{ id: string; name: string }>> {
const uniqueNames = normalizeTagLabelNames(tagNames);
if (uniqueNames.length === 0) return [];
await tx
.insert(labels)
.values(
uniqueNames.map((name) => ({
companyId,
name,
color: DEFAULT_TAG_LABEL_COLOR,
})),
)
.onConflictDoNothing({
target: [labels.companyId, labels.name],
});
return tx
.select({ id: labels.id, name: labels.name })
.from(labels)
.where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames)));
}
export async function attachTagLabelsToIssues(
tx: DbOrTx,
companyId: string,
items: Array<{ issueId: string; tagNames: string[] }>,
): Promise<Map<string, string[]>> {
const normalizedByIssue = items.map((item) => ({
issueId: item.issueId,
names: normalizeTagLabelNames(item.tagNames),
}));
const allTagNames = Array.from(
new Set(normalizedByIssue.flatMap((entry) => entry.names)),
).sort();
const result = new Map<string, string[]>();
for (const entry of normalizedByIssue) {
result.set(entry.issueId, []);
}
if (allTagNames.length === 0) {
return result;
}
const labelRows = await ensureCompanyTagLabels(tx, companyId, allTagNames);
const tagIdByName = new Map(labelRows.map((row) => [row.name, row.id]));
const issueLabelValues: Array<{
issueId: string;
labelId: string;
companyId: string;
}> = [];
for (const entry of normalizedByIssue) {
const attached: string[] = [];
for (const name of entry.names) {
const labelId = tagIdByName.get(name);
if (labelId) {
attached.push(name);
issueLabelValues.push({
issueId: entry.issueId,
labelId,
companyId,
});
}
}
result.set(entry.issueId, attached);
}
issueLabelValues.sort((a, b) =>
a.issueId !== b.issueId
? a.issueId.localeCompare(b.issueId)
: a.labelId.localeCompare(b.labelId),
);
if (issueLabelValues.length > 0) {
await tx
.insert(issueLabels)
.values(issueLabelValues)
.onConflictDoNothing({
target: [issueLabels.issueId, issueLabels.labelId],
});
}
return result;
}
export async function attachTagLabels(
tx: DbOrTx,
companyId: string,
issueId: string,
tagNames: string[],
): Promise<string[]> {
const attachedMap = await attachTagLabelsToIssues(tx, companyId, [
{ issueId, tagNames },
]);
return attachedMap.get(issueId) ?? [];
}
async function addChannelCreatorMembership(
dbOrTx: DbOrTx,
companyId: string,
channelId: string,
actor: HeadlessActorContext,
): Promise<void> {
const member = actor.agentId
? { subjectType: "agent", subjectId: actor.agentId }
: actor.userId
? { subjectType: "user", subjectId: actor.userId }
: null;
if (!member) return;
await dbOrTx
.insert(channelAccessMembers)
.values({
companyId,
channelId,
subjectType: member.subjectType,
subjectId: member.subjectId,
})
.onConflictDoNothing({
target: [
channelAccessMembers.channelId,
channelAccessMembers.subjectType,
channelAccessMembers.subjectId,
],
});
}
export interface EnsureChannelInput {
path: string;
description?: string | null;
visibility?: ChannelVisibility;
defaultProjectId?: string | null;
queueConfig?: ChannelQueueConfig;
}
export async function assertChannelPathWritePreconditions(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rawPath: string,
): Promise<{
normalizedPath: string;
existingChannel: typeof channels.$inferSelect | null;
hasPrivateAncestor: boolean;
}> {
const normalized = normalizeChannelPathOrThrow(rawPath, {
allowSubtreePrefix: false,
});
const lookupPaths = collectChannelAndAncestorPaths([normalized.path]);
const rows =
lookupPaths.length === 1
? await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
eq(channels.path, lookupPaths[0]!),
),
)
.limit(1)
: await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, lookupPaths),
),
);
const channelByPath = new Map(rows.map((row) => [row.path, row]));
const { existingChannel, hasPrivateAncestor } =
await validateChannelPathWriteFromMap(
dbOrTx,
actor,
normalized.path,
channelByPath,
);
return {
normalizedPath: normalized.path,
existingChannel,
hasPrivateAncestor,
};
}
export async function ensureChannel(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
input: EnsureChannelInput | CreateChannelInput,
opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {},
): Promise<typeof channels.$inferSelect> {
const { normalizedPath, existingChannel, hasPrivateAncestor } =
await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path);
const normalized = { path: normalizedPath };
let resolvedDefaultProjectId: string | null | undefined;
if (input.defaultProjectId !== undefined) {
resolvedDefaultProjectId =
input.defaultProjectId === null
? null
: await resolveProjectReference(dbOrTx, companyId, input.defaultProjectId, actor);
}
let validatedQueueConfig: ChannelQueueConfig | undefined;
if (input.queueConfig !== undefined) {
const parsedQc = channelQueueConfigSchema.safeParse(input.queueConfig);
if (!parsedQc.success) {
throw badRequest(
parsedQc.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsedQc.error.issues,
},
);
}
validatedQueueConfig = parsedQc.data;
}
let visibility: ChannelVisibility | undefined = input.visibility;
if (visibility !== undefined && !CHANNEL_VISIBILITIES.includes(visibility)) {
throw badRequest(`Invalid channel visibility '${visibility}'`, {
error: "validation_error",
code: "validation_error",
});
}
if (hasPrivateAncestor) {
if (visibility === "open") {
throw forbidden("Cannot create or expose an open channel under a private ancestor", {
code: "private_ancestor_required",
});
}
visibility = "private";
}
if (existingChannel && !opts.allowUpdateExisting) {
return existingChannel;
}
let existing = existingChannel;
if (!existing) {
if (validatedQueueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
visibility: visibility ?? "open",
createdByAgentId: actor.agentId,
defaultProjectId: resolvedDefaultProjectId ?? null,
},
validatedQueueConfig.managedPool.agentId,
actor,
);
}
const now = new Date();
const [inserted] = await dbOrTx
.insert(channels)
.values({
companyId,
path: normalized.path,
description: input.description ?? null,
visibility: visibility ?? "open",
defaultProjectId: resolvedDefaultProjectId ?? null,
queueConfig: validatedQueueConfig ?? {},
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
lastActivityAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing({
target: [channels.companyId, channels.path],
})
.returning();
if (inserted) {
if (inserted.visibility === "private") {
await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor);
}
if (opts.publications) {
await logActivity(
dbOrTx as unknown as Db,
{
companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
responsibleUserIdOverride: actor.responsibleUserId,
action: "channel.created",
entityType: "channel",
entityId: inserted.id,
details: {
path: inserted.path,
visibility: inserted.visibility,
},
},
opts.publications,
);
}
return inserted;
}
const [raced] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!raced || raced.archivedAt !== null) {
throw notFound(`Channel '${normalized.path}' not found`);
}
if (raced.visibility === "private") {
await assertChannelAccess(dbOrTx, raced, actor);
}
if (!opts.allowUpdateExisting) {
return raced;
}
existing = raced;
}
const updates: Partial<typeof channels.$inferInsert> = {};
if (input.description !== undefined && input.description !== existing.description) {
updates.description = input.description;
}
if (input.visibility !== undefined && input.visibility !== existing.visibility) {
updates.visibility = input.visibility;
}
if (
resolvedDefaultProjectId !== undefined &&
resolvedDefaultProjectId !== existing.defaultProjectId
) {
updates.defaultProjectId = resolvedDefaultProjectId;
}
if (
validatedQueueConfig !== undefined &&
JSON.stringify(validatedQueueConfig) !== JSON.stringify(existing.queueConfig ?? {})
) {
updates.queueConfig = validatedQueueConfig;
}
if (Object.keys(updates).length > 0) {
enforceHeadlessScopes(actor, {
action: "channels.manage",
channelPath: existing.path,
});
const isOwnerOrCreator =
actor.isInstanceAdmin ||
actor.principalType === "local_trusted" ||
(Boolean(actor.userId) && existing.createdByUserId === actor.userId) ||
(Boolean(actor.agentId) && existing.createdByAgentId === actor.agentId);
let canManage = isOwnerOrCreator;
if (!canManage && actor.userId && actor.principalType === "user") {
const [membership] = await dbOrTx
.select({ role: companyMemberships.membershipRole })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actor.userId),
eq(companyMemberships.status, "active"),
inArray(companyMemberships.membershipRole, ["owner", "admin"]),
),
)
.limit(1);
canManage = Boolean(membership);
}
if (!canManage) {
throw forbidden("Only the channel creator or a company admin can update channel settings");
}
if (updates.queueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
id: existing.id,
visibility: updates.visibility ?? existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId:
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId,
},
updates.queueConfig.managedPool.agentId,
actor,
);
}
updates.updatedAt = new Date();
const privatizingTree =
updates.visibility === "private" && existing.visibility !== "private";
let childChannels: Array<{ id: string; visibility: string }> = [];
let affectedChannelIds: string[] = [];
if (privatizingTree) {
childChannels = await dbOrTx
.select({ id: channels.id, visibility: channels.visibility })
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
channelDescendantsCondition(existing.path),
),
);
affectedChannelIds = [existing.id, ...childChannels.map((c) => c.id)].sort();
await dbOrTx.execute(
sql`SELECT id FROM issues WHERE company_id = ${companyId} AND channel_id IN (${sql.join(
affectedChannelIds.map((id) => sql`${id}`),
sql`, `,
)}) AND visibility <> 'private' ORDER BY id FOR UPDATE`,
);
await dbOrTx.execute(
sql`SELECT id FROM channels WHERE company_id = ${companyId} AND id IN (${sql.join(
affectedChannelIds.map((id) => sql`${id}`),
sql`, `,
)}) ORDER BY id FOR UPDATE`,
);
}
const [updated] = await dbOrTx
.update(channels)
.set(updates)
.where(eq(channels.id, existing.id))
.returning();
if (updated?.visibility === "private" && existing.visibility !== "private") {
await addChannelCreatorMembership(dbOrTx, companyId, updated.id, actor);
const newlyPrivatizedChildIds = childChannels
.filter((c) => c.visibility !== "private")
.map((c) => c.id)
.sort();
if (newlyPrivatizedChildIds.length > 0) {
await dbOrTx
.update(channels)
.set({ visibility: "private", updatedAt: updates.updatedAt })
.where(inArray(channels.id, newlyPrivatizedChildIds));
for (const childId of newlyPrivatizedChildIds) {
await addChannelCreatorMembership(dbOrTx, companyId, childId, actor);
}
}
await dbOrTx
.update(issues)
.set({
visibility: "private",
privacyRootIssueId: sql`coalesce(${issues.privacyRootIssueId}, ${issues.id})`,
updatedAt: updates.updatedAt,
})
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.channelId, affectedChannelIds),
ne(issues.visibility, "private"),
),
);
}
if (updated && opts.publications) {
await logActivity(
dbOrTx as unknown as Db,
{
companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
responsibleUserIdOverride: actor.responsibleUserId,
action: "channel.updated",
entityType: "channel",
entityId: updated.id,
details: {
path: updated.path,
visibility: updated.visibility,
},
},
opts.publications,
);
}
return updated ?? existing;
}
return existing;
}