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.

🐛 fix(channel): run a project Channel inside its project (#22930)

Arvin Xu8a97ab8228a6
diff --git a/apps/server/src/services/channel/ChannelCoordinator.project.test.ts b/apps/server/src/services/channel/ChannelCoordinator.project.test.ts
new file mode 100644
index 00000000000..15913e297ac
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelCoordinator.project.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelCoordinator } from './ChannelCoordinator';
+
+const { executions, execAgent, getScopedOnlineDevices } = vi.hoisted(() => ({
+ execAgent: vi.fn(),
+ executions: {
+ accepted: vi.fn(),
+ candidates: vi.fn(),
+ claim: vi.fn(),
+ finishDispatch: vi.fn(),
+ heartbeat: vi.fn(),
+ input: vi.fn(),
+ openingReply: vi.fn(),
+ primaryReply: vi.fn(),
+ recentContext: vi.fn(),
+ },
+ getScopedOnlineDevices: vi.fn(),
+}));
+
+vi.mock('@/database/repositories/channel', () => ({
+ ChannelExecutionRepository: class {
+ constructor() {
+ return executions;
+ }
+ },
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ execAgent = execAgent;
+ },
+}));
+vi.mock('@/server/globalConfig', () => ({ getServerDefaultAgentConfig: () => ({}) }));
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({ getScopedOnlineDevices }));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => false }));
+vi.mock('./attachments', () => ({ resolveChannelAttachments: vi.fn().mockResolvedValue({}) }));
+vi.mock('./ChannelRoutingService', () => ({
+ ChannelRoutingService: class {
+ advance = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));
+vi.mock('./replyOpening', () => ({ openChannelReply: vi.fn() }));
+vi.mock('./worktree', () => ({ createChannelWorktree: vi.fn() }));
+
+const chain = (rows: unknown[]) => {
+ const result = Object.assign(Promise.resolve(rows), {
+ from: vi.fn(),
+ limit: vi.fn(),
+ orderBy: vi.fn(),
+ where: vi.fn(),
+ });
+ for (const method of ['from', 'limit', 'orderBy', 'where'] as const)
+ result[method].mockReturnValue(result);
+ return result;
+};
+
+/** A Channel row as `advance` reads it, with only the fields the dispatch path needs. */
+const channelRow = (projectId: string | null) => ({
+ id: 'channel',
+ isDeleted: false,
+ projectId,
+ status: 'active',
+ workspaceId: null,
+});
+
+const oneJob = (projectId: string | null) => {
+ const coordinator = new ChannelCoordinator({
+ select: vi
+ .fn()
+ .mockReturnValueOnce(chain([channelRow(projectId)]))
+ .mockReturnValueOnce(chain([])),
+ } as never);
+ executions.candidates.mockResolvedValue({
+ heads: [{ id: 'job-1', memberId: 'job-1', status: 'queued' }],
+ inFlight: [],
+ });
+ executions.claim.mockResolvedValue({
+ job: {
+ channelId: 'channel',
+ executionConfig: { runtime: 'native' },
+ id: 'job-1',
+ leaseOwner: 'dispatcher',
+ manifest: {
+ cutoffSequence: 1,
+ requestMessageId: 'message-1',
+ self: { agentId: 'agt-1', memberId: 'job-1', name: 'Agent' },
+ threadId: null,
+ threadRootSequence: null,
+ },
+ operationId: 'op-1',
+ },
+ member: { agentId: 'agt-1' },
+ topic: { id: 'tpc-1', userId: 'user-1' },
+ });
+ return coordinator;
+};
+
+describe('Channel dispatch project context', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ getScopedOnlineDevices.mockResolvedValue([]);
+ executions.input.mockResolvedValue([]);
+ executions.recentContext.mockResolvedValue({ messages: [], omitted: 0 });
+ executions.primaryReply.mockResolvedValue(null);
+ executions.openingReply.mockResolvedValue(undefined);
+ executions.heartbeat.mockResolvedValue(true);
+ execAgent.mockResolvedValue({ success: true });
+ });
+
+ it("passes the Channel's project to the run as appContext.projectId", async () => {
+ await oneJob('proj-apollo').advance('channel');
+
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ expect(execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: { projectId: 'proj-apollo', topicId: 'tpc-1' },
+ }),
+ );
+ });
+
+ it('sends no projectId for a Channel that belongs to no project', async () => {
+ await oneJob(null).advance('channel');
+
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ const [{ appContext }] = execAgent.mock.calls[0];
+ expect(appContext).toEqual({ topicId: 'tpc-1' });
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index e3692c7aa61..11527f1380f 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -106,7 +106,9 @@ export class ChannelCoordinator {
claim = await claimNow();
await Promise.all([
notifyChannel(this.db, channelId),
- claim ? this.dispatch(claim, channel.workspaceId) : undefined,
+ claim
+ ? this.dispatch(claim, channel.workspaceId, channel.projectId)
+ : undefined,
]);
}
},
@@ -139,7 +141,17 @@ export class ChannelCoordinator {
return this.executions.assignWorktree(channelId, candidate, created.path);
}
- private async dispatch({ job, member, topic }: ChannelClaim, workspaceId: string | null) {
+ /**
+ * `projectId` is the Channel's own project (`channels.projectId`), not one inferred
+ * from the Agent: a Channel that belongs to a project runs inside it. It travels as
+ * `appContext.projectId` so the run gets the project prompt, is recognised as the
+ * project coordinator, and files the tasks it creates under the project.
+ */
+ private async dispatch(
+ { job, member, topic }: ChannelClaim,
+ workspaceId: string | null,
+ projectId?: string | null,
+ ) {
if (
!job.operationId ||
!job.leaseOwner ||
@@ -225,7 +237,7 @@ export class ChannelCoordinator {
additionalPluginIds: [ChannelIdentifier],
agentId: member.agentId,
agentConfigSnapshot: config,
- appContext: { topicId: topic.id },
+ appContext: { ...(projectId ? { projectId } : {}), topicId: topic.id },
deviceId: config.deviceId,
disableLocalSystem: !config.deviceId,
...attachments,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts
index cfd4b8674f0..d39f1de6524 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts
@@ -39,7 +39,11 @@ const createdTask = {
status: 'backlog',
};
-const setup = (overrides: { parent?: { id: string; identifier: string; projectId: string } }) => {
+const setup = (
+ overrides: { parent?: { id: string; identifier: string; projectId: string } },
+ /** `null` runs outside any project; omitted runs inside the fixture project. */
+ runProjectId: string | null = 'proj-apollo',
+) => {
const taskService = {
createTask: vi.fn().mockResolvedValue(createdTask),
updateTaskWithAssigneeLock: vi.fn().mockResolvedValue({}),
@@ -53,7 +57,7 @@ const setup = (overrides: { parent?: { id: string; identifier: string; projectId
agentId: 'agt-coordinator',
agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
db: {} as any,
- projectId: 'proj-apollo',
+ projectId: runProjectId ?? undefined,
taskCaller: { update: vi.fn().mockResolvedValue({ data: { id: 'task-1' } }) } as any,
taskModel: taskModel as any,
taskService: taskService as any,
@@ -151,6 +155,15 @@ describe('task runtime inside a project', () => {
);
});
+ it('leaves a run outside any project its tasks unfiled', async () => {
+ const { runtime, taskService } = setup({}, null);
+
+ const result = await runtime.createTask({ instruction: 'Workspace chore', name: 'Chore' });
+
+ expect(result.success).toBe(true);
+ expect(taskService.createTask.mock.calls[0][0].projectId).toBeUndefined();
+ });
+
it("checks a reassignment against the edited task's own project", async () => {
const { runtime, taskModel } = setup({});
taskModel.resolve.mockResolvedValue({
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index bf4a771a480..63355f47282 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -1097,6 +1097,38 @@ describe('ProjectModel', () => {
]);
});
+ // A Channel run topic carries the requester's Channel request and the history
+ // the Agent read there; the project sidebar must not become a second door into
+ // that transcript for members who are not in the Channel.
+ it("keeps a Channel's run topics out of the project conversation listing", async () => {
+ const project = await createProject(repo, { name: 'Channel host' });
+ const [channelAgent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Channel responder', userId, visibility: 'public' })
+ .returning();
+ await serverDB.insert(topics).values([
+ {
+ agentId: channelAgent.id,
+ id: 'project-regular-topic',
+ projectId: project.id,
+ title: 'Planning',
+ userId,
+ },
+ {
+ agentId: channelAgent.id,
+ id: 'project-channel-topic',
+ projectId: project.id,
+ title: 'Launch checklist from the Channel',
+ trigger: 'channel',
+ userId,
+ },
+ ]);
+
+ const list = await model.listTopics(project.id);
+
+ expect(list.map((topic) => topic.id)).toEqual(['project-regular-topic']);
+ });
+
// The project sidebar renders a running row's elapsed clock from this. Rows
// the client holds no local operation for (every non-active running topic
// after a refresh) otherwise show a spinner with no timer.
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index f184d9e954b..2e52ebbd607 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -23,6 +23,7 @@ import { works } from '../schemas/work';
import type { LobeChatDatabase } from '../type';
import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';
import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';
+import { notChannelTopic } from '../utils/topicVisibility';
import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';
import {
buildWorkspacePayload,
@@ -1158,6 +1159,10 @@ export class ProjectModel {
eq(topics.projectId, projectId),
buildWorkspaceWhere(scope, topics),
isNull(topics.deletedAt),
+ // A Channel run topic holds the requester's Channel request and the
+ // history the Agent read there; it is surfaced through the Channel
+ // UI only, never as a project conversation — see `notChannelTopic`.
+ notChannelTopic(),
),
)
.orderBy(desc(topics.updatedAt));
diff --git a/packages/database/src/repositories/channel/__tests__/topicProject.test.ts b/packages/database/src/repositories/channel/__tests__/topicProject.test.ts
new file mode 100644
index 00000000000..01158a2eba6
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/topicProject.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { resolveTopic } from '../topic';
+
+const executionConfig = { model: 'gpt-5', provider: 'openai', runtime: 'native' } as never;
+
+const channel = (projectId: string | null) =>
+ ({ id: 'channel-1', projectId, workspaceId: 'ws-1' }) as never;
+
+const member = { agentId: 'agt-1', id: 'member-1' } as never;
+const job = { id: 'job-1', requesterMemberId: 'member-1', threadId: null } as never;
+
+/** A completed run this Channel/topic pair can continue from. */
+const reusableRun = (topicProjectId: string | null) => {
+ const now = new Date();
+ return {
+ job: {
+ acceptedAt: now,
+ claimedAt: now,
+ draft: 'The reply',
+ executionConfig,
+ id: 'job-0',
+ isolatedAt: false,
+ manifest: { cutoffSequence: 1 },
+ publicationRevoked: false,
+ writerHeld: false,
+ },
+ operation: { status: 'done' },
+ topic: {
+ agentId: 'agt-1',
+ id: 'tpc-1',
+ isDeleted: false,
+ projectId: topicProjectId,
+ updatedAt: now,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ },
+ };
+};
+
+const chain = (rows: unknown[]) => {
+ const result = Object.assign(Promise.resolve(rows), {
+ from: vi.fn(),
+ leftJoin: vi.fn(),
+ limit: vi.fn(),
+ orderBy: vi.fn(),
+ where: vi.fn(),
+ });
+ for (const method of ['from', 'leftJoin', 'limit', 'orderBy', 'where'] as const)
+ result[method].mockReturnValue(result);
+ return result;
+};
+
+/** A transaction stub covering the reads/writes `resolveTopic` makes. */
+const transaction = (rows: unknown[], returned: Record<string, unknown[]>) => {
+ const insertValues = vi.fn(() => ({
+ returning: vi.fn(async () => returned.insert ?? []),
+ }));
+ const updateReturning = vi.fn(async () => returned.update ?? []);
+ const updateSet = vi.fn(() => ({ where: vi.fn(() => ({ returning: updateReturning })) }));
+ const update = vi.fn(() => ({ set: updateSet }));
+ const insert = vi.fn(() => ({ values: insertValues }));
+
+ return {
+ insert,
+ insertValues,
+ select: vi.fn(() => chain(rows)),
+ tx: { insert, select: vi.fn(() => chain(rows)), update } as never,
+ update,
+ updateReturning,
+ updateSet,
+ };
+};
+
+describe('resolveTopic — the topic inherits the Channel’s project', () => {
+ it('creates the topic inside the Channel’s project', async () => {
+ const store = transaction([], {
+ insert: [{ id: 'tpc-new', projectId: 'proj-1' }],
+ });
+
+ const topic = await resolveTopic(
+ store.tx,
+ channel('proj-1'),
+ job,
+ member,
+ 'user-1',
+ 2,
+ executionConfig,
+ );
+
+ expect(store.insertValues).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'proj-1', userId: 'user-1', workspaceId: 'ws-1' }),
+ );
+ expect(topic).toMatchObject({ id: 'tpc-new', projectId: 'proj-1' });
+ });
+
+ it('adopts the project for a reused topic that has none', async () => {
+ const store = transaction([reusableRun(null)], {
+ update: [{ id: 'tpc-1', projectId: 'proj-1' }],
+ });
+
+ const topic = await resolveTopic(
+ store.tx,
+ channel('proj-1'),
+ job,
+ member,
+ 'user-1',
+ 2,
+ executionConfig,
+ );
+
+ expect(store.updateSet).toHaveBeenCalledWith({ projectId: 'proj-1' });
+ expect(topic).toMatchObject({ id: 'tpc-1', projectId: 'proj-1' });
+ });
+
+ it('never re-homes a topic already bound to another project', async () => {
+ const store = transaction([reusableRun('proj-9')], {});
+
+ const topic = await resolveTopic(
+ store.tx,
+ channel('proj-1'),
+ job,
+ member,
+ 'user-1',
+ 2,
+ executionConfig,
+ );
+
+ expect(store.update).not.toHaveBeenCalled();
+ expect(topic).toMatchObject({ id: 'tpc-1', projectId: 'proj-9' });
+ });
+
+ it('leaves a workspace Channel’s topic without a project', async () => {
+ const store = transaction([reusableRun(null)], {});
+
+ const topic = await resolveTopic(
+ store.tx,
+ channel(null),
+ job,
+ member,
+ 'user-1',
+ 2,
+ executionConfig,
+ );
+
+ expect(store.update).not.toHaveBeenCalled();
+ expect(topic).toMatchObject({ id: 'tpc-1', projectId: null });
+ });
+});
diff --git a/packages/database/src/repositories/channel/topic.ts b/packages/database/src/repositories/channel/topic.ts
index c9d66f55d0e..1063788f847 100644
--- a/packages/database/src/repositories/channel/topic.ts
+++ b/packages/database/src/repositories/channel/topic.ts
@@ -65,6 +65,19 @@ export const resolveTopic = async (
!topic.isDeleted &&
(job.threadId || Date.now() - topic.updatedAt.getTime() <= TOPIC_STALE_THRESHOLD)
) {
+ // A Channel that belongs to a project runs inside it, so the topic it works in
+ // must say which project it belongs to: that binding is what the run resolves
+ // its project context from (project prompt, coordinator scope, task ownership).
+ // Topics created before the Channel was bound carry none — adopt the Channel's
+ // project once. A topic already bound elsewhere is never re-homed by a run.
+ if (!topic.projectId && channel.projectId) {
+ const [adopted] = await tx
+ .update(topics)
+ .set({ projectId: channel.projectId })
+ .where(eq(topics.id, topic.id))
+ .returning();
+ return adopted ?? topic;
+ }
return topic;
}
@@ -73,6 +86,9 @@ export const resolveTopic = async (
.values({
agentId: member.agentId,
mode: 'default',
+ // The Channel's project, read from the Channel itself (never inferred from the
+ // Agent), so a conversation started by a project Channel is born in the project.
+ projectId: channel.projectId ?? undefined,
trigger: CHANNEL_TOPIC_TRIGGER,
userId,
workspaceId: channel.workspaceId,