Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(channel): per-person sidebar sections and hidden conversations (#23418)

Arvin Xu5ea57be8999a
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 77b00f3642c..a24388f0029 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -25,6 +25,8 @@ import { channelHistoryProcedures } from './channelHistory';
const channelId = z.string().regex(/^chn_[\dA-Za-z]{12}$/);
const threadId = z.string().regex(/^cht_[\dA-Za-z]{12}$/);
+const sectionId = z.string().uuid();
+const sectionName = z.string().trim().min(1).max(100);
const agentSelection = z.object({
agentId: z.string().min(1),
description: z.string().max(1000).optional(),
@@ -316,6 +318,55 @@ export const channelRouter = router({
data: await ctx.channelService.repository.setPinned(input.channelId, input.pinned),
success: true,
})),
+ /** Files the conversation under one of the caller's own sections; null returns it to the built-in one. */
+ moveToSection: externalChannelProcedure
+ .input(z.object({ channelId, sectionId: sectionId.nullable() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.repository.moveToSection(input.channelId, input.sectionId),
+ success: true,
+ })),
+ /** Hides the conversation from the caller's own list until its next message, or shows it again. */
+ setHidden: externalChannelProcedure
+ .input(z.object({ channelId, hidden: z.boolean() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.repository.setHidden(input.channelId, input.hidden),
+ success: true,
+ })),
+ /** The caller's own sidebar sections in the current scope, in order. */
+ listSections: externalChannelProcedure.query(async ({ ctx }) => ({
+ data: await ctx.channelService.repository.sections.list(),
+ success: true,
+ })),
+ createSection: externalChannelProcedure
+ .input(z.object({ name: sectionName }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.repository.sections.create(input.name),
+ success: true,
+ })),
+ updateSection: externalChannelProcedure
+ .input(
+ z.object({
+ id: sectionId,
+ value: z.object({ collapsed: z.boolean().optional(), name: sectionName.optional() }),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.repository.sections.update(input.id, input.value),
+ success: true,
+ })),
+ reorderSections: externalChannelProcedure
+ .input(z.object({ ids: z.array(sectionId).max(200) }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.repository.sections.reorder(input.ids);
+ return { success: true };
+ }),
+ /** Deletes a section; its conversations return to the built-in sections. */
+ removeSection: externalChannelProcedure
+ .input(z.object({ id: sectionId }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.repository.sections.remove(input.id);
+ return { success: true };
+ }),
remove: channelProcedure.input(z.object({ channelId })).mutation(async ({ ctx, input }) => {
await ctx.channelService.remove(input.channelId);
return { success: true };
diff --git a/packages/database/src/repositories/channel/__tests__/sections.test.ts b/packages/database/src/repositories/channel/__tests__/sections.test.ts
new file mode 100644
index 00000000000..16ef934fa1c
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/sections.test.ts
@@ -0,0 +1,79 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { ChannelRepository } from '../index';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-sections');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+describe('Channel sections', () => {
+ it('keeps each person their own sections, in order', async () => {
+ const { asMember, asOwner } = await fixture.createTeamChannel();
+
+ const work = await asOwner.sections.create('Work');
+ const later = await asOwner.sections.create('Later');
+ expect((await asOwner.sections.list()).map(({ name }) => name)).toEqual(['Work', 'Later']);
+
+ await asOwner.sections.reorder([later.id, work.id]);
+ await asOwner.sections.update(work.id, { collapsed: true, name: 'Projects' });
+ expect(await asOwner.sections.list()).toEqual([
+ expect.objectContaining({ id: later.id, name: 'Later' }),
+ expect.objectContaining({ collapsed: true, id: work.id, name: 'Projects' }),
+ ]);
+
+ // Another person, or the same person in their personal space, sees none of them.
+ expect(await asMember.sections.list()).toEqual([]);
+ expect(await new ChannelRepository(db, fixture.ownerId).sections.list()).toEqual([]);
+ await expect(asMember.sections.update(work.id, { name: 'Mine' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(asMember.sections.reorder([work.id])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(asMember.sections.remove(work.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('files a conversation for the caller only and returns it when the section goes', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const work = await asOwner.sections.create('Work');
+
+ await expect(asOwner.moveToSection(channel.id, work.id)).resolves.toBe(work.id);
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ id: channel.id, sectionId: work.id }),
+ ]);
+ expect(await asMember.list()).toEqual([
+ expect.objectContaining({ id: channel.id, sectionId: null }),
+ ]);
+
+ // Nobody files a conversation under someone else's section.
+ await expect(asMember.moveToSection(channel.id, work.id)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+
+ await asOwner.sections.remove(work.id);
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ id: channel.id, sectionId: null }),
+ ]);
+ });
+
+ it('hides a conversation for the caller until the next message', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+
+ await expect(asOwner.setHidden(channel.id, true)).resolves.toBe(true);
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ hidden: true, id: channel.id }),
+ ]);
+ expect(await asMember.list()).toEqual([
+ expect.objectContaining({ hidden: false, id: channel.id }),
+ ]);
+
+ await asMember.send(channel.id, { content: 'Hi', requestKey: 'hi', routing: 'fallback' });
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ hidden: false, id: channel.id }),
+ ]);
+ });
+});
diff --git a/packages/database/src/repositories/channel/delivery.ts b/packages/database/src/repositories/channel/delivery.ts
index 50e61b86df3..9a5d525b822 100644
--- a/packages/database/src/repositories/channel/delivery.ts
+++ b/packages/database/src/repositories/channel/delivery.ts
@@ -17,6 +17,7 @@ import {
import type { Transaction } from '../../type';
import { notTrashed } from '../../utils/softDelete';
import { ChannelError } from './error';
+import { unhideForActivity } from './sections';
/** Why a deferred `followup` has not started; see {@link deliver} and `claimJob`. */
export const AWAITING_PRIMARY_REASON = 'Waiting for the first responder to finish';
@@ -186,6 +187,7 @@ export const appendMessage = async (
.insert(channelMessages)
.values({ ...values, sequence })
.returning();
+ await unhideForActivity(tx, values.channelId);
return message;
};
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 3d15d224207..7aac7d87f45 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -56,6 +56,7 @@ import { joinPublicChannel, listJoinableChannels } from './publicAccess';
import { retryJob } from './retry';
import { retryRouting } from './routing';
import { type ChannelSearchOptions, searchChannelMessages } from './search';
+import { ChannelSectionRepository } from './sections';
import type { ChannelSendInput } from './send';
import { sendMessage } from './send';
import type { ChannelStopScope } from './stop';
@@ -64,6 +65,13 @@ import { channelThreadMentions } from './threadMentions';
import { audit, lockChannel } from './transaction';
import type { ChannelAccess, ChannelAgentPairAccess, ChannelWriteOptions } from './types';
import { createChannelThread, readChannelView } from './view';
+import {
+ readWakeConfig,
+ replaceChannelWake,
+ replaceMemberWake,
+ wakeRecordScope,
+ withMemberWake,
+} from './wake';
export type { ChannelAddAgentInput } from './agent';
export { memberEnvironment } from './agent';
@@ -90,6 +98,7 @@ export type {
} from './opening';
export type { ChannelAgentPostInput } from './post';
export type { AppliedChannelRouting, ChannelRoutingDecision } from './routing';
+export { ChannelSectionRepository } from './sections';
export type { ChannelSendInput } from './send';
export type { ChannelStopScope } from './stop';
export type { ChannelAccess, ChannelAgentPairAccess, ChannelWriteOptions } from './types';
@@ -114,16 +123,10 @@ const WORKSPACE_MANAGER_ROLES = ['owner', 'admin'];
* scope (personal, or the given workspace). Every write runs inside `write`, which holds the
* `channels` row lock so mutations of one channel serialize in a transaction.
*/
-/** A member config with its reply strategy set, or without one when `wake` is empty. */
-/** An environment plus the member's own settings that live beside it: reply strategy and mute. */
-const withMemberWake = (
- config: ChannelMemberConfig,
- wake: Record<string, unknown> | null | undefined,
- muted: boolean | undefined,
-): ChannelMemberConfig => ({ ...config, ...(wake && { wake }), ...(muted && { muted }) });
-
export class ChannelRepository {
private readonly workspaceId: string | null;
+ /** The caller's own sidebar sections in this scope. */
+ readonly sections: ChannelSectionRepository;
constructor(
private readonly db: LobeChatDatabase,
@@ -131,6 +134,7 @@ export class ChannelRepository {
workspaceId?: string | null,
) {
this.workspaceId = normalizeWorkspaceId(workspaceId);
+ this.sections = new ChannelSectionRepository(db, userId, this.workspaceId);
}
/** Opens the unique direct conversation, or creates a group with its initial members. */
@@ -301,65 +305,22 @@ export class ChannelRepository {
* `null` means the defaults apply. Validation belongs to the shared wake schema in the caller.
*/
wakeConfig = async (channelId: string) =>
- this.write(
- channelId,
- async (tx, { channel }) => {
- const members = await tx
- .select({ config: channelMembers.config, id: channelMembers.id })
- .from(channelMembers)
- .where(
- and(
- eq(channelMembers.channelId, channelId),
- eq(channelMembers.actorType, 'agent'),
- eq(channelMembers.status, 'active'),
- ),
- );
- return {
- channel: channel.config?.wake ?? null,
- members: members.map((member) => ({
- memberId: member.id,
- wake: member.config?.wake ?? null,
- })),
- };
- },
- { minRole: 'admin' },
- );
+ this.write(channelId, (tx, { channel }) => readWakeConfig(tx, channel), { minRole: 'admin' });
/**
* Whose records one Agent member's wake decisions are filed under: its Agent's owner, in the
* channel's workspace. `null` when the Agent has no owner left to file them under.
*/
memberWakeRecordScope = async (channelId: string, memberId: string) =>
- this.write(
- channelId,
- async (tx, { channel }) => {
- const member = await requireAgentMember(tx, channelId, memberId);
- const [agent] = await tx
- .select({ userId: agents.userId })
- .from(agents)
- .where(eq(agents.id, member.agentId));
- return agent?.userId ? { userId: agent.userId, workspaceId: channel.workspaceId } : null;
- },
- { minRole: 'admin' },
- );
+ this.write(channelId, (tx, { channel }) => wakeRecordScope(tx, channel, memberId), {
+ minRole: 'admin',
+ });
/** Replaces the channel's reply strategy; `null` returns it to the defaults. */
updateChannelWakeConfig = async (channelId: string, wake: Record<string, unknown> | null) =>
- this.write(
- channelId,
- async (tx, { channel }) => {
- const { wake: _previous, ...rest } = channel.config ?? {};
- const config = wake ? { ...rest, wake } : rest;
- const [updated] = await tx
- .update(channels)
- .set({ config: Object.keys(config).length ? config : null })
- .where(eq(channels.id, channelId))
- .returning();
- await audit(tx, channelId, 'wake_config_changed', channelId, { reset: !wake });
- return updated.config?.wake ?? null;
- },
- { minRole: 'admin' },
- );
+ this.write(channelId, (tx, { channel }) => replaceChannelWake(tx, channel, wake), {
+ minRole: 'admin',
+ });
/**
* Replaces one Agent member's own reply strategy over the channel's; `null` removes it. Its
@@ -370,22 +331,9 @@ export class ChannelRepository {
memberId: string,
wake: Record<string, unknown> | null,
) =>
- this.write(
- channelId,
- async (tx) => {
- const current = await requireAgentMember(tx, channelId, memberId);
- const [member] = await tx
- .update(channelMembers)
- .set({
- config: withMemberWake(memberEnvironment(current.config), wake, current.config?.muted),
- })
- .where(eq(channelMembers.id, memberId))
- .returning();
- await audit(tx, channelId, 'member_wake_config_changed', memberId, { reset: !wake });
- return member.config?.wake ?? null;
- },
- { minRole: 'admin' },
- );
+ this.write(channelId, (tx) => replaceMemberWake(tx, channelId, memberId, wake), {
+ minRole: 'admin',
+ });
rename = async (channelId: string, title: string) =>
this.write(
@@ -556,6 +504,35 @@ export class ChannelRepository {
{ allowArchived: true, allowTrashed: true },
);
+ /**
+ * Files the conversation under one of the caller's own sections, or back into its built-in
+ * section with `null`; nobody else sees it.
+ */
+ moveToSection = async (channelId: string, sectionId: string | null) =>
+ this.write(
+ channelId,
+ async (tx, { member }) => {
+ if (sectionId) await this.sections.assertOwned(tx, sectionId);
+ await tx.update(channelMembers).set({ sectionId }).where(eq(channelMembers.id, member.id));
+ return sectionId;
+ },
+ { allowArchived: true, allowTrashed: true },
+ );
+
+ /**
+ * Hides the conversation from the caller's own list, or shows it again; the next message
+ * brings it back by itself.
+ */
+ setHidden = async (channelId: string, hidden: boolean) =>
+ this.write(
+ channelId,
+ async (tx, { member }) => {
+ await tx.update(channelMembers).set({ hidden }).where(eq(channelMembers.id, member.id));
+ return hidden;
+ },
+ { allowArchived: true, allowTrashed: true },
+ );
+
/**
* Channels the caller belongs to in the current scope, newest first. Archived ones are
* included with their `status`, so they stay readable outside the active list. Active open
@@ -572,8 +549,10 @@ export class ChannelRepository {
memberAvatars: ChannelAvatarMember[];
memberRole: ChannelMemberRole | null;
mentionCount: number;
+ hidden: boolean;
pinnedAt: Date | null;
replyJobs: ChannelReplyJob[];
+ sectionId: string | null;
sharedAgentHandle: string | null;
threadMentions: ChannelThreadMention[];
unreadCount: number;
@@ -586,10 +565,12 @@ export class ChannelRepository {
agentVisibility: agents.visibility,
agentWorkspaceId: agents.workspaceId,
channel: channels,
+ hidden: channelMembers.hidden,
lastReadSequence: channelMembers.lastReadSequence,
memberId: channelMembers.id,
pinnedAt: channelMembers.pinnedAt,
role: this.callerRole(),
+ sectionId: channelMembers.sectionId,
shareId: agentShares.id,
shareSlug: sql<string | null>`${agentShares.shareConfig} ->> 'slug'`,
})
@@ -702,7 +683,17 @@ export class ChannelRepository {
}
const joined = rows.map(
- ({ channel, lastReadSequence, pinnedAt, role, shareId, shareSlug, ...agent }) => {
+ ({
+ channel,
+ hidden,
+ lastReadSequence,
+ pinnedAt,
+ role,
+ sectionId,
+ shareId,
+ shareSlug,
+ ...agent
+ }) => {
const sharedAgent = isSharedAgentChannel(channel, agent, this.userId);
return {
...channel,
@@ -711,6 +702,7 @@ export class ChannelRepository {
// Its visitor page (`/a/<handle>`) is where the caller can see this Agent; it has no other.
sharedAgentHandle: sharedAgent ? (shareSlug ?? shareId) : null,
canDelete: hasRole(role, 'admin'),
+ hidden,
joined: true,
lastMessage: lastMessageOf.get(channel.id) ?? null,
memberAvatars: avatarsOf.get(channel.id) ?? [],
@@ -719,6 +711,7 @@ export class ChannelRepository {
peerUserId: peerOf(channel, this.userId),
pinnedAt,
replyJobs: replyJobsOf.get(channel.id) ?? [],
+ sectionId,
threadMentions: threadMentionsOf.get(channel.id) ?? [],
unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),
};
@@ -733,6 +726,7 @@ export class ChannelRepository {
sharedAgent: false,
sharedAgentHandle: null,
canDelete: false,
+ hidden: false,
joined: false,
lastMessage: lastMessageOf.get(channel.id) ?? null,
memberAvatars: avatarsOf.get(channel.id) ?? [],
@@ -741,6 +735,7 @@ export class ChannelRepository {
peerUserId: peerOf(channel, this.userId),
pinnedAt: null,
replyJobs: [],
+ sectionId: null,
threadMentions: [],
unreadCount: 0,
})),
diff --git a/packages/database/src/repositories/channel/sections.ts b/packages/database/src/repositories/channel/sections.ts
new file mode 100644
index 00000000000..a4ac5108bbf
--- /dev/null
+++ b/packages/database/src/repositories/channel/sections.ts
@@ -0,0 +1,117 @@
+import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm';
+
+import type { ChannelSectionItem } from '../../schemas';
+import { channelMembers, channelSections } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { ChannelError } from './error';
+
+/**
+ * A person's own sidebar sections in one scope (personal or a workspace). Channels are shared,
+ * so how each member files them lives here and on their own member row, never on the channel.
+ */
+export class ChannelSectionRepository {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId: string | null,
+ ) {}
+
+ /** The caller's sections in this scope, in sidebar order. */
+ list = (): Promise<ChannelSectionItem[]> =>
+ this.db
+ .select()
+ .from(channelSections)
+ .where(this.ownedWhere())
+ .orderBy(
+ sql`${channelSections.sort} ASC NULLS LAST`,
+ asc(channelSections.createdAt),
+ asc(channelSections.id),
+ );
+
+ /** Adds a section after the existing ones. */
+ create = (name: string): Promise<ChannelSectionItem> =>
+ this.db.transaction(async (tx) => {
+ const [{ last }] = await tx
+ .select({ last: sql<number | null>`max(${channelSections.sort})` })
+ .from(channelSections)
+ .where(this.ownedWhere());
+ const [section] = await tx
+ .insert(channelSections)
+ .values({
+ name,
+ sort: (last ?? -1) + 1,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ })
+ .returning();
+ return section;
+ });
+
+ update = async (
+ id: string,
+ value: { collapsed?: boolean; name?: string },
+ ): Promise<ChannelSectionItem> => {
+ const [section] = await this.db
+ .update(channelSections)
+ .set({ ...value, updatedAt: new Date() })
+ .where(and(eq(channelSections.id, id), this.ownedWhere()))
+ .returning();
+ if (!section) throw new ChannelError('NOT_FOUND', 'Section not found');
+ return section;
+ };
+
+ /** Sets the order to `ids`; sections left out keep their own `sort`. */
+ reorder = (ids: string[]): Promise<void> =>
+ this.db.transaction(async (tx) => {
+ await this.requireOwned(tx, ids);
+ for (const [sort, id] of ids.entries())
+ await tx
+ .update(channelSections)
+ .set({ sort, updatedAt: new Date() })
+ .where(eq(channelSections.id, id));
+ });
+
+ /** Deletes a section; its conversations fall back to the built-in sections. */
+ remove = async (id: string): Promise<void> => {
+ const [removed] = await this.db
+ .delete(channelSections)
+ .where(and(eq(channelSections.id, id), this.ownedWhere()))
+ .returning({ id: channelSections.id });
+ if (!removed) throw new ChannelError('NOT_FOUND', 'Section not found');
+ };
+
+ /** Throws unless `sectionId` is one of the caller's sections in this scope. */
+ assertOwned = async (tx: Transaction, sectionId: string): Promise<void> => {
+ await this.requireOwned(tx, [sectionId]);
+ };
+
+ private requireOwned = async (tx: Transaction, ids: string[]): Promise<void> => {
+ const unique = [...new Set(ids)];
+ if (!unique.length) return;
+ const rows = await tx
+ .select({ id: channelSections.id })
+ .from(channelSections)
+ .where(and(inArray(channelSections.id, unique), this.ownedWhere()));
+ if (rows.length !== unique.length) throw new ChannelError('NOT_FOUND', 'Section not found');
+ };
+
+ private ownedWhere() {
+ return and(
+ eq(channelSections.userId, this.userId),
+ this.workspaceId
+ ? eq(channelSections.workspaceId, this.workspaceId)
+ : isNull(channelSections.workspaceId),
+ );
+ }
+}
+
+/**
+ * Brings a hidden conversation back into every member's list when a new message lands. The caller
+ * holds the channel lock.
+ */
+export const unhideForActivity = async (tx: Transaction, channelId: string): Promise<void> => {
+ await tx
+ .update(channelMembers)
+ .set({ hidden: false })
+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.hidden, true)));
+};
diff --git a/packages/database/src/repositories/channel/wake.ts b/packages/database/src/repositories/channel/wake.ts
new file mode 100644
index 00000000000..33cf0e3f301
--- /dev/null
+++ b/packages/database/src/repositories/channel/wake.ts
@@ -0,0 +1,82 @@
+import type { ChannelMemberConfig } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import type { ChannelItem } from '../../schemas';
+import { agents, channelMembers, channels } from '../../schemas';
+import type { Transaction } from '../../type';
+import { memberEnvironment, requireAgentMember } from './agent';
+import { audit } from './transaction';
+
+/** An environment plus the member's own settings that live beside it: reply strategy and mute. */
+export const withMemberWake = (
+ config: ChannelMemberConfig,
+ wake: Record<string, unknown> | null | undefined,
+ muted: boolean | undefined,
+): ChannelMemberConfig => ({ ...config, ...(wake && { wake }), ...(muted && { muted }) });
+
+/** The channel's reply strategy and each active Agent member's own, as stored. */
+export const readWakeConfig = async (tx: Transaction, channel: ChannelItem) => {
+ const members = await tx
+ .select({ config: channelMembers.config, id: channelMembers.id })
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, channel.id),
+ eq(channelMembers.actorType, 'agent'),
+ eq(channelMembers.status, 'active'),
+ ),
+ );
+ return {
+ channel: channel.config?.wake ?? null,
+ members: members.map((member) => ({
+ memberId: member.id,
+ wake: member.config?.wake ?? null,
+ })),
+ };
+};
+
+/** Whose records one Agent member's wake decisions are filed under; see `memberWakeRecordScope`. */
+export const wakeRecordScope = async (tx: Transaction, channel: ChannelItem, memberId: string) => {
+ const member = await requireAgentMember(tx, channel.id, memberId);
+ const [agent] = await tx
+ .select({ userId: agents.userId })
+ .from(agents)
+ .where(eq(agents.id, member.agentId));
+ return agent?.userId ? { userId: agent.userId, workspaceId: channel.workspaceId } : null;
+};
+
+/** Replaces the channel's reply strategy; `null` returns it to the defaults. */
+export const replaceChannelWake = async (
+ tx: Transaction,
+ channel: ChannelItem,
+ wake: Record<string, unknown> | null,
+) => {
+ const { wake: _previous, ...rest } = channel.config ?? {};
+ const config = wake ? { ...rest, wake } : rest;
+ const [updated] = await tx
+ .update(channels)
+ .set({ config: Object.keys(config).length ? config : null })
+ .where(eq(channels.id, channel.id))
+ .returning();
+ await audit(tx, channel.id, 'wake_config_changed', channel.id, { reset: !wake });
+ return updated.config?.wake ?? null;
+};
+
+/** Replaces one Agent member's own reply strategy; its environment and mute are kept. */
+export const replaceMemberWake = async (
+ tx: Transaction,
+ channelId: string,
+ memberId: string,
+ wake: Record<string, unknown> | null,
+) => {
+ const current = await requireAgentMember(tx, channelId, memberId);
+ const [member] = await tx
+ .update(channelMembers)
+ .set({
+ config: withMemberWake(memberEnvironment(current.config), wake, current.config?.muted),
+ })
+ .where(eq(channelMembers.id, memberId))
+ .returning();
+ await audit(tx, channelId, 'member_wake_config_changed', memberId, { reset: !wake });
+ return member.config?.wake ?? null;
+};
diff --git a/packages/database/src/schemas/channel.ts b/packages/database/src/schemas/channel.ts
index 0760e2d7da8..b395c6527ac 100644
--- a/packages/database/src/schemas/channel.ts
+++ b/packages/database/src/schemas/channel.ts
@@ -183,7 +183,10 @@ export const channelMembers = pgTable(
lastReadSequence: integer('last_read_sequence'),
/** This person's sidebar section; NULL falls back to the built-in section. */
sectionId: uuid('section_id').references(() => channelSections.id, { onDelete: 'set null' }),
- /** Pinned to the top of this person's sidebar. */
+ /**
+ * @deprecated Unused duplicate of `pinnedAt`, which carries both the pin and its order. Kept
+ * only so dropping it needs no migration; read and write `pinnedAt` instead.
+ */
pinned: boolean('pinned').notNull().default(false),
/** Hidden from this person's sidebar until new activity reaches them. */
hidden: boolean('hidden').notNull().default(false),
@@ -564,6 +567,7 @@ export const channelJobs = pgTable(
export type ChannelItem = typeof channels.$inferSelect;
export type NewChannel = typeof channels.$inferInsert;
export type ChannelMemberItem = typeof channelMembers.$inferSelect;
+export type ChannelSectionItem = typeof channelSections.$inferSelect;
export type NewChannelMember = typeof channelMembers.$inferInsert;
export type ChannelMemberGrantItem = typeof channelMemberGrants.$inferSelect;
export type ChannelThreadItem = typeof channelThreads.$inferSelect;
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 44bd7b61523..b77f0358b96 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -591,6 +591,11 @@ export interface ChannelListItem {
/** Server-computed for the current member. */
canDelete: boolean;
createdAt: Date;
+ /**
+ * The caller hid the conversation from their list; new activity brings it back. Set by the
+ * Channel list. Personal: other members never see it.
+ */
+ hidden?: boolean;
id: string;
/**
* False for a project Channel the caller can read through the project but has not joined; it
@@ -628,6 +633,11 @@ export interface ChannelListItem {
* show them without loading the conversation; set by the Channel list.
*/
replyJobs?: ChannelReplyJob[];
+ /**
+ * The caller's own sidebar section holding the conversation; null keeps it in the built-in one.
+ * Set by the Channel list. Personal: other members never see it.
+ */
+ sectionId?: string | null;
sequence: number;
/**
* A direct conversation with another person's Agent, reached through the caller's contact entry