Skip to content

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

✨ feat(desktop): serve the remote terminal from the desktop app (#22852)

Arvin Xu08f19391eb42
diff --git a/apps/cli/src/commands/connect/index.ts b/apps/cli/src/commands/connect/index.ts
index e3ef6731fbe..2a6fc64898c 100644
--- a/apps/cli/src/commands/connect/index.ts
+++ b/apps/cli/src/commands/connect/index.ts
@@ -10,6 +10,7 @@ import {
DeviceMetricsSampler,
pushMetrics,
} from '@lobechat/device-control';
+import { createTerminalDeps, TerminalSessionManager } from '@lobechat/device-control/terminal';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
@@ -56,7 +57,6 @@ import {
resolveWorkspaceDeviceIdentity,
} from '../../device/register';
import { probeNativeRuntimes } from '../../device/systemInfo';
-import { TerminalSessionManager } from '../../device/terminal';
import { redactUrlCredentials } from '../../doctor/redact';
import { cliVersion } from '../../pkg';
import {
@@ -574,7 +574,14 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Constructing it is cheap β€” the native PTY binding is only loaded when a
// session is actually created, so a daemon that never opens a terminal never
// touches it.
- const terminals = new TerminalSessionManager({ logger: { warn: (message) => info(message) } });
+ const terminals = new TerminalSessionManager({
+ client: 'cli',
+ // Lazy: the CLI bundle is embedded in contexts that have no `node_modules`
+ // at all (the desktop app runs it from `Resources/bin`), so a static import
+ // would fail every one of them at startup.
+ loadPty: () => import('@lydell/node-pty'),
+ logger: { warn: (message) => info(message) },
+ });
const countActiveTasks = () =>
getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length;
@@ -589,8 +596,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const deviceControlDeps: DeviceControlDeps = {
checkCliUpdate: maintenance.check,
- closeTerminal: (params) => Promise.resolve(terminals.close(params)),
- createTerminalSession: (params) => terminals.create(params),
+ ...createTerminalDeps(terminals),
getCliUpdateState: maintenance.getState,
getLocalFilePreview: defaultGetLocalFilePreview,
getProjectFileIndex: defaultGetProjectFileIndex,
@@ -599,11 +605,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
...params,
env: { ...process.env, ...params.env },
}),
- readTerminal: (params) => Promise.resolve(terminals.read(params)),
- resizeTerminal: (params) => Promise.resolve(terminals.resize(params)),
restartCli: maintenance.restart,
searchProjectFiles: defaultSearchProjectFiles,
- writeTerminal: (params) => Promise.resolve(terminals.write(params)),
};
// One native runtime probe per connection: system info is queried by tool runs and
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 16d40bdac90..558261fc923 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -27,6 +27,7 @@ import { managedProcessEnvironment, spawnManaged } from '@lobechat/utils/managed
import { app as electronApp } from 'electron';
import { withEmbeddedCliEnv } from '@/modules/cliEmbedding';
+import { getRemoteTerminalDeps } from '@/modules/terminal/remote';
import { updaterConfig } from '@/modules/updater/configs';
import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';
import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';
@@ -401,10 +402,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
return this.localSystemRuntime;
}
- /**
- * Desktop handlers for the shared `@lobechat/device-control` dispatcher: only
- * file preview / index (and preview approval) route back to controllers here.
- */
+ /** Desktop handlers for the shared `@lobechat/device-control` dispatcher. */
private get deviceControlDeps(): DeviceControlDeps {
return {
approveProjectRoot: async (root) => {
@@ -438,6 +436,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
enabled: updaterConfig.enableAppUpdate,
getUpdater: () => this.app.getUpdaterManager(),
}),
+ ...getRemoteTerminalDeps(),
};
}
diff --git a/apps/desktop/src/main/modules/terminal/remote.test.ts b/apps/desktop/src/main/modules/terminal/remote.test.ts
new file mode 100644
index 00000000000..00843d05842
--- /dev/null
+++ b/apps/desktop/src/main/modules/terminal/remote.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getRemoteTerminalDeps } from './remote';
+
+const spawn = vi.fn(() => ({
+ kill: vi.fn(),
+ onData: vi.fn(),
+ onExit: vi.fn(),
+ pid: 4242,
+ resize: vi.fn(),
+ write: vi.fn(),
+}));
+vi.mock('@lydell/node-pty', () => ({ spawn }));
+
+describe('getRemoteTerminalDeps', () => {
+ it('serves every terminal RPC from one shared session manager', async () => {
+ const first = getRemoteTerminalDeps();
+ const session = await first.createTerminalSession!({ cols: 80, rows: 24 });
+
+ expect(spawn).toHaveBeenCalledTimes(1);
+ expect(session.pid).toBe(4242);
+
+ // A second connection (e.g. a workspace share) reaches the same session.
+ const second = getRemoteTerminalDeps();
+ await expect(second.readTerminal!({ cursor: 0, id: session.id })).resolves.toMatchObject({
+ exited: false,
+ });
+ await expect(second.closeTerminal!({ id: session.id })).resolves.toEqual({ closed: true });
+ });
+});
diff --git a/apps/desktop/src/main/modules/terminal/remote.ts b/apps/desktop/src/main/modules/terminal/remote.ts
new file mode 100644
index 00000000000..00b84a926ec
--- /dev/null
+++ b/apps/desktop/src/main/modules/terminal/remote.ts
@@ -0,0 +1,26 @@
+import { createTerminalDeps, TerminalSessionManager } from '@lobechat/device-control/terminal';
+
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('modules:terminal:remote');
+
+let remoteTerminals: TerminalSessionManager | undefined;
+
+/**
+ * Device-control terminal handlers, so a browser or another desktop can open a
+ * shell on this machine over the device gateway β€” the same RPCs `lh connect`
+ * serves. One manager per process: the personal and every workspace-share
+ * connection dispatch through it, so they all reach the same sessions.
+ *
+ * Kept apart from the in-app terminal's `PtySessionManager`: that one pushes
+ * output to this app's renderer over IPC, while a remote reader polls a
+ * buffer with a cursor.
+ */
+export const getRemoteTerminalDeps = () => {
+ remoteTerminals ??= new TerminalSessionManager({
+ client: 'desktop',
+ loadPty: () => import('@lydell/node-pty'),
+ logger: { warn: (message) => logger.warn(message) },
+ });
+ return createTerminalDeps(remoteTerminals);
+};
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 769199e138f..6d62f783300 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -35,10 +35,11 @@ import type {
} from '@lobechat/electron-client-ipc';
import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
import { executeDeviceOperation } from '@lobechat/local-file-shell/shell';
-import { app, powerSaveBlocker } from 'electron';
+import { powerSaveBlocker } from 'electron';
import { isDev } from '@/const/env';
import { getDesktopEnv } from '@/env';
+import { getDesktopDeviceMetadata } from '@/utils/deviceMetadata';
import { createLogger } from '@/utils/logger';
import { getDesktopUserAgent } from '@/utils/user-agent';
import { safeGetPath } from '@/utils/user-path';
@@ -679,12 +680,7 @@ export default class GatewayConnectionService extends ServiceModule {
deviceId: identity.deviceId,
hostname: os.hostname(),
identitySource: identity.identitySource,
- metadata: {
- appVersion: app.getVersion(),
- electron: process.versions.electron,
- node: process.versions.node,
- osRelease: os.release(),
- },
+ metadata: getDesktopDeviceMetadata(),
platform: process.platform,
},
{ serverUrl, token },
diff --git a/apps/desktop/src/main/utils/deviceMetadata.test.ts b/apps/desktop/src/main/utils/deviceMetadata.test.ts
new file mode 100644
index 00000000000..22aa0a8c8d1
--- /dev/null
+++ b/apps/desktop/src/main/utils/deviceMetadata.test.ts
@@ -0,0 +1,15 @@
+import { DEVICE_TERMINAL_METADATA_KEY } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { getDesktopDeviceMetadata } from './deviceMetadata';
+
+vi.mock('electron', () => ({ app: { getVersion: () => '2.4.0' } }));
+
+describe('getDesktopDeviceMetadata', () => {
+ it('reports the app version and that this desktop serves remote terminals', () => {
+ expect(getDesktopDeviceMetadata()).toMatchObject({
+ appVersion: '2.4.0',
+ [DEVICE_TERMINAL_METADATA_KEY]: '1',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/utils/deviceMetadata.ts b/apps/desktop/src/main/utils/deviceMetadata.ts
new file mode 100644
index 00000000000..6fd9a0ddcf0
--- /dev/null
+++ b/apps/desktop/src/main/utils/deviceMetadata.ts
@@ -0,0 +1,14 @@
+import os from 'node:os';
+
+import { DEVICE_TERMINAL_METADATA_KEY } from '@lobechat/types';
+import { app } from 'electron';
+
+/** What this desktop reports about itself when it registers its device row. */
+export const getDesktopDeviceMetadata = (): Record<string, string> => ({
+ appVersion: app.getVersion(),
+ electron: process.versions.electron,
+ node: process.versions.node,
+ osRelease: os.release(),
+ // Its gateway connection serves the terminal RPCs (`modules/terminal/remote`).
+ [DEVICE_TERMINAL_METADATA_KEY]: '1',
+});
diff --git a/apps/server/src/routers/lambda/device/operate.ts b/apps/server/src/routers/lambda/device/operate.ts
index f2f5633d8e9..4ade8ff2ed7 100644
--- a/apps/server/src/routers/lambda/device/operate.ts
+++ b/apps/server/src/routers/lambda/device/operate.ts
@@ -24,6 +24,9 @@ const assertTunnelDeviceWritable = (
*/
const MAX_TERMINAL_WRITE_CHARS = 65_536;
+/** The client a terminal session lives on, as `createTerminalSession` answered. */
+const terminalClientSchema = z.enum(['cli', 'desktop']).optional();
+
/**
* Relay a terminal call, surfacing the device's own reason. A device that is
* offline β€” or a client without PTY support β€” answers with a message the user
@@ -169,6 +172,7 @@ export const operateRouter = router({
writeTerminal: deviceProcedure
.input(
z.object({
+ client: terminalClientSchema,
/** Base64 keystrokes. */
data: z.string().max(MAX_TERMINAL_WRITE_CHARS),
deviceId: z.string(),
@@ -179,6 +183,7 @@ export const operateRouter = router({
await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');
return relayTerminal(() =>
deviceGateway.writeTerminal({
+ client: input.client,
data: input.data,
deviceId: input.deviceId,
id: input.id,
@@ -188,11 +193,19 @@ export const operateRouter = router({
);
}),
readTerminal: deviceProcedure
- .input(z.object({ cursor: z.number().int().min(0), deviceId: z.string(), id: z.string() }))
+ .input(
+ z.object({
+ client: terminalClientSchema,
+ cursor: z.number().int().min(0),
+ deviceId: z.string(),
+ id: z.string(),
+ }),
+ )
.mutation(async ({ ctx, input }) => {
await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');
return relayTerminal(() =>
deviceGateway.readTerminal({
+ client: input.client,
cursor: input.cursor,
deviceId: input.deviceId,
id: input.id,
@@ -204,6 +217,7 @@ export const operateRouter = router({
resizeTerminal: deviceProcedure
.input(
z.object({
+ client: terminalClientSchema,
cols: z.number().int().min(1).max(1000),
deviceId: z.string(),
id: z.string(),
@@ -214,6 +228,7 @@ export const operateRouter = router({
await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');
return relayTerminal(() =>
deviceGateway.resizeTerminal({
+ client: input.client,
cols: input.cols,
deviceId: input.deviceId,
id: input.id,
@@ -224,11 +239,12 @@ export const operateRouter = router({
);
}),
closeTerminal: deviceProcedure
- .input(z.object({ deviceId: z.string(), id: z.string() }))
+ .input(z.object({ client: terminalClientSchema, deviceId: z.string(), id: z.string() }))
.mutation(async ({ ctx, input }) => {
await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');
return relayTerminal(() =>
deviceGateway.closeTerminal({
+ client: input.client,
deviceId: input.deviceId,
id: input.id,
userId: ctx.userId,
diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
index 931b27a6588..7cb6ebd24e6 100644
--- a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
@@ -518,6 +518,14 @@ const cases: RpcCase[] = [
payload: { method: 'resizeTerminal', params: { cols: 100, id: 't1', rows: 30 } },
success: undefined,
},
+ {
+ // A session's later calls stay on the client that created it.
+ address: address(15_000, { channel: 'cli', clientKinds: ['desktop'] }),
+ call: (g) => g.readTerminal({ ...base, client: 'desktop', cursor: 0, id: 't1' }),
+ failure: terminalThrow('readTerminal'),
+ name: 'readTerminal (pinned to the desktop)',
+ payload: { method: 'readTerminal', params: { cursor: 0, id: 't1' } },
+ },
{
address: address(15_000, { channel: 'cli' }),
call: (g) => g.closeTerminal({ ...base, id: 't1' }),
diff --git a/apps/server/src/services/deviceGateway/terminal.ts b/apps/server/src/services/deviceGateway/terminal.ts
index e47dae3122d..9e7b6f5794d 100644
--- a/apps/server/src/services/deviceGateway/terminal.ts
+++ b/apps/server/src/services/deviceGateway/terminal.ts
@@ -1,7 +1,9 @@
/**
- * Interactive terminal (PTY) RPCs, relayed to the `lh connect` process.
+ * Interactive terminal (PTY) RPCs, relayed to the device client hosting the
+ * shell β€” `lh connect` or the desktop app.
*/
import type {
+ DeviceClient,
DeviceCloseTerminalResult,
DeviceCreateTerminalSessionResult,
DeviceReadTerminalResult,
@@ -17,6 +19,15 @@ interface TerminalRpcScope {
workspaceId?: string;
}
+/**
+ * Scope of a call on an existing session. `client` is what `createTerminalSession`
+ * answered with: each client keeps its own sessions, so on a device holding
+ * both connections the call has to reach the one that created the shell.
+ */
+interface TerminalSessionRpcScope extends TerminalRpcScope {
+ client?: DeviceClient;
+}
+
/** The five device RPCs that make up one interactive terminal session. */
type TerminalRpcMethod =
'closeTerminal' | 'createTerminalSession' | 'readTerminal' | 'resizeTerminal' | 'writeTerminal';
@@ -40,14 +51,14 @@ export async function createTerminalSession(
export async function writeTerminal(
getClient: DeviceClientGetter,
- params: TerminalRpcScope & { data: string; id: string },
+ params: TerminalSessionRpcScope & { data: string; id: string },
): Promise<void> {
await invokeTerminalRpc(getClient, 'writeTerminal', params, { data: params.data, id: params.id });
}
export async function readTerminal(
getClient: DeviceClientGetter,
- params: TerminalRpcScope & { cursor: number; id: string },
+ params: TerminalSessionRpcScope & { cursor: number; id: string },
): Promise<DeviceReadTerminalResult> {
return invokeTerminalRpc(getClient, 'readTerminal', params, {
cursor: params.cursor,
@@ -57,7 +68,7 @@ export async function readTerminal(
export async function resizeTerminal(
getClient: DeviceClientGetter,
- params: TerminalRpcScope & { cols: number; id: string; rows: number },
+ params: TerminalSessionRpcScope & { cols: number; id: string; rows: number },
): Promise<void> {
await invokeTerminalRpc(getClient, 'resizeTerminal', params, {
cols: params.cols,
@@ -68,7 +79,7 @@ export async function resizeTerminal(
export async function closeTerminal(
getClient: DeviceClientGetter,
- params: TerminalRpcScope & { id: string },
+ params: TerminalSessionRpcScope & { id: string },
): Promise<DeviceCloseTerminalResult> {
return invokeTerminalRpc(getClient, 'closeTerminal', params, { id: params.id });
}
@@ -76,24 +87,33 @@ export async function closeTerminal(
/**
* Relay one terminal RPC and unwrap its result.
*
- * Every call carries the `cli` channel hint: the PTY lives in the `lh
- * connect` process, so on a machine also running the desktop app the RPC has
- * to reach that connection β€” the desktop's own terminal is local-only and
- * would refuse these. A gateway that predates the hint ignores it, which is
- * why the refusal below still has to surface as an error.
+ * Opening a shell carries the `cli` channel hint, so a device running both
+ * `lh connect` and the desktop app hosts it in the daemon. Calls on an existing
+ * session are restricted (`clientKinds`) to the client that created it β€” the
+ * two keep separate sessions, so letting the gateway re-pick per call would
+ * send a desktop session's reads to the CLI as soon as `lh connect` comes up.
+ * A gateway that predates either field ignores it, which is why a refusal
+ * still has to surface as an error.
*/
export async function invokeTerminalRpc<T>(
getClient: DeviceClientGetter,
method: TerminalRpcMethod,
- params: TerminalRpcScope,
+ params: TerminalSessionRpcScope,
rpcParams: Record<string, unknown>,
): Promise<T> {
- const { deviceId, timeout = 15_000, userId, workspaceId } = params;
+ const { client: sessionClient, deviceId, timeout = 15_000, userId, workspaceId } = params;
const client = getClient();
if (!client) throw new Error('Device gateway is not configured on this deployment.');
const result = await client.invokeRpc<T>(
- { channel: 'cli', deviceId, timeout, userId, workspaceId },
+ {
+ channel: 'cli',
+ ...(sessionClient ? { clientKinds: [sessionClient] } : {}),
+ deviceId,
+ timeout,
+ userId,
+ workspaceId,
+ },
{ method, params: rpcParams },
);
// `writeTerminal` / `resizeTerminal` answer with no payload, so absence of
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index 894953411ac..bfc14e3d721 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -15,6 +15,7 @@
"./project-file-index": "./src/projectFileIndex.ts",
"./rpc-clients": "./src/rpcClients.ts",
"./skill-directory": "./src/skillDirectory.ts",
+ "./terminal": "./src/terminal.ts",
"./workspace": "./src/workspace.ts"
},
"main": "./src/index.ts",
diff --git a/apps/cli/src/device/terminal.test.ts b/packages/device-control/src/terminal.test.ts
similarity index 95%
rename from apps/cli/src/device/terminal.test.ts
rename to packages/device-control/src/terminal.test.ts
index 90aca5ebb0f..2337d4c28b1 100644
--- a/apps/cli/src/device/terminal.test.ts
+++ b/packages/device-control/src/terminal.test.ts
@@ -14,7 +14,7 @@ interface FakePty {
const ptys: FakePty[] = [];
let spawnOptions: Record<string, unknown> | undefined;
-vi.mock('@lydell/node-pty', () => ({
+const fakePtyModule = {
spawn: (_shell: string, _args: string[], options: Record<string, unknown>) => {
spawnOptions = options;
let dataHandler: ((data: string) => void) | undefined;
@@ -38,7 +38,8 @@ vi.mock('@lydell/node-pty', () => ({
},
};
},
-}));
+};
+const loadPty = async () => fakePtyModule;
const decode = (base64: string) => Buffer.from(base64, 'base64').toString('utf8');
@@ -48,7 +49,7 @@ describe('TerminalSessionManager', () => {
beforeEach(() => {
ptys.length = 0;
spawnOptions = undefined;
- manager = new TerminalSessionManager();
+ manager = new TerminalSessionManager({ client: 'cli', loadPty });
});
afterEach(() => {
@@ -65,7 +66,11 @@ describe('TerminalSessionManager', () => {
// only exists when the shell has a controlling terminal.
const { info } = await openSession();
- expect(info).toMatchObject({ shell: expect.any(String), pid: expect.any(Number) });
+ expect(info).toMatchObject({
+ client: 'cli',
+ pid: expect.any(Number),
+ shell: expect.any(String),
+ });
expect(spawnOptions).toMatchObject({
cols: 80,
env: expect.objectContaining({ TERM: 'xterm-256color' }),
@@ -168,7 +173,7 @@ describe('TerminalSessionManager', () => {
it('answers a read for a session it no longer holds as an ended shell', async () => {
const warn = vi.fn();
- const reaped = new TerminalSessionManager({ logger: { warn } });
+ const reaped = new TerminalSessionManager({ client: 'cli', loadPty, logger: { warn } });
try {
const info = await reaped.create({ cols: 80, rows: 24 });
reaped.close({ id: info.id });
diff --git a/apps/cli/src/device/terminal.ts b/packages/device-control/src/terminal.ts
similarity index 79%
rename from apps/cli/src/device/terminal.ts
rename to packages/device-control/src/terminal.ts
index a9f8f00478c..5c4e94fc82e 100644
--- a/apps/cli/src/device/terminal.ts
+++ b/packages/device-control/src/terminal.ts
@@ -2,36 +2,51 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
+import { detectWindowsShell } from '@lobechat/local-file-shell/shell';
+import type { DeviceClient } from '@lobechat/types';
+
import type {
CloseTerminalParams,
CloseTerminalResult,
CreateTerminalSessionParams,
CreateTerminalSessionResult,
+ DeviceControlDeps,
ReadTerminalParams,
ReadTerminalResult,
ResizeTerminalParams,
WriteTerminalParams,
-} from '@lobechat/device-control';
-import { detectWindowsShell } from '@lobechat/local-file-shell/shell';
-import type { IPty } from '@lydell/node-pty';
+} from './types';
-/**
- * `@lydell/node-pty` is a native module: it ships a prebuilt binary per
- * platform and cannot be bundled, so it stays a real runtime dependency and is
- * marked external in `tsdown.config.ts`. It is also imported lazily, because
- * the CLI bundle is embedded in contexts that have no `node_modules` at all
- * (the desktop app runs it from `Resources/bin`) β€” a static import would make
- * every one of those fail at startup, while a host that never opens a terminal
- * never resolves this at all.
- */
-const importPty = () => import('@lydell/node-pty');
-let ptyModule: ReturnType<typeof importPty> | undefined;
-const loadPty = () => (ptyModule ??= importPty());
+/** The slice of a `node-pty` PTY this manager drives. */
+export interface TerminalPty {
+ kill: () => void;
+ onData: (listener: (data: string) => void) => unknown;
+ onExit: (listener: (event: { exitCode: number }) => void) => unknown;
+ pid: number;
+ resize: (cols: number, rows: number) => void;
+ write: (data: string | Buffer) => void;
+}
+
+/** The slice of the `node-pty` module this manager needs. */
+export interface TerminalPtyModule {
+ spawn: (
+ file: string,
+ args: string[],
+ options: {
+ cols: number;
+ cwd: string;
+ env: Record<string, string>;
+ name: string;
+ rows: number;
+ },
+ ) => TerminalPty;
+}
/**
* PTY sessions for the remote terminal, driven by the `createTerminalSession` /
* `writeTerminal` / `readTerminal` / `resizeTerminal` / `closeTerminal` device
- * RPCs.
+ * RPCs. Hosted by both the CLI daemon (`lh connect`) and the desktop app's
+ * gateway connection, so either kind of device can serve a remote shell.
*
* Unlike the desktop app's local terminal β€” which pushes `onData` at the
* renderer over IPC β€” the device RPC surface is strictly request/response, so
@@ -75,11 +90,20 @@ interface TerminalSession {
id: string;
lastActiveAt: number;
pid: number;
- pty?: IPty;
+ pty?: TerminalPty;
shell: string;
}
export interface TerminalManagerOptions {
+ /** Which client this host is; returned on create so callers can pin the session to it. */
+ client: DeviceClient;
+ /**
+ * Resolves the `node-pty` module. Injected rather than imported: it is a
+ * native module each host ships its own way (the CLI as an external runtime
+ * dependency, the desktop app unpacked from its asar), and a host that never
+ * opens a terminal should never load it.
+ */
+ loadPty: () => Promise<TerminalPtyModule>;
logger?: { warn: (message: string) => void };
}
@@ -102,7 +126,9 @@ export class TerminalSessionManager {
private sessions = new Map<string, TerminalSession>();
private sweepTimer: NodeJS.Timeout;
- constructor(private options: TerminalManagerOptions = {}) {
+ private ptyModule?: Promise<TerminalPtyModule>;
+
+ constructor(private options: TerminalManagerOptions) {
this.sweepTimer = setInterval(() => this.sweep(), SWEEP_INTERVAL_MS);
this.sweepTimer.unref();
}
@@ -116,7 +142,7 @@ export class TerminalSessionManager {
const cols = params.cols > 0 ? params.cols : 80;
const rows = params.rows > 0 ? params.rows : 24;
- const { spawn } = await loadPty();
+ const { spawn } = await (this.ptyModule ??= this.options.loadPty());
const pty = spawn(shell, [], {
cols,
cwd,
@@ -153,7 +179,7 @@ export class TerminalSessionManager {
session.pty = undefined;
});
- return { cwd, id, pid: pty.pid, shell };
+ return { client: this.options.client, cwd, id, pid: pty.pid, shell };
}
write(params: WriteTerminalParams): void {
@@ -277,3 +303,17 @@ export class TerminalSessionManager {
}
}
}
+
+type TerminalDeps = Pick<
+ DeviceControlDeps,
+ 'closeTerminal' | 'createTerminalSession' | 'readTerminal' | 'resizeTerminal' | 'writeTerminal'
+>;
+
+/** The device-control terminal handlers, backed by one {@link TerminalSessionManager}. */
+export const createTerminalDeps = (terminals: TerminalSessionManager): TerminalDeps => ({
+ closeTerminal: async (params) => terminals.close(params),
+ createTerminalSession: (params) => terminals.create(params),
+ readTerminal: async (params) => terminals.read(params),
+ resizeTerminal: async (params) => terminals.resize(params),
+ writeTerminal: async (params) => terminals.write(params),
+});
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index f88d3832b5f..46739c23f54 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -6,7 +6,7 @@
* desktop wiring can pass its own IPC-typed implementations directly.
*/
-import type { DeviceCliRestartParams, DeviceCliUpdateState } from '@lobechat/types';
+import type { DeviceClient, DeviceCliRestartParams, DeviceCliUpdateState } from '@lobechat/types';
// ─── Workspace scan ───
@@ -551,6 +551,8 @@ export interface CreateTerminalSessionParams {
}
export interface CreateTerminalSessionResult {
+ /** The client hosting the session, so callers can keep its later calls there. */
+ client: DeviceClient;
/** Directory the shell actually started in (the request's `cwd` may not exist). */
cwd: string;
id: string;
diff --git a/packages/device-gateway-client/src/http.clientKinds.test.ts b/packages/device-gateway-client/src/http.clientKinds.test.ts
index 1fb98b1da7f..6466e532639 100644
--- a/packages/device-gateway-client/src/http.clientKinds.test.ts
+++ b/packages/device-gateway-client/src/http.clientKinds.test.ts
@@ -107,6 +107,19 @@ describe('GatewayHttpClient clientKinds', () => {
expect(resolveClientKinds).not.toHaveBeenCalled();
});
+ it('sends clientKinds given for an RPC instead of resolving them from the method', async () => {
+ const { kindsClient, resolveClientKinds } = withResolver();
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true }), ok: true });
+
+ await kindsClient.invokeRpc(
+ { clientKinds: ['cli'], deviceId: 'device-1', userId: 'user-1' },
+ { method: 'readTerminal' },
+ );
+
+ expect(bodyOf()).toMatchObject({ clientKinds: ['cli'] });
+ expect(resolveClientKinds).not.toHaveBeenCalled();
+ });
+
it('omits clientKinds when any client can serve the request', async () => {
const { kindsClient } = withResolver();
mockFetch({ json: vi.fn().mockResolvedValue({ success: true }), ok: true });
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 2ed4c689937..1a72be9b1a5 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -376,10 +376,15 @@ export class GatewayHttpClient {
* (e.g. `desktop` alongside `cli`). A gateway that predates the hint ignores
* it and picks by its own channel priority, so callers must still handle an
* answer from another channel.
+ *
+ * `clientKinds`, when given, replaces the per-method answer of
+ * `resolveClientKinds` β€” e.g. to keep a terminal session's calls on the
+ * client that created it.
*/
async invokeRpc<T = unknown>(
params: {
channel?: string;
+ clientKinds?: DeviceClient[];
deviceId?: string;
timeout?: number;
userId: string;
@@ -395,7 +400,9 @@ export class GatewayHttpClient {
'/api/device/rpc',
{
channel: params.channel,
- clientKinds: this.clientKindsFor({ kind: 'rpc', method: rpc.method }),
+ clientKinds: params.clientKinds?.length
+ ? params.clientKinds
+ : this.clientKindsFor({ kind: 'rpc', method: rpc.method }),
deviceId: params.deviceId,
method: rpc.method,
params: rpc.params,
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 937e707597a..b73dd180141 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -2,6 +2,7 @@ import { z } from 'zod';
import type { DeviceLocalFilePreviewFailure } from './deviceFilePreviewFailure';
import type { ManagedDevicePhase } from './managedDevice';
+import type { DeviceClient } from './tool/builtin';
/** Structured context for an unavailable logical device. */
export interface DeviceUnavailableErrorData {
@@ -334,6 +335,14 @@ export interface DeviceRunningSummary {
users: DeviceEnroller[];
}
+/**
+ * `metadata` key a desktop client reports when its gateway connection serves
+ * the terminal RPCs. A CLI connection always does; an older desktop answers
+ * them with a refusal, so a desktop-only row counts as a terminal host only
+ * with this key set.
+ */
+export const DEVICE_TERMINAL_METADATA_KEY = 'terminal';
+
export interface DeviceListItem {
architecture?: string | null;
channels: DeviceChannel[];
@@ -1083,6 +1092,12 @@ export type DeviceAppUpdateInstallResult =
/** Result of the `createTerminalSession` device RPC. */
export interface DeviceCreateTerminalSessionResult {
+ /**
+ * The client hosting the session. Its later calls must reach the same
+ * client: the desktop app and `lh connect` keep separate sessions, and a
+ * device can hold both connections. Absent from hosts that predate it.
+ */
+ client?: DeviceClient;
/** Directory the shell actually started in (a missing `cwd` falls back home). */
cwd: string;
id: string;
diff --git a/src/features/ChatTerminal/deviceTerminal.test.ts b/src/features/ChatTerminal/deviceTerminal.test.ts
index 629bfbfac50..85fbacec2d4 100644
--- a/src/features/ChatTerminal/deviceTerminal.test.ts
+++ b/src/features/ChatTerminal/deviceTerminal.test.ts
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
})),
notifyExit: vi.fn(),
readTerminal: vi.fn(),
+ resizeTerminal: vi.fn(async () => {}),
+ writeTerminal: vi.fn(async () => {}),
setSessionSink: vi.fn(),
write: vi.fn(),
}));
@@ -25,8 +27,8 @@ vi.mock('@/services/device', () => ({
closeTerminal: mocks.closeTerminal,
createTerminalSession: mocks.createTerminalSession,
readTerminal: mocks.readTerminal,
- resizeTerminal: vi.fn(),
- writeTerminal: vi.fn(),
+ resizeTerminal: mocks.resizeTerminal,
+ writeTerminal: mocks.writeTerminal,
},
}));
@@ -117,4 +119,30 @@ describe('DeviceTerminalSession polling', () => {
expect(mocks.closeTerminal).toHaveBeenCalledWith({ deviceId: 'dev-1', id: 'term_1' });
expect(mocks.readTerminal.mock.calls.length).toBe(before);
});
+
+ it('keeps every call on the client that created the session', async () => {
+ // A device can hold `lh connect` and the desktop app at once, each with its
+ // own sessions; a desktop shell's calls must not drift to the CLI.
+ mocks.createTerminalSession.mockResolvedValueOnce({
+ client: 'desktop',
+ cwd: '/root',
+ id: 'term_1',
+ pid: 4321,
+ shell: '/bin/zsh',
+ } as never);
+ mocks.readTerminal.mockResolvedValue({ chunk: '', exited: false, nextCursor: 0 });
+
+ const session = await open();
+ await vi.advanceTimersByTimeAsync(0);
+ session.sink.write('term_1', 'ls');
+ session.sink.resize('term_1', 100, 30);
+ await vi.advanceTimersByTimeAsync(0);
+ await session.dispose();
+
+ const pinned = { client: 'desktop', deviceId: 'dev-1', id: 'term_1' };
+ expect(mocks.readTerminal).toHaveBeenCalledWith(expect.objectContaining(pinned));
+ expect(mocks.writeTerminal).toHaveBeenCalledWith(expect.objectContaining(pinned));
+ expect(mocks.resizeTerminal).toHaveBeenCalledWith(expect.objectContaining(pinned));
+ expect(mocks.closeTerminal).toHaveBeenCalledWith(pinned);
+ });
});
diff --git a/src/features/ChatTerminal/deviceTerminal.ts b/src/features/ChatTerminal/deviceTerminal.ts
index ac440891ea1..4284960c07c 100644
--- a/src/features/ChatTerminal/deviceTerminal.ts
+++ b/src/features/ChatTerminal/deviceTerminal.ts
@@ -1,3 +1,4 @@
+import type { DeviceClient } from '@lobechat/types';
import debug from 'debug';
import { deviceService } from '@/services/device';
@@ -42,6 +43,8 @@ const decodeBase64 = (base64: string): string => {
};
interface DeviceTerminalInfo {
+ /** The device client hosting the shell; every later call is kept on it. */
+ client?: DeviceClient;
cwd: string;
id: string;
pid: number;
@@ -51,8 +54,9 @@ interface DeviceTerminalInfo {
/**
* One interactive shell on a remote device, driven over the device RPC surface.
*
- * The PTY itself lives in the device's `lh connect` process; this object owns
- * only the polling cursor and the sink that routes keystrokes back. Because the
+ * The PTY itself lives on the device, in its `lh connect` process or desktop
+ * app; this object owns only the polling cursor and the sink that routes
+ * keystrokes back. Because the
* shell is a real PTY, `sudo` sees a controlling terminal and prompts for its
* password exactly as it would locally β€” the password never leaves the device
* and nothing about it is stored anywhere.
@@ -107,6 +111,15 @@ export class DeviceTerminalSession {
return this.info.id;
}
+ /**
+ * Where this session's calls go. A device can hold both `lh connect` and the
+ * desktop app, each with its own sessions, so the calls name the client that
+ * created this shell instead of letting the gateway pick one per call.
+ */
+ private get target() {
+ return { client: this.info.client, deviceId: this.deviceId };
+ }
+
/** How this session's keystrokes and resizes reach the device. */
readonly sink: TerminalSessionSink = {
close: () => {
@@ -114,7 +127,7 @@ export class DeviceTerminalSession {
},
resize: (sessionId, cols, rows) => {
void deviceService
- .resizeTerminal({ cols, deviceId: this.deviceId, id: sessionId, rows })
+ .resizeTerminal({ ...this.target, cols, id: sessionId, rows })
.catch((error) => log('resizeTerminal %s failed: %O', sessionId, error));
},
write: (sessionId, data) => {
@@ -135,8 +148,8 @@ export class DeviceTerminalSession {
const batch = this.pendingInput;
this.pendingInput = '';
await deviceService.writeTerminal({
+ ...this.target,
data: encodeBase64(batch),
- deviceId: this.deviceId,
id: sessionId,
});
}
@@ -159,7 +172,7 @@ export class DeviceTerminalSession {
this.timer = undefined;
}
try {
- await deviceService.closeTerminal({ deviceId: this.deviceId, id: this.info.id });
+ await deviceService.closeTerminal({ ...this.target, id: this.info.id });
} catch (error) {
log('closeTerminal %s failed: %O', this.info.id, error);
}
@@ -173,8 +186,8 @@ export class DeviceTerminalSession {
// per interval, so a burst (a build log) is not paced by the poll.
for (;;) {
const result = await deviceService.readTerminal({
+ ...this.target,
cursor: this.cursor,
- deviceId: this.deviceId,
id: this.info.id,
});
diff --git a/src/features/ChatTerminal/useTerminalEntry.test.ts b/src/features/ChatTerminal/useTerminalEntry.test.ts
new file mode 100644
index 00000000000..4985a39d2cb
--- /dev/null
+++ b/src/features/ChatTerminal/useTerminalEntry.test.ts
@@ -0,0 +1,53 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTerminalEntry } from './useTerminalEntry';
+
+const env = vi.hoisted(() => ({ hasDevice: false, isDesktop: false, isHetero: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ get isDesktop() {
+ return env.isDesktop;
+ },
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: { isCurrentAgentHeterogeneous: () => env.isHetero },
+}));
+vi.mock('@/store/device', () => ({
+ deviceSelectors: { hasTerminalTarget: () => env.hasDevice },
+ useDeviceStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+const entry = (placement: 'header' | 'overview') =>
+ renderHook(() => useTerminalEntry(placement)).result.current;
+
+describe('useTerminalEntry', () => {
+ beforeEach(() => {
+ Object.assign(env, { hasDevice: false, isDesktop: true, isHetero: false });
+ });
+
+ it('keeps an ordinary agent’s terminal in the Overview, not the header', () => {
+ expect(entry('header')).toBe(false);
+ expect(entry('overview')).toBe(true);
+ });
+
+ it('keeps a coding agent’s terminal in the header, not the Overview', () => {
+ env.isHetero = true;
+
+ expect(entry('header')).toBe(true);
+ expect(entry('overview')).toBe(false);
+ });
+
+ it('shows neither on the web until a device can host a shell', () => {
+ env.isDesktop = false;
+ expect(entry('header')).toBe(false);
+ expect(entry('overview')).toBe(false);
+
+ env.hasDevice = true;
+ expect(entry('overview')).toBe(true);
+ });
+});
diff --git a/src/features/ChatTerminal/useTerminalEntry.ts b/src/features/ChatTerminal/useTerminalEntry.ts
new file mode 100644
index 00000000000..31361c336d1
--- /dev/null
+++ b/src/features/ChatTerminal/useTerminalEntry.ts
@@ -0,0 +1,27 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+
+/** Where a conversation offers its way into the terminal panel. */
+export type TerminalEntryPlacement = 'header' | 'overview';
+
+/**
+ * Whether the terminal entry at `placement` shows for the current agent.
+ *
+ * A coding agent (Claude Code, Codex, …) works in a shell, so its terminal
+ * sits one click away in the conversation header. For any other agent it is
+ * an occasional tool and lives with the workspace resources in the Overview
+ * instead of taking a header slot.
+ *
+ * Either way it needs somewhere to run: the desktop always has its own shell;
+ * the web needs a connected device that can host one.
+ */
+export const useTerminalEntry = (placement: TerminalEntryPlacement): boolean => {
+ const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
+ const hasDevice = useDeviceStore(deviceSelectors.hasTerminalTarget);
+
+ if (!isDesktop && !hasDevice) return false;
+ return placement === 'header' ? isHetero : !isHetero;
+};
diff --git a/src/features/ChatTerminal/useTerminalTarget.test.ts b/src/features/ChatTerminal/useTerminalTarget.test.ts
index 1e1a2007f7f..824e947e62c 100644
--- a/src/features/ChatTerminal/useTerminalTarget.test.ts
+++ b/src/features/ChatTerminal/useTerminalTarget.test.ts
@@ -1,4 +1,4 @@
-import type { DeviceListItem } from '@lobechat/types';
+import { DEVICE_TERMINAL_METADATA_KEY, type DeviceListItem } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { create } from 'zustand';
@@ -99,4 +99,25 @@ describe('useTerminalTarget', () => {
expect(createTab).toHaveBeenCalledWith('tpc_1', undefined, undefined);
});
+
+ it("offers a desktop app's remote device but not this desktop's own row", () => {
+ env.isDesktop = true;
+ env.currentDeviceId = 'dev_local';
+ const desktopChannel = { channel: 'desktop', connectedAt: '', hostname: null, platform: null };
+ const metadata = { [DEVICE_TERMINAL_METADATA_KEY]: '1' };
+ deviceStore.current.setState({
+ deviceListMap: {
+ all: [
+ { ...device('dev_local', '/home/local'), channels: [desktopChannel], metadata },
+ { ...device('dev_b', '/home/b'), channels: [desktopChannel], metadata },
+ { ...device('dev_old', '/home/old'), channels: [desktopChannel] },
+ ],
+ },
+ });
+
+ const { result } = renderHook(() => useTerminalTarget('tpc_1', 'agt_1'));
+
+ expect(result.current.targets.map((target) => target.deviceId)).toEqual(['dev_b']);
+ expect(result.current.targetDeviceId).toBe('dev_b');
+ });
});
diff --git a/src/features/ChatTerminal/useTerminalTarget.ts b/src/features/ChatTerminal/useTerminalTarget.ts
index 51ec3d99701..f94b7f8e87e 100644
--- a/src/features/ChatTerminal/useTerminalTarget.ts
+++ b/src/features/ChatTerminal/useTerminalTarget.ts
@@ -57,9 +57,16 @@ export const useTerminalTarget = (topicKey: string, agentId?: string): TerminalT
const devices = useDeviceStore(deviceSelectors.deviceList);
const deviceListConfirmed = useDeviceStore(deviceSelectors.isDeviceListConfirmed);
// Only devices that can actually open a shell. An offline row, or one whose
- // live connections are all desktop ones, answers a terminal RPC with a
- // refusal β€” offering it would fail the session the moment it is claimed.
- const targets = useMemo(() => devices.filter(canHostTerminal), [devices]);
+ // live connections are all from a desktop without terminal support, answers
+ // a terminal RPC with a refusal β€” offering it would fail the session the
+ // moment it is claimed. This desktop's own row is "this machine" already.
+ const targets = useMemo(
+ () =>
+ devices.filter(
+ (device) => canHostTerminal(device) && !(isDesktop && device.deviceId === currentDeviceId),
+ ),
+ [devices, currentDeviceId],
+ );
const { deviceId: targetDeviceId, ready: canSpawn } = resolveTerminalDevice({
configLoading: isPreferenceLoading,
listSettled: deviceListConfirmed || !!deviceListError,
diff --git a/src/features/Conversation/WorkingSidebar/Overview/TerminalRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/TerminalRow.tsx
new file mode 100644
index 00000000000..a854f1ab6ad
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/TerminalRow.tsx
@@ -0,0 +1,30 @@
+import { SquareTerminalIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTerminalEntry } from '@/features/ChatTerminal/useTerminalEntry';
+import { useGlobalStore } from '@/store/global';
+
+import { ChevronRight, OverviewRow } from './OverviewRow';
+
+/** Opens the terminal panel for agents that don't keep it in the header. */
+export const TerminalRow = memo(() => {
+ const { t } = useTranslation('chat');
+ const visible = useTerminalEntry('overview');
+ const toggleTerminalPanel = useGlobalStore((s) => s.toggleTerminalPanel);
+
+ if (!visible) return null;
+
+ return (
+ <OverviewRow
+ weak
+ icon={SquareTerminalIcon}
+ iconSize={15}
+ trailing={<ChevronRight />}
+ value={t('terminalPanel.title')}
+ onClick={() => toggleTerminalPanel(true)}
+ />
+ );
+});
+
+TerminalRow.displayName = 'OverviewTerminalRow';
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index 9fe51d2481c..e8f4fa32bb5 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -69,6 +69,7 @@ import OverviewHeader from './OverviewHeader';
import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';
import PortSwitcher from './PortSwitcher';
import { sectionStyles } from './sectionStyles';
+import { TerminalRow } from './TerminalRow';
const styles = createStaticStyles(({ css }) => ({
body: css`
@@ -553,6 +554,7 @@ const Overview = memo<OverviewProps>(
onClick={() => onOpenTab('documents')}
/>
)}
+ <TerminalRow />
</Flexbox>
</Flexbox>
);
diff --git a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
index 76127e3684d..16b6a444121 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
@@ -6,10 +6,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import TerminalPanelToggle from './index';
const mocks = vi.hoisted(() => ({
- hasTerminalTarget: false,
- isDesktop: true,
showTerminalPanel: false,
toggleTerminalPanel: vi.fn(),
+ visible: true,
}));
const actionIconPropsSpy = vi.hoisted(() => vi.fn());
@@ -25,20 +24,10 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
};
});
-vi.mock('@/const/version', () => ({
- get isDesktop() {
- return mocks.isDesktop;
- },
-}));
-
-vi.mock('@/store/device', () => ({
- deviceSelectors: {
- // The real selector decides this from the device list; the header consumes
- // the derived boolean, so the mock supplies it directly.
- hasTerminalTarget: (s: { hasTerminalTarget: boolean }) => s.hasTerminalTarget,
- },
- useDeviceStore: (selector: (state: { hasTerminalTarget: boolean }) => unknown) =>
- selector({ hasTerminalTarget: mocks.hasTerminalTarget }),
+// Where the entry shows is `useTerminalEntry`'s call (tested beside it); the
+// header only renders what it answers.
+vi.mock('@/features/ChatTerminal/useTerminalEntry', () => ({
+ useTerminalEntry: () => mocks.visible,
}));
vi.mock('@/store/global', () => ({
@@ -73,9 +62,8 @@ vi.mock('@/store/user/selectors', () => ({
describe('TerminalPanelToggle', () => {
beforeEach(() => {
- mocks.hasTerminalTarget = false;
- mocks.isDesktop = true;
mocks.showTerminalPanel = false;
+ mocks.visible = true;
mocks.toggleTerminalPanel.mockReset();
actionIconPropsSpy.mockClear();
});
@@ -96,21 +84,11 @@ describe('TerminalPanelToggle', () => {
expect(actionIconPropsSpy).toHaveBeenCalledWith(expect.objectContaining({ active: true }));
});
- it('stays hidden on the web while no device can host a shell', () => {
- mocks.isDesktop = false;
+ it('renders nothing where the header holds no terminal entry', () => {
+ mocks.visible = false;
render(<TerminalPanelToggle />);
expect(screen.queryByRole('button')).toBeNull();
});
-
- it('appears on the web once a device can host a shell', () => {
- mocks.isDesktop = false;
- mocks.hasTerminalTarget = true;
-
- render(<TerminalPanelToggle />);
-
- fireEvent.click(screen.getByRole('button'));
- expect(mocks.toggleTerminalPanel).toHaveBeenCalledTimes(1);
- });
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx
index e70a93a20e3..c350ed1f745 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx
@@ -7,8 +7,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
-import { isDesktop } from '@/const/version';
-import { deviceSelectors, useDeviceStore } from '@/store/device';
+import { useTerminalEntry } from '@/features/ChatTerminal/useTerminalEntry';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
@@ -22,13 +21,11 @@ const TerminalPanelToggle = memo(() => {
]);
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleTerminalPanel));
- // On the web the panel has no local shell to fall back on: it renders only
- // while a device that can host one is connected, so the toggle would be a
- // dead button without one. The device list is fetched by the panel itself,
- // which is mounted alongside this header.
- const hasDevice = useDeviceStore(deviceSelectors.hasTerminalTarget);
+ // Shown for coding agents only, and only where a shell can run; other agents
+ // reach the terminal from the Overview resources (see `useTerminalEntry`).
+ const visible = useTerminalEntry('header');
- if (!isDesktop && !hasDevice) return null;
+ if (!visible) return null;
return (
<ActionIcon
diff --git a/src/store/device/selectors.test.ts b/src/store/device/selectors.test.ts
index 91034b2a3da..2c21b295693 100644
--- a/src/store/device/selectors.test.ts
+++ b/src/store/device/selectors.test.ts
@@ -1,4 +1,4 @@
-import type { DeviceListItem } from '@lobechat/types';
+import { DEVICE_TERMINAL_METADATA_KEY, type DeviceListItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import type { DeviceState } from './initialState';
@@ -26,13 +26,21 @@ describe('canHostTerminal', () => {
expect(canHostTerminal(device({ channels: [channel('cli')], online: false }))).toBe(false);
});
- it('rejects a device whose live connections are all desktop ones', () => {
- // The PTY lives in `lh connect`; terminal RPCs are sent with a `cli` hint,
- // so a desktop-only machine answers them with a refusal.
+ it('rejects a device whose live connections are all from a desktop without terminal support', () => {
+ // An older desktop answers terminal RPCs with a refusal.
expect(canHostTerminal(device({ channels: [channel('desktop')] }))).toBe(false);
expect(canHostTerminal(device({ channels: [channel('desktop-dev')] }))).toBe(false);
});
+ it('accepts a desktop connection whose app reports terminal support', () => {
+ const metadata = { appVersion: '2.4.0', [DEVICE_TERMINAL_METADATA_KEY]: '1' };
+ expect(canHostTerminal(device({ channels: [channel('desktop')], metadata }))).toBe(true);
+ expect(canHostTerminal(device({ channels: [channel('desktop-dev')], metadata }))).toBe(true);
+ expect(
+ canHostTerminal(device({ channels: [channel('desktop')], metadata, online: false })),
+ ).toBe(false);
+ });
+
it('rejects connections of an unknown kind', () => {
expect(canHostTerminal(device({ channels: [channel('mobile'), channel(null)] }))).toBe(false);
});
diff --git a/src/store/device/selectors.ts b/src/store/device/selectors.ts
index 16382da69b9..d99d9118996 100644
--- a/src/store/device/selectors.ts
+++ b/src/store/device/selectors.ts
@@ -1,4 +1,8 @@
-import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
+import {
+ DEVICE_TERMINAL_METADATA_KEY,
+ type DeviceListItem,
+ type DeviceMetricSeries,
+} from '@lobechat/types';
import { getChannelKind } from '@/features/DeviceManager/channelKind';
@@ -29,11 +33,12 @@ const isDeviceListConfirmed = (s: DeviceState): boolean =>
/**
* Whether a shell opened from the browser can run on this device.
*
- * The PTY lives in the machine's `lh connect` process, and terminal RPCs carry
- * a `cli` channel hint that the gateway only treats as a *preference* β€” so a
- * row whose live connections are all desktop ones answers those RPCs with a
- * refusal. Requiring a live `cli` connection is what keeps the picker from
- * offering a target that cannot open a shell.
+ * The PTY lives in the machine's `lh connect` process or, on a desktop that
+ * reports {@link DEVICE_TERMINAL_METADATA_KEY}, in the app's own gateway
+ * connection. Terminal RPCs carry a `cli` channel hint the gateway only treats
+ * as a *preference*, so a row whose live connections are all from an older
+ * desktop answers them with a refusal. Requiring a capable live connection is
+ * what keeps the picker from offering a target that cannot open a shell.
*
* Two edges: an offline row is a registry entry rather than a reachable host,
* and a live row that reports no connections at all is a gateway that predates
@@ -43,7 +48,11 @@ export const canHostTerminal = (device: DeviceListItem): boolean => {
if (!device.online) return false;
const channels = device.channels ?? [];
if (channels.length === 0) return true;
- return channels.some((channel) => getChannelKind(channel.channel) === 'cli');
+ const desktopServesTerminal = device.metadata?.[DEVICE_TERMINAL_METADATA_KEY] === '1';
+ return channels.some((channel) => {
+ const kind = getChannelKind(channel.channel);
+ return kind === 'cli' || (kind === 'desktop' && desktopServesTerminal);
+ });
};
/**