π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(channel): record who added a member so join lines stop crediting the owner (#23343)
Arvin Xuc7e38f585600
diff --git a/packages/database/src/repositories/channel/__tests__/visibility.test.ts b/packages/database/src/repositories/channel/__tests__/visibility.test.tsindex bfb93704a20..bab2671cf44 100644--- a/packages/database/src/repositories/channel/__tests__/visibility.test.ts+++ b/packages/database/src/repositories/channel/__tests__/visibility.test.ts@@ -87,6 +87,22 @@ describe('Channel visibility', () => {await expect(outsider.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });});+ it('records who added a member, and drops it when they rejoin on their own', async () => {+ const { channel, outsider, owner } = await create();+ const added = await owner.addUser(channel.id, fixture.memberId);+ const ownerMember = (await owner.detail(channel.id)).members.find(+ (entry) => entry.role === 'owner',+ );+ const invitedBy = async () =>+ (await owner.detail(channel.id)).members.find((entry) => entry.id === added.id)?.invitedBy;+ expect(await invitedBy()).toBe(ownerMember?.id);++ await owner.updateVisibility(channel.id, 'public');+ await db.update(channelMembers).set({ status: 'left' }).where(eq(channelMembers.id, added.id));+ await outsider.join(channel.id);+ expect(await invitedBy()).toBeNull();+ });+it('hides archived and trashed public channels, and rejects people outside the workspace', async () => {const { channel, outsider, owner } = await create();await owner.updateVisibility(channel.id, 'public');diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.tsindex e5647ef991e..27a2b21587f 100644--- a/packages/database/src/repositories/channel/agent.ts+++ b/packages/database/src/repositories/channel/agent.ts@@ -130,13 +130,18 @@ export const requireChannelAgent = async (return { name: shared.name, title: shared.title };};-/** Called under the Channel lock after the caller's admin role has been checked. */+/**+ * Called under the Channel lock after the caller's admin role has been checked. `inviter` is the+ * caller's own member: its person must be able to use the Agent, and the join line names it.+ */export const addAgentMember = async (tx: Transaction,channel: ChannelItem,- userId: string,+ inviter: ChannelMemberItem,input: ChannelAddAgentInput,): Promise<ChannelMemberItem> => {+ const { id: invitedBy, userId } = inviter;+ if (!userId) throw new ChannelError('FORBIDDEN', 'Only a person adds an Agent');if (channel.peerUserId)throw new ChannelError('BAD_REQUEST', 'A conversation between two people has no Agents');if (channel.agentId) {@@ -176,6 +181,7 @@ export const addAgentMember = async (channelId: channel.id,config: memberEnvironment(input.config),description: input.description,+ metadata: { invitedBy },name: input.name?.trim() || agentDisplayName(agent, 'Agent'),}).returning();diff --git a/packages/database/src/repositories/channel/agentPair.ts b/packages/database/src/repositories/channel/agentPair.tsindex f1daad5d67a..ebd8044633a 100644--- a/packages/database/src/repositories/channel/agentPair.ts+++ b/packages/database/src/repositories/channel/agentPair.ts@@ -56,8 +56,7 @@ export const openAgentPair = async (}).returning();const agents = [];- for (const agent of params.agents)- agents.push(await addAgentMember(tx, channel, scope.userId, agent));+ for (const agent of params.agents) agents.push(await addAgentMember(tx, channel, member, agent));return { agents, channel, member };};diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 297d220bb96..3d15d224207 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -55,8 +55,8 @@ import {import { joinPublicChannel, listJoinableChannels } from './publicAccess';import { retryJob } from './retry';import { retryRouting } from './routing';-import type { ChannelSendInput } from './send';import { type ChannelSearchOptions, searchChannelMessages } from './search';+import type { ChannelSendInput } from './send';import { sendMessage } from './send';import type { ChannelStopScope } from './stop';import { stopScope } from './stop';@@ -190,9 +190,8 @@ export class ChannelRepository {const member = await this.addOwner(tx, channel.id);if (agentId)- await addAgentMember(tx, channel, this.userId, { agentId, config: params.agentConfig });- for (const agent of params.agents ?? [])- await addAgentMember(tx, channel, this.userId, agent);+ await addAgentMember(tx, channel, member, { agentId, config: params.agentConfig });+ for (const agent of params.agents ?? []) await addAgentMember(tx, channel, member, agent);const access = { channel, member } satisfies ChannelAccess;for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);@@ -234,14 +233,13 @@ export class ChannelRepository {.returning();const member = await this.addOwner(tx, channel.id);const access = { channel, member } satisfies ChannelAccess;- await addAgentMember(tx, channel, this.userId, {+ await addAgentMember(tx, channel, member, {agentId: direct.agentId,config: bound.config ?? undefined,description: bound.description,name: bound.name ?? undefined,});- for (const agent of params.agents ?? [])- await addAgentMember(tx, channel, this.userId, agent);+ for (const agent of params.agents ?? []) await addAgentMember(tx, channel, member, agent);for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);return access;},@@ -250,7 +248,7 @@ export class ChannelRepository {/** Adds a usable Agent reference; a missing reference is allowed only for retained history. */addAgent = async (channelId: string, input: ChannelAddAgentInput) =>- this.write(channelId, (tx, { channel }) => addAgentMember(tx, channel, this.userId, input), {+ this.write(channelId, (tx, { channel, member }) => addAgentMember(tx, channel, member, input), {minRole: 'admin',});diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.tsindex 96d766d1010..34170e0ef91 100644--- a/packages/database/src/repositories/channel/people.ts+++ b/packages/database/src/repositories/channel/people.ts@@ -1,5 +1,5 @@import type { SQL } from 'drizzle-orm';-import { and, asc, eq, isNull, ne, notExists, or } from 'drizzle-orm';+import { and, asc, eq, isNull, ne, notExists, or, sql } from 'drizzle-orm';import { channelMembers, users, workspaceMembers } from '../../schemas';import type { Transaction } from '../../type';@@ -110,6 +110,15 @@ export const newChannelUserCandidates = async (return workspaceUserCandidates(tx, workspaceId, ne(users.id, userId), search);};+/**+ * Member metadata naming who added the member, merged into what it already holds. A null inviter,+ * someone joining on their own, drops an earlier one so a rejoin does not keep the old adder.+ */+export const memberInviterMetadata = (invitedBy: string | null) =>+ invitedBy+ ? sql`coalesce(${channelMembers.metadata}, '{}'::jsonb) || jsonb_build_object('invitedBy', ${invitedBy}::text)`+ : sql`coalesce(${channelMembers.metadata}, '{}'::jsonb) - 'invitedBy'`;+export const addChannelUser = async (tx: Transaction, access: ChannelAccess, userId: string) => {const workspaceId = await requireGroupWorkspace(tx, access);await requireWorkspaceMember(tx, workspaceId, userId);@@ -121,7 +130,11 @@ export const addChannelUser = async (tx: Transaction, access: ChannelAccess, useconst [member] = existing? await tx.update(channelMembers)- .set({ role: 'member', status: 'active' })+ .set({+ metadata: memberInviterMetadata(access.member.id),+ role: 'member',+ status: 'active',+ }).where(eq(channelMembers.id, existing.id)).returning(): await tx@@ -130,6 +143,7 @@ export const addChannelUser = async (tx: Transaction, access: ChannelAccess, useactorType: 'user',channelId: access.channel.id,lastReadSequence: 0,+ metadata: { invitedBy: access.member.id },role: 'member',userId,})diff --git a/packages/database/src/repositories/channel/projectAccess.ts b/packages/database/src/repositories/channel/projectAccess.tsindex ad5a6210da4..ffb60660800 100644--- a/packages/database/src/repositories/channel/projectAccess.ts+++ b/packages/database/src/repositories/channel/projectAccess.ts@@ -6,7 +6,7 @@ import type { LobeChatDatabase, Transaction } from '../../type';import { notTrashed } from '../../utils/softDelete';import { buildWorkspaceWhere } from '../../utils/workspace';import { ChannelError } from './error';-import { requireWorkspaceMember } from './people';+import { memberInviterMetadata, requireWorkspaceMember } from './people';import { audit } from './transaction';import type { ChannelAccess } from './types';import { readChannelView } from './view';@@ -179,7 +179,12 @@ export const joinOpenChannel = async (const [member] = existing? await tx.update(channelMembers)- .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })+ .set({+ lastReadSequence: channel.sequence,+ metadata: memberInviterMetadata(null),+ role: 'member',+ status: 'active',+ }).where(eq(channelMembers.id, existing.id)).returning(): await txdiff --git a/packages/database/src/repositories/channel/publicAccess.ts b/packages/database/src/repositories/channel/publicAccess.tsindex 928c71f3750..45df394fd98 100644--- a/packages/database/src/repositories/channel/publicAccess.ts+++ b/packages/database/src/repositories/channel/publicAccess.ts@@ -5,7 +5,7 @@ import type { LobeChatDatabase } from '../../type';import { ilikeContains } from '../../utils/like';import { notTrashed } from '../../utils/softDelete';import { ChannelError } from './error';-import { requireWorkspaceMember } from './people';+import { memberInviterMetadata, requireWorkspaceMember } from './people';import { audit, lockChannel } from './transaction';import type { ChannelAccess } from './types';@@ -102,7 +102,12 @@ export const joinPublicChannel = async (const [member] = existing? await tx.update(channelMembers)- .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })+ .set({+ lastReadSequence: channel.sequence,+ metadata: memberInviterMetadata(null),+ role: 'member',+ status: 'active',+ }).where(eq(channelMembers.id, existing.id)).returning(): await txdiff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 57abb9a8cfb..0cc26b62864 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -354,6 +354,7 @@ export const readChannelView = async (string | null>`coalesce(nullif(${channelMembers.description}, ''), ${agents.description})`,id: channelMembers.id,+ invitedBy: sql<string | null>`${channelMembers.metadata}->>'invitedBy'`,muted: sql<boolean>`coalesce((${channelMembers.config}->>'muted')::boolean, false)`,name: channelMembers.name,role: channelMembers.role,diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 592c28b04be..44bd7b61523 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -144,6 +144,8 @@ export interface ChannelMemberWorktree {/** Free-form member state that does not need its own column. */export type ChannelMemberMetadata = Record<string, unknown> & {+ /** The member who added this one; absent when they joined on their own or before it was kept. */+ invitedBy?: string;/** Worktree per conversation branch: a Thread id, or `main` for the main timeline. */worktrees?: Record<string, ChannelMemberWorktree>;/** The configured directory could not host a worktree (e.g. not a git repo); retried later. */@@ -670,6 +672,8 @@ export interface ChannelPublicMember {/** Agent members only; null when the Channel sets no device or directory for it. */environment?: ChannelMemberEnvironmentPreview | null;id: string;+ /** The member who added this one; null when they joined on their own or the adder is unknown. */+ invitedBy: string | null;joinedAt: Date;/** An Agent that answers only when @mentioned; see `ChannelMemberConfig.muted`. */muted?: boolean;diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex 9863168d15f..c01d9373caf 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -22,7 +22,7 @@ import { ChannelMessage, ThreadRootMessage } from './ChannelMessage';import { Composer } from './Composer';import { hasReplyActivity } from './jobStatus';import { JoinEventLine } from './JoinEventLine';-import { channelJoinEvents, channelTimeline, isSelfJoinable } from './joinEvents';+import { channelJoinEvents, channelTimeline } from './joinEvents';import { isCurrentUserMember } from './memberName';import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';import { presentOutgoingMessage, timelineTail } from './outgoing';@@ -129,9 +129,7 @@ const Timeline = ({outgoing.length? [...detail.messages, ...outgoing.map((item) => item.message)]: detail.messages,- threadId || direct- ? []- : channelJoinEvents(detail.members, { selfJoinable: isSelfJoinable(detail.channel) }),+ threadId || direct ? [] : channelJoinEvents(detail.members),!detail.hasMore && before === undefined,): [];diff --git a/src/features/Channels/joinEvents.test.ts b/src/features/Channels/joinEvents.test.tsindex 54bb535fe47..9db48ebb364 100644--- a/src/features/Channels/joinEvents.test.ts+++ b/src/features/Channels/joinEvents.test.ts@@ -1,12 +1,13 @@import type { ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { channelJoinEvents, channelTimeline, isSelfJoinable } from './joinEvents';+import { channelJoinEvents, channelTimeline } from './joinEvents';const member = (id: string, joinedAt: number, patch: Partial<ChannelPublicMember> = {}) =>({actorType: 'agent',id,+ invitedBy: null,joinedAt: new Date(joinedAt),role: null,...patch,@@ -16,12 +17,12 @@ const message = (id: string, at: number) =>({ createdAt: new Date(at), id }) as ChannelPublicMessage;describe('channelJoinEvents', () => {- it('groups members added together and credits the owner', () => {+ it('groups members one person added together and names that person', () => {const events = channelJoinEvents([owner,- member('a', 10),- member('b', 20),- member('c', 60_000),+ member('a', 10, { invitedBy: 'owner' }),+ member('b', 20, { invitedBy: 'owner' }),+ member('c', 60_000, { invitedBy: 'owner' }),]);expect(events.map((event) => event.members.map((entry) => entry.id))).toEqual([['a', 'b'],@@ -30,29 +31,28 @@ describe('channelJoinEvents', () => {expect(events.every((event) => event.inviter === owner)).toBe(true);});- it('names no inviter where people join by themselves', () => {- const [event] = channelJoinEvents([owner, member('a', 60_000, { actorType: 'user' })], {- selfJoinable: true,- });- expect(event.inviter).toBeUndefined();+ it('names the admin who added a member, not the owner', () => {+ const admin = member('admin', 0, { actorType: 'user', invitedBy: 'owner', role: 'admin' });+ const [, event] = channelJoinEvents([+ owner,+ admin,+ member('a', 60_000, { invitedBy: 'admin' }),+ ]);+ expect(event.inviter).toBe(admin);});- it.each([- [{ projectId: 'prj_1', visibility: 'private', workspaceId: 'ws' }, true],- [{ projectId: null, visibility: 'public', workspaceId: 'ws' }, true],- [{ projectId: null, visibility: 'private', workspaceId: 'ws' }, false],- [{ projectId: 'prj_1', visibility: 'private', workspaceId: null }, false],- ] as const)('tells which Channels take self-joins: %o β %s', (channel, expected) => {- expect(isSelfJoinable(channel)).toBe(expected);+ it('names no inviter for someone who joined on their own', () => {+ const [event] = channelJoinEvents([owner, member('a', 60_000, { actorType: 'user' })]);+ expect(event.inviter).toBeUndefined();});- it('does not guess the inviter when an admin could have added members', () => {- const [event] = channelJoinEvents([+ it('splits members joining together when different people added them', () => {+ const events = channelJoinEvents([owner,- member('admin', 0, { actorType: 'user', role: 'admin' }),- member('a', 60_000),+ member('a', 10, { invitedBy: 'owner' }),+ member('b', 20, { actorType: 'user' }),]);- expect(event.inviter).toBeUndefined();+ expect(events.map((event) => event.members.map((entry) => entry.id))).toEqual([['a'], ['b']]);});});diff --git a/src/features/Channels/joinEvents.ts b/src/features/Channels/joinEvents.tsindex 4d1245af3b0..d5bf91e5094 100644--- a/src/features/Channels/joinEvents.ts+++ b/src/features/Channels/joinEvents.ts@@ -1,4 +1,4 @@-import type { ChannelListItem, ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';+import type { ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';/** Members added by one action land within this window and read as one line. */const BATCH_MS = 5000;@@ -7,9 +7,8 @@ export interface ChannelJoinEvent {at: number;id: string;/**- * Only owners and admins add members. With no admin besides the owner, the owner added- * everyone else; otherwise the adder is unknown and the line says who joined. A Channel people- * can join on their own (see {@link isSelfJoinable}) never names an inviter.+ * The member who added them, from `ChannelPublicMember.invitedBy`. Absent when they joined on+ * their own, or joined before the adder was kept: the line then says who joined.*/inviter?: ChannelPublicMember;members: ChannelPublicMember[];@@ -17,26 +16,18 @@ export interface ChannelJoinEvent {const time = (value: Date | string) => new Date(value).getTime();-/** A workspace project's Channels and public Channels take members who join by themselves. */-export const isSelfJoinable = (- channel: Pick<ChannelListItem, 'projectId' | 'visibility' | 'workspaceId'>,-) => !!channel.workspaceId && (!!channel.projectId || channel.visibility === 'public');--export const channelJoinEvents = (- members: ChannelPublicMember[],- { selfJoinable = false }: { selfJoinable?: boolean } = {},-): ChannelJoinEvent[] => {+export const channelJoinEvents = (members: ChannelPublicMember[]): ChannelJoinEvent[] => {+ const byId = new Map(members.map((member) => [member.id, member]));const owner = members.find((member) => member.role === 'owner');- const inviter =- selfJoinable || members.some((member) => member.role === 'admin') ? undefined : owner;const joined = members.filter((member) => member !== owner).sort((a, b) => time(a.joinedAt) - time(b.joinedAt));const events: ChannelJoinEvent[] = [];for (const member of joined) {const at = time(member.joinedAt);+ const inviter = member.invitedBy ? byId.get(member.invitedBy) : undefined;const last = events.at(-1);- if (last && at - last.at <= BATCH_MS) last.members.push(member);+ if (last && at - last.at <= BATCH_MS && last.inviter === inviter) last.members.push(member);else events.push({ at, id: `join:${member.id}`, inviter, members: [member] });}return events;diff --git a/src/libs/i18n/serverTranslation.test.ts b/src/libs/i18n/serverTranslation.test.tsindex 4638779d75e..6ab9260ace1 100644--- a/src/libs/i18n/serverTranslation.test.ts+++ b/src/libs/i18n/serverTranslation.test.ts@@ -1,11 +1,4 @@// @vitest-environment node-// Vitest 5 races the first dynamic import inside `translation()` against-// `vi.mock` registration (vitest#7040). Resolving the mocked default modules-// here β at module scope, after `vi.mock` hoisting and before any test runs β-// makes the loader hit the mock instead of the real locale file.-import '@/locales/default/models';-import '@/locales/default/providers';-import { cookies } from 'next/headers';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -14,7 +7,42 @@ import { normalizeLocale } from '@/locales/resources';import { getLocale, translation } from './serverTranslation';-// Mock external dependencies+// Locale files by namespace. The loader is faked instead of mocking `@/locales/default/*`:+// those modules are reached by a templated dynamic import, which `vi.mock` does not reliably+// intercept, so a test could read the real English file instead (vitest#7040).+const { defaults, locales } = vi.hoisted(() => ({+ defaults: {+ chat: { welcome: 'Welcome to the chat' },+ // Flat keys: `nested.key` is one key, not a nested path.+ common: {+ 'key1': 'Value 1',+ 'key2': 'Value 2 with {{param}}',+ 'multiParam': 'Hello {{name}}, you have {{count}} messages',+ 'nested.key': 'Nested value',+ 'simpleText': 'Just a simple text',+ 'very.deeply.nested.key': 'Found the nested value',+ 'withParam': 'Text with {{param}}',+ },+ models: { 'gpt-4.description': 'GPT-4 description' },+ providers: { 'openai.description': 'OpenAI provider description' },+ } as Record<string, Record<string, string>>,+ locales: {+ 'fr-FR': { common: { key1: 'Valeur 1' } },+ } as Record<string, Record<string, Record<string, string>>>,+}));++// Same contract as the real loader: the default locale reads the default module, another locale+// its JSON, and a missing JSON reports the fallback and reads the default module instead.+vi.mock('@/utils/i18n/loadI18nNamespaceModule', () => ({+ loadI18nNamespaceModuleWithFallback: vi.fn(async ({ defaultLang, lng, ns, onFallback }) => {+ if (lng === defaultLang) return { default: defaults[ns] };+ const module = locales[lng]?.[ns];+ if (module) return { default: module };+ onFallback?.({ error: new Error(`No ${lng}/${ns}`), lng, ns });+ return { default: defaults[ns] };+ }),+}));+vi.mock('next/headers', () => ({cookies: vi.fn(),}));@@ -32,37 +60,6 @@ vi.mock('@/utils/env', () => ({isDev: false,}));-// Mock default locale modules with flat key structure (i18n keys are flat, not nested objects)-// Keys like 'nested.key' are direct string keys, not nested property paths-vi.mock('@/locales/default/common', () => ({- 'key1': 'Value 1',- 'key2': 'Value 2 with {{param}}',- 'nested.key': 'Nested value',- 'multiParam': 'Hello {{name}}, you have {{count}} messages',- 'simpleText': 'Just a simple text',- 'withParam': 'Text with {{param}}',- 'very.deeply.nested.key': 'Found the nested value',- // Add exports for testing missing keys (will be undefined, triggering fallback)- 'nonexistent': undefined,- 'totally.missing.key': undefined,-}));--vi.mock('@/locales/default/chat', () => ({- welcome: 'Welcome to the chat',-}));--vi.mock('@/locales/default/models', () => ({- default: {- 'gpt-4.description': 'GPT-4 description',- },-}));--vi.mock('@/locales/default/providers', () => ({- default: {- 'openai.description': 'OpenAI provider description',- },-}));-describe('getLocale', () => {const mockCookieStore = {get: vi.fn(),@@ -108,6 +105,7 @@ describe('translation', () => {it('should fallback to the default locale when a locale file is missing a key', async () => {const { t } = await translation('common', 'fr-FR');+ expect(t('key1')).toBe('Valeur 1');expect(t('key2', { param: 'fallback' })).toBe('Value 2 with fallback');});@@ -151,24 +149,18 @@ describe('translation', () => {});it('should fallback to default module when locale JSON is missing (models)', async () => {- vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Vitest 5 races the concurrent first imports inside `translation` against mock- // registration (vitest#7040), so warm the default module through the loader first.- await translation('models', 'en-US');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const { t } = await translation('models', 'zz-ZZ');+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('zz-ZZ/models'));expect(t('gpt-4.description')).toBe('GPT-4 description');});it('should fallback to default module when locale JSON is missing (providers)', async () => {- vi.spyOn(console, 'warn').mockImplementation(() => {});-- // Vitest 5 races the concurrent first imports inside `translation` against mock- // registration (vitest#7040), so warm the default module through the loader first.- await translation('providers', 'en-US');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const { t } = await translation('providers', 'zz-ZZ');+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('zz-ZZ/providers'));expect(t('openai.description')).toBe('OpenAI provider description');});});