From 85913acc6158619851561cb86588a35f0f041b4e Mon Sep 17 00:00:00 2001 From: Zhihe Li Date: Wed, 6 Sep 2023 16:39:55 -0400 Subject: [PATCH] Desktop Client Session Terminal (#1884) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: 💡 Turn on sandboxing for renderer process (#1870) * chore: 🤖 add tabs for details and terminal view (#1871) * feat: 🎸 Allow creating multiple terminals (#1872) * chore: 🤖 add remove method to terminal (#1875) * feat: 🎸 Clean up terminal tab (#1876) * feat: 🎸 Handle resizing xterm and node-pty (#1879) * feat: 🎸 Clean up killing terminals (#1881) * refactor: 💡 Rename tabs component (#1882) --------- Co-authored-by: Carlos Alcaide Corvo Co-authored-by: Dharini Jeeva --- addons/core/translations/resources/en-us.yaml | 1 + .../app/components/session/tabs/index.hbs | 30 +++++++ .../app/components/session/tabs/index.js | 86 +++++++++++++++++++ ui/desktop/app/styles/app.scss | 8 +- .../scope/projects/sessions/session.hbs | 25 +----- ui/desktop/electron-app/package.json | 1 + ui/desktop/electron-app/src/ipc/handlers.js | 54 +++++++++++- ui/desktop/electron-app/src/preload.js | 34 +++++++- ui/desktop/electron-app/yarn.lock | 18 +++- ui/desktop/ember-cli-build.js | 2 + ui/desktop/package.json | 9 +- yarn.lock | 16 +++- 12 files changed, 250 insertions(+), 34 deletions(-) create mode 100644 ui/desktop/app/components/session/tabs/index.hbs create mode 100644 ui/desktop/app/components/session/tabs/index.js diff --git a/addons/core/translations/resources/en-us.yaml b/addons/core/translations/resources/en-us.yaml index cfcccd7dc..40ea5c3f8 100644 --- a/addons/core/translations/resources/en-us.yaml +++ b/addons/core/translations/resources/en-us.yaml @@ -309,6 +309,7 @@ session: proxy-url: address-port: Address & port ssh: SSH + shell: Shell org: title: Org title_plural: Orgs diff --git a/ui/desktop/app/components/session/tabs/index.hbs b/ui/desktop/app/components/session/tabs/index.hbs new file mode 100644 index 000000000..8b55303cb --- /dev/null +++ b/ui/desktop/app/components/session/tabs/index.hbs @@ -0,0 +1,30 @@ + + {{t 'titles.details'}} + + {{t 'resources.session.shell'}} + + + {{#if (and @model.proxy_address @model.proxy_port)}} + + {{/if}} + {{#if @model.credentials}} + + {{else}} + + + + + {{/if}} + +
+
+
\ No newline at end of file diff --git a/ui/desktop/app/components/session/tabs/index.js b/ui/desktop/app/components/session/tabs/index.js new file mode 100644 index 000000000..636de6f4a --- /dev/null +++ b/ui/desktop/app/components/session/tabs/index.js @@ -0,0 +1,86 @@ +import Component from '@glimmer/component'; +import { action } from '@ember/object'; +import { Terminal } from 'xterm'; +import { FitAddon } from 'xterm-addon-fit'; +import { v4 as uuidv4 } from 'uuid'; +import debounce from 'lodash/debounce'; + +const terminalOptions = { + cursorBlink: true, +}; + +export default class SessionTerminalTabsComponent extends Component { + // =attributes + + id; + terminal; + removeListener; + + // =actions + + @action + openTerminal() { + // Don't re-initialize the terminal if it's already been opened + if (this.terminal) { + return; + } + + const xterm = new Terminal(terminalOptions); + this.terminal = xterm; + const fitAddon = new FitAddon(); + const termContainer = document.getElementById(`terminal-container`); + + xterm.loadAddon(fitAddon); + xterm.open(termContainer); + fitAddon.fit(); + xterm.focus(); + + // Generate a UUID to have the terminal handlers be unique + this.id = uuidv4(); + this.#setupTerminal(fitAddon, xterm); + + const { model } = this.args; + if (model.target?.isSSH) { + const { proxy_address, proxy_port } = model; + + // Send an SSH command immediately + window.terminal.send(`ssh ${proxy_address} -p ${proxy_port}\r`, this.id); + } + } + + willDestroy() { + super.willDestroy(...arguments); + + // Kill terminal and clean up event listeners + if (this.terminal) { + this.terminal.dispose(); + } + window.terminal?.remove(this.id); + window.onresize = null; + if (this.removeListener) { + this.removeListener(); + } + } + + #setupTerminal(fitAddon, xterm) { + // Terminal is exposed by contextBridge within the preload script + window.terminal.create({ id: this.id, cols: xterm.cols, rows: xterm.rows }); + xterm.onData((data) => window.terminal.send(data, this.id)); + this.removeListener = window.terminal.receive((event, value) => { + xterm.write(value); + }, this.id); + + // Handle resizing terminal windows. We debounce the resizing as we + // don't want to resize xterm and the pty process before the previous + // one has finished + const debouncedFit = debounce(() => { + fitAddon.fit(); + }, 150); + window.onresize = () => { + debouncedFit(); + }; + xterm.onResize((size) => { + window.terminal.resize(size, this.id); + }); + } +} diff --git a/ui/desktop/app/styles/app.scss b/ui/desktop/app/styles/app.scss index a27ff8c71..2e5be7251 100644 --- a/ui/desktop/app/styles/app.scss +++ b/ui/desktop/app/styles/app.scss @@ -516,6 +516,7 @@ $chevron-down: url("data:image/svg+xml;utf-8, + - {{#if (and @model.proxy_address @model.proxy_port)}} - - {{/if}} + - {{#if @model.credentials}} - - {{else}} - - - - - {{/if}} +
diff --git a/ui/desktop/electron-app/package.json b/ui/desktop/electron-app/package.json index ebc6749ab..01cd4c1c9 100644 --- a/ui/desktop/electron-app/package.json +++ b/ui/desktop/electron-app/package.json @@ -26,6 +26,7 @@ "electron-is-dev": "^2.0.0", "electron-squirrel-startup": "^1.0.0", "node-html-parser": "^5.3.3", + "node-pty": "^1.0.0", "semver": "^7.5.3", "shell-quote": "^1.7.3", "tree-kill": "^1.2.2" diff --git a/ui/desktop/electron-app/src/ipc/handlers.js b/ui/desktop/electron-app/src/ipc/handlers.js index 909f8831b..df4aae363 100644 --- a/ui/desktop/electron-app/src/ipc/handlers.js +++ b/ui/desktop/electron-app/src/ipc/handlers.js @@ -3,7 +3,7 @@ * SPDX-License-Identifier: MPL-2.0 */ -const { app, shell, BrowserWindow } = require('electron'); +const { app, shell, BrowserWindow, ipcMain } = require('electron'); const isDev = require('electron-is-dev'); const handle = require('./ipc-handler.js'); const boundaryCli = require('../cli/index.js'); @@ -11,6 +11,8 @@ const sessionManager = require('../services/session-manager.js'); const runtimeSettings = require('../services/runtime-settings.js'); const sanitizer = require('../utils/sanitizer.js'); const { isMac } = require('../helpers/platform.js'); +const os = require('node:os'); +const pty = require('node-pty'); /** * Returns the current runtime clusterUrl, which is used by the main thread to @@ -108,3 +110,53 @@ handle('toggleFullscreenWindow', () => { * Quit app */ handle('closeWindow', () => app.quit()); + +/** + * Handler to help create terminal windows. We don't use the helper `handle` method + * as we need access to the event and don't need to be using `ipcMain.handle`. + */ +ipcMain.on('createTerminal', (event, payload) => { + const { id, cols, rows } = payload; + const { sender } = event; + const terminalShell = + os.platform() === 'win32' ? 'powershell.exe' : '/bin/bash'; + const ptyProcess = pty.spawn(terminalShell, [], { + name: 'xterm-color', + cols, + rows, + cwd: process.env.HOME, + env: process.env, + }); + const incomingDataChannel = `terminalIncomingData-${id}`; + const keystrokeChannel = `terminalKeystroke-${id}`; + const resizeChannel = `resize-${id}`; + const removeChannel = `removeTerminal-${id}`; + + // This sends to the renderer and xterm whatever the ptyProcess (host terminal) outputs. + ptyProcess.on('data', function (data) { + sender.send(incomingDataChannel, data); + }); + + // This writes into ptyProcess (host terminal) whatever we write through xterm. + ipcMain.on(keystrokeChannel, (event, value) => { + ptyProcess.write(value); + }); + + // Resize the number of columns and rows received from xterm. + ipcMain.on(resizeChannel, (event, { cols, rows }) => { + ptyProcess.resize(cols, rows); + }); + + // We use `ipcMain.once` as we want this listener cleaned up + // after killing the ptyProcess as well. + ipcMain.once(removeChannel, () => { + // Just let the error bubble up since we can't do anything + try { + ptyProcess.kill(); + } finally { + // Remove listeners + ipcMain.removeAllListeners(keystrokeChannel); + ipcMain.removeAllListeners(resizeChannel); + } + }); +}); diff --git a/ui/desktop/electron-app/src/preload.js b/ui/desktop/electron-app/src/preload.js index 538afc1fe..3b860e9f3 100644 --- a/ui/desktop/electron-app/src/preload.js +++ b/ui/desktop/electron-app/src/preload.js @@ -3,11 +3,43 @@ * SPDX-License-Identifier: MPL-2.0 */ -const { ipcRenderer } = require('electron'); +const { ipcRenderer, contextBridge } = require('electron'); // Messages must originate from this origin const emberAppOrigin = window.location.origin; +/** + * Exposing terminal creation to an isolated context (Ember) + * More information about contextBridge https://www.electronjs.org/docs/latest/api/context-bridge + * usage example: window.terminal.send(data); + */ +contextBridge.exposeInMainWorld('terminal', { + // We could've sent data through our established postMessage pattern + // but we don't need a response back so we can make it include it here + // to make it simpler. This keeps sending and receiving handlers symmetrical. + send: (data, id) => { + ipcRenderer.send(`terminalKeystroke-${id}`, data); + }, + receive: (callback, id) => { + const incomingDataChannel = `terminalIncomingData-${id}`; + ipcRenderer.on(incomingDataChannel, callback); + + // Return a function for the caller to handle cleaning up the listener + return () => { + return ipcRenderer.removeListener(incomingDataChannel, callback); + }; + }, + create: (vars) => { + ipcRenderer.send('createTerminal', vars); + }, + remove: (id) => { + ipcRenderer.send(`removeTerminal-${id}`); + }, + resize: (size, id) => { + ipcRenderer.send(`resize-${id}`, size); + }, +}); + process.once('loaded', () => { /** * Ember-land has no access to the renderer or node modules, and thus diff --git a/ui/desktop/electron-app/yarn.lock b/ui/desktop/electron-app/yarn.lock index e01b892d8..d1079f02c 100644 --- a/ui/desktop/electron-app/yarn.lock +++ b/ui/desktop/electron-app/yarn.lock @@ -2310,6 +2310,11 @@ ms@^2.0.0, ms@^2.1.1: fmix "^0.1.0" imul "^1.0.0" +nan@^2.17.0: + version "2.17.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.17.0.tgz#c0150a2368a182f033e9aa5195ec76ea41a199cb" + integrity sha512-2ZTgtl0nJsO0KQCjEpxcIr5D+Yv90plTitZt9JBfQvVJDS5seMl3FOvsh3+9CoYWXf/1l5OaZzzF6nDm4cagaQ== + nan@^2.4.0: version "2.14.2" resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.2.tgz#f5376400695168f4cc694ac9393d0c9585eeea19" @@ -2326,9 +2331,9 @@ nice-try@^1.0.4: integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-abi@^3.0.0: - version "3.22.0" - resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.22.0.tgz#00b8250e86a0816576258227edbce7bbe0039362" - integrity sha512-u4uAs/4Zzmp/jjsD9cyFYDXeISfUWaAVWshPmDZOFOv4Xl4SbzTXm53I04C2uRueYJ+0t5PEtLH/owbn2Npf/w== + version "3.47.0" + resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.47.0.tgz#6cbfa2916805ae25c2b7156ca640131632eb05e8" + integrity sha512-2s6B2CWZM//kPgwnuI0KrYwNjfdByE25zvAaEpq9IH4zcNsarH8Ihu/UuX6XMPEogDAxkuUFeZn60pXNHAqn3A== dependencies: semver "^7.3.5" @@ -2380,6 +2385,13 @@ node-html-parser@^5.3.3: css-select "^4.2.1" he "1.2.0" +node-pty@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/node-pty/-/node-pty-1.0.0.tgz#7daafc0aca1c4ca3de15c61330373af4af5861fd" + integrity sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA== + dependencies: + nan "^2.17.0" + nopt@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/nopt/-/nopt-6.0.0.tgz#245801d8ebf409c6df22ab9d95b65e1309cdb16d" diff --git a/ui/desktop/ember-cli-build.js b/ui/desktop/ember-cli-build.js index 1666d080b..c5399aabf 100644 --- a/ui/desktop/ember-cli-build.js +++ b/ui/desktop/ember-cli-build.js @@ -41,5 +41,7 @@ module.exports = function (defaults) { // please specify an object with the list of modules as keys // along with the exports of each module as its value. + app.import('node_modules/xterm/css/xterm.css'); + return app.toTree(); }; diff --git a/ui/desktop/package.json b/ui/desktop/package.json index c497d253f..b80e0017f 100644 --- a/ui/desktop/package.json +++ b/ui/desktop/package.json @@ -44,7 +44,10 @@ "posttest": "ember coverage-merge && yarn clean:coverage" }, "dependencies": { - "ember-named-blocks-polyfill": "^0.2.5" + "ember-named-blocks-polyfill": "^0.2.5", + "uuid": "^9.0.0", + "xterm": "^5.2.1", + "xterm-addon-fit": "^0.7.0" }, "devDependencies": { "@babel/eslint-parser": "^7.18.2", @@ -98,6 +101,7 @@ "eslint-plugin-qunit": "^7.3.0", "js-bexpr": "hashicorp/js-bexpr#9b4a4b54d85eba67fdfc0990133d1518d890b1e1", "loader.js": "^4.7.0", + "lodash": "4.17.21", "npm-run-all": "^4.1.5", "playwright": "^1.15.0", "prettier": "^2.7.1", @@ -110,8 +114,7 @@ "stylelint": "^15.10.1", "stylelint-config-prettier-scss": "^0.0.1", "stylelint-config-standard-scss": "^7.0.1", - "webpack": "^5.76.0", - "lodash": "4.17.21" + "webpack": "^5.76.0" }, "engines": { "node": "16.* || 18.*" diff --git a/yarn.lock b/yarn.lock index 6db08d62f..fe643d65a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -21047,9 +21047,9 @@ terser-webpack-plugin@^5.3.7: terser "^5.16.8" terser@^4.1.2, terser@^5.14.2, terser@^5.16.8, terser@^5.3.0, terser@^5.7.2: - version "5.19.4" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.19.4.tgz#941426fa482bf9b40a0308ab2b3cd0cf7c775ebd" - integrity sha512-6p1DjHeuluwxDXcuT9VR8p64klWJKo1ILiy19s6C9+0Bh2+NWTX6nD9EPppiER4ICkHDVB1RkVpin/YW2nQn/g== + version "5.19.3" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.19.3.tgz#359baeba615aef13db4b8c4d77a2aa0d8814aa9e" + integrity sha512-pQzJ9UJzM0IgmT4FAtYI6+VqFf0lj/to58AV0Xfgg0Up37RyPG7Al+1cepC6/BVuAxR9oNb41/DL4DEoHJvTdg== dependencies: "@jridgewell/source-map" "^0.3.3" acorn "^8.8.2" @@ -22459,6 +22459,16 @@ xtend@~2.1.1: dependencies: object-keys "~0.4.0" +xterm-addon-fit@^0.7.0: + version "0.7.0" + resolved "https://registry.yarnpkg.com/xterm-addon-fit/-/xterm-addon-fit-0.7.0.tgz#b8ade6d96e63b47443862088f6670b49fb752c6a" + integrity sha512-tQgHGoHqRTgeROPnvmtEJywLKoC/V9eNs4bLLz7iyJr1aW/QFzRwfd3MGiJ6odJd9xEfxcW36/xRU47JkD5NKQ== + +xterm@^5.2.1: + version "5.2.1" + resolved "https://registry.yarnpkg.com/xterm/-/xterm-5.2.1.tgz#b3fea7bdb55b9be1d4b31f4cd1091f26ac42afb8" + integrity sha512-cs5Y1fFevgcdoh2hJROMVIWwoBHD80P1fIP79gopLHJIE4kTzzblanoivxTiQ4+92YM9IxS36H1q0MxIJXQBcA== + y18n@^4.0.0: version "4.0.3" resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.3.tgz#b5f259c82cd6e336921efd7bfd8bf560de9eeedf"