π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(terminal): run interactive shells on connected devices from the web (#20600)
LiJian028bce19c8e3
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 02025c78220..e2e0f7f2551 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -29,6 +29,7 @@"type-check": "tsc --noEmit"},"dependencies": {+ "@lydell/node-pty": "1.2.0-beta.15","ws": "^8.21.0"},"devDependencies": {diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 63053c9dd53..7359d2074d9 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -56,6 +56,7 @@ import {resolveDeviceIdentity,resolveWorkspaceDeviceIdentity,} from '../device/register';+import { TerminalSessionManager } from '../device/terminal';import {installConnectService,readConnectServiceStatus,@@ -457,6 +458,15 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// mode-specific `enrollWorkspace` / `unenrollWorkspace` handlers are attached// further below once the workspace-share machinery is in scope β every bound// connection reads this object by reference, so late attachment is safe.+ //+ // Interactive shells for the remote terminal. One manager per process, read+ // by reference by every gateway connection this daemon owns, so a+ // workspace-share connection reaches the same sessions as the personal one.+ // 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 maintenance = new CliMaintenance({activeTasks: () =>getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length,@@ -465,8 +475,11 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {restartArgs: buildDaemonArgs(options).slice(1),shutdown: () => shutdown(),});+const deviceControlDeps: DeviceControlDeps = {checkCliUpdate: maintenance.check,+ closeTerminal: (params) => Promise.resolve(terminals.close(params)),+ createTerminalSession: (params) => terminals.create(params),getCliUpdateState: maintenance.getState,getLocalFilePreview: defaultGetLocalFilePreview,getProjectFileIndex: defaultGetProjectFileIndex,@@ -475,8 +488,11 @@ 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)),};const handlerContext: GatewayHandlerContext = {@@ -822,6 +838,9 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {info('Shutting down...');cancelRefreshTimer?.();cleanupAllProcesses();+ // Kill every remote-terminal shell this daemon started, so a stopping+ // `lh connect` does not leave orphaned PTYs behind on the machine.+ terminals.dispose();// Close share connections but keep the persisted enrollments β the next// startup restores them (or clears them if revoked meanwhile).for (const wsId of workspaceConnections.keys()) closeWorkspaceConnection(wsId);diff --git a/apps/cli/src/device/terminal.test.ts b/apps/cli/src/device/terminal.test.tsnew file mode 100644index 00000000000..90aca5ebb0f--- /dev/null+++ b/apps/cli/src/device/terminal.test.ts@@ -0,0 +1,201 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TerminalSessionManager } from './terminal';++interface FakePty {+ emitData: (data: string) => void;+ emitExit: (exitCode: number) => void;+ kill: ReturnType<typeof vi.fn>;+ pid: number;+ resize: ReturnType<typeof vi.fn>;+ write: ReturnType<typeof vi.fn>;+}++const ptys: FakePty[] = [];+let spawnOptions: Record<string, unknown> | undefined;++vi.mock('@lydell/node-pty', () => ({+ spawn: (_shell: string, _args: string[], options: Record<string, unknown>) => {+ spawnOptions = options;+ let dataHandler: ((data: string) => void) | undefined;+ let exitHandler: ((event: { exitCode: number }) => void) | undefined;+ const pty: FakePty = {+ emitData: (data) => dataHandler?.(data),+ emitExit: (exitCode) => exitHandler?.({ exitCode }),+ kill: vi.fn(),+ pid: 4000 + ptys.length,+ resize: vi.fn(),+ write: vi.fn(),+ };+ ptys.push(pty);+ return {+ ...pty,+ onData: (cb: (data: string) => void) => {+ dataHandler = cb;+ },+ onExit: (cb: (event: { exitCode: number }) => void) => {+ exitHandler = cb;+ },+ };+ },+}));++const decode = (base64: string) => Buffer.from(base64, 'base64').toString('utf8');++describe('TerminalSessionManager', () => {+ let manager: TerminalSessionManager;++ beforeEach(() => {+ ptys.length = 0;+ spawnOptions = undefined;+ manager = new TerminalSessionManager();+ });++ afterEach(() => {+ manager.dispose();+ });++ const openSession = async () => {+ const info = await manager.create({ cols: 80, rows: 24 });+ return { info, pty: ptys.at(-1)! };+ };++ it('spawns a PTY with xterm capabilities instead of a piped child', async () => {+ // The whole point of a pty: `sudo` reads its password from /dev/tty, which+ // 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(spawnOptions).toMatchObject({+ cols: 80,+ env: expect.objectContaining({ TERM: 'xterm-256color' }),+ name: 'xterm-256color',+ rows: 24,+ });+ });++ it('returns only output produced after the caller cursor', async () => {+ const { info, pty } = await openSession();++ pty.emitData('first');+ const first = manager.read({ cursor: 0, id: info.id });+ expect(decode(first.chunk)).toBe('first');+ expect(first).toMatchObject({ exited: false, nextCursor: 5 });++ // Nothing new yet.+ expect(manager.read({ cursor: first.nextCursor, id: info.id }).chunk).toBe('');++ pty.emitData('second');+ const second = manager.read({ cursor: first.nextCursor, id: info.id });+ expect(decode(second.chunk)).toBe('second');+ expect(second.nextCursor).toBe(11);+ });++ it('writes the caller bytes straight through to the PTY', async () => {+ const { info, pty } = await openSession();+ const keystrokes = Buffer.from('TituPass123!\n', 'utf8').toString('base64');++ manager.write({ data: keystrokes, id: info.id });++ const written = pty.write.mock.calls[0][0];+ expect(Buffer.isBuffer(written)).toBe(true);+ expect(written.toString('utf8')).toBe('TituPass123!\n');+ });++ it('keeps a shell that exited readable so its last output is not swallowed', async () => {+ const { info, pty } = await openSession();++ pty.emitData('bye\n');+ pty.emitExit(3);++ const result = manager.read({ cursor: 0, id: info.id });+ expect(decode(result.chunk)).toBe('bye\n');+ expect(result).toMatchObject({ exitCode: 3, exited: true });++ // The buffer survives the exit, so a later read still reports the status.+ expect(manager.read({ cursor: 0, id: info.id }).exited).toBe(true);+ // ...but writing to a dead shell is an error, not a silent no-op.+ expect(() => manager.write({ data: '', id: info.id })).toThrow(/has exited/);+ });++ it('clamps a reader that fell behind rather than refusing to read', async () => {+ const { info, pty } = await openSession();++ // Overflow the ring buffer, so the marker at the very front is dropped.+ pty.emitData(`HEAD${'x'.repeat(1_000_000)}`);+ pty.emitData('TAIL');++ const first = manager.read({ cursor: 0, id: info.id });+ const firstText = decode(first.chunk);++ // The read resumes at the oldest output still held: 8 characters were+ // dropped ('HEAD' plus the tail of the 'x' run), so the marker never comes+ // back, and the call stops at the per-read cap rather than the buffer end.+ expect(firstText).not.toContain('HEAD');+ expect(first.nextCursor).toBe(8 + 131_072);++ // Draining to the end reaches the newest output and a stable cursor.+ let cursor = first.nextCursor;+ let text = firstText;+ for (;;) {+ const next = manager.read({ cursor, id: info.id });+ if (!next.chunk) break;+ cursor = next.nextCursor;+ text += decode(next.chunk);+ }+ expect(cursor).toBe(1_000_008);+ expect(text.endsWith('TAIL')).toBe(true);+ });++ it('caps one read so a burst is drained by repeated calls', async () => {+ const { info, pty } = await openSession();++ pty.emitData('a'.repeat(300_000));+ const first = manager.read({ cursor: 0, id: info.id });++ // 128Ki characters per call, so the next read continues where this stopped.+ expect(first.nextCursor).toBe(131_072);+ expect(manager.read({ cursor: first.nextCursor, id: info.id }).chunk).not.toBe('');+ });++ it('kills the shell on close and reports an unknown session honestly', async () => {+ const { info, pty } = await openSession();++ expect(manager.close({ id: info.id })).toEqual({ closed: true });+ expect(pty.kill).toHaveBeenCalledOnce();+ expect(manager.close({ id: info.id })).toEqual({ closed: false });+ });++ 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 } });+ try {+ const info = await reaped.create({ cols: 80, rows: 24 });+ reaped.close({ id: info.id });++ // A client polling an id this host no longer holds β daemon restarted, or+ // the LRU cap evicted it β must not read as a transport failure, or it+ // would retry the missing session forever. It reads as "the shell is gone".+ expect(reaped.read({ cursor: 0, id: info.id })).toEqual({+ chunk: '',+ exited: true,+ nextCursor: 0,+ });+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(info.id));+ // Writing to it is still an error: that is a caller bug, not an exit.+ expect(() => reaped.write({ data: '', id: info.id })).toThrow(/Unknown terminal session/);+ } finally {+ reaped.dispose();+ }+ });++ it('forwards resize and ignores degenerate dimensions', async () => {+ const { info, pty } = await openSession();++ manager.resize({ cols: 120, id: info.id, rows: 40 });+ expect(pty.resize).toHaveBeenCalledWith(120, 40);++ manager.resize({ cols: 0, id: info.id, rows: 0 });+ expect(pty.resize).toHaveBeenCalledOnce();+ });+});diff --git a/apps/cli/src/device/terminal.ts b/apps/cli/src/device/terminal.tsnew file mode 100644index 00000000000..a9f8f00478c--- /dev/null+++ b/apps/cli/src/device/terminal.ts@@ -0,0 +1,279 @@+import { randomUUID } from 'node:crypto';+import fs from 'node:fs/promises';+import os from 'node:os';++import type {+ CloseTerminalParams,+ CloseTerminalResult,+ CreateTerminalSessionParams,+ CreateTerminalSessionResult,+ ReadTerminalParams,+ ReadTerminalResult,+ ResizeTerminalParams,+ WriteTerminalParams,+} from '@lobechat/device-control';+import { detectWindowsShell } from '@lobechat/local-file-shell/shell';+import type { IPty } from '@lydell/node-pty';++/**+ * `@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());++/**+ * PTY sessions for the remote terminal, driven by the `createTerminalSession` /+ * `writeTerminal` / `readTerminal` / `resizeTerminal` / `closeTerminal` device+ * RPCs.+ *+ * Unlike the desktop app's local terminal β which pushes `onData` at the+ * renderer over IPC β the device RPC surface is strictly request/response, so+ * this manager keeps each session's output in a bounded buffer that the caller+ * drains with a cursor. It spawns a REAL pty rather than a piped child: that is+ * what makes `sudo` work, because `sudo` reads its password from `/dev/tty` and+ * only prompts when it has a controlling terminal. The password therefore flows+ * device-side only β it is never sent to, or stored by, the server.+ */++/** Hard cap on concurrent sessions; the least recently active one is evicted. */+const MAX_SESSIONS = 5;+/** Reap a session with no input and no output for this long. */+const IDLE_TIMEOUT_MS = 30 * 60 * 1000;+/**+ * How long a session that has exited stays readable. `exit` and a failed+ * `sudo` both print on the way out, and dropping the session the moment the+ * shell dies would swallow that last output.+ */+const EXITED_TTL_MS = 60 * 1000;+const SWEEP_INTERVAL_MS = 60 * 1000;+/**+ * Output kept per session. The oldest characters are dropped past this, which+ * only matters for a reader that stopped polling entirely β the dropped+ * characters are then simply missing from its stream.+ */+const MAX_BUFFER_CHARS = 1_000_000;+/** Output returned by a single read. A burst is drained by repeated reads. */+const MAX_CHUNK_CHARS = 128 * 1024;++interface TerminalSession {+ /** Characters already dropped from the front of {@link buffer}. */+ baseOffset: number;+ /** Rolling output; `baseOffset + buffer.length` is the session's cursor. */+ buffer: string;+ cwd: string;+ exitCode?: number;+ exited: boolean;+ /** Set once the shell exits, so the finished buffer can be reaped later. */+ exitedAt?: number;+ id: string;+ lastActiveAt: number;+ pid: number;+ pty?: IPty;+ shell: string;+}++export interface TerminalManagerOptions {+ logger?: { warn: (message: string) => void };+}++const resolveDefaultShell = async (): Promise<string> => {+ // Reuse the shared runCommand shell detection instead of ComSpec, which+ // effectively always points at cmd.exe.+ if (process.platform === 'win32') return (await detectWindowsShell()).path;+ return process.env.SHELL || (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');+};++const isDirectory = async (candidate: string): Promise<boolean> => {+ try {+ return (await fs.stat(candidate)).isDirectory();+ } catch {+ return false;+ }+};++export class TerminalSessionManager {+ private sessions = new Map<string, TerminalSession>();+ private sweepTimer: NodeJS.Timeout;++ constructor(private options: TerminalManagerOptions = {}) {+ this.sweepTimer = setInterval(() => this.sweep(), SWEEP_INTERVAL_MS);+ this.sweepTimer.unref();+ }++ async create(params: CreateTerminalSessionParams): Promise<CreateTerminalSessionResult> {+ this.evictLruIfFull();++ const id = `term_${randomUUID()}`;+ const shell = await resolveDefaultShell();+ const cwd = params.cwd && (await isDirectory(params.cwd)) ? params.cwd : os.homedir();+ const cols = params.cols > 0 ? params.cols : 80;+ const rows = params.rows > 0 ? params.rows : 24;++ const { spawn } = await loadPty();+ const pty = spawn(shell, [], {+ cols,+ cwd,+ env: {+ ...process.env,+ COLORTERM: 'truecolor',+ TERM: 'xterm-256color',+ } as Record<string, string>,+ name: 'xterm-256color',+ rows,+ });++ const session: TerminalSession = {+ baseOffset: 0,+ buffer: '',+ cwd,+ exited: false,+ id,+ lastActiveAt: Date.now(),+ pid: pty.pid,+ pty,+ shell,+ };+ this.sessions.set(id, session);++ pty.onData((data) => {+ session.lastActiveAt = Date.now();+ this.append(session, data);+ });+ pty.onExit(({ exitCode }) => {+ session.exitCode = exitCode;+ session.exited = true;+ session.exitedAt = Date.now();+ session.pty = undefined;+ });++ return { cwd, id, pid: pty.pid, shell };+ }++ write(params: WriteTerminalParams): void {+ const session = this.require(params.id);+ if (!session.pty) throw new Error(`Terminal session ${params.id} has exited`);+ session.lastActiveAt = Date.now();+ // Decoded back to bytes so the PTY receives exactly what the caller sent β+ // a keystroke and a partial UTF-8 sequence are both just bytes here.+ session.pty.write(Buffer.from(params.data, 'base64'));+ }++ read(params: ReadTerminalParams): ReadTerminalResult {+ const session = this.sessions.get(params.id);+ if (!session) {+ // A session this client no longer holds: the daemon restarted, the idle+ // sweep reaped it, or the LRU cap evicted it. That is not a transport+ // failure and the caller cannot bring it back, so answer the same way an+ // exited shell is answered β the reader closes its pane instead of+ // polling an id that will never be known here again. Reported rather than+ // thrown because throwing leaves every caller to recognise one message+ // string to tell "gone" apart from "the device is unreachable".+ this.options.logger?.warn(`terminal: read for unknown session ${params.id}`);+ return { chunk: '', exited: true, nextCursor: params.cursor };+ }+ session.lastActiveAt = Date.now();++ // A caller that fell behind the ring buffer is clamped forward rather than+ // refused: the terminal resumes at the oldest output still held.+ const start = Math.max(params.cursor, session.baseOffset);+ const available = session.baseOffset + session.buffer.length;+ const end = Math.min(available, start + MAX_CHUNK_CHARS);+ const chunk = session.buffer.slice(start - session.baseOffset, end - session.baseOffset);++ return {+ chunk: Buffer.from(chunk, 'utf8').toString('base64'),+ ...(session.exitCode === undefined ? {} : { exitCode: session.exitCode }),+ exited: session.exited,+ nextCursor: end,+ };+ }++ resize(params: ResizeTerminalParams): void {+ if (params.cols <= 0 || params.rows <= 0) return;+ const session = this.sessions.get(params.id);+ if (!session?.pty) return;+ session.lastActiveAt = Date.now();+ session.pty.resize(params.cols, params.rows);+ }++ close(params: CloseTerminalParams): CloseTerminalResult {+ const session = this.sessions.get(params.id);+ if (!session) return { closed: false };+ this.sessions.delete(params.id);+ if (session.pty) {+ try {+ session.pty.kill();+ } catch {+ /* already dead */+ }+ }+ return { closed: true };+ }++ /** Kill every live shell and stop sweeping. Called on daemon shutdown. */+ dispose(): void {+ clearInterval(this.sweepTimer);+ for (const session of this.sessions.values()) {+ try {+ session.pty?.kill();+ } catch {+ /* already dead */+ }+ }+ this.sessions.clear();+ }++ private append(session: TerminalSession, chunk: string) {+ session.buffer += chunk;+ if (session.buffer.length <= MAX_BUFFER_CHARS) return;+ const dropped = session.buffer.length - MAX_BUFFER_CHARS;+ session.buffer = session.buffer.slice(dropped);+ session.baseOffset += dropped;+ }++ private require(id: string): TerminalSession {+ const session = this.sessions.get(id);+ if (!session) throw new Error(`Unknown terminal session: ${id}`);+ return session;+ }++ private evictLruIfFull() {+ while (this.sessions.size >= MAX_SESSIONS) {+ let lruId: string | undefined;+ let lruAt = Infinity;+ for (const [id, session] of this.sessions) {+ // An exited session is dead weight β it only lingers so its final+ // output can be read β so it is evicted before any live shell.+ const rank = session.exited ? -Infinity : session.lastActiveAt;+ if (rank < lruAt) {+ lruAt = rank;+ lruId = id;+ }+ }+ if (!lruId) return;+ this.options.logger?.warn(`terminal: evicting session ${lruId} (session limit)`);+ this.close({ id: lruId });+ }+ }++ private sweep() {+ const now = Date.now();+ for (const [id, session] of this.sessions) {+ const expired = session.exited+ ? now - (session.exitedAt ?? session.lastActiveAt) > EXITED_TTL_MS+ : now - session.lastActiveAt > IDLE_TIMEOUT_MS;+ if (!expired) continue;+ this.options.logger?.warn(+ `terminal: reaping session ${id} (${session.exited ? 'exited' : 'idle'})`,+ );+ this.close({ id });+ }+ }+}diff --git a/apps/cli/tsdown.config.test.ts b/apps/cli/tsdown.config.test.tsindex 6c974914080..d46327c14bc 100644--- a/apps/cli/tsdown.config.test.ts+++ b/apps/cli/tsdown.config.test.ts@@ -22,6 +22,16 @@ describe('CLI build configuration', () => {);});+ it('keeps the native PTY module external instead of bundling its binary', () => {+ expect(config).toEqual(+ expect.objectContaining({+ deps: expect.objectContaining({+ neverBundle: expect.arrayContaining(['@lydell/node-pty']),+ }),+ }),+ );+ });+it('fails the build instead of externalizing an unresolved import', async () => {const { onLog } = await resolveInputOptions();diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.tsindex fde41b8b2bb..91656218496 100644--- a/apps/cli/tsdown.config.ts+++ b/apps/cli/tsdown.config.ts@@ -9,6 +9,12 @@ export default defineConfig({// production dependency inside the bundle so the embedded CLI is truly// self-contained instead of failing at startup with ERR_MODULE_NOT_FOUND.alwaysBundle: ['ws'],+ // `@lydell/node-pty` is deliberately NOT bundled: it loads a prebuilt+ // native binary per platform, which bundling would break. It stays a real+ // runtime dependency and is imported lazily (see `src/device/terminal.ts`),+ // so only a process that actually opens a remote terminal resolves it β+ // the desktop-embedded CLI keeps working without it.+ neverBundle: ['@lydell/node-pty'],},entry: ['src/index.ts'],fixedExtension: false,diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex c99399572e5..897edb28f89 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -761,6 +761,9 @@ importers:../cli:dependencies:+ '@lydell/node-pty':+ specifier: 1.2.0-beta.15+ version: 1.2.0-beta.15ws:specifier: ^8.21.0version: 8.22.0diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex e5464ab610a..6e793bdc3d6 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -96,6 +96,29 @@ const assertTunnelDeviceWritable = (deviceId: string,) => assertDeviceOperable(ctx, deviceId, 'expose a port');+/**+ * Base64 characters accepted by one `writeTerminal` call. A keystroke is a+ * handful of bytes; this only bounds what a malicious caller can push through+ * in a single request.+ */+const MAX_TERMINAL_WRITE_CHARS = 65_536;++/**+ * 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+ * needs to read; a bare 500 would make it look like a LobeHub bug.+ */+const relayTerminal = async <T>(run: () => Promise<T>): Promise<T> => {+ try {+ return await run();+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_GATEWAY',+ message: error instanceof Error ? error.message : String(error),+ });+ }+};+/** Append a freshly minted access token to a tunnel URL. */const buildTunnelOpenUrl = async (url: string,@@ -1431,6 +1454,109 @@ export const deviceRouter = router({});}),+ // βββ Interactive terminal βββ+ //+ // A terminal hands the caller a shell on the device, so it is gated exactly+ // like exposing a port. The check runs on the polling reads too, not just on+ // create β otherwise a session would outlive the permission that opened it.++ createTerminalSession: deviceProcedure+ .input(+ z.object({+ cols: z.number().int().min(1).max(1000),+ cwd: z.string().optional(),+ deviceId: z.string(),+ rows: z.number().int().min(1).max(1000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'open a terminal on');+ return relayTerminal(() =>+ deviceGateway.createTerminalSession({+ cols: input.cols,+ cwd: input.cwd,+ deviceId: input.deviceId,+ rows: input.rows,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),++ writeTerminal: deviceProcedure+ .input(+ z.object({+ /** Base64 keystrokes. */+ data: z.string().max(MAX_TERMINAL_WRITE_CHARS),+ deviceId: z.string(),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.writeTerminal({+ data: input.data,+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),++ readTerminal: deviceProcedure+ .input(z.object({ 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({+ cursor: input.cursor,+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),++ resizeTerminal: deviceProcedure+ .input(+ z.object({+ cols: z.number().int().min(1).max(1000),+ deviceId: z.string(),+ id: z.string(),+ rows: z.number().int().min(1).max(1000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.resizeTerminal({+ cols: input.cols,+ deviceId: input.deviceId,+ id: input.id,+ rows: input.rows,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),++ closeTerminal: deviceProcedure+ .input(z.object({ deviceId: z.string(), id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.closeTerminal({+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+getCliUpdateState: deviceProcedure.input(z.object({ deviceId: z.string() }).strict()).query(async ({ ctx, input }) => {diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex f70e30e7932..b62d34602d1 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -22,10 +22,12 @@ import type {DeviceCliRestartParams,DeviceCliUpdateState,DeviceCliUpdateStateResult,+ DeviceCloseTerminalResult,DeviceCopyAssetForPublishResult,DeviceCopyProjectFileItem,DeviceCopyProjectFileResultItem,DeviceCreateProjectEntryResult,+ DeviceCreateTerminalSessionResult,DeviceDirectoryBrowseResult,DeviceExternalAssetForPublishResult,DeviceGitAddWorktreeResult,@@ -59,6 +61,7 @@ import type {DeviceProjectDirectoryListResult,DeviceProjectFileIndexResult,DeviceProjectFileSearchResult,+ DeviceReadTerminalResult,DeviceRenameProjectFileResult,DeviceTrashProjectFilesResult,DeviceUnavailableErrorData,@@ -151,6 +154,18 @@ interface AppUpdateRpcParams {const DEVICE_READ_ATTEMPTS = 2;const DEVICE_READ_RETRY_DELAY_MS = 250;+/** Scope every terminal RPC carries; mirrors {@link AppUpdateRpcParams}. */+interface TerminalRpcScope {+ deviceId: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+}++/** The five device RPCs that make up one interactive terminal session. */+type TerminalRpcMethod =+ 'closeTerminal' | 'createTerminalSession' | 'readTerminal' | 'resizeTerminal' | 'writeTerminal';+export class DeviceGateway {private client: GatewayHttpClient | null = null;@@ -2096,6 +2111,81 @@ export class DeviceGateway {: result;}+ // βββ Interactive terminal (PTY) βββ+ //+ // A terminal is a session the caller drives, not a one-shot read, so these+ // deliberately THROW on failure instead of returning `undefined` the way the+ // best-effort readers above do: the panel has to say why a shell did not open+ // (device offline, a client without PTY support) rather than wait forever on+ // one that will never exist.++ async createTerminalSession(+ params: TerminalRpcScope & { cols: number; cwd?: string; rows: number },+ ): Promise<DeviceCreateTerminalSessionResult> {+ return this.invokeTerminalRpc('createTerminalSession', params, {+ cols: params.cols,+ cwd: params.cwd,+ rows: params.rows,+ });+ }++ async writeTerminal(params: TerminalRpcScope & { data: string; id: string }): Promise<void> {+ await this.invokeTerminalRpc('writeTerminal', params, { data: params.data, id: params.id });+ }++ async readTerminal(+ params: TerminalRpcScope & { cursor: number; id: string },+ ): Promise<DeviceReadTerminalResult> {+ return this.invokeTerminalRpc('readTerminal', params, {+ cursor: params.cursor,+ id: params.id,+ });+ }++ async resizeTerminal(+ params: TerminalRpcScope & { cols: number; id: string; rows: number },+ ): Promise<void> {+ await this.invokeTerminalRpc('resizeTerminal', params, {+ cols: params.cols,+ id: params.id,+ rows: params.rows,+ });+ }++ async closeTerminal(+ params: TerminalRpcScope & { id: string },+ ): Promise<DeviceCloseTerminalResult> {+ return this.invokeTerminalRpc('closeTerminal', params, { id: params.id });+ }++ /**+ * 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.+ */+ private async invokeTerminalRpc<T>(+ method: TerminalRpcMethod,+ params: TerminalRpcScope,+ rpcParams: Record<string, unknown>,+ ): Promise<T> {+ const { deviceId, timeout = 15_000, userId, workspaceId } = params;+ const client = this.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 },+ { method, params: rpcParams },+ );+ // `writeTerminal` / `resizeTerminal` answer with no payload, so absence of+ // `data` is not a failure β only an explicit `success: false` is.+ if (!result.success) throw new Error(result.error || `${method} failed`);+ return result.data as T;+ }+/*** Shared relay for the remote app-update RPCs. Only the desktop app can* update itself, so the call asks for the `desktop` channel; an older gatewaydiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 99fda0735b7..57e6f688669 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2328,6 +2328,7 @@"terminalPanel.createFailed": "Failed to start the terminal session","terminalPanel.newTab": "New terminal","terminalPanel.split": "Split terminal",+ "terminalPanel.targetLocal": "This computer","terminalPanel.title": "Terminal","textSelection.addToConversation": "Add to conversation","textSelection.added": "Added to conversation context",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 65f269abffa..b18813a5570 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2328,6 +2328,7 @@"terminalPanel.createFailed": "η»η«―δΌθ―ε―ε¨ε€±θ΄₯","terminalPanel.newTab": "ζ°ε»Ίη»η«―","terminalPanel.split": "ζεη»η«―",+ "terminalPanel.targetLocal": "ζ¬ζΊ","terminalPanel.title": "η»η«―","textSelection.addToConversation": "ζ·»ε ε°ε―Ήθ―","textSelection.added": "ε·²ζ·»ε ε°ε―Ήθ―δΈδΈζ",diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 31c1b019708..76e8b63ca2e 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -9,6 +9,7 @@ import {CLI_UPDATE_UNSUPPORTED_MESSAGE,DEVICE_RPC_METHODS,executeDeviceRpc,+ TERMINAL_UNSUPPORTED_MESSAGE,TRASH_UNSUPPORTED_MESSAGE,} from '../dispatch';import type { DeviceControlDeps } from '../types';@@ -622,4 +623,69 @@ describe('executeDeviceRpc', () => {)) as { success: boolean };expect(result.success).toBe(false);});++ describe('interactive terminal', () => {+ /** The PTY handlers a host opts into; absent they all refuse. */+ const terminalDeps = () => ({+ closeTerminal: vi.fn(async () => ({ closed: true })),+ createTerminalSession: vi.fn(async () => ({+ cwd: '/home/dev',+ id: 'term_1',+ pid: 4242,+ shell: '/bin/bash',+ })),+ readTerminal: vi.fn(async () => ({ chunk: 'aGk=', exited: false, nextCursor: 2 })),+ resizeTerminal: vi.fn(async () => {}),+ writeTerminal: vi.fn(async () => {}),+ });++ it('publishes the terminal RPCs on the device surface', () => {+ expect(DEVICE_RPC_METHODS).toEqual(+ expect.arrayContaining([+ 'createTerminalSession',+ 'writeTerminal',+ 'readTerminal',+ 'resizeTerminal',+ 'closeTerminal',+ ]),+ );+ });++ it('routes each terminal RPC to its host handler', async () => {+ const terminals = terminalDeps();+ const deps: DeviceControlDeps = { ...makeDeps(), ...terminals };++ await executeDeviceRpc('createTerminalSession', { cols: 80, rows: 24 }, deps);+ expect(terminals.createTerminalSession).toHaveBeenCalledWith({ cols: 80, rows: 24 });++ await executeDeviceRpc('writeTerminal', { data: 'bHM=', id: 'term_1' }, deps);+ expect(terminals.writeTerminal).toHaveBeenCalledWith({ data: 'bHM=', id: 'term_1' });++ await executeDeviceRpc('readTerminal', { cursor: 0, id: 'term_1' }, deps);+ expect(terminals.readTerminal).toHaveBeenCalledWith({ cursor: 0, id: 'term_1' });++ await executeDeviceRpc('resizeTerminal', { cols: 120, id: 'term_1', rows: 40 }, deps);+ expect(terminals.resizeTerminal).toHaveBeenCalledWith({ cols: 120, id: 'term_1', rows: 40 });++ await executeDeviceRpc('closeTerminal', { id: 'term_1' }, deps);+ expect(terminals.closeTerminal).toHaveBeenCalledWith({ id: 'term_1' });+ });++ it('refuses every terminal RPC on a host that has no PTY handlers', async () => {+ // A desktop client serves its own terminal over IPC and does not opt in,+ // so a terminal opened against it must fail loudly rather than hang.+ const deps = makeDeps();+ for (const method of [+ 'createTerminalSession',+ 'writeTerminal',+ 'readTerminal',+ 'resizeTerminal',+ 'closeTerminal',+ ] as const) {+ await expect(executeDeviceRpc(method, { id: 'term_1' }, deps)).rejects.toThrow(+ TERMINAL_UNSUPPORTED_MESSAGE,+ );+ }+ });+ });});diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 41e5726a588..12f974e532c 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -47,7 +47,9 @@ import { defaultListProjectDirectory } from './projectFileIndex';import { prepareSkillDirectory } from './skillDirectory';import type {BrowseDirectoryParams,+ CloseTerminalParams,CopyAssetForPublishParams,+ CreateTerminalSessionParams,DeviceControlDeps,EnrollWorkspaceParams,ExternalAssetForPublishParams,@@ -59,8 +61,11 @@ import type {ProjectDirectoryListParams,ProjectFileIndexParams,ProjectFileSearchParams,+ ReadTerminalParams,+ ResizeTerminalParams,TrashLocalFilesParams,UnenrollWorkspaceParams,+ WriteTerminalParams,} from './types';import { browseDirectory, initWorkspace, listProjectSkills, statPath } from './workspace';import { assertEntriesWithinWorkspace, WORKSPACE_ESCAPE_MESSAGE } from './workspaceGuard';@@ -122,6 +127,13 @@ export const DEVICE_RPC_METHODS = ['getAppUpdateState','checkAppUpdate','installAppUpdate',+ // Interactive terminal (PTY). One session, drained by cursor β see+ // `CreateTerminalSessionParams` for why this is polling and not a stream.+ 'createTerminalSession',+ 'writeTerminal',+ 'readTerminal',+ 'resizeTerminal',+ 'closeTerminal','getCliUpdateState','checkCliUpdate','restartCli',@@ -138,6 +150,14 @@ export const CLI_UPDATE_UNSUPPORTED_MESSAGE =/** Why a client without a recoverable trash (the CLI daemon) rejects `trashLocalFiles`. */export const TRASH_UNSUPPORTED_MESSAGE = 'This device does not support moving files to the trash';+/**+ * Why a client without PTY handlers rejects the terminal RPCs. Hosts opt in by+ * providing the `*Terminal*` deps; the desktop app serves its own terminal over+ * IPC instead, so until it opts in a terminal opened against it is refused here+ * rather than left waiting for a session.+ */+export const TERMINAL_UNSUPPORTED_MESSAGE = 'This device client does not support a terminal';+/** File-mutation params carry the approved workspace root they must stay inside. */type WorkspaceScoped<T> = T & { workspaceRoot?: string };@@ -439,6 +459,34 @@ export const executeDeviceRpc = async (return deps.installAppUpdate();}+ // Interactive terminal. All five handlers are host-injected together, so a+ // host that provides none of them refuses every one of these with the same+ // reason instead of exposing a half-working session.+ case 'createTerminalSession': {+ if (!deps.createTerminalSession) throw new Error(TERMINAL_UNSUPPORTED_MESSAGE);+ return deps.createTerminalSession(params as CreateTerminalSessionParams);+ }++ case 'writeTerminal': {+ if (!deps.writeTerminal) throw new Error(TERMINAL_UNSUPPORTED_MESSAGE);+ return deps.writeTerminal(params as WriteTerminalParams);+ }++ case 'readTerminal': {+ if (!deps.readTerminal) throw new Error(TERMINAL_UNSUPPORTED_MESSAGE);+ return deps.readTerminal(params as ReadTerminalParams);+ }++ case 'resizeTerminal': {+ if (!deps.resizeTerminal) throw new Error(TERMINAL_UNSUPPORTED_MESSAGE);+ return deps.resizeTerminal(params as ResizeTerminalParams);+ }++ case 'closeTerminal': {+ if (!deps.closeTerminal) throw new Error(TERMINAL_UNSUPPORTED_MESSAGE);+ return deps.closeTerminal(params as CloseTerminalParams);+ }+case 'getCliUpdateState': {if (!deps.getCliUpdateState) throw new Error(CLI_UPDATE_UNSUPPORTED_MESSAGE);return deps.getCliUpdateState();diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.tsindex 03207321c47..052701f81e2 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -5,6 +5,7 @@ export {DEVICE_RPC_METHODS,type DeviceRpcMethod,executeDeviceRpc,+ TERMINAL_UNSUPPORTED_MESSAGE,TRASH_UNSUPPORTED_MESSAGE,} from './dispatch';export {diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 6d0bce84a1e..28c0aab2736 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -305,8 +305,18 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps*/checkAppUpdate?: () => Promise<AppUpdateState>;checkCliUpdate?: () => Promise<DeviceCliUpdateState>;+ /**+ * Interactive PTY handlers. Optional: a host without a PTY implementation+ * (or one whose runtime forbids spawning shells) omits them, and the+ * dispatcher fails the RPC with {@link TERMINAL_UNSUPPORTED_MESSAGE} rather+ * than leaving a terminal panel waiting on a session that will never appear.+ */+ closeTerminal?: (params: CloseTerminalParams) => Promise<CloseTerminalResult>;/** Copy a publish asset (possibly outside the workspace) to a path inside the workspace. */copyAssetForPublish?: (params: CopyAssetForPublishParams) => Promise<CopyAssetForPublishResult>;+ createTerminalSession?: (+ params: CreateTerminalSessionParams,+ ) => Promise<CreateTerminalSessionResult>;/*** Enroll this machine into a workspace pool: derive the workspace-scoped* deviceId and open a second gateway connection authenticated with `token`@@ -337,6 +347,8 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDepsreadExternalAssetForPublish?: (params: ExternalAssetForPublishParams,) => Promise<ExternalAssetForPublishResult>;+ readTerminal?: (params: ReadTerminalParams) => Promise<ReadTerminalResult>;+ resizeTerminal?: (params: ResizeTerminalParams) => Promise<void>;restartCli?: (params: DeviceCliRestartParams) => Promise<DeviceCliUpdateState>;/** Search project files without shipping the whole index to the caller. */searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;@@ -353,6 +365,7 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps* state. Optional, mirroring {@link DeviceControlDeps.enrollWorkspace}.*/unenrollWorkspace?: (params: UnenrollWorkspaceParams) => Promise<{ success: boolean }>;+ writeTerminal?: (params: WriteTerminalParams) => Promise<void>;}// βββ Heterogeneous agent model discovery βββ@@ -458,3 +471,81 @@ export interface InstallAppUpdateResult {/** Version the client restarts into. */targetVersion: string;}++// βββ Interactive terminal (PTY) βββ+//+// The device RPC surface is strictly request/response, so an interactive shell+// is expressed as a session plus polling rather than a byte stream: the host+// spawns a real PTY, keeps its output in a bounded ring buffer, and the caller+// drains that buffer with a cursor. A real PTY (rather than a piped child) is+// the whole point β `sudo` reads the password from `/dev/tty`, so it prompts+// and accepts input exactly as it would in a local shell, and no credential+// ever leaves the device.+//+// Runnable bytes are base64 in both directions: PTY output is not guaranteed to+// be valid UTF-8 at chunk boundaries, and JSON strings cannot carry arbitrary+// bytes. Mirrors the tunnel frames' own `data` encoding.++export interface CreateTerminalSessionParams {+ /** Initial grid width. Re-sent later through {@link ResizeTerminalParams}. */+ cols: number;+ /** Directory to start in; the host falls back to the home directory. */+ cwd?: string;+ /** Initial grid height. */+ rows: number;+}++export interface CreateTerminalSessionResult {+ /** Directory the shell actually started in (the request's `cwd` may not exist). */+ cwd: string;+ id: string;+ pid: number;+ /** Absolute path of the shell binary that was spawned. */+ shell: string;+}++export interface WriteTerminalParams {+ /** Base64-encoded bytes to write to the PTY. */+ data: string;+ id: string;+}++export interface ReadTerminalParams {+ /**+ * Only output produced after this point is returned. Pass the previous+ * response's `nextCursor`; start at 0. A caller that fell behind the ring+ * buffer is clamped forward rather than refused, so the terminal resumes at+ * the oldest output still held.+ */+ cursor: number;+ id: string;+}++export interface ReadTerminalResult {+ /**+ * Base64-encoded output produced since `cursor` (empty when nothing new).+ * Capped per call; keep reading while it is non-empty to drain a burst.+ */+ chunk: string;+ /** Present once the shell has exited. */+ exitCode?: number;+ /** Whether the shell has exited. */+ exited: boolean;+ /** Cursor for the next read. */+ nextCursor: number;+}++export interface ResizeTerminalParams {+ cols: number;+ id: string;+ rows: number;+}++export interface CloseTerminalParams {+ id: string;+}++export interface CloseTerminalResult {+ /** False when the session was already gone (exited, reaped, or never existed). */+ closed: boolean;+}diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ef306c80136..0a80ad9ba7f 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2728,6 +2728,7 @@ export default {'terminalPanel.createFailed': 'Failed to start the terminal session','terminalPanel.newTab': 'New terminal','terminalPanel.split': 'Split terminal',+ 'terminalPanel.targetLocal': 'This computer','terminalPanel.title': 'Terminal','thread.threadMessageCount': '{{messageCount}} messages','thread.title': 'Subtopic',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex ee2eb6496de..b78ed19fdaf 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -1043,6 +1043,41 @@ export type DeviceAppUpdateStateResult =export type DeviceAppUpdateInstallResult ={ status: 'ok'; targetVersion: string } | { message: string; status: DeviceAppUpdateFailure };+// βββ Interactive terminal (PTY) βββ+//+// Server-side mirror of `@lobechat/device-control`'s terminal types. An+// interactive shell over a request/response RPC is a session plus a cursor:+// the device holds the PTY's output, the caller drains it. Runnable bytes are+// base64 in both directions β PTY output is not valid UTF-8 at every chunk+// boundary, and JSON strings cannot carry arbitrary bytes.++/** Result of the `createTerminalSession` device RPC. */+export interface DeviceCreateTerminalSessionResult {+ /** Directory the shell actually started in (a missing `cwd` falls back home). */+ cwd: string;+ id: string;+ pid: number;+ /** Absolute path of the shell binary the device spawned. */+ shell: string;+}++/** Result of the `readTerminal` device RPC. */+export interface DeviceReadTerminalResult {+ /** Base64 output produced since the caller's cursor; empty when nothing new. */+ chunk: string;+ /** Present once the shell has exited. */+ exitCode?: number;+ exited: boolean;+ /** Cursor to pass to the next read. */+ nextCursor: number;+}++/** Result of the `closeTerminal` device RPC. */+export interface DeviceCloseTerminalResult {+ /** False when the session was already gone (exited, reaped, or never existed). */+ closed: boolean;+}+/** A CLI maintenance request is acknowledged before the connection goes away. */export interface DeviceCliUpdateOperation {error?: string;diff --git a/src/features/ChatTerminal/Content.tsx b/src/features/ChatTerminal/Content.tsxindex 6f97563e971..70a704bb5a8 100644--- a/src/features/ChatTerminal/Content.tsx+++ b/src/features/ChatTerminal/Content.tsx@@ -1,11 +1,13 @@'use client';+import { isDesktop } from '@lobechat/const';import { Flexbox } from '@lobehub/ui';import {ActionIcon,Button,type ContextMenuItem,ContextMenuTrigger,+ Select,TabsIndicator,TabsList,TabsRoot,@@ -20,13 +22,14 @@ import {SquareTerminalIcon,XIcon,} from 'lucide-react';-import { memo, useEffect, useRef } from 'react';+import { memo, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';+import { canHostTerminal, deviceSelectors, useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';@@ -36,6 +39,9 @@ import { useChatTerminalStore } from './store';const EMPTY_TABS: TerminalTab[] = [];+/** Sentinel for "run on this machine"; device ids are never empty strings. */+const LOCAL_TARGET = '';+const styles = createStaticStyles(({ css, cssVar }) => ({container: css`overflow: hidden;@@ -118,19 +124,37 @@ const Content = memo(() => {const closePane = useChatTerminalStore((s) => s.closePane);const setActivePane = useChatTerminalStore((s) => s.setActivePane);const setPaneFlex = useChatTerminalStore((s) => s.setPaneFlex);+ const targetDeviceId = useChatTerminalStore((s) => s.deviceByTopic[topicKey]);+ const setTerminalDevice = useChatTerminalStore((s) => s.setTerminalDevice);++ const devices = useDeviceStore(deviceSelectors.deviceList);+ // 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]);+ // Desktop can always run a shell here; the web build needs a device.+ const canSpawn = isDesktop || !!targetDeviceId;const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? tabs.at(-1);const prevTabCountRef = useRef(0);- // Open a first shell automatically when this topic has none yet. Runs on- // open / topic switch only β NOT on tab-count changes, so closing the last- // tab doesn't immediately respawn a shell.+ // The web build has no local shell, so a topic must name a device before the+ // first terminal can open. Claim the first usable one until the user picks+ // another.+ useEffect(() => {+ if (isDesktop || targetDeviceId || targets.length === 0) return;+ setTerminalDevice(topicKey, targets[0].deviceId);+ }, [targets, setTerminalDevice, targetDeviceId, topicKey]);++ // Open a first shell automatically when this topic has none yet and we know+ // where it would run. Runs on open / topic switch / target arrival only β NOT+ // on tab-count changes, so closing the last tab doesn't respawn a shell.useEffect(() => {prevTabCountRef.current = tabs.length;- if (tabs.length === 0) void createTab(topicKey, cwd);+ if (tabs.length === 0 && canSpawn) void createTab(topicKey, cwd);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [topicKey]);+ }, [topicKey, canSpawn]);// Closing the last tab (X button or the shell exiting) collapses the panel.useEffect(() => {@@ -155,6 +179,23 @@ const Content = memo(() => {},];+ /**+ * Point the topic at another machine. Existing shells keep running where they+ * started, so open one β otherwise picking a device looks like it did nothing.+ */+ const selectTarget = (next: string) => {+ setTerminalDevice(topicKey, next === LOCAL_TARGET ? undefined : next);+ void createTab(topicKey, cwd);+ };++ const targetOptions = [+ ...(isDesktop ? [{ label: t('terminalPanel.targetLocal'), value: LOCAL_TARGET }] : []),+ ...targets.map((device) => ({+ label: device.friendlyName || device.hostname || device.deviceId,+ value: device.deviceId,+ })),+ ];+return (<Flexbox className={styles.container}><Flexbox horizontal align={'center'} className={styles.tabBar} gap={4}>@@ -194,6 +235,13 @@ const Content = memo(() => {title={t('terminalPanel.newTab')}onClick={() => createTab(topicKey, cwd)}/>+ <Select+ options={targetOptions}+ size={'small'}+ style={{ minWidth: 120 }}+ value={targetDeviceId ?? LOCAL_TARGET}+ onChange={(value) => selectTarget(String(value))}+ /><Flexbox flex={1} /><ActionIcondisabled={!activeTab || creating}diff --git a/src/features/ChatTerminal/deviceTerminal.test.ts b/src/features/ChatTerminal/deviceTerminal.test.tsnew file mode 100644index 00000000000..629bfbfac50--- /dev/null+++ b/src/features/ChatTerminal/deviceTerminal.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ DeviceTerminalSession,+ TERMINAL_POLL_INTERVAL_MS,+ TERMINAL_RETRY_MAX_MS,+} from './deviceTerminal';++const mocks = vi.hoisted(() => ({+ closeTerminal: vi.fn(async () => ({ closed: true })),+ createTerminalSession: vi.fn(async () => ({+ cwd: '/root',+ id: 'term_1',+ pid: 4321,+ shell: '/bin/bash',+ })),+ notifyExit: vi.fn(),+ readTerminal: vi.fn(),+ setSessionSink: vi.fn(),+ write: vi.fn(),+}));++vi.mock('@/services/device', () => ({+ deviceService: {+ closeTerminal: mocks.closeTerminal,+ createTerminalSession: mocks.createTerminalSession,+ readTerminal: mocks.readTerminal,+ resizeTerminal: vi.fn(),+ writeTerminal: vi.fn(),+ },+}));++vi.mock('./xtermManager', () => ({+ xtermManager: {+ notifyExit: mocks.notifyExit,+ setSessionSink: mocks.setSessionSink,+ write: mocks.write,+ },+}));++const open = () => DeviceTerminalSession.open('dev-1', { cols: 80, rows: 24 });++describe('DeviceTerminalSession polling', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('widens the delay while reads keep failing instead of hammering the device', async () => {+ mocks.readTerminal.mockRejectedValue(new Error('Device is offline'));++ await open();+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(1);++ // First failure doubles the interval: 300ms is no longer enough to retry.+ await vi.advanceTimersByTimeAsync(TERMINAL_POLL_INTERVAL_MS);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(TERMINAL_POLL_INTERVAL_MS);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(2);++ // Second failure: 900ms of a 1200ms wait is still not enough.+ await vi.advanceTimersByTimeAsync(900);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(300);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(3);++ // ...and the widening stops at the ceiling rather than growing forever.+ await vi.advanceTimersByTimeAsync(TERMINAL_RETRY_MAX_MS * 10);+ const settled = mocks.readTerminal.mock.calls.length;+ await vi.advanceTimersByTimeAsync(TERMINAL_RETRY_MAX_MS * 10);+ expect(mocks.readTerminal.mock.calls.length - settled).toBeLessThanOrEqual(20);+ });++ it('returns to the poll interval once a read succeeds again', async () => {+ mocks.readTerminal.mockRejectedValueOnce(new Error('Device is offline'));++ await open();+ await vi.advanceTimersByTimeAsync(0);+ mocks.readTerminal.mockResolvedValue({ chunk: '', exited: false, nextCursor: 0 });++ // Ride out the backed-off retry, which succeeds and resets the delay.+ await vi.advanceTimersByTimeAsync(TERMINAL_POLL_INTERVAL_MS * 2);+ const afterRecovery = mocks.readTerminal.mock.calls.length;++ await vi.advanceTimersByTimeAsync(TERMINAL_POLL_INTERVAL_MS + 1);+ expect(mocks.readTerminal.mock.calls.length).toBeGreaterThan(afterRecovery);+ });++ it('ends the session when the device answers that it is gone', async () => {+ // What `lh connect` now returns for a session it no longer holds: the+ // reader must stop polling and close the pane, not retry a dead id forever.+ mocks.readTerminal.mockResolvedValue({ chunk: '', exited: true, exitCode: 0, nextCursor: 0 });++ await open();+ await vi.advanceTimersByTimeAsync(0);++ expect(mocks.notifyExit).toHaveBeenCalledWith('term_1', 0);+ await vi.advanceTimersByTimeAsync(TERMINAL_RETRY_MAX_MS * 10);+ expect(mocks.readTerminal).toHaveBeenCalledTimes(1);+ });++ it('stops polling once disposed', async () => {+ mocks.readTerminal.mockResolvedValue({ chunk: '', exited: false, nextCursor: 0 });++ const session = await open();+ await vi.advanceTimersByTimeAsync(0);+ const before = mocks.readTerminal.mock.calls.length;++ await session.dispose();+ await vi.advanceTimersByTimeAsync(TERMINAL_RETRY_MAX_MS * 10);++ expect(mocks.closeTerminal).toHaveBeenCalledWith({ deviceId: 'dev-1', id: 'term_1' });+ expect(mocks.readTerminal.mock.calls.length).toBe(before);+ });+});diff --git a/src/features/ChatTerminal/deviceTerminal.ts b/src/features/ChatTerminal/deviceTerminal.tsnew file mode 100644index 00000000000..ac440891ea1--- /dev/null+++ b/src/features/ChatTerminal/deviceTerminal.ts@@ -0,0 +1,213 @@+import debug from 'debug';++import { deviceService } from '@/services/device';++import { type TerminalSessionSink, xtermManager } from './xtermManager';++const log = debug('lobe-desktop:chat-terminal');++/**+ * How long an idle terminal waits before asking its device for new output.+ *+ * The device RPC surface is request/response, so output arrives by polling+ * rather than pushed over a socket. 300ms is a deliberate middle: fast enough+ * that typing feels live (a `sudo` password prompt is indistinguishable from a+ * local one), slow enough that an idle panel is not a request flood.+ * Full-screen interactive programs are out of scope for this transport.+ */+export const TERMINAL_POLL_INTERVAL_MS = 300;++/**+ * Longest a failed read waits before the next attempt.+ *+ * A device that dropped off the network comes back on its own, so a read that+ * failed for a transport reason is retried rather than ending the session β but+ * a disconnected panel must not keep asking at poll speed. Consecutive failures+ * double the delay up to this ceiling.+ */+export const TERMINAL_RETRY_MAX_MS = 5000;++/** Device RPC payloads carry bytes as base64; PTY output is not always valid UTF-8. */+const encodeBase64 = (text: string): string => {+ const bytes = new TextEncoder().encode(text);+ let binary = '';+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary);+};++const decodeBase64 = (base64: string): string => {+ const binary = atob(base64);+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));+ return new TextDecoder().decode(bytes);+};++interface DeviceTerminalInfo {+ cwd: string;+ id: string;+ pid: number;+ shell: string;+}++/**+ * 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+ * 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.+ */+export class DeviceTerminalSession {+ private cursor = 0;+ private disposed = false;+ private exited = false;+ /** Consecutive failed reads, which is what widens the retry delay. */+ private failures = 0;+ private timer?: ReturnType<typeof setTimeout>;++ /**+ * Keystrokes waiting to be sent.+ *+ * Each `writeTerminal` is a separate request, and two of them in flight can+ * arrive out of order β which scrambles fast input (a paste, or a test+ * typing at machine speed) even though it looks fine at typing speed. So+ * input is appended here and flushed strictly one request at a time, which+ * also coalesces a burst of keystrokes into a single call.+ */+ private pendingInput = '';+ private sendingInput = false;++ private constructor(+ readonly deviceId: string,+ readonly info: DeviceTerminalInfo,+ ) {}++ /**+ * Open a shell on `deviceId` and start draining it. Throws when the device+ * refuses (offline, or a client without PTY support) so the panel can show+ * why instead of waiting on a session that will never appear.+ */+ static async open(+ deviceId: string,+ params: { cols: number; cwd?: string; rows: number },+ ): Promise<DeviceTerminalSession> {+ const info = (await deviceService.createTerminalSession({+ ...params,+ deviceId,+ })) as DeviceTerminalInfo;+ const session = new DeviceTerminalSession(deviceId, info);+ // Registered before the first poll so input typed during the initial read+ // is not dropped.+ xtermManager.setSessionSink(info.id, session.sink);+ void session.poll();+ return session;+ }++ get sessionId() {+ return this.info.id;+ }++ /** How this session's keystrokes and resizes reach the device. */+ readonly sink: TerminalSessionSink = {+ close: () => {+ void this.dispose();+ },+ resize: (sessionId, cols, rows) => {+ void deviceService+ .resizeTerminal({ cols, deviceId: this.deviceId, id: sessionId, rows })+ .catch((error) => log('resizeTerminal %s failed: %O', sessionId, error));+ },+ write: (sessionId, data) => {+ this.queueInput(sessionId, data);+ },+ };++ private queueInput(sessionId: string, data: string) {+ this.pendingInput += data;+ if (this.sendingInput || this.disposed) return;+ this.sendingInput = true;+ void this.flushInput(sessionId);+ }++ private async flushInput(sessionId: string) {+ try {+ while (this.pendingInput) {+ const batch = this.pendingInput;+ this.pendingInput = '';+ await deviceService.writeTerminal({+ data: encodeBase64(batch),+ deviceId: this.deviceId,+ id: sessionId,+ });+ }+ } catch (error) {+ // The batch is dropped rather than retried: a persistent failure here+ // would otherwise spin. Output keeps flowing, so the terminal stays+ // usable and the failure is visible in the log.+ log('writeTerminal %s failed: %O', sessionId, error);+ } finally {+ this.sendingInput = false;+ }+ }++ /** Stop polling and end the shell on the device. Safe to call twice. */+ async dispose(): Promise<void> {+ if (this.disposed) return;+ this.disposed = true;+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = undefined;+ }+ try {+ await deviceService.closeTerminal({ deviceId: this.deviceId, id: this.info.id });+ } catch (error) {+ log('closeTerminal %s failed: %O', this.info.id, error);+ }+ }++ private async poll(): Promise<void> {+ if (this.disposed || this.exited) return;++ try {+ // Drain until the device has nothing left rather than returning one chunk+ // per interval, so a burst (a build log) is not paced by the poll.+ for (;;) {+ const result = await deviceService.readTerminal({+ cursor: this.cursor,+ deviceId: this.deviceId,+ id: this.info.id,+ });++ this.cursor = result.nextCursor;+ if (result.chunk) {+ xtermManager.write(this.info.id, decodeBase64(result.chunk));+ }++ if (result.exited) {+ this.exited = true;+ // The session is gone device-side; the exit code only tells the store+ // to close the pane.+ xtermManager.notifyExit(this.info.id, result.exitCode ?? 0);+ return;+ }++ if (!result.chunk) break;+ }+ this.failures = 0;+ } catch (error) {+ // A single failed read is usually a dropped request, not a dead shell, so+ // keep polling β but on a widening delay: a device that is off the network+ // cannot be read from, and asking every 300ms would turn a disconnected+ // panel into a request flood. A device that outlived its session does not+ // land here at all: it answers such a read with `exited`.+ this.failures += 1;+ log('readTerminal %s failed (%d in a row): %O', this.info.id, this.failures, error);+ }++ if (this.disposed || this.exited) return;+ const delay = this.failures+ ? Math.min(TERMINAL_POLL_INTERVAL_MS * 2 ** this.failures, TERMINAL_RETRY_MAX_MS)+ : TERMINAL_POLL_INTERVAL_MS;+ this.timer = setTimeout(() => void this.poll(), delay);+ }+}diff --git a/src/features/ChatTerminal/index.tsx b/src/features/ChatTerminal/index.tsxindex 1e70f8e1e5e..4993c644800 100644--- a/src/features/ChatTerminal/index.tsx+++ b/src/features/ChatTerminal/index.tsx@@ -6,6 +6,7 @@ import { cssVar } from 'antd-style';import { lazy, memo, Suspense, useEffect, useState } from 'react';import { useToggleTerminalPanelHotkey } from '@/hooks/useHotkeys';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -19,17 +20,28 @@ const COLLAPSE_UNMOUNT_DELAY = 250;/*** Codex-style built-in terminal: a full-width bottom panel on the chat page- * with per-topic tab groups. Desktop-only.+ * with per-topic tab groups.+ *+ * On desktop the shell is local (Electron main process). On the web there is no+ * local shell at all β the panel only exists once a device is connected, and+ * every terminal it opens runs there.*/const ChatTerminalPanel = memo(() => {- useToggleTerminalPanelHotkey();-const [show, height, updateSystemStatus] = useGlobalStore((s) => [systemStatusSelectors.showTerminalPanel(s),systemStatusSelectors.terminalPanelHeight(s),s.updateSystemStatus,]);+ // Asked unconditionally (hooks cannot be skipped) but only meaningful on the+ // web, where the device list is what decides whether the panel can exist.+ useDeviceStore((s) => s.useFetchDevices)(!isDesktop);+ const hasDevice = useDeviceStore(deviceSelectors.hasTerminalTarget);++ // Same condition the panel itself opens under, so the hotkey can never toggle+ // a panel that has nothing to run on.+ useToggleTerminalPanelHotkey(isDesktop || hasDevice);+// Open/close is driven by DraggablePanel's controlled `expand` so the panel// animates its height. The terminal is mounted while open and kept through// the collapse animation, then unmounted once hidden to release the xterm@@ -45,7 +57,9 @@ const ChatTerminalPanel = memo(() => {return () => clearTimeout(timer);}, [show]);- if (!isDesktop) return null;+ // Desktop always has a shell to hand. The web build needs a connected device+ // to run one at all.+ if (!isDesktop && !hasDevice) return null;return (<DraggablePaneldiff --git a/src/features/ChatTerminal/store.ts b/src/features/ChatTerminal/store.tsindex 00aa788f889..ba0acf2a286 100644--- a/src/features/ChatTerminal/store.ts+++ b/src/features/ChatTerminal/store.ts@@ -3,10 +3,19 @@ import { create } from 'zustand';import { electronTerminalService } from '@/services/electron/terminal';+import { DeviceTerminalSession } from './deviceTerminal';import { xtermManager } from './xtermManager';const log = debug('lobe-desktop:chat-terminal');+/** What a freshly spawned session reports back, from either transport. */+interface SpawnedSession {+ cwd: string;+ id: string;+ pid: number;+ shell: string;+}+export interface TerminalPane {/** Relative width inside the tab β only meaningful against sibling panes */flex: number;@@ -29,6 +38,12 @@ interface ChatTerminalState {createErrors: Record<string, string | undefined>;/** Per topic key, so a create in-flight for one topic doesn't block another */creatingByTopic: Record<string, boolean>;+ /**+ * Device a topic's NEW terminals run on. Absent means this machine: the+ * Electron main process on desktop, or no target at all on the web. Sessions+ * already opened keep running where they started.+ */+ deviceByTopic: Record<string, string | undefined>;/** Terminal tabs per topic key β sessions created in a topic only show in that topic */tabsByTopic: Record<string, TerminalTab[]>;}@@ -41,6 +56,8 @@ interface ChatTerminalActions {setActivePane: (topicKey: string, tabId: string, paneId: string) => void;setActiveTab: (topicKey: string, tabId: string) => void;setPaneFlex: (topicKey: string, tabId: string, flex: number[]) => void;+ /** Point a topic's next terminal at a device; `undefined` means this machine. */+ setTerminalDevice: (topicKey: string, deviceId?: string) => void;splitPane: (topicKey: string, tabId: string, cwd?: string) => Promise<void>;}@@ -86,7 +103,13 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalStacreatingByTopic: { ...s.creatingByTopic, [topicKey]: true },}));try {- const info = await electronTerminalService.createSession({ cols: 80, cwd, rows: 24 });+ const deviceId = get().deviceByTopic[topicKey];+ // A device session owns its own polling transport, which also registers+ // the sink routing this terminal's input back to that device. Without a+ // target the shell is local, and only the desktop app has one.+ const info: SpawnedSession = deviceId+ ? (await DeviceTerminalSession.open(deviceId, { cols: 80, cwd, rows: 24 })).info+ : await electronTerminalService.createSession({ cols: 80, cwd, rows: 24 });xtermManager.ensure(info.id);return info;} catch (error) {@@ -190,6 +213,8 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalStacreatingByTopic: {},+ deviceByTopic: {},+setActivePane: (topicKey, tabId, paneId) => {updateTab(topicKey, tabId, (tab) =>tab.activePaneId === paneId || !tab.panes.some((pane) => pane.id === paneId)@@ -210,6 +235,10 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalSta);},+ setTerminalDevice: (topicKey, deviceId) => {+ set((s) => ({ deviceByTopic: { ...s.deviceByTopic, [topicKey]: deviceId } }));+ },+splitPane: async (topicKey, tabId, cwd) => {const info = await spawnSession(topicKey, cwd);if (!info) return;diff --git a/src/features/ChatTerminal/xtermManager.ts b/src/features/ChatTerminal/xtermManager.tsindex f3b0aedac59..73699ba2a86 100644--- a/src/features/ChatTerminal/xtermManager.ts+++ b/src/features/ChatTerminal/xtermManager.ts@@ -26,6 +26,20 @@ interface TermInstance {type ExitListener = (sessionId: string, exitCode: number) => void;type PaneNavListener = (sessionId: string, direction: -1 | 1) => void;+/**+ * How one session's terminal talks to its shell.+ *+ * The default sink is this machine's Electron main process. A session opened on+ * a remote device registers its own sink instead β the panel, the xterm+ * instance and the tab bookkeeping are identical either way, only the wire+ * differs.+ */+export interface TerminalSessionSink {+ close: (sessionId: string) => void;+ resize: (sessionId: string, cols: number, rows: number) => void;+ write: (sessionId: string, data: string) => void;+}+/*** Module-level registry of live xterm instances, keyed by PTY session id.*@@ -39,6 +53,48 @@ class XtermManager {private paneNavListeners = new Set<PaneNavListener>();private ipcBound = false;private webglUnavailable = false;+ /** Per-session overrides; absent means the local Electron sink below. */+ private sinks = new Map<string, TerminalSessionSink>();++ /**+ * The sink every session uses unless it registers its own: this machine's+ * Electron main process, which owns the PTY.+ */+ private localSink: TerminalSessionSink = {+ close: (sessionId) => {+ // Best-effort: the session may already be gone (shell exited / reaped).+ // The main process logs kill failures on its side too.+ void electronTerminalService.killSession({ id: sessionId }).catch((error) => {+ log('killSession %s failed: %O', sessionId, error);+ });+ },+ resize: (sessionId, cols, rows) => {+ void electronTerminalService.resizeSession({ cols, id: sessionId, rows });+ },+ write: (sessionId, data) => {+ void electronTerminalService.writeSession({ data, id: sessionId });+ },+ };++ /** Route one session's input and resize to a shell that is not on this machine. */+ setSessionSink(sessionId: string, sink: TerminalSessionSink) {+ this.sinks.set(sessionId, sink);+ }++ private sinkFor(sessionId: string): TerminalSessionSink {+ return this.sinks.get(sessionId) ?? this.localSink;+ }++ /** Write output into a session's terminal. Called by a remote transport. */+ write(sessionId: string, data: string) {+ this.instances.get(sessionId)?.term.write(data);+ }++ /** A remote session ended: drop the view and let the store close its pane. */+ notifyExit(sessionId: string, exitCode: number) {+ this.disposeInstance(sessionId);+ for (const listener of this.exitListeners) listener(sessionId, exitCode);+ }private bindIpc() {if (this.ipcBound) return;@@ -119,7 +175,7 @@ class XtermManager {return false;});term.onData((data) => {- void electronTerminalService.writeSession({ data, id: sessionId });+ this.sinkFor(sessionId).write(sessionId, data);});const instance: TermInstance = { container, fit, opened: false, term };@@ -177,11 +233,7 @@ class XtermManager {if (width <= 0 || height <= 0) return;instance.fit.fit();- void electronTerminalService.resizeSession({- cols: instance.term.cols,- id: sessionId,- rows: instance.term.rows,- });+ this.sinkFor(sessionId).resize(sessionId, instance.term.cols, instance.term.rows);}applyTheme(theme: ITheme, fontFamily: string) {@@ -192,13 +244,9 @@ class XtermManager {}}- /** Kill the PTY in the main process and drop the local instance. */+ /** End the shell (wherever it runs) and drop the local instance. */close(sessionId: string) {- // Best-effort: the session may already be gone (shell exited / reaped).- // The main process logs kill failures on its side too.- void electronTerminalService.killSession({ id: sessionId }).catch((error) => {- log('killSession %s failed: %O', sessionId, error);- });+ this.sinkFor(sessionId).close(sessionId);this.disposeInstance(sessionId);}@@ -217,6 +265,9 @@ class XtermManager {}private disposeInstance(sessionId: string) {+ // Drop the routing either way: a session whose transport died must not keep+ // a stale sink alive for an id that could be reused.+ this.sinks.delete(sessionId);const instance = this.instances.get(sessionId);if (!instance) return;this.instances.delete(sessionId);diff --git a/src/hooks/useHotkeys/chatScope.test.ts b/src/hooks/useHotkeys/chatScope.test.tsindex fe198b7c531..d60a225966d 100644--- a/src/hooks/useHotkeys/chatScope.test.ts+++ b/src/hooks/useHotkeys/chatScope.test.ts@@ -64,4 +64,17 @@ describe('useToggleTerminalPanelHotkey', () => {scopes: [HotkeyScopeEnum.Chat],});});++ it('leaves the binding off when the caller has no shell to open', () => {+ renderHook(() => useToggleTerminalPanelHotkey(false));++ expect(mocks.useHotkeyById).toHaveBeenCalledWith(+ HotkeyEnum.ToggleTerminalPanel,+ expect.any(Function),+ {+ enableOnContentEditable: true,+ enabled: false,+ },+ );+ });});diff --git a/src/hooks/useHotkeys/chatScope.ts b/src/hooks/useHotkeys/chatScope.tsindex 86ec0994b4d..96f9db75314 100644--- a/src/hooks/useHotkeys/chatScope.ts+++ b/src/hooks/useHotkeys/chatScope.ts@@ -22,12 +22,17 @@ export const useOpenChatSettingsHotkey = () => {return useHotkeyById(HotkeyEnum.OpenChatSettings, openChatSettings);};-export const useToggleTerminalPanelHotkey = () => {+/**+ * `enabled` defaults to the desktop gate, where a local shell always exists.+ * The web build passes its own condition β there the panel can only open once a+ * device is connected, so the binding must stay off until one is.+ */+export const useToggleTerminalPanelHotkey = (enabled: boolean = isDesktop) => {const toggleTerminalPanel = useGlobalStore((s) => s.toggleTerminalPanel);return useHotkeyById(HotkeyEnum.ToggleTerminalPanel, () => toggleTerminalPanel(), {enableOnContentEditable: true,- enabled: isDesktop,+ enabled,});};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.tsxindex d292ca2e081..5bd40e03860 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,6 +6,8 @@ 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(),}));@@ -23,7 +25,21 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {};});-vi.mock('@/const/version', () => ({ isDesktop: true }));+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 }),+}));vi.mock('@/store/global', () => ({useGlobalStore: (@@ -57,6 +73,8 @@ vi.mock('@/store/user/selectors', () => ({describe('TerminalPanelToggle', () => {beforeEach(() => {+ mocks.hasTerminalTarget = false;+ mocks.isDesktop = true;mocks.showTerminalPanel = false;mocks.toggleTerminalPanel.mockReset();actionIconPropsSpy.mockClear();@@ -77,4 +95,22 @@ 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;++ 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.tsxindex 37f7b917462..b50910c5d80 100644--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.tsx@@ -8,6 +8,7 @@ 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 { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';@@ -21,7 +22,13 @@ const TerminalPanelToggle = memo(() => {]);const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleTerminalPanel));- if (!isDesktop) return null;+ // 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);++ if (!isDesktop && !hasDevice) return null;return (<ActionIcondiff --git a/src/services/device.ts b/src/services/device.tsindex b2374fbedcc..764cae6299e 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -97,6 +97,33 @@ class DeviceService {return lambdaClient.device.restartCli.mutate(input);}+ /**+ * Interactive terminal on the device. `createTerminalSession` opens a PTY and+ * the rest drive it: `writeTerminal` for input, `readTerminal` to drain+ * output from a cursor, `resizeTerminal` when the panel changes size and+ * `closeTerminal` to end it. Polling rather than streaming is deliberate β+ * see `@lobechat/device-control`'s terminal types.+ */+ createTerminalSession(input: Parameters<DeviceClient['createTerminalSession']['mutate']>[0]) {+ return lambdaClient.device.createTerminalSession.mutate(input);+ }++ writeTerminal(input: Parameters<DeviceClient['writeTerminal']['mutate']>[0]) {+ return lambdaClient.device.writeTerminal.mutate(input);+ }++ readTerminal(input: Parameters<DeviceClient['readTerminal']['mutate']>[0]) {+ return lambdaClient.device.readTerminal.mutate(input);+ }++ resizeTerminal(input: Parameters<DeviceClient['resizeTerminal']['mutate']>[0]) {+ return lambdaClient.device.resizeTerminal.mutate(input);+ }++ closeTerminal(input: Parameters<DeviceClient['closeTerminal']['mutate']>[0]) {+ return lambdaClient.device.closeTerminal.mutate(input);+ }+/** The device's recent CPU / memory / load history, bucketed for charting. */getMetricSeries(deviceId: string) {return lambdaClient.deviceMetric.getSeries.query({ deviceId });diff --git a/src/store/device/selectors.test.ts b/src/store/device/selectors.test.tsnew file mode 100644index 00000000000..ab7a0956586--- /dev/null+++ b/src/store/device/selectors.test.ts@@ -0,0 +1,64 @@+import type { DeviceListItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { DeviceState } from './initialState';+import { canHostTerminal, deviceSelectors } from './selectors';++const device = (overrides: Partial<DeviceListItem>): DeviceListItem =>+ ({ channels: [], deviceId: 'dev-1', lastSeen: '', online: true, ...overrides }) as DeviceListItem;++const channel = (name: string | null) => ({+ channel: name,+ connectedAt: '',+ hostname: null,+ platform: null,+});++const state = (devices: DeviceListItem[]) => ({ devices }) as DeviceState;++describe('canHostTerminal', () => {+ it('accepts a live CLI connection, including its suffixed variants', () => {+ expect(canHostTerminal(device({ channels: [channel('cli')] }))).toBe(true);+ expect(canHostTerminal(device({ channels: [channel('cli-dev')] }))).toBe(true);+ });++ it('rejects an offline row even when it was last seen on a CLI channel', () => {+ 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.+ expect(canHostTerminal(device({ channels: [channel('desktop')] }))).toBe(false);+ expect(canHostTerminal(device({ channels: [channel('desktop-dev')] }))).toBe(false);+ });++ it('rejects connections of an unknown kind', () => {+ expect(canHostTerminal(device({ channels: [channel('mobile'), channel(null)] }))).toBe(false);+ });++ it('treats a live row that reports no connections as unknown, not unusable', () => {+ // A gateway older than the connections field leaves this empty on live rows;+ // hiding the terminal from those deployments would be a regression.+ expect(canHostTerminal(device({ channels: [] }))).toBe(true);+ });+});++describe('deviceSelectors.hasTerminalTarget', () => {+ it('is true when any device can host a shell', () => {+ const devices = [+ device({ channels: [channel('desktop')] }),+ device({ channels: [channel('cli')] }),+ ];+ expect(deviceSelectors.hasTerminalTarget(state(devices))).toBe(true);+ });++ it('is false when every device is offline or desktop-only', () => {+ const devices = [+ device({ channels: [channel('cli')], online: false }),+ device({ channels: [channel('desktop')] }),+ ];+ expect(deviceSelectors.hasTerminalTarget(state(devices))).toBe(false);+ expect(deviceSelectors.hasTerminalTarget(state([]))).toBe(false);+ });+});diff --git a/src/store/device/selectors.ts b/src/store/device/selectors.tsindex f48e86cd703..927a75764f8 100644--- a/src/store/device/selectors.ts+++ b/src/store/device/selectors.ts@@ -1,9 +1,40 @@import type { DeviceListItem } from '@lobechat/types';+import { getChannelKind } from '@/features/DeviceManager/channelKind';+import type { DeviceState } from './initialState';const deviceList = (s: DeviceState): DeviceListItem[] => s.devices;+/**+ * 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.+ *+ * 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+ * the field β unknown, not unusable.+ */+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');+};++/**+ * Whether any device can host a terminal.+ *+ * A boolean, not the filtered list: zustand compares selector results with+ * `Object.is`, and a fresh array on every call would re-render the panel on+ * every unrelated store write.+ */+const hasTerminalTarget = (s: DeviceState): boolean => s.devices.some(canHostTerminal);+const getDeviceById =(deviceId: string | undefined) =>(s: DeviceState): DeviceListItem | undefined =>@@ -24,4 +55,5 @@ export const deviceSelectors = {getDeviceById,getDeviceDefaultCwd,getDeviceWorkingDirs,+ hasTerminalTarget,};