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): bind no device to a Channel by default (#23037)

Arvin Xu538ae5820ade
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts
index e1f48c49bed..6527a7345d7 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts
@@ -40,16 +40,15 @@ describe('agent.createAgent direct Channel', () => {
"opens the creator's direct Channel to the new Agent in scope %s",
async (workspaceId) => {
const config = { name: '小满', title: 'Health Assistant' };
- await expect(
- caller(workspaceId).createAgent({ config, localDeviceId: 'desktop' }),
- ).resolves.toEqual({ agentId: 'agt_new' });
+ await expect(caller(workspaceId).createAgent({ config })).resolves.toEqual({
+ agentId: 'agt_new',
+ });
- // The device hint is for the Channel only; the Agent itself is created without it.
expect(mocks.createAgent).toHaveBeenCalledWith({ config });
+ // The direct Channel binds no device, so nothing about this desktop is passed along.
expect(mocks.createAgentDirectChannel).toHaveBeenCalledWith({
agentId: 'agt_new',
db: {},
- localDeviceId: 'desktop',
userId: 'owner',
workspaceId,
});
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
index ce7056f6178..359410dd66c 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -63,21 +63,17 @@ export const lifecycleRouter = router({
z.object({
config: CreateAgentSchema.optional(),
groupId: z.string().optional(),
- /** The caller's own desktop, where a direct Channel to a local Agent runs. */
- localDeviceId: z.string().min(1).optional(),
visibility: z.enum(['private', 'public']).optional(),
}),
)
.mutation(async ({ input, ctx }) => {
- const { localDeviceId, ...params } = input;
- const result = await ctx.agentService.createAgent(params);
+ const result = await ctx.agentService.createAgent(input);
// A hidden (virtual) copy, such as a Market agent run from an @ mention, is
// never a conversation of its own, so it gets no direct Channel.
- if (params.config?.virtual) return result;
+ if (input.config?.virtual) return result;
await createAgentDirectChannel({
agentId: result.agentId,
db: ctx.serverDB,
- localDeviceId,
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
});
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 8e261d52c0e..3d84b9303cf 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -224,11 +224,9 @@ export const channelRouter = router({
* direct Channels. Null when the Agent cannot answer in a Channel (no reachable device).
*/
openDirect: channelProcedure
- .input(z.object({ agentId: z.string().min(1), localDeviceId: z.string().min(1).optional() }))
+ .input(z.object({ agentId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
- const access = await ctx.channelService.openDirect(input.agentId, {
- localDeviceId: input.localDeviceId,
- });
+ const access = await ctx.channelService.openDirect(input.agentId);
return { data: access?.channel.id ?? null, success: true };
}),
list: channelProcedure.query(async ({ ctx }) => ({
diff --git a/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts b/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts
index 9a160b54255..68f7056f798 100644
--- a/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts
@@ -127,6 +127,48 @@ describe('resolveRunAgentConfig', () => {
expect(memberDeviceOverride).toEqual({ boundDeviceId: 'dev-1', executionTarget: 'local' });
expect(agentConfig.agencyConfig?.executionTarget).toBe('local');
});
+
+ // A Channel run with no device picked follows the requester's own device for the Agent, as
+ // their ordinary conversation would; the frozen snapshot still decides the model.
+ describe('a dispatcher snapshot', () => {
+ const regular = () =>
+ ({ ...(webOnboardingRow() as object), id: 'agent-regular', slug: null }) as never;
+ const run = (snapshotFollowsCallerDevice?: boolean) =>
+ resolveRunAgentConfig(
+ { ...deps, resolveAgentConfigOrThrow: async () => regular() },
+ {
+ agentConfigSnapshot: { model: 'gpt-5', provider: 'openai' } as never,
+ identifier: 'agent-regular',
+ snapshotFollowsCallerDevice,
+ throwIfExecutionAborted: async () => {},
+ },
+ );
+
+ beforeEach(() => {
+ getPreference.mockResolvedValue({
+ agentDeviceOverrides: {
+ 'agent-regular': { boundDeviceId: 'dev-1', executionTarget: 'local' },
+ },
+ agentModelOverrides: { 'agent-regular': { model: 'claude', provider: 'anthropic' } },
+ });
+ });
+
+ it("layers the caller's device override when it follows the caller's device", async () => {
+ const { agentConfig, memberDeviceOverride } = await run(true);
+
+ expect(memberDeviceOverride).toEqual({ boundDeviceId: 'dev-1', executionTarget: 'local' });
+ expect(agentConfig.agencyConfig?.executionTarget).toBe('local');
+ expect(agentConfig.model).toBe('gpt-5');
+ });
+
+ it('applies no member override otherwise', async () => {
+ const { agentConfig, memberDeviceOverride } = await run();
+
+ expect(memberDeviceOverride).toBeUndefined();
+ expect(agentConfig.agencyConfig?.executionTarget).not.toBe('local');
+ expect(getPreference).not.toHaveBeenCalled();
+ });
+ });
});
describe('Codex Task model overrides', () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 82863023aa6..e787dba464a 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -278,6 +278,7 @@ export const execAgentTurn = async (
appContext,
chatConfigOverride,
agentConfigSnapshot: params.agentConfigSnapshot,
+ snapshotFollowsCallerDevice: params.snapshotFollowsCallerDevice,
identifier,
instructions,
modelOverride,
diff --git a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
index 2ce807b47ec..d17b58305ce 100644
--- a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
+++ b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts
@@ -42,6 +42,7 @@ export interface ResolveRunAgentConfigInput {
* language appended to the system role) must be read for this user instead.
*/
shareVisitorUserId?: string;
+ snapshotFollowsCallerDevice?: InternalExecAgentParams['snapshotFollowsCallerDevice'];
throwIfExecutionAborted: (stage: string) => Promise<void>;
toolModeOverride?: InternalExecAgentParams['toolModeOverride'];
}
@@ -198,7 +199,12 @@ export const resolveRunAgentConfig = async (
const scope = (appContext?.scope ?? undefined) as MessageMapScope | undefined;
const [overrides, canManageAgent, userLocale, pageSandboxAvailable] = await Promise.all([
input.agentConfigSnapshot
- ? Promise.resolve({} as WorkspaceMemberOverrides)
+ ? // The snapshot decided model and mode; only the caller's device may still follow them.
+ input.snapshotFollowsCallerDevice
+ ? loadWorkspaceMemberOverrides(deps, resolvedAgentId).then(
+ ({ device }): WorkspaceMemberOverrides => ({ device }),
+ )
+ : Promise.resolve({} as WorkspaceMemberOverrides)
: loadWorkspaceMemberOverrides(deps, resolvedAgentId),
resolveCanManage(deps, row, agentWorkspaceId, isPublicWorkspaceAgent),
// A share visitor replies in their own language, not the owner's.
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 99d7f2ccb6c..4b0dfc4b237 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -329,6 +329,12 @@ export interface InternalExecAgentParams extends ExecAgentParams {
shareGate?: AgentShareGate;
/** Abort startup before the agent runtime operation is created */
signal?: AbortSignal;
+ /**
+ * With `agentConfigSnapshot`, still layer the caller's own device override on top, as an
+ * ordinary conversation would. Set by a Channel run whose member has no device picked in the
+ * Channel; the snapshot keeps deciding everything else. Server-only, never client-passable.
+ */
+ snapshotFollowsCallerDevice?: boolean;
/**
* The send directly steered the turn it replaces: an interrupting "send
* now", not a follow-up that waited in queue and started as the next turn.
diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts
index 204aa9c1944..d37c858744b 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts
@@ -118,6 +118,45 @@ describe('Channel concurrent startup', () => {
});
afterEach(() => vi.restoreAllMocks());
+ // A Channel binds no device by default: an unbound run keeps the Agent's own settings and the
+ // requester's device for it, while a device picked in the Channel pins the run there.
+ it.each([
+ ['no device picked', { agencyConfig: { boundDeviceId: 'mac', executionTarget: 'device' } }],
+ [
+ 'a device picked in the Channel',
+ { agencyConfig: { boundDeviceId: 'mac' }, deviceId: 'dev-2', workingDirectory: '/repo' },
+ ],
+ ])('dispatches with %s', async (_, environment) => {
+ const claim = executions.claim.getMockImplementation()!;
+ executions.claim.mockImplementation(async (...args: Parameters<typeof claim>) => {
+ const claimed = await claim(...args);
+ return {
+ ...claimed,
+ job: { ...claimed.job, executionConfig: { runtime: 'codex', ...environment } },
+ };
+ });
+
+ await coordinator(1).advance('channel');
+
+ const [params] = execAgent.mock.calls[0];
+ if ('deviceId' in environment) {
+ expect(params).toMatchObject({ deviceId: 'dev-2', snapshotFollowsCallerDevice: false });
+ expect(params.agentConfigSnapshot.agencyConfig).toEqual({
+ boundDeviceId: 'dev-2',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ workingDirByDevice: { 'dev-2': '/repo' },
+ });
+ } else {
+ expect(params).toMatchObject({ deviceId: undefined, snapshotFollowsCallerDevice: true });
+ expect(params).not.toHaveProperty('disableLocalSystem');
+ expect(params.agentConfigSnapshot.agencyConfig).toEqual({
+ boundDeviceId: 'mac',
+ executionTarget: 'device',
+ });
+ }
+ });
+
it('notifies the claimed reply state before runtime startup resolves', async () => {
const gate = Promise.withResolvers<{ success: boolean }>();
execAgent.mockReturnValue(gate.promise);
diff --git a/apps/server/src/services/channel/ChannelCoordinator.test.ts b/apps/server/src/services/channel/ChannelCoordinator.test.ts
index 95588397056..b8386626dff 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.test.ts
@@ -62,6 +62,7 @@ describe('Channel completion physical writer confirmation', () => {
leaseOwner: string | null = null,
status = 'done',
topicId: string | null = null,
+ deviceId: string | null = 'device',
) => {
const job = {
channelId: 'channel',
@@ -80,7 +81,7 @@ describe('Channel completion physical writer confirmation', () => {
...job,
job,
operation,
- config: { runtime, deviceId: 'device', deviceOwnerId: 'owner' },
+ config: deviceId ? { runtime, deviceId, deviceOwnerId: 'owner' } : { runtime },
},
];
const query = Object.assign(Promise.resolve(rows), {
@@ -136,6 +137,35 @@ describe('Channel completion physical writer confirmation', () => {
expect(updateTopic).not.toHaveBeenCalled();
});
+ // With no device picked in the Channel the run went through the ordinary pipeline, so its
+ // writer used to stay held after the reply and every later request waited as member_busy.
+ it('releases an external writer with no Channel device once the ordinary run stops', async () => {
+ await coordinator(false, 'codex', null, 'done', null, null).complete('channel', 'job', 'op');
+ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op', topicId: undefined });
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
+ });
+
+ it('keeps an unbound external writer while its run can neither stop nor has ended', async () => {
+ interruptTask.mockResolvedValueOnce({ success: false });
+ await coordinator(true, 'codex', null, 'running', null, null).complete('channel', 'job', 'op');
+ expect(executions.releaseWriter).not.toHaveBeenCalled();
+ });
+
+ // An unbound coding Agent may still have run on a device through its own settings; a failed
+ // operation does not prove its CLI exited, so the writer waits for confirmed cancellation.
+ it('keeps an unbound external writer while its device cancellation is unconfirmed', async () => {
+ interruptTask.mockResolvedValueOnce({ deviceCancellationConfirmed: false, success: false });
+ await coordinator(true, 'codex', null, 'error', null, null).complete('channel', 'job', 'op');
+ expect(executions.releaseWriter).not.toHaveBeenCalled();
+ });
+
+ it('releases an ended unbound external writer that left no device process behind', async () => {
+ interruptTask.mockResolvedValueOnce({ success: false });
+ await coordinator(true, 'codex', null, 'error', null, null).complete('channel', 'job', 'op');
+ expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
+ });
+
it('releases a completed writer only after the device confirms termination', async () => {
executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
await coordinator().complete('channel', 'job', 'op');
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index 70b15e717c0..d71431a1c9b 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -107,9 +107,7 @@ export class ChannelCoordinator {
claim = await claimNow();
await Promise.all([
notifyChannel(this.db, channelId),
- claim
- ? this.dispatch(claim, channel.workspaceId, channel.projectId)
- : undefined,
+ claim ? this.dispatch(claim, channel.workspaceId, channel.projectId) : undefined,
]);
}
},
@@ -163,17 +161,19 @@ export class ChannelCoordinator {
)
throw new Error('Incomplete Channel execution claim');
const config: ChannelExecutionConfig = structuredClone(job.executionConfig);
- // The claimed Channel environment is authoritative for this run.
- config.agencyConfig = {
- ...config.agencyConfig,
- executionTarget: config.deviceId ? 'device' : 'none',
- executionTargetSelectionPolicy: 'fixed',
- boundDeviceId: config.deviceId,
- workingDirByDevice:
- config.deviceId && config.workingDirectory
+ // A device a member picked for this Agent in the Channel is authoritative for the run.
+ // Without one the Channel binds nothing: the Agent runs where its own settings say, as the
+ // requester's ordinary conversation with it would.
+ if (config.deviceId)
+ config.agencyConfig = {
+ ...config.agencyConfig,
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ boundDeviceId: config.deviceId,
+ workingDirByDevice: config.workingDirectory
? { [config.deviceId]: config.workingDirectory }
: {},
- };
+ };
const completion: AgentHook = {
id: `channel:${job.id}`,
type: 'onComplete',
@@ -238,9 +238,10 @@ export class ChannelCoordinator {
additionalPluginIds: [ChannelIdentifier],
agentId: member.agentId,
agentConfigSnapshot: config,
+ // No device picked in the Channel: the requester's own device for this Agent applies.
+ snapshotFollowsCallerDevice: !config.deviceId,
appContext: { ...(projectId ? { projectId } : {}), topicId: topic.id },
deviceId: config.deviceId,
- disableLocalSystem: !config.deviceId,
...attachments,
hooks: [completion],
instructions: CHANNEL_INSTRUCTIONS,
@@ -434,7 +435,10 @@ export class ChannelCoordinator {
? await this.executions.revokeExpiredLease(job.channelId, job.id)
: 'settled';
if (dispatch === 'live') continue;
- if (row.config?.runtime === 'native') {
+ // A Native run, or any run with no device picked in the Channel, went through the
+ // ordinary pipeline, which knows where it routed the run; stop it there. Only a run on a
+ // device picked in the Channel needs that device to confirm the external process exited.
+ if (row.config?.runtime === 'native' || !row.config?.deviceId) {
const result = await this.service(
row.operation.userId,
row.operation.workspaceId,
@@ -442,12 +446,16 @@ export class ChannelCoordinator {
operationId: job.operationId,
topicId: row.operation.topicId ?? undefined,
});
+ // The ordinary pipeline may have run it on a device. A terminal status does not prove that
+ // process exited (a lost acknowledgement can fail the operation while it runs on), so an
+ // unconfirmed device cancellation keeps the writer, as for a device picked in the Channel.
+ if (result.deviceCancellationConfirmed === false) continue;
if (
!result.success &&
!['done', 'error', 'interrupted', 'abandoned'].includes(row.operation.status)
)
continue;
- if (row.config.deviceId) {
+ if (row.config?.runtime === 'native' && row.config.deviceId) {
const stopped = await deviceGateway.executeToolCall(
{
deviceId: row.config.deviceId,
@@ -462,7 +470,7 @@ export class ChannelCoordinator {
continue;
}
await this.executions.releaseWriter(job.channelId, job.id);
- } else if (row.config?.deviceId) {
+ } else {
// Use the frozen identity even if runtime cleanup already removed the topic marker.
const result = await deviceGateway.executeToolCall(
{
diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.ts
index 9e0cd84f88b..03fdb3274d1 100644
--- a/apps/server/src/services/channel/ChannelService.direct.test.ts
+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts
@@ -73,8 +73,7 @@ describe('the direct Channel of a new Agent', () => {
}));
querySystemInfo.mockResolvedValue({ homePath: '/Users/owner' });
});
- const createDirect = (localDeviceId?: string) =>
- new ChannelService({} as never, 'owner').createDirect('agt_new', { localDeviceId });
+ const createDirect = () => new ChannelService({} as never, 'owner').createDirect('agt_new');
it.each([
['its personal name', { name: ' 小满 ', title: 'Health Assistant' }, '小满'],
@@ -85,76 +84,32 @@ describe('the direct Channel of a new Agent', () => {
{ name: 'x'.repeat(CHANNEL_LIMITS.titleLength + 20) },
'x'.repeat(CHANNEL_LIMITS.titleLength),
],
- ])('binds a native Agent and titles the Channel with %s', async (_, identity, title) => {
+ ])('titles the Channel with %s', async (_, identity, title) => {
getAgent.mockResolvedValue({ model: 'gpt-5', ...identity });
- await expect(createDirect('desktop')).resolves.toEqual({ channel: { id: 'chn_1' } });
+ await expect(createDirect()).resolves.toEqual({ channel: { id: 'chn_1' } });
expect(getAgent).toHaveBeenCalledTimes(1);
- // A native Agent with no device of its own answers without one, even from a desktop.
- expect(findDevice).not.toHaveBeenCalled();
expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_new', title });
});
+ // A Channel binds no device by default: the Agent runs where its own settings say. Opening the
+ // conversation used to probe the bound device and failed while it was offline.
it.each([
+ ['a native Agent bound to a device', { boundDeviceId: 'mac', executionTarget: 'device' }],
[
- 'its own directory on that device',
- { workingDirByDevice: { mac: { path: '/repo' } } },
- null,
- '/real/repo',
+ 'an external Agent bound to a device with a directory',
+ { ...claudeCode, boundDeviceId: 'mac', workingDirByDevice: { mac: { path: '/repo' } } },
],
- ["the device's default directory", {}, '/projects', '/real/projects'],
- ["the device's home folder", {}, null, '/real/Users/owner'],
- ])(
- 'seats an external Agent on its bound device in %s',
- async (_, directories, defaultCwd, workingDirectory) => {
- getAgent.mockResolvedValue({
- agencyConfig: { ...claudeCode, ...directories, boundDeviceId: 'mac' },
- name: 'Claude',
- });
- findDevice.mockResolvedValue({
- defaultCwd,
- deviceId: 'mac',
- platform: 'darwin',
- userId: 'owner',
- });
-
- await createDirect('desktop');
-
- expect(findDevice).toHaveBeenCalledWith('mac');
- expect(create).toHaveBeenCalledWith({
- agentConfig: { deviceId: 'mac', deviceOwnerId: 'owner', workingDirectory },
- agentId: 'agt_new',
- title: 'Claude',
- });
- },
- );
-
- it("seats a local external Agent on its creator's desktop", async () => {
- getAgent.mockResolvedValue({ agencyConfig: claudeCode, name: 'Claude' });
- await createDirect('desktop');
- expect(create).toHaveBeenCalledWith(
- expect.objectContaining({
- agentConfig: {
- deviceId: 'desktop',
- deviceOwnerId: 'owner',
- workingDirectory: '/real/Users/owner',
- },
- }),
- );
- });
+ ['a local external Agent', claudeCode],
+ ['an external Agent that runs in a sandbox', { ...claudeCode, executionTarget: 'sandbox' }],
+ ])('opens %s without binding or probing a device', async (_, agencyConfig) => {
+ getAgent.mockResolvedValue({ agencyConfig, model: 'gpt-5', name: 'Windy' });
+
+ await expect(createDirect()).resolves.toEqual({ channel: { id: 'chn_1' } });
- it.each([
- ['a local external Agent created away from a desktop', claudeCode, undefined],
- [
- 'an external Agent that runs in a sandbox',
- { ...claudeCode, executionTarget: 'sandbox' },
- 'desktop',
- ],
- ])('opens the conversation without a device for %s', async (_, agencyConfig, localDeviceId) => {
- getAgent.mockResolvedValue({ agencyConfig, name: 'Claude' });
- await expect(createDirect(localDeviceId)).resolves.toEqual({ channel: { id: 'chn_1' } });
- // Its device is chosen in the Channel; nothing is probed before then.
expect(findDevice).not.toHaveBeenCalled();
- expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_new', title: 'Claude' });
+ expect(statPath).not.toHaveBeenCalled();
+ expect(querySystemInfo).not.toHaveBeenCalled();
+ expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_new', title: 'Windy' });
});
it('opens nothing for a runtime Channels do not support', async () => {
@@ -162,23 +117,13 @@ describe('the direct Channel of a new Agent', () => {
agencyConfig: { heterogeneousProvider: { type: 'openclaw' } },
name: 'Agent',
});
- await expect(createDirect('desktop')).resolves.toBeUndefined();
+ await expect(createDirect()).resolves.toBeUndefined();
expect(create).not.toHaveBeenCalled();
});
it('opens nothing for an Agent the creator cannot reach', async () => {
getAgent.mockResolvedValue(null);
- await expect(createDirect('desktop')).resolves.toBeUndefined();
- expect(create).not.toHaveBeenCalled();
- });
-
- it.each([
- ['a device that is not the creator’s', () => findDevice.mockResolvedValue(undefined)],
- ['a device that cannot be reached', () => statPath.mockResolvedValue(undefined)],
- ])('refuses %s rather than seat the Agent where it cannot run', async (_, arrange) => {
- getAgent.mockResolvedValue({ agencyConfig: claudeCode, name: 'Claude' });
- arrange();
- await expect(createDirect('desktop')).rejects.toBeInstanceOf(ChannelError);
+ await expect(createDirect()).resolves.toBeUndefined();
expect(create).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/channel/ChannelService.environment.test.ts b/apps/server/src/services/channel/ChannelService.environment.test.ts
index a50f10d13e9..c6b93816e6f 100644
--- a/apps/server/src/services/channel/ChannelService.environment.test.ts
+++ b/apps/server/src/services/channel/ChannelService.environment.test.ts
@@ -120,14 +120,24 @@ describe('changing an Agent member’s channel environment', () => {
expect(notify).toHaveBeenCalledWith(expect.anything(), 'channel');
});
- it('keeps the old environment when a coding Agent would lose its device', async () => {
- await expect(service().updateAgentEnvironment('channel', 'member-1', {})).rejects.toMatchObject(
- { code: 'BAD_REQUEST' },
- );
+ // A Channel binds no device by default, so clearing one returns a coding Agent to its own
+ // settings instead of being refused.
+ it("clears a coding Agent's device so it runs where its own settings say", async () => {
+ await expect(
+ service().updateAgentEnvironment('channel', 'member-1', {}),
+ ).resolves.toBeDefined();
+
+ expect(update).toHaveBeenCalledWith('channel', 'member-1', {});
+ expect(wake).toHaveBeenCalledWith('channel');
+ expect(notify).toHaveBeenCalledWith(expect.anything(), 'channel');
+ });
+
+ it('still refuses a directory without a device', async () => {
+ await expect(
+ service().updateAgentEnvironment('channel', 'member-1', { workingDirectory: '/repo' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
expect(update).not.toHaveBeenCalled();
- expect(wake).not.toHaveBeenCalled();
- expect(notify).not.toHaveBeenCalled();
});
it('creates a member in the device home folder when the Agent has no directory there', async () => {
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 85345abff1c..058c97d5f44 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -4,7 +4,6 @@ import type { LobeChatDatabase } from '@lobechat/database';
import {
agentDisplayName,
CHANNEL_LIMITS,
- defaultChannelAgentDevice,
defaultChannelAgentDirectory,
isChannelRuntime,
} from '@lobechat/types';
@@ -120,7 +119,9 @@ export class ChannelService {
config.deviceId = device.deviceId;
config.deviceOwnerId = device.userId;
config.workingDirectory = path.canonicalPath;
- } else if (runtime !== 'native' || input.workingDirectory) {
+ } else if (input.workingDirectory) {
+ // A directory only means something on a device. Without one the Agent runs where its own
+ // settings say, as in an ordinary conversation.
throw new ChannelError('BAD_REQUEST', 'Choose an online device and working directory');
}
return { agentId: input.agentId, config, description: input.description, name: input.name };
@@ -191,27 +192,16 @@ export class ChannelService {
};
/**
- * The direct conversation between a person and an Agent, titled with the Agent's name. The Agent
- * keeps the device and directory a new Channel would give it, checked the same way. An external
- * Agent with no device yet still gets its conversation; it asks for a device in the Channel
- * before it can reply.
+ * The direct conversation between a person and an Agent, titled with the Agent's name. A Channel
+ * binds no device by default: the Agent runs where its own settings say, as in an ordinary
+ * conversation, until a member picks a device for it in the Channel.
*/
- createDirect = async (agentId: string, { localDeviceId }: { localDeviceId?: string } = {}) => {
+ createDirect = async (agentId: string) => {
const agent = await this.agentService.getAgentConfigById(agentId);
if (!agent) return;
- const runtime = agentRuntime(agent);
- if (!isChannelRuntime(runtime)) return;
- const deviceId = defaultChannelAgentDevice({
- agencyConfig: agent.agencyConfig,
- localDeviceId,
- runtime,
- });
- const { config } =
- deviceId || runtime === 'native'
- ? await this.resolveAgent({ agentId, deviceId }, agent)
- : { config: {} };
+ if (!isChannelRuntime(agentRuntime(agent))) return;
return this.repository.create({
- agentConfig: config,
+ agentConfig: {},
agentId,
title: agentDisplayName(agent, 'Agent').slice(0, CHANNEL_LIMITS.titleLength),
});
@@ -222,10 +212,10 @@ export class ChannelService {
* Channels. An existing conversation opens as it is, without probing its device again; one the
* person moved to the trash stays there, and the Agent opens as before.
*/
- openDirect = async (agentId: string, options: { localDeviceId?: string } = {}) => {
+ openDirect = async (agentId: string) => {
const existing = await this.repository.findDirectAccess(agentId);
if (existing) return existing.channel.isDeleted ? undefined : existing;
- return this.createDirect(agentId, options);
+ return this.createDirect(agentId);
};
/**
diff --git a/apps/server/src/services/channel/defaultChannel.test.ts b/apps/server/src/services/channel/defaultChannel.test.ts
index 8a32deb5f52..558e161d3a1 100644
--- a/apps/server/src/services/channel/defaultChannel.test.ts
+++ b/apps/server/src/services/channel/defaultChannel.test.ts
@@ -94,9 +94,10 @@ describe('createAgentDirectChannel', () => {
it.each([undefined, 'ws_1'])(
"opens the creator's direct Channel to the new Agent in scope %s",
async (workspaceId) => {
- await createAgentDirectChannel({ ...params, localDeviceId: 'desktop', workspaceId });
+ await createAgentDirectChannel({ ...params, workspaceId });
expect(ChannelServiceCtor).toHaveBeenCalledWith(db, 'owner', workspaceId);
- expect(createDirect).toHaveBeenCalledWith('agt_main', { localDeviceId: 'desktop' });
+ // Bound to no device; the Agent runs where its own settings say.
+ expect(createDirect).toHaveBeenCalledWith('agt_main');
expect(createDefault).not.toHaveBeenCalled();
},
);
diff --git a/apps/server/src/services/channel/defaultChannel.ts b/apps/server/src/services/channel/defaultChannel.ts
index 7623583cba3..c0d5a0153b7 100644
--- a/apps/server/src/services/channel/defaultChannel.ts
+++ b/apps/server/src/services/channel/defaultChannel.ts
@@ -49,28 +49,16 @@ export interface AgentDirectChannelParams {
/** The Agent its creator just made. */
agentId: string;
db: LobeChatDatabase;
- /** The creator's own desktop, where an Agent that runs locally answers; checked before use. */
- localDeviceId?: string;
userId: string;
workspaceId?: string;
}
/**
* Opens the direct conversation between a person and the Agent they just created, named after the
- * Agent and on the device and directory a new Channel would give it; see
- * `ChannelService.createDirect`.
+ * Agent and bound to no device; see `ChannelService.createDirect`.
*/
-export const createAgentDirectChannel = async ({
- db,
- localDeviceId,
- ...context
-}: AgentDirectChannelParams) =>
+export const createAgentDirectChannel = async ({ db, ...context }: AgentDirectChannelParams) =>
openForCreator('the direct channel of a new agent', context, async () => {
if (!(await isChannelEnabled(context.userId))) return;
- await new ChannelService(db, context.userId, context.workspaceId).createDirect(
- context.agentId,
- {
- localDeviceId,
- },
- );
+ await new ChannelService(db, context.userId, context.workspaceId).createDirect(context.agentId);
});
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 1e691127809..6d89d8d78f8 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -64,13 +64,11 @@
"directoryRequired": "Choose a working directory for each device.",
"environment.agentUnavailable": "This Agent is no longer available. Remove it and choose another.",
"environment.checkingDevice": "Checking status",
- "environment.chooseDevice": "Choose a device",
"environment.configurationFailed": "Could not load this Agent’s settings. Try again.",
"environment.configurationLoading": "Loading this Agent’s settings…",
"environment.connectorUpgradeRequired": "This device’s LobeHub connector needs an update. Update LobeHub Desktop or the LobeHub CLI on that device, then reconnect and try again.",
"environment.deviceLabel": "Device for {{name}}",
"environment.deviceOffline": "This device is offline. Reconnect it or choose another device.",
- "environment.deviceRequired": "Choose an online device for this coding Agent.",
"environment.deviceUnavailable": "This device is unavailable in the current space. Choose an accessible device.",
"environment.deviceUnreachable": "Could not connect to the device to check the working directory. Check the device connection and try again.",
"environment.devicesFailed": "Could not confirm device status. Refresh the device list and try again.",
@@ -81,8 +79,8 @@
"environment.directoryUnavailable": "Could not verify the directory. Check the device connection and choose the directory again.",
"environment.editNamed": "Change where {{name}} runs",
"environment.executionRequired": "Choose an online device and working directory for every coding Agent.",
+ "environment.followAgent": "Use the Agent's own settings",
"environment.inherited.deviceOffline": "This Agent’s device is offline. Reconnect the device, or remove the Agent.",
- "environment.inherited.deviceRequired": "This coding Agent has no default device. Choose one in its settings, or remove the Agent.",
"environment.inherited.deviceUnavailable": "This Agent’s device is unavailable in the current space. Change it in the Agent’s settings, or remove the Agent.",
"environment.permissionRequired": "You do not have permission to save these members. Check channel and Agent access.",
"environment.resolveRequired": "Resolve the issues shown under the selected Agents first.",
@@ -133,7 +131,6 @@
"moveToTrashConfirm": "Move “{{title}}” to trash? Replies will stop. You can restore the channel and its history from Trash. Agents and files will be kept.",
"moveToTrashSuccess": "Channel moved to trash",
"nameOptional": "Channel name (optional)",
- "noDevice": "No device",
"noDevices": "No device is connected. Connect one, then choose it here.",
"offline": "Offline",
"olderMessages": "Older messages",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index f0bc5ad84a7..18660ef919a 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -64,13 +64,11 @@
"directoryRequired": "请为每台设备选择工作目录。",
"environment.agentUnavailable": "此 Agent 已不可用,请移除后选择其他 Agent。",
"environment.checkingDevice": "正在确认状态",
- "environment.chooseDevice": "选择设备",
"environment.configurationFailed": "未能读取此 Agent 的配置,请重试。",
"environment.configurationLoading": "正在读取 Agent 配置…",
"environment.connectorUpgradeRequired": "设备连接器需升级。请更新目标设备上的 LobeHub 桌面端或 LobeHub CLI,重新连接后重试。",
"environment.deviceLabel": "{{name}} 的设备",
"environment.deviceOffline": "此设备已离线,请重新连接或选择其他设备。",
- "environment.deviceRequired": "请为此编程 Agent 选择在线设备。",
"environment.deviceUnavailable": "当前空间无法使用此设备,请选择有权限访问的设备。",
"environment.deviceUnreachable": "无法连接设备以验证工作目录,请检查设备连接后重试。",
"environment.devicesFailed": "未能确认设备状态,请刷新设备列表后重试。",
@@ -81,8 +79,8 @@
"environment.directoryUnavailable": "无法验证工作目录,请检查设备连接并重新选择目录。",
"environment.editNamed": "修改 {{name}} 的运行环境",
"environment.executionRequired": "请为每位编程 Agent 选择在线设备和工作目录。",
+ "environment.followAgent": "使用助手自己的设置",
"environment.inherited.deviceOffline": "此 Agent 的设备已离线,请重新连接设备,或移除此 Agent。",
- "environment.inherited.deviceRequired": "此编程 Agent 还没有默认设备,请先在它的设置里选择设备,或移除此 Agent。",
"environment.inherited.deviceUnavailable": "当前空间无法使用此 Agent 的设备,请在它的设置里更换设备,或移除此 Agent。",
"environment.permissionRequired": "你无权保存这些成员,请检查频道和 Agent 的访问权限。",
"environment.resolveRequired": "请先处理成员下方提示的问题。",
@@ -133,7 +131,6 @@
"moveToTrashConfirm": "将「{{title}}」移至回收站?进行中的回复会停止,你可以在回收站恢复频道和历史消息。Agent 和文件将保留。",
"moveToTrashSuccess": "频道已移至回收站",
"nameOptional": "频道名称(可选)",
- "noDevice": "不使用设备",
"noDevices": "还没有已连接的设备。连接设备后,再回来选择。",
"offline": "离线",
"olderMessages": "更早的消息",
diff --git a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
index e2ddb77cc91..3041563e1a7 100644
--- a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
@@ -48,7 +48,9 @@ const answer = async (channelId: string, jobId: string) => {
};
describe('claim guards', () => {
- it('asks for a device before an external Agent without one replies', async () => {
+ // A Channel binds no device by default: an external Agent without a picked device replies
+ // right away, running where its own settings say, instead of waiting for one.
+ it('lets an external Agent without a picked device reply on its own settings', async () => {
const model = new ChannelRepository(db, fixture.ownerId);
const { channel } = await model.create({ title: 'Direct to Codex' });
const agent = await fixture.addAgent(channel.id, 'Codex', {
@@ -57,20 +59,16 @@ describe('claim guards', () => {
runtime: 'codex',
});
- const waiting = await request(model, channel.id, agent.id, 'no-device');
- expect(await execution.claim(channel.id, waiting.job.id, lease)).toBeNull();
- expect(await jobById(waiting.job.id)).toMatchObject({
- blockedCode: 'device_required',
- status: 'queued',
- });
+ const job = await request(model, channel.id, agent.id, 'no-device');
+ const claim = await execution.claim(channel.id, job.job.id, lease);
- // Choosing a device lets the same queued job start.
- await model.updateAgentEnvironment(channel.id, agent.id, {
- deviceId: 'device-4',
- deviceOwnerId: fixture.ownerId,
- workingDirectory: '/repo',
+ expect(claim).not.toBeNull();
+ expect(await jobById(job.job.id)).toMatchObject({
+ blockedCode: null,
+ deviceId: null,
+ status: 'running',
+ workingDirectory: null,
});
- expect(await execution.claim(channel.id, waiting.job.id, lease)).not.toBeNull();
});
it('requires an approved grant that matches the device, directory and owner', async () => {
diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.ts
index b655080a37c..c42e53582fe 100644
--- a/packages/database/src/repositories/channel/claim.ts
+++ b/packages/database/src/repositories/channel/claim.ts
@@ -336,12 +336,6 @@ export const claimJob = async (
return null;
}
- // An external Agent runs on a device; its direct conversation can open before one is chosen.
- if (executionConfig.runtime !== 'native' && !member.config?.deviceId) {
- await block(tx, job, 'device_required', 'Choose a device for this Agent to run on');
- return null;
- }
-
const blocked =
(await deviceBlock(tx, channel, member)) ??
(await directoryBlock(tx, member.config.deviceId, executionConfig.workingDirectory));
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 53ffefeab82..d4d30987fe4 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -35,14 +35,13 @@ export default {
'environment.agentUnavailable':
'This Agent is no longer available. Remove it and choose another.',
'environment.checkingDevice': 'Checking status',
- 'environment.chooseDevice': 'Choose a device',
+ 'environment.followAgent': "Use the Agent's own settings",
'environment.configurationFailed': 'Could not load this Agent’s settings. Try again.',
'environment.configurationLoading': 'Loading this Agent’s settings…',
'environment.connectorUpgradeRequired':
'This device’s LobeHub connector needs an update. Update LobeHub Desktop or the LobeHub CLI on that device, then reconnect and try again.',
'environment.deviceLabel': 'Device for {{name}}',
'environment.deviceOffline': 'This device is offline. Reconnect it or choose another device.',
- 'environment.deviceRequired': 'Choose an online device for this coding Agent.',
'environment.deviceUnreachable':
'Could not connect to the device to check the working directory. Check the device connection and try again.',
'environment.deviceUnavailable':
@@ -56,8 +55,6 @@ export default {
'environment.directoryRequired': 'Choose a working directory on this device.',
'environment.inherited.deviceOffline':
'This Agent’s device is offline. Reconnect the device, or remove the Agent.',
- 'environment.inherited.deviceRequired':
- 'This coding Agent has no default device. Choose one in its settings, or remove the Agent.',
'environment.inherited.deviceUnavailable':
'This Agent’s device is unavailable in the current space. Change it in the Agent’s settings, or remove the Agent.',
'environment.directoryUnavailable':
@@ -74,7 +71,6 @@ export default {
'environment.unsupportedRuntime': 'This Agent cannot run in a channel yet. Choose another Agent.',
'directoryRequired': 'Choose a working directory for each device.',
'deviceRequired': 'Choose an online device and a working directory for each coding Agent.',
- 'noDevice': 'No device',
'chooseDevice': 'Choose a device',
'noDevices': 'No device is connected. Connect one, then choose it here.',
'offline': 'Offline',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 3c35a706a3f..443fc8fbe1d 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -39,31 +39,6 @@ export const isChannelRuntime = (runtime: string): runtime is ChannelRuntime =>
!Object.hasOwn(CHANNEL_EXCLUDED_RUNTIMES, runtime) &&
(CHANNEL_RUNTIMES as readonly string[]).includes(runtime);
-/**
- * The device a Channel seats an Agent on until someone picks another: the one the Agent is bound
- * to, else this person's own desktop for an Agent that runs on its user's machine (`local`, or an
- * external runtime with no target). Never another available or online device.
- */
-export const defaultChannelAgentDevice = ({
- agencyConfig,
- localDeviceId,
- runtime,
- workspaceScoped,
-}: {
- agencyConfig?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null;
- /** This person's own desktop, when they act from one. */
- localDeviceId?: string;
- runtime: string;
- /** The Agent runs on workspace devices only, never a personal desktop. */
- workspaceScoped?: boolean;
-}): string | undefined => {
- const target = agencyConfig?.executionTarget;
- if (target === 'none' || target === 'sandbox' || target === 'auto') return;
- const localDefault =
- !workspaceScoped && (target === 'local' || (target === undefined && runtime !== 'native'));
- return agencyConfig?.boundDeviceId || (localDefault ? localDeviceId : undefined);
-};
-
/** The directory on that device: the Agent's own choice there, else the device's default. */
export const defaultChannelAgentDirectory = (
agencyConfig: Pick<LobeAgentAgencyConfig, 'workingDirByDevice'> | null | undefined,
diff --git a/src/features/Channels/CreateChannel/EnvironmentFields.tsx b/src/features/Channels/CreateChannel/EnvironmentFields.tsx
index b08d1b8d0fe..e4d53e4e274 100644
--- a/src/features/Channels/CreateChannel/EnvironmentFields.tsx
+++ b/src/features/Channels/CreateChannel/EnvironmentFields.tsx
@@ -22,7 +22,7 @@ type DraftControls = ReturnType<typeof useChannelAgentDraft>;
/** Device and working directory for one Agent in one Channel. */
export const EnvironmentFields = ({
- controls: { change, changeDevice, draft, requiresDevice },
+ controls: { change, changeDevice, draft },
devices,
name,
}: {
@@ -45,10 +45,11 @@ export const EnvironmentFields = ({
<Select
aria-describedby={draft.issue ? `channel-agent-${draft.agentId}-issue` : undefined}
aria-label={t('environment.deviceLabel', { name })}
- placeholder={t(requiresDevice ? 'environment.chooseDevice' : 'noDevice')}
+ placeholder={t('environment.followAgent')}
value={draft.deviceId ?? ''}
options={[
- ...(!requiresDevice ? [{ label: t('noDevice'), value: '' }] : []),
+ // No device is the default: the Agent runs where its own settings say.
+ { label: t('environment.followAgent'), value: '' },
...(missingDevice
? [
{
diff --git a/src/features/Channels/CreateChannel/agentEnvironment.test.ts b/src/features/Channels/CreateChannel/agentEnvironment.test.ts
index fbb8f6ea716..4aa073aa8b7 100644
--- a/src/features/Channels/CreateChannel/agentEnvironment.test.ts
+++ b/src/features/Channels/CreateChannel/agentEnvironment.test.ts
@@ -35,79 +35,27 @@ const environment = (extra: Partial<ChannelAgentEnvironment> = {}): ChannelAgent
heterogeneousProvider: { type: 'pi' },
workingDirByDevice: { bound: '/agent-project', other: '/other-project' },
},
- currentDeviceId: 'current',
devices: [device('bound'), device('current'), device('other')],
devicesConfirmed: true,
- isDesktop: true,
...extra,
});
+// A Channel binds no device by default: an Agent without a picked device runs where its own
+// settings say, as in an ordinary conversation.
describe('Channel Agent environment defaults', () => {
- it('inherits the connected Agent device and its working directory', () => {
- expect(createChannelAgentSelection('pi', environment())).toEqual({
- agentId: 'pi',
- deviceId: 'bound',
- workingDirectory: '/agent-project',
- });
- });
-
- it('resolves a desktop-local Agent without choosing an unrelated online device', () => {
- const env = environment({ agencyConfig: { heterogeneousProvider: { type: 'codex' } } });
- expect(createChannelAgentSelection('codex', env)).toEqual({
- agentId: 'codex',
- deviceId: 'current',
- workingDirectory: undefined,
- });
- expect(
- createChannelAgentSelection('codex', { ...env, isDesktop: false }).deviceId,
- ).toBeUndefined();
- expect(
- createChannelAgentSelection('codex', { ...env, workspaceScoped: true }).deviceId,
- ).toBeUndefined();
- });
-
- it('keeps an explicitly bound local device rather than switching to this machine', () => {
- const env = environment();
- env.agencyConfig!.executionTarget = 'local';
- expect(createChannelAgentSelection('pi', env).deviceId).toBe('bound');
- });
-
- it.each(['none', 'sandbox', 'auto'] as const)(
- 'does not turn %s into an arbitrary device',
- (executionTarget) => {
- const env = environment();
- env.agencyConfig!.executionTarget = executionTarget;
- expect(createChannelAgentSelection('pi', env).deviceId).toBeUndefined();
- },
- );
-
- it('keeps Native Agents without a device when none was configured', () => {
- const env = environment({ agencyConfig: undefined, model: 'gpt-4o' });
- const selection = createChannelAgentSelection('native', env);
- expect(selection).toEqual({ agentId: 'native' });
+ it.each([
+ ['an Agent bound to a device', environment()],
+ [
+ 'a desktop-local coding Agent',
+ environment({ agencyConfig: { heterogeneousProvider: { type: 'codex' } } }),
+ ],
+ ['a Native Agent', environment({ agencyConfig: undefined, model: 'gpt-4o' })],
+ ])('picks no device for %s', (_, env) => {
+ const selection = createChannelAgentSelection('agent');
+ expect(selection).toEqual({ agentId: 'agent' });
expect(getChannelAgentIssue(selection, env)).toBeUndefined();
});
- it('uses a same-device active worktree, then a same-device default directory', () => {
- const env = environment();
- env.agencyConfig!.workingDirByDevice = {
- bound: { path: '/repo', git: { activeWorktree: '/worktrees/topic', isWorktree: true } },
- };
- expect(createChannelAgentSelection('pi', env).workingDirectory).toBe('/worktrees/topic');
- env.agencyConfig!.workingDirByDevice = { other: '/wrong-device' };
- env.devices = [device('bound', { defaultCwd: '/device-default' })];
- expect(createChannelAgentSelection('pi', env).workingDirectory).toBe('/device-default');
- });
-
- it('preserves an offline or missing binding for an explicit recovery, without falling back', () => {
- for (const devices of [
- [device('bound', { online: false }), device('other')],
- [device('other')],
- ]) {
- expect(createChannelAgentSelection('pi', environment({ devices })).deviceId).toBe('bound');
- }
- });
-
it('device changes use only the new device directory and never mutate the Agent defaults', () => {
const env = environment();
const original = structuredClone(env.agencyConfig);
@@ -120,28 +68,32 @@ describe('Channel Agent environment defaults', () => {
expect(env.agencyConfig).toEqual(original);
expect(selected.workingDirectory).toBe('/channel-override');
});
+
+ it('uses a same-device active worktree, then a same-device default directory, on a pick', () => {
+ const env = environment();
+ env.agencyConfig!.workingDirByDevice = {
+ bound: { path: '/repo', git: { activeWorktree: '/worktrees/topic', isWorktree: true } },
+ };
+ expect(changeChannelAgentDevice({ agentId: 'pi' }, 'bound', env).workingDirectory).toBe(
+ '/worktrees/topic',
+ );
+ env.agencyConfig!.workingDirByDevice = { other: '/wrong-device' };
+ env.devices = [device('bound', { defaultCwd: '/device-default' })];
+ expect(changeChannelAgentDevice({ agentId: 'pi' }, 'bound', env).workingDirectory).toBe(
+ '/device-default',
+ );
+ });
});
describe('Channel form hydration', () => {
- it('waits for settings and confirmed device data before snapshotting defaults', () => {
+ it('waits for the Agent settings, not the device list, before it is ready', () => {
const draft = { agentId: 'pi', initialized: false };
const pending = reconcileChannelAgentDraft(draft, environment(), 'configurationLoading');
expect(pending.initialized).toBe(false);
expect(pending.issue).toBe('configurationLoading');
- const devicesPending = reconcileChannelAgentDraft(
- draft,
- environment({ devicesConfirmed: false }),
- );
- expect(devicesPending.initialized).toBe(false);
- expect(devicesPending.issue).toBe('devicesLoading');
- const ready = reconcileChannelAgentDraft(devicesPending, environment());
- expect(ready).toEqual({
- agentId: 'pi',
- deviceId: 'bound',
- workingDirectory: '/agent-project',
- initialized: true,
- issue: undefined,
- });
+ const ready = reconcileChannelAgentDraft(draft, environment({ devicesConfirmed: false }));
+ expect(ready).toEqual({ agentId: 'pi', initialized: true, issue: undefined });
+ expect(canSubmitChannelAgents([ready])).toBe(true);
});
it('leaves a failed settings read retryable, not a usable blank selection', () => {
@@ -152,7 +104,6 @@ describe('Channel form hydration', () => {
);
expect(canSubmitChannelAgents([draft])).toBe(false);
expect(draft.issue).toBe('configurationFailed');
- expect(reconcileChannelAgentDraft(draft, environment()).deviceId).toBe('bound');
});
it('never overwrites channel edits or an explicit cleared device on refresh', () => {
@@ -165,17 +116,19 @@ describe('Channel form hydration', () => {
};
expect(reconcileChannelAgentDraft(edited, env)).toBe(edited);
const cleared = { agentId: 'pi', initialized: true };
- expect(reconcileChannelAgentDraft(cleared, env)).toEqual({
- ...cleared,
- issue: 'deviceRequired',
- });
+ expect(reconcileChannelAgentDraft(cleared, env)).toEqual({ ...cleared, issue: undefined });
expect(env.agencyConfig?.workingDirByDevice?.bound).toBe('/agent-project');
});
- it('reacts to a selected device going offline without losing its directory', () => {
- const ready = reconcileChannelAgentDraft({ agentId: 'pi', initialized: false }, environment());
+ it('reacts to a picked device going offline without losing its directory', () => {
+ const picked = {
+ agentId: 'pi',
+ deviceId: 'bound',
+ initialized: true,
+ workingDirectory: '/agent-project',
+ };
const offline = reconcileChannelAgentDraft(
- ready,
+ picked,
environment({ devices: [device('bound', { online: false })] }),
);
expect(offline.issue).toBe('deviceOffline');
@@ -184,32 +137,27 @@ describe('Channel form hydration', () => {
expect(canSubmitChannelAgents([reconcileChannelAgentDraft(offline, environment())])).toBe(true);
});
- it('does not let a device-list outage prevent a device-free Native Agent', () => {
- const native = reconcileChannelAgentDraft(
- { agentId: 'native', initialized: false },
- environment({
- agencyConfig: undefined,
- devices: undefined,
- devicesConfirmed: false,
- devicesError: new Error('offline'),
- }),
+ it('does not let a device-list outage block an Agent without a picked device', () => {
+ const draft = reconcileChannelAgentDraft(
+ { agentId: 'pi', initialized: false },
+ environment({ devices: undefined, devicesConfirmed: false, devicesError: new Error('x') }),
);
- expect(canSubmitChannelAgents([native])).toBe(true);
+ expect(canSubmitChannelAgents([draft])).toBe(true);
});
});
describe('Channel Agent submission guard', () => {
- it('requires a device for Pi and legacy heterogeneous model IDs', () => {
- expect(getChannelAgentIssue({ agentId: 'pi' }, environment())).toBe('deviceRequired');
+ it('needs no device, for coding and Native Agents alike', () => {
+ expect(getChannelAgentIssue({ agentId: 'pi' }, environment())).toBeUndefined();
expect(
getChannelAgentIssue(
{ agentId: 'codex' },
environment({ agencyConfig: undefined, model: 'codex' }),
),
- ).toBe('deviceRequired');
+ ).toBeUndefined();
});
- it('requires a nonblank directory, including for a Native Agent with a device', () => {
+ it('requires a nonblank directory on a picked device', () => {
for (const workingDirectory of [undefined, '', ' ']) {
expect(
getChannelAgentIssue(
@@ -220,23 +168,11 @@ describe('Channel Agent submission guard', () => {
}
});
- it('accepts an inherited device without a directory, but not a missing or offline device', () => {
+ it('accepts a picked device without a directory where it may be inherited', () => {
const inherited = { directoryOptional: true };
- const draft = reconcileChannelAgentDraft(
- { agentId: 'native', initialized: false },
- environment({ agencyConfig: { boundDeviceId: 'bound', executionTarget: 'device' } }),
- undefined,
- inherited,
- );
- expect(draft).toMatchObject({ deviceId: 'bound', initialized: true, issue: undefined });
- expect(canSubmitChannelAgents([draft])).toBe(true);
expect(
- getChannelAgentIssue(
- { agentId: 'codex' },
- environment({ agencyConfig: undefined, model: 'codex' }),
- inherited,
- ),
- ).toBe('deviceRequired');
+ getChannelAgentIssue({ agentId: 'pi', deviceId: 'bound' }, environment(), inherited),
+ ).toBeUndefined();
expect(
getChannelAgentIssue(
{ agentId: 'pi', deviceId: 'bound' },
@@ -256,7 +192,7 @@ describe('Channel Agent submission guard', () => {
{ devices: [device('bound', { scope: 'workspace', visibility: 'private' })] },
'deviceUnavailable',
],
- ] as const)('blocks unsafe device state %o', (patch, issue) => {
+ ] as const)('blocks unsafe state of a picked device %o', (patch, issue) => {
const env = environment({
...patch,
...('devices' in patch ? { devices: [...patch.devices] } : {}),
@@ -266,13 +202,13 @@ describe('Channel Agent submission guard', () => {
).toBe(issue);
});
- it('allows a fully configured Agent and prevents pending/invalid/empty submissions', () => {
- const selection = createChannelAgentSelection('pi', environment());
+ it('allows a ready Agent and prevents pending/invalid/empty submissions', () => {
+ const selection = { agentId: 'pi', deviceId: 'bound', workingDirectory: '/project' };
expect(getChannelAgentIssue(selection, environment())).toBeUndefined();
expect(canSubmitChannelAgents([])).toBe(false);
expect(canSubmitChannelAgents([{ ...selection, initialized: false }])).toBe(false);
expect(
- canSubmitChannelAgents([{ ...selection, initialized: true, issue: 'deviceRequired' }]),
+ canSubmitChannelAgents([{ ...selection, initialized: true, issue: 'deviceOffline' }]),
).toBe(false);
expect(canSubmitChannelAgents([{ ...selection, initialized: true }])).toBe(true);
expect(toChannelAgentSelection({ ...selection, initialized: true, issue: undefined })).toEqual(
diff --git a/src/features/Channels/CreateChannel/agentEnvironment.ts b/src/features/Channels/CreateChannel/agentEnvironment.ts
index 366e2fdd24c..4054996cfd2 100644
--- a/src/features/Channels/CreateChannel/agentEnvironment.ts
+++ b/src/features/Channels/CreateChannel/agentEnvironment.ts
@@ -1,10 +1,6 @@
import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { DeviceListItem, LobeAgentAgencyConfig } from '@lobechat/types';
-import {
- defaultChannelAgentDevice,
- defaultChannelAgentDirectory,
- isChannelRuntime,
-} from '@lobechat/types';
+import { defaultChannelAgentDirectory, isChannelRuntime } from '@lobechat/types';
import type { ChannelAgentSelection } from '@/services/channel';
@@ -18,7 +14,6 @@ export type ChannelAgentIssue =
| 'configurationFailed'
| 'configurationLoading'
| 'deviceOffline'
- | 'deviceRequired'
| 'deviceUnavailable'
| 'devicesFailed'
| 'devicesLoading'
@@ -27,17 +22,14 @@ export type ChannelAgentIssue =
export interface ChannelAgentEnvironment {
agencyConfig?: LobeAgentAgencyConfig;
- currentDeviceId?: string;
devices?: DeviceListItem[];
devicesConfirmed: boolean;
devicesError?: unknown;
- isDesktop: boolean;
model?: string;
- workspaceScoped?: boolean;
}
/** Device issues of an inherited environment are fixed in the Agent's settings, not here. */
-const INHERITED_ISSUES = ['deviceOffline', 'deviceRequired', 'deviceUnavailable'] as const;
+const INHERITED_ISSUES = ['deviceOffline', 'deviceUnavailable'] as const;
const isInheritedIssue = (issue: ChannelAgentIssue): issue is (typeof INHERITED_ISSUES)[number] =>
(INHERITED_ISSUES as readonly ChannelAgentIssue[]).includes(issue);
@@ -63,21 +55,13 @@ const getDeviceDirectory = (deviceId: string | undefined, environment: ChannelAg
);
};
-/** Snapshot only the Agent's chosen machine, never another available/online device. */
-export const createChannelAgentSelection = (
- agentId: string,
- environment: ChannelAgentEnvironment,
-): ChannelAgentSelection => {
- const { agencyConfig, currentDeviceId, isDesktop, workspaceScoped } = environment;
- const deviceId = defaultChannelAgentDevice({
- agencyConfig,
- localDeviceId: isDesktop ? currentDeviceId : undefined,
- runtime: getRuntime(environment),
- workspaceScoped,
- });
- if (!deviceId) return { agentId };
- return { agentId, deviceId, workingDirectory: getDeviceDirectory(deviceId, environment) };
-};
+/**
+ * A Channel binds no device by default: the Agent runs where its own settings say until a member
+ * picks a device for it here.
+ */
+export const createChannelAgentSelection = (agentId: string): ChannelAgentSelection => ({
+ agentId,
+});
export interface ChannelAgentIssueOptions {
/** Inherited defaults may omit the directory; the server then uses the device's home folder. */
@@ -91,7 +75,8 @@ export const getChannelAgentIssue = (
): ChannelAgentIssue | undefined => {
const runtime = getRuntime(environment);
if (!isChannelRuntime(runtime)) return 'unsupportedRuntime';
- if (!selection.deviceId) return runtime === 'native' ? undefined : 'deviceRequired';
+ // No device picked: it follows the Agent's own settings, like an ordinary conversation.
+ if (!selection.deviceId) return;
if (environment.devicesError) return 'devicesFailed';
if (!environment.devicesConfirmed) return 'devicesLoading';
const device = environment.devices?.find((item) => item.deviceId === selection.deviceId);
@@ -122,14 +107,8 @@ export const reconcileChannelAgentDraft = (
let next = draft;
let issue = sourceIssue;
if (!issue) {
- if (!draft.initialized) {
- const selection = createChannelAgentSelection(draft.agentId, environment);
- if (selection.deviceId && (environment.devicesError || !environment.devicesConfirmed)) {
- issue = environment.devicesError ? 'devicesFailed' : 'devicesLoading';
- } else {
- next = { ...draft, ...selection, initialized: true };
- }
- }
+ if (!draft.initialized)
+ next = { ...draft, ...createChannelAgentSelection(draft.agentId), initialized: true };
issue ??= getChannelAgentIssue(next, environment, options);
}
return next === draft && draft.issue === issue ? draft : { ...next, issue };
diff --git a/src/features/Channels/CreateChannel/useChannelAgentDraft.test.ts b/src/features/Channels/CreateChannel/useChannelAgentDraft.test.ts
index 2bb1322de5f..e5e161249e1 100644
--- a/src/features/Channels/CreateChannel/useChannelAgentDraft.test.ts
+++ b/src/features/Channels/CreateChannel/useChannelAgentDraft.test.ts
@@ -32,12 +32,6 @@ vi.mock('@/store/agent', () => ({
useHydrateAgentConfig: () => sync,
}),
}));
-vi.mock('@/store/electron', () => ({
- useElectronStore: (selector: (state: unknown) => unknown) =>
- selector({
- gatewayDeviceInfo: { deviceId: 'bound' },
- }),
-}));
const devices: DeviceListResult = {
data: [
{
@@ -80,13 +74,21 @@ describe('Channel Agent device selection events', () => {
});
afterEach(cleanup);
+ // A Channel binds no device by default, even for an Agent bound to one.
+ it('starts without a device, following the Agent settings', () => {
+ const { result } = setup();
+ expect(result.current.draft).toMatchObject({ agentId: 'agent', initialized: true });
+ expect(result.current.draft.deviceId).toBeUndefined();
+ expect(result.current.draft.issue).toBeUndefined();
+ expect(canSubmitChannelAgents(result.current.drafts)).toBe(true);
+ });
+
it.each([undefined, null, ''])(
- 'clears the inherited Native device and directory for an empty selection (%s)',
+ 'clears a picked device and directory for an empty selection (%s)',
(value) => {
const defaults = structuredClone(source.agencyConfig);
const { result, rerender } = setup();
- expect(result.current.requiresDevice).toBe(false);
- expect(result.current.draft.deviceId).toBe('bound');
+ act(() => result.current.changeDevice('bound'));
expect(result.current.draft.workingDirectory).toBe('/agent-project');
// Select normalizes its empty-string option to undefined in onChange.
act(() => result.current.changeDevice(value));
@@ -116,17 +118,15 @@ describe('Channel Agent device selection events', () => {
});
it.each(['pi', 'codex'] as const)(
- 'clears %s visibly but still requires a device before submission',
+ 'lets a %s coding Agent go without a device, following its own settings',
(runtime) => {
source.agencyConfig.heterogeneousProvider = { type: runtime };
const { result, rerender } = setup();
- expect(result.current.requiresDevice).toBe(true);
act(() => result.current.changeDevice(undefined));
rerender();
expect(result.current.draft.deviceId).toBeUndefined();
- expect(result.current.draft.workingDirectory).toBeUndefined();
- expect(result.current.draft.issue).toBe('deviceRequired');
- expect(canSubmitChannelAgents(result.current.drafts)).toBe(false);
+ expect(result.current.draft.issue).toBeUndefined();
+ expect(canSubmitChannelAgents(result.current.drafts)).toBe(true);
},
);
});
diff --git a/src/features/Channels/CreateChannel/useChannelAgentDraft.ts b/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
index fbc92445b83..b74d99a0ff6 100644
--- a/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
+++ b/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
@@ -1,11 +1,9 @@
-import { isDesktop } from '@lobechat/const';
import type { Dispatch, SetStateAction } from 'react';
import { useEffect } from 'react';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import type { DeviceListResult } from '@/store/device/useDeviceList';
-import { useElectronStore } from '@/store/electron';
import type {
ChannelAgentDraft,
@@ -32,19 +30,15 @@ export const useChannelAgentDraft = (
(s) => s.agentConfigReplica.entries[agentId]?.source === 'server',
);
const notFound = useAgentStore((s) => s.agentNotFoundMap[agentId]);
- const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
- const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId, {
+ const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId, {
topicId: null,
});
const environment: ChannelAgentEnvironment = {
agencyConfig,
- currentDeviceId,
devices: devices.data,
devicesConfirmed: devices.isConfirmed,
devicesError: devices.error,
- isDesktop,
model: agent?.model ?? undefined,
- workspaceScoped,
};
const sourceIssue: ChannelAgentIssue | undefined = sync.error
? 'configurationFailed'
@@ -86,7 +80,6 @@ export const useChannelAgentDraft = (
change,
changeDevice,
draft: resolved,
- requiresDevice: getChannelAgentIssue({ agentId }, environment) === 'deviceRequired',
retry: sync.mutate,
sync,
};
diff --git a/src/services/agent.ts b/src/services/agent.ts
index d8a97aa2688..8101d51ffb8 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -75,8 +75,6 @@ const normalizeMarketAgentModel = (config?: PartialDeep<AgentItem>): PartialDeep
export interface CreateAgentParams {
config?: PartialDeep<AgentItem>;
groupId?: string;
- /** This desktop's gateway device, where the creator's direct Channel to a local Agent runs. */
- localDeviceId?: string;
/**
* `private` keeps the agent visible only to its creator within the active
* workspace; `public` (default) makes it visible to every member. The
@@ -151,7 +149,6 @@ class AgentService {
return lambdaClient.agent.createAgent.mutate({
config: normalizedConfig as any,
groupId: params.groupId,
- localDeviceId: params.localDeviceId,
visibility: params.visibility,
});
};
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 6c862180444..4e1816daafe 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -66,7 +66,7 @@ class ChannelService {
userIds: string[];
}) => lambdaClient.channel.createGroupFromDirect.mutate(input);
/** The caller's direct Channel with an Agent, opened if missing; null when it cannot answer there. */
- openDirect = async (input: { agentId: string; localDeviceId?: string }) =>
+ openDirect = async (input: { agentId: string }) =>
(await lambdaClient.channel.openDirect.mutate(input)).data;
detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>
(await lambdaClient.channel.detail.query(params)).data;
diff --git a/src/store/agent/slices/agent/action.createAgentChannel.test.ts b/src/store/agent/slices/agent/action.createAgentChannel.test.ts
index f1dd3e51036..277427d8caf 100644
--- a/src/store/agent/slices/agent/action.createAgentChannel.test.ts
+++ b/src/store/agent/slices/agent/action.createAgentChannel.test.ts
@@ -49,32 +49,24 @@ describe('createAgent direct Channel', () => {
expect(refreshChannelListIfEnabled).toHaveBeenCalledTimes(1);
});
- it('names this desktop so a local Agent can answer in its direct Channel here', async () => {
- mocks.isDesktop = true;
- mocks.resolveGatewayDeviceId.mockResolvedValue('desktop-device');
- vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-new' });
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.createAgent(params);
- });
-
- expect(vi.mocked(agentService.createAgent).mock.calls[0][0].localDeviceId).toBe(
- 'desktop-device',
- );
- });
-
- it('sends no device from the web', async () => {
- vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-new' });
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.createAgent(params);
- });
-
- expect(mocks.resolveGatewayDeviceId).not.toHaveBeenCalled();
- expect(vi.mocked(agentService.createAgent).mock.calls[0][0].localDeviceId).toBeUndefined();
- });
+ // The direct Channel binds no device, so creating an Agent never asks for this desktop's id.
+ it.each([true, false])(
+ 'sends no device when creating an Agent (desktop: %s)',
+ async (desktop) => {
+ mocks.isDesktop = desktop;
+ vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-new' });
+ const { result } = renderHook(() => useAgentStore());
+
+ await act(async () => {
+ await result.current.createAgent(params);
+ });
+
+ expect(mocks.resolveGatewayDeviceId).not.toHaveBeenCalled();
+ expect(vi.mocked(agentService.createAgent).mock.calls[0][0]).not.toHaveProperty(
+ 'localDeviceId',
+ );
+ },
+ );
it('refetches nothing when the Agent was not created', async () => {
vi.mocked(agentService.createAgent).mockRejectedValue(new Error('forbidden'));
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index bb4acce1ff8..e2a78ea48a6 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -30,7 +30,6 @@ import { resolveAgentDocumentsContext } from '@/services/agentDocument';
import { aiAgentService } from '@/services/aiAgent';
import { refreshChannelListIfEnabled } from '@/store/channel/refreshIfEnabled';
import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
-import { getElectronStoreState } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
// Projection module only (no store import), so this does not cycle through the home store.
@@ -330,11 +329,7 @@ export class AgentSliceActionImpl {
: randomAgentName(locale, await getSidebarAgentNames())),
};
- // On desktop, name this machine so a direct Channel to a local Agent can run here.
- const localDeviceId = isDesktop
- ? await getElectronStoreState().resolveGatewayDeviceId()
- : undefined;
- const result = await agentService.createAgent({ ...params, config, localDeviceId });
+ const result = await agentService.createAgent({ ...params, config });
this.#get().invalidateAvailableAgents();
// The server opened the creator's direct Channel to the new Agent alongside it.
refreshChannelListIfEnabled();
diff --git a/src/store/channel/action.ts b/src/store/channel/action.ts
index 585082af407..5f74e0ffa13 100644
--- a/src/store/channel/action.ts
+++ b/src/store/channel/action.ts
@@ -1,4 +1,3 @@
-import { isDesktop } from '@lobechat/const';
import type { ChannelPublicThread, ChannelStatus, ChannelThreadStatus } from '@lobechat/types';
import { cacheScope } from '@/libs/replica';
@@ -10,7 +9,6 @@ import {
type ChannelViewParams,
type ChannelWakeConfig,
} from '@/services/channel';
-import { getElectronStoreState } from '@/store/electron';
import {
addOutgoing,
@@ -117,11 +115,7 @@ class ChannelActionImpl {
openDirect = async (agentId: string) => {
const existing = channelSelectors.directByAgent(agentId)(useChannelStore.getState());
if (existing) return existing.id;
- // On desktop, name this machine so a direct Channel to a local Agent can run here.
- const localDeviceId = isDesktop
- ? await getElectronStoreState().resolveGatewayDeviceId()
- : undefined;
- const channelId = await channelService.openDirect({ agentId, localDeviceId });
+ const channelId = await channelService.openDirect({ agentId });
if (channelId) await this.#refreshAfterWrite(this.refreshList);
return channelId ?? undefined;
};