Make Terminal a native feature

- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0.
- Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module.
- Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key.
- The 16 ANSI colors come from the --rs-ansi-* tokens.
- Off asks first when a shell runs in any window (pty_running).
- Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close.
- Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness.
- Check only the tested switches in the Background smoke test.
- Update the tests, the menu inventory, the docs, and UI-058.
This commit is contained in:
Knotty Wyvern
2026-10-29 19:02:58 -07:00
parent 53b9cea7f0
commit 833f793244
78 changed files with 2971 additions and 659 deletions
+2 -2
View File
@@ -2,8 +2,8 @@
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files. RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`). A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
Git and Background are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API. Git, Background, and Terminal are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`. Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
The [development guide](docs/development.md#architecture) maps the source folders. The [development guide](docs/development.md#architecture) maps the source folders.
## Skills ## Skills
+17
View File
@@ -591,6 +591,7 @@ The overlay retains the source hue. Selected glyph backgrounds stay transparent,
Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast. Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast.
Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light. Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light.
Native shell, background image, and desktop acceptance remain open. Native shell, background image, and desktop acceptance remain open.
Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-selection` ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
### UI-030 — Settings installation checkbox theme drift ### UI-030 — Settings installation checkbox theme drift
@@ -813,6 +814,7 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names. - Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names.
- Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains. - Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains.
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. - Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
- Update 2026-10-29: The native Terminal feature uses the terminal roles ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
### UI-043 — Opaque menus ### UI-043 — Opaque menus
@@ -1059,3 +1061,18 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/features/background.smoke.mjs` and the updated `tests/smoke/appearance/background*.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/background/`. - Evidence: `tests/smoke/features/background.smoke.mjs` and the updated `tests/smoke/appearance/background*.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/background/`.
- Replaces / replaced by: The Background image section of Appearance and the Background Slideshow plugin. The rules of [UI-015](#ui-015--slower-slideshow-fades) and [UI-020](#ui-020--per-image-slideshow-layout) stay. - Replaces / replaced by: The Background image section of Appearance and the Background Slideshow plugin. The rules of [UI-015](#ui-015--slower-slideshow-fades) and [UI-020](#ui-020--per-image-slideshow-layout) stay.
- Limits: Each window has its own timer, so windows can show different images. The settings window runs no slideshow. The old package stays installed until the user removes it. - Limits: Each window has its own timer, so windows can show different images. The settings window runs no slideshow. The old package stays installed until the user removes it.
### UI-058 — Settings → Terminal and theme colors in the terminal
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-3 (2026-10-29), and decision 5C. The card "Use the host terminal colors".
- Previous rule: The Terminal plugin (`runestone.terminal` 0.1.11) kept its settings in a modal dialog with **Save settings** and **Cancel**. It saved them in the `runestone.terminal` key of `localStorage`. Its ANSI colors came from the status and accent tokens. Thus blue was the accent color, and most bright colors were the same as the normal colors.
- New rule: Terminal is a native feature with a switch in Settings → Features. **Settings → Terminal** shows only while Terminal is on. It has **Default profile** (a shared action menu without the JavaScript Debug Terminal), **Font size**, **Scrollback lines**, and **Blink cursor**. Each change saves at once to the `terminal` section of `settings.json`. Open terminals take the font, the scrollback, and the cursor. **Terminal settings** in the profile menu opens Settings. The 16 ANSI colors come from the `--rs-ansi-*` tokens. Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. Off asks first when a window runs a shell, with the words of the close guard.
- Reason: The owner chose response time and memory over the plugin API. Settings apply at once on one Settings page, as the [Settings](ui-design.md#settings) rules require. Terminal colors keep their ANSI meaning in every theme.
- Scope: Settings → Terminal, Settings → Features, the terminal panel, terminal windows, and Help.
- Shared implementation: `src/lib/features/terminal/` (`theme.ts` for the colors), `src/lib/features/TerminalSettings.svelte`, `src/lib/features/terminalSettings.ts`, `src/lib/features/terminalKeys.ts`, `src/lib/theme/roles.ts`, and `src-tauri/src/pty.rs`.
- Evidence: `tests/smoke/features/terminal.smoke.mjs` and `tests/unit/features/terminal.spec.ts`, with screenshots in both themes and at 360 pixels in `output/smoke/features/terminal/`.
- Replaces / replaced by: The settings dialog and the ANSI color map of the Terminal plugin. The terminal roles of [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) and the selection cap of [UI-029](#ui-029--text-selection-transparency) stay.
- Limits: The smoke tests use mock shells. Real shells, dictation, and native desktop appearance need user review. The old package stays installed until the user removes it.
+14 -10
View File
@@ -64,7 +64,7 @@ Windows is the primary platform. macOS and Linux builds are experimental.
| `plugin_sources.rs` | Plugin downloads from Gitea releases | | `plugin_sources.rs` | Plugin downloads from Gitea releases |
| `git.rs` | The Git service of the Git feature. It runs the `git` program. | | `git.rs` | The Git service of the Git feature. It runs the `git` program. |
| `features.rs` | Reads the old plugin packages of the native features one time, for the first-start migration. It changes no plugin file. | | `features.rs` | Reads the old plugin packages of the native features one time, for the first-start migration. It changes no plugin file. |
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin | | `pty.rs`, `terminal_platform.rs` | The shell sessions of the Terminal feature, the shell search, and terminal windows. A session belongs to the window and the page that opened it. |
| `browser.rs` | The process of the built-in browser engine | | `browser.rs` | The process of the built-in browser engine |
| `backgrounds.rs` | The image folder of the Background feature: the folder dialog, the kept folder (`background-folder.json` in the app data folder), the image list and reads, the sidecar file, and the folder migration from the Background Slideshow plugin | | `backgrounds.rs` | The image folder of the Background feature: the folder dialog, the kept folder (`background-folder.json` in the app data folder), the image list and reads, the sidecar file, and the folder migration from the Background Slideshow plugin |
| `spelling.rs` | Spelling suggestions from the operating system (Windows) | | `spelling.rs` | Spelling suggestions from the operating system (Windows) |
@@ -88,7 +88,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) | | `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
| `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins | | `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins |
| `browser/` | The interface of the built-in browser | | `browser/` | The interface of the built-in browser |
| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, the launch rules, the Background settings (`backgroundSettings.ts`), and one folder for each feature (`git/`, `background/`). See [Native features](#native-features). | | `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, the launch rules, the Background settings (`backgroundSettings.ts`), and one folder for each feature (`git/`, `background/`, `terminal/`). The main-bundle files of Terminal are `terminalKeys.ts`, `terminalSettings.ts`, `terminalHost.ts`, `TerminalHost.svelte`, and `TerminalSettings.svelte`. See [Native features](#native-features). |
| `completion/` | Contracts and services that plugins use | | `completion/` | Contracts and services that plugins use |
| `git/` | The Git service and its types, for the Git feature and the line history in the status bar | | `git/` | The Git service and its types, for the Git feature and the line history in the status bar |
| `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) | | `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) |
@@ -116,7 +116,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Documents | Ordinary files in the workspace folder | | Documents | Ordinary files in the workspace folder |
| Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace | | Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace |
| Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). | | Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). |
| Preferences: general settings, appearance, custom themes, display language, feature switches, Background | `settings.json` in the app config folder | | Preferences: general settings, appearance, custom themes, display language, feature switches, Background, Terminal | `settings.json` in the app config folder |
| The image folder of Background | `background-folder.json` in the app data folder. The image of the image source stays in the WebView storage (IndexedDB). | | The image folder of Background | `background-folder.json` in the app data folder. The image of the image source stays in the WebView storage (IndexedDB). |
| Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). | | Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). |
| Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. | | Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
@@ -136,14 +136,15 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
"customThemes": [], "customThemes": [],
"customThemesLegacy": [], "customThemesLegacy": [],
"language": "en", "language": "en",
"features": { "git": true, "background": true }, "features": { "git": true, "background": true, "terminal": true },
"background": { "source": "folder", "seconds": 60, "order": "name", "paused": false, "targets": ["app"], "overlay": 0, "position": "center", "size": "cover" } "background": { "source": "folder", "seconds": 60, "order": "name", "paused": false, "targets": ["app"], "overlay": 0, "position": "center", "size": "cover" },
"terminal": { "defaultProfile": "", "fontSize": 13, "scrollback": 10000, "cursorBlink": true }
} }
``` ```
| Rule | Detail | | Rule | Detail |
| --- | --- | | --- | --- |
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, `features` (the switches of the native features), and `background` (the source, the timing, the targets, and the folder layout of Background). The host does not interpret their values. The frontend normalizes each section. | | Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, `features` (the switches of the native features), `background` (the source, the timing, the targets, and the folder layout of Background), and `terminal` (the default profile, the font size, the scrollback, and the cursor of Terminal). The host does not interpret their values. The frontend normalizes each section. |
| Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. | | Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. |
| Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. | | Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. |
| Damaged file | The host moves the file to `settings.corrupt-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. | | Damaged file | The host moves the file to `settings.corrupt-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. |
@@ -208,7 +209,7 @@ Errors of the plugin API stay in English, because they are for plugin developers
## Native features ## Native features
Git and Background are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API. Git, Background, and Terminal are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API.
| Part | File | | Part | File |
| --- | --- | | --- | --- |
@@ -224,6 +225,10 @@ Git and Background are native features: host code with an off switch in **Settin
- A command without a view loads the feature and calls `FeatureInstance.run`. A launch rule starts the instance at once when it wants it, and again after each change of its settings. - A command without a view loads the feature and calls `FeatureInstance.run`. A launch rule starts the instance at once when it wants it, and again after each change of its settings.
- Background has a launch rule: it loads when the `background` section selects a folder, or an image that exists. Its settings section and its "has a source" test are in `src/lib/features/backgroundSettings.ts`, in the main bundle. It also runs in browser windows. In the settings window, only its settings component loads (`mountSettings`). - Background has a launch rule: it loads when the `background` section selects a folder, or an image that exists. Its settings section and its "has a source" test are in `src/lib/features/backgroundSettings.ts`, in the main bundle. It also runs in browser windows. In the settings window, only its settings component loads (`mountSettings`).
- The first start makes the `background` section from the kept settings of the Background Slideshow plugin and from the old background image. `background_migrate` copies the folder of the old plugin grant to the host only when the host has no folder. - The first start makes the `background` section from the kept settings of the Background Slideshow plugin and from the old background image. `background_migrate` copies the folder of the old plugin grant to the host only when the host has no folder.
- Terminal has no view and no launch rule. `TerminalHost.svelte` puts the panel in the workbench and in the terminal window, and the first use loads the module. `terminalKeys.ts` holds the shortcuts and the Help rows. Settings → Terminal (`TerminalSettings.svelte`) loads no xterm.
- `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks.
- The first start makes the `terminal` section from the `runestone.terminal` key of `localStorage`, which the Terminal plugin wrote. The old key stays.
- Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window.
- Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start. - Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start.
- Saved tabs and tab transfers keep the ID of the old plugin package as the owner ID, for example `runestone.git`. `builtInPackages` in `external.ts` lists the old package, so it never loads. - Saved tabs and tab transfers keep the ID of the old plugin package as the owner ID, for example `runestone.git`. `builtInPackages` in `external.ts` lists the old package, so it never loads.
- Off stops the feature at once in each window and closes its views. The loaded module stays in memory until the window reloads. - Off stops the feature at once in each window and closes its views. The loaded module stays in memory until the window reloads.
@@ -270,7 +275,6 @@ A test states what it needs near its top. The runner skips the test, with the re
| Line | Requirement | | Line | Requirement |
| --- | --- | | --- | --- |
| `// @requires plugin:terminal` | The compiled Terminal plugin |
| `// @requires repo:RuneStone_Local_Autocomplete/src` | A file or folder in a sibling plugin checkout | | `// @requires repo:RuneStone_Local_Autocomplete/src` | A file or folder in a sibling plugin checkout |
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. | | `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
| `// @known-issue <defect>` | The test fails because of a known app defect. The run reports it as `known`. If the test passes, the run fails, so that someone removes the line. | | `// @known-issue <defect>` | The test fails because of a known app defect. The run reports it as `known`. If the test passes, the run fails, so that someone removes the line. |
@@ -279,14 +283,14 @@ A test states what it needs near its top. The runner skips the test, with the re
| --- | --- | | --- | --- |
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. | | `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. | | `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. | | `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
| `CHROME_PATH` | A Chromium browser for Playwright | | `CHROME_PATH` | A Chromium browser for Playwright |
| `PLAYWRIGHT_MODULE` | A different Playwright package | | `PLAYWRIGHT_MODULE` | A different Playwright package |
To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace. To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace.
The harness also has default handlers for the settings file and for tab transfers. All pages of one browser context share them. The harness also has default handlers for the settings file, for tab transfers, and for the `pty_*` shells of Terminal. All pages of one browser context share them.
The mock shell sends its output through the channel of `pty_open`. To send more, use `window.__TEST__.pty.output(id, text)` and `window.__TEST__.pty.exit(id, code)`.
To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them. To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them.
To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`. To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`.
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings. A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
+47 -20
View File
@@ -1,29 +1,30 @@
# Terminal guide # Terminal guide
[RuneStone](../../README.md) · [User guide](../user-guide.md) · [Install a plugin](../plugins.md#install-a-plugin) [RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to use shells, scripts, and workspace tasks with the optional Terminal plugin. This guide explains how to use shells, scripts, and workspace tasks in the terminal of RuneStone.
Install and enable the Terminal plugin first. The shells and script runtimes that you use must be installed on your computer. Terminal is part of RuneStone and is on by default. The shells and script runtimes that you use must be installed on your computer. To turn Terminal off, see [Turn Terminal off](#turn-terminal-off).
## Open and arrange terminals ## Open and arrange terminals
| Action | How | | Action | How |
| --- | --- | | --- | --- |
| Show or hide the terminal panel | Ctrl+` or Ctrl+J. Sessions and scrollback stay. | | Show or hide the terminal panel | **Terminal** in the left ribbon, Ctrl+`, or Ctrl+J. Sessions and scrollback stay. |
| New terminal | Ctrl+Shift+` or the + button | | New terminal | Ctrl+Shift+` or the + button |
| Split the active terminal | Ctrl+Shift+5. The new pane uses the same folder and profile. | | Split the active terminal | Ctrl+Shift+5 or **Split terminal**. The new pane uses the same folder and profile. |
| New terminal window | Ctrl+Shift+Alt+` | | New terminal window | Ctrl+Shift+Alt+`, or **New terminal window** in the profile menu |
| End the active session | **Kill terminal**, or Delete while an entry in the terminal list has focus | | End the active session | **Kill terminal**, or Delete while an entry in the terminal list has focus |
| Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. | | Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. |
| End all sessions in the panel | **Close terminal (end all sessions)** | | End all sessions in the panel | **Close terminal (end all sessions)** |
The terminal list shows only when more than one session is open. The terminal list shows only when more than one session is open.
Closing a separate terminal window ends its sessions. Closing a terminal window ends its sessions. When you close a workspace window with running sessions, RuneStone asks first.
You can type before a shell starts. RuneStone sends the text when the shell is ready.
## Choose a shell ## Choose a shell
Open the menu beside the + button to start a terminal with a specific profile. Open **Terminal profiles and tasks** (the arrow beside the + button) to start a terminal with a specific profile.
| System | Profiles | | System | Profiles |
| --- | --- | | --- | --- |
@@ -31,10 +32,26 @@ Open the menu beside the + button to start a terminal with a specific profile.
| macOS and Linux | Bash and PowerShell | | macOS and Linux | Bash and PowerShell |
The menu shows only the shells that RuneStone finds on your computer. The menu shows only the shells that RuneStone finds on your computer.
The same menu has **Split Terminal with Profile**, **Select Default Profile**, **Configure Terminal Settings**, and the task commands. The same menu has **Split terminal with profile**, **Terminal settings**, **Select the default profile**, and the task commands.
Terminal settings set the font size, scrollback lines, cursor blink, and default profile. RuneStone keeps them on this computer.
New terminals get the RuneStone environment, including `PATH`. New terminals get the RuneStone environment, including `PATH`.
## Change the terminal settings
Open **Settings → Terminal**, or choose **Terminal settings** in the profile menu. The page shows only while Terminal is on.
| Setting | Values |
| --- | --- |
| **Default profile** | The shell of a new terminal. The JavaScript Debug Terminal is not a choice. |
| **Font size** | 9 to 28 pixels. The default is 13. |
| **Scrollback lines** | 100 to 100,000 lines. The default is 10,000. |
| **Blink cursor** | The cursor blinks in the focused terminal. On by default. |
A change saves at once and applies to all windows. Open terminals take the new font size, scrollback, and cursor. The default profile applies to new terminals.
After an update, the first start copies the settings of the old Terminal plugin.
The terminal colors come from the color theme. The text, the cursor, and the selection use the theme colors. The 16 ANSI colors use the `ansi-*` keys of the theme.
To change them, see [Edit a theme](themes.md#edit-a-theme) and [Color keys](themes.md#color-keys).
## Copy and paste ## Copy and paste
- Drag across terminal text to select it. - Drag across terminal text to select it.
@@ -48,24 +65,25 @@ Open **More terminal actions** for these commands:
| Command | Result | | Command | Result |
| --- | --- | | --- | --- |
| **Run Active File** | Saves and runs the active file in the terminal. | | **Scroll to the previous command** / **Scroll to the next command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
| **Run Selected Text** | Sends the text that is selected in the editor to the terminal. | | **Clear the terminal** | Clears the scrollback. |
| **Clear Terminal** | Clears the scrollback. | | **Run the active file** | Saves and runs the active file in the terminal. |
| **Run Recent Command…** (Ctrl+Alt+R) | Runs a command from this session again. | | **Run selected text** | Sends the text that is selected in the editor to the terminal. |
| **Go to Recent Directory…** (Ctrl+G) | Changes to a recent folder. | | **Start dictation** | Starts Windows voice typing. See [Debug JavaScript and use dictation](#debug-javascript-and-use-dictation). |
| **Scroll to Previous Command** / **Next Command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. | | **Go to a recent folder…** (Ctrl+G) | Changes to a recent folder. |
| **Run a recent command…** (Ctrl+Alt+R) | Runs a command from this session again. |
**Run Active File** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables. **Run the active file** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
The terminal keeps command history in memory only. PowerShell and Bash record a command after it finishes. Command Prompt records the text that you submit. The terminal keeps command history in memory only. PowerShell and Bash record a command after it finishes. Command Prompt records the text that you submit.
## Configure workspace tasks ## Configure workspace tasks
A task is a named command that you can start from a menu. A task is a named command that you can start from a menu.
1. Choose **Configure Tasks…**. RuneStone creates or opens `.runestone/tasks.json`. 1. Choose **Configure tasks…**. RuneStone creates or opens `.runestone/tasks.json`.
2. Add an object to the `tasks` array with `label` and `command`. 2. Add an object to the `tasks` array with `label` and `command`.
3. Optionally, add `profile` with one of these IDs: `powershell`, `pwsh`, `git-bash`, `cmd`, or `bash`. 3. Optionally, add `profile` with one of these IDs: `powershell`, `pwsh`, `git-bash`, `cmd`, or `bash`.
4. Choose **Run Task…** and select the task. 4. Choose **Run a task…** and select the task.
Example (`.runestone/tasks.json`): Example (`.runestone/tasks.json`):
@@ -84,5 +102,14 @@ Each task runs in its own terminal at the workspace root. Tasks run only when yo
**JavaScript Debug Terminal** in the profile menu starts a Node.js REPL with a local inspector on a free port. **JavaScript Debug Terminal** in the profile menu starts a Node.js REPL with a local inspector on a free port.
Attach an external debugger to the address that the terminal shows. RuneStone does not include a debugger. Attach an external debugger to the address that the terminal shows. RuneStone does not include a debugger.
**Start Dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first. **Start dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first.
On other systems, use the dictation shortcut of the operating system. On other systems, use the dictation shortcut of the operating system.
## Turn Terminal off
1. Open **Settings → Features**.
2. Clear **Terminal**.
3. If a window runs a shell, RuneStone asks "Terminal sessions will end. Turn off Terminal?". Confirm to continue.
Off ends the terminal sessions of every window. The Terminal buttons, shortcuts, and Help rows do not show. A terminal window shows "Terminal is off. Turn it on in Settings → Features."
Your terminal settings and `.runestone/tasks.json` stay. Turn Terminal on again in the same place.
+2 -2
View File
@@ -70,10 +70,10 @@ Voice typing is not part of the Linux checks.
| Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. | | Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. |
| Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. | | Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. |
| Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check that plugin data stays. | | Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check that plugin data stays. |
| Terminal plugin | Install the Terminal ZIP. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. | | Terminal | Open the terminal panel. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
| Settings | Change preferences, restart, and make sure that they stay. Check separate workspace windows. | | Settings | Change preferences, restart, and make sure that they stay. Check separate workspace windows. |
For the Terminal ZIP, see [Build examples](plugin-development.md#build-examples) and the [plugin installation guide](plugins.md). For the use of Terminal, see the [Terminal guide](guides/terminal.md).
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell. Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
Known Linux limits: Known Linux limits:
+23 -24
View File
@@ -3,7 +3,6 @@
"scope": [ "scope": [
"RuneStone", "RuneStone",
"RuneStone_Project_Management", "RuneStone_Project_Management",
"RuneStone_Terminal",
"RuneStone_Background_Slideshow", "RuneStone_Background_Slideshow",
"RuneStone_Local_Autocomplete", "RuneStone_Local_Autocomplete",
"RuneStone_PDF_Viewer", "RuneStone_PDF_Viewer",
@@ -241,29 +240,6 @@
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts" "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts"
}, },
"RuneStone_Terminal/src/TerminalDock.svelte": {
"counts": {
"action": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalPicker.svelte": {
"counts": {
"picker": 2,
"localPopup": 3
},
"design": "Shared searchable picker",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Background_Slideshow/src/contracts.ts": { "RuneStone_Background_Slideshow/src/contracts.ts": {
"counts": { "counts": {
"action": 1 "action": 1
@@ -336,6 +312,29 @@
}, },
"design": "Shared action menu for the fit and the position of one image. The image list is the shared searchable picker (rs-picker).", "design": "Shared action menu for the fit and the position of one image. The image list is the shared searchable picker (rs-picker).",
"check": "tests/smoke/features/background.smoke.mjs" "check": "tests/smoke/features/background.smoke.mjs"
},
"RuneStone/src/lib/features/terminal/TerminalDock.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu through showActionMenu",
"check": "tests/smoke/features/terminal.smoke.mjs"
},
"RuneStone/src/lib/features/terminal/TerminalPicker.svelte": {
"counts": {
"picker": 2,
"localPopup": 3
},
"design": "Shared searchable picker",
"check": "tests/smoke/features/terminal.smoke.mjs"
},
"RuneStone/src/lib/features/TerminalSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 1
},
"design": "Shared action menu for the default profile in Settings → Terminal",
"check": "tests/smoke/features/terminal.smoke.mjs"
} }
} }
} }
+14 -52
View File
@@ -11,7 +11,6 @@ This reference gives the package contract, the build procedure, and the API for
- [Versions and releases](#versions-and-releases) - [Versions and releases](#versions-and-releases)
- [Plugin API](#plugin-api) - [Plugin API](#plugin-api)
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls) - [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
- [Terminal API](#terminal-api)
- [Folder grants](#folder-grants) - [Folder grants](#folder-grants)
- [Plugin services](#plugin-services) - [Plugin services](#plugin-services)
- [Background API](#background-api) - [Background API](#background-api)
@@ -146,22 +145,21 @@ In user instructions, do not tell users to load JSON, select a build folder, ren
Each example is specific to one plugin. Read the package scripts of a plugin before you build it. Each example is specific to one plugin. Read the package scripts of a plugin before you build it.
For the RuneStone source setup, see [Run from source](development.md#run-from-source). For the RuneStone source setup, see [Run from source](development.md#run-from-source).
### Example: Terminal ### Example: CSV Viewer
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern/RuneStone_Terminal), its `package.json`, and its `scripts/build.mjs`. Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
| Item | Value | | Item | Value |
| --- | --- | | --- | --- |
| Prerequisites | Node.js 24 and pnpm 10. Run `pnpm install --frozen-lockfile` in the Terminal folder. | | Prerequisites | Node.js 24 or later and pnpm. Run `pnpm install --frozen-lockfile` in the CSV Viewer folder. Put the RuneStone source checkout beside it, in a folder with the name `RuneStone`. The source imports shared interface files from `../../RuneStone/src/lib/ui/`. |
| Working folder | The Terminal repository root | | Working folder | The CSV Viewer repository root |
| Command | `pnpm build` | | Command | `pnpm build` |
| Output | `releases/runestone.terminal-<version>.zip` in the Terminal folder | | Output | `releases/runestone.csv-viewer-<version>.zip` in the CSV Viewer folder. `<version>` is the `version` of `plugin.json`, for example `0.1.3`. |
The build compiles the Svelte interface and its dependencies into `dist/` (`main.js`, `style.css`, `plugin.json`, and `README.md`). Then it makes the ZIP. The build compiles `src/index.js` with esbuild into a readable `dist/main.js`. It copies `plugin.json` and `README.md` into `dist/` and writes `dist/build.json`.
The build stops when the versions in `package.json` and `plugin.json` are different. Then it runs `scripts/packagePlugin.mjs` of the RuneStone checkout on `dist/`. Set `RUNESTONE_ROOT` to use another RuneStone checkout for this step.
To compile into `dist/` without a ZIP, run `node scripts/build.mjs --no-package`. The build stops when the versions in `package.json` and `plugin.json` are different. It also stops when the release ZIP of the version exists. Set the next version in both files first.
RuneStone supplies the native terminal sessions. The plugin supplies the interface, shortcuts, and session controls. To compile into `dist/` without a ZIP, run `pnpm compile`.
For use of the terminal, see the [Terminal guide](guides/terminal.md).
### Example: Workspace overview ### Example: Workspace overview
@@ -216,8 +214,8 @@ The SDK feature checks do this. Their error names each missing feature and tells
```ts ```ts
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk"; import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
requireFeatures(api, ["pty", "workspace.readBytes"]); requireFeatures(api, ["files", "workspace.readBytes"]);
const pty = requireFeature(api, "pty"); const files = requireFeature(api, "files");
if (hasFeature(api, "settings.subscribe")) watchSettings(); if (hasFeature(api, "settings.subscribe")) watchSettings();
``` ```
@@ -264,7 +262,6 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
| `assets.read(path)` | | Read a package file as a `Uint8Array`. | | `assets.read(path)` | | Read a package file as a `Uint8Array`. |
| `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). | | `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). |
| `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). | | `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). |
| `pty` | yes | Terminal sessions. See [Terminal API](#terminal-api). |
| `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). | | `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). |
| `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). | | `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). |
| `backgrounds` | yes | Background image frames. See [Background API](#background-api). | | `backgrounds` | yes | Background image frames. See [Background API](#background-api). |
@@ -385,10 +382,9 @@ Only one enabled plugin can own each key. The host removes contributions before
| Key | Purpose | Owner | | Key | Purpose | Owner |
| --- | --- | --- | | --- | --- | --- |
| `terminal` | Mounts terminal controls in a host element. Returns update, command, and dispose functions. | Terminal plugin |
| `browser` | The built-in browser. `newTab(url?)` opens a browser tab. `open(url)` returns false when the system browser must open a web link, for example before the engine is installed. | RuneStone | | `browser` | The built-in browser. `newTab(url?)` opens a browser tab. `open(url)` returns false when the system browser must open a web link, for example before the engine is installed. | RuneStone |
A terminal contribution must stop its controls and native sessions before its cleanup finishes. Earlier hosts also had `api.pty` and a `terminal` key for the Terminal plugin. They are gone, because RuneStone now includes Terminal as a native feature.
### Theme tokens ### Theme tokens
@@ -423,46 +419,12 @@ The window sends a `runestone-theme-changed` event after each theme change. A pl
## Use the SDK instead of native calls ## Use the SDK instead of native calls
Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins. Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins.
Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context. Use the `api` members of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts. Make sure that an optional member exists before you use it.
The host still accepts the native calls of released plugins. A later host can remove them.
| Plugin | Current call | Purpose | Use instead |
| --- | --- | --- | --- |
| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` |
| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` |
| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` |
| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` |
| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` |
| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` |
The Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls. The Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls.
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package. Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
## Terminal API
`api.pty` (`version: 1`) starts shells in pseudo terminals. The SDK types are `PtyApi` and `PtySession`.
| Member | Contract |
| --- | --- |
| `profiles()` | Returns the installed shells as `{ id, title, kind }`. |
| `open(options)` | Starts a shell and returns a session. See the options below. |
| `openWindow()` | Opens a terminal window for the workspace of the current window. |
| `dictation()` | Starts Windows voice typing. Focus the terminal first. Fails on other systems. |
| Option | Rule |
| --- | --- |
| `cwd` | Required. The workspace root of the window. The start fails when the workspace changed. |
| `cols`, `rows` | Required. Positive integers. |
| `profile` | A profile `id` from `profiles()`. Without it, the host uses the first installed shell. |
| `directory` | A start folder other than the workspace root. |
| `onData(data)` | Required. Receives the output as a `Uint8Array`. A UTF-8 character can be split between two calls. |
| `onExit(code)` | Receives the exit code, or `null`. |
A session has `id`, `write(text)`, `resize(cols, rows)`, and `close()`. `close()` stops the shell, and more calls return the same promise.
Output goes only to the session that started the shell, as raw bytes.
When the plugin stops, the host stops the output, runs the plugin cleanup, and then closes the sessions that are still open.
## Folder grants ## Folder grants
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path. `api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
+9 -11
View File
@@ -33,7 +33,7 @@ The browser preview (`pnpm dev`) has no installed plugins unless a smoke test su
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser. The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it. `builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
Native features, such as Git and Background, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views share the tab model of plugin views. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features). Native features, such as Git, Background, and Terminal, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views share the tab model of plugin views. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features).
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file. `features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
### Scans ### Scans
@@ -160,7 +160,7 @@ The policy stops a script that comes in through rendered content, for example a
| --- | --- | --- | | --- | --- | --- |
| `default-src` | `'self'` | All other types come only from the app. | | `default-src` | `'self'` | All other types come only from the app. |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. | | `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer). | | `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer, PDF Viewer). |
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. | | `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. | | `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. | | `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
@@ -186,17 +186,18 @@ Workers that the app loads from its own files get no policy. Workers from Blob U
| Capability | Windows | Plugins | Commands | | Capability | Windows | Plugins | Commands |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands | | `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser | | `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser, `pty_profiles`, and `pty_running` |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) | | `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this. A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work: The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
- Terminal windows use the plugin host commands, `pty_*` through the Terminal plugin, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API. - Terminal windows use the `pty_*` commands of the Terminal feature, the plugin host commands, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there. - Settings windows use no `workspace_*` or `git_*` commands, but plugin settings views run there. Of the `pty_*` commands, they use only `pty_profiles` for Settings → Terminal and `pty_running` before Terminal goes off.
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace. - Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal. - `pty_write`, `pty_resize`, and `pty_close` act only on the sessions of the calling window. A session of another window counts as a missing session.
- `pty_open` needs an output channel and a page ID. The first open of a new page in a window, after a reload, closes the sessions of the earlier page. The host refuses a late open from an old page.
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave. - `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it. - `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it. - A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
@@ -209,7 +210,7 @@ The other windows load every enabled plugin. A smaller command set for them woul
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads | | `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
| `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants | | `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants |
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images | | `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
| `src-tauri/src/pty.rs` | Terminal sessions for `api.pty`. A session with an IPC channel gets raw output bytes; a session without one gets the older window events | | `src-tauri/src/pty.rs` | The shell sessions of the Terminal feature. Output goes as raw bytes through the channel of `pty_open`, in messages of up to 64 KiB or 8 ms. `pty_running` counts the sessions of all windows |
| `src/lib/plugins/sdk.ts` | The public package API types | | `src/lib/plugins/sdk.ts` | The public package API types |
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown | | `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
| `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types | | `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types |
@@ -219,7 +220,7 @@ The other windows load every enabled plugin. A smaller command set for them woul
| `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings | | `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings |
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views | | `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
| `src/lib/plugins/backgrounds.ts` | Background frames | | `src/lib/plugins/backgrounds.ts` | Background frames |
| `src/lib/plugins/nativeServices.ts` | The host side of `api.pty` and `api.files`. It binds the plugin ID; the plugin never sends it | | `src/lib/plugins/nativeServices.ts` | The host side of `api.files`. It binds the plugin ID. The plugin never sends it |
| `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window | | `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
| `src/lib/completion/` | The [completion API](completion.md) | | `src/lib/completion/` | The [completion API](completion.md) |
| `scripts/packagePlugin.mjs` | The packager for plugin authors | | `scripts/packagePlugin.mjs` | The packager for plugin authors |
@@ -229,9 +230,6 @@ The other windows load every enabled plugin. A smaller command set for them woul
Run these commands from the RuneStone repository root. Run these commands from the RuneStone repository root.
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests). For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
The feature smoke tests read the compiled Terminal plugin from `../RuneStone_Terminal/dist/`.
To make it without a release ZIP, run `node scripts/build.mjs --no-package` in the Terminal folder. Set `RUNESTONE_TERMINAL_DIST` to use another folder.
Unit tests: Unit tests:
```powershell ```powershell
+4 -4
View File
@@ -2,15 +2,15 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, PDF Viewer, and CSV Viewer. This guide explains how to install, enable, update, and remove optional plugins such as Project Management, PDF Viewer, and CSV Viewer.
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, and Git are part of RuneStone and are not plugins. To turn Git off, see [Turn features on or off](user-guide.md#turn-features-on-or-off). Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, and Terminal are part of RuneStone and are not plugins. To turn Git, Background, or Terminal off, see [Turn features on or off](user-guide.md#turn-features-on-or-off).
Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust. Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust.
## Install a plugin ## Install a plugin
Get the release ZIP of the plugin, such as `runestone.terminal-<version>.zip`. Do not extract it. Get the release ZIP of the plugin, such as `runestone.csv-viewer-<version>.zip`. Do not extract it.
1. Open **Settings → Plug-ins**. 1. Open **Settings → Plug-ins**.
2. Choose **Install plugin ZIP**. 2. Choose **Install plugin ZIP**.
@@ -75,7 +75,6 @@ RuneStone uses the token for this request only and does not save it.
| Plugin | Guide | | Plugin | Guide |
| --- | --- | | --- | --- |
| Terminal | [Terminal guide](guides/terminal.md) |
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) | | Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) |
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) | | Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
| PDF Viewer | [PDF Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_PDFViewer/src/branch/master/README.md) | | PDF Viewer | [PDF Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_PDFViewer/src/branch/master/README.md) |
@@ -95,6 +94,7 @@ RuneStone uses the token for this request only and does not save it.
| An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. | | An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. |
| An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). | | An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). |
| An old Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). | | An old Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). |
| An old Terminal plugin shows in the list | RuneStone includes Terminal. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its terminal settings. See the [Terminal guide](guides/terminal.md). |
| An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). | | An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). |
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins. To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
+2
View File
@@ -38,6 +38,8 @@ Correct a wrong color in the theme data or in the derivation rule. Do not add lo
| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. | | Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. |
| Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. | | Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. |
The Terminal feature uses these tokens directly (`src/lib/features/terminal/theme.ts`). Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. The 16 ANSI colors are the `--rs-ansi-*` tokens. The terminal reads them again after each theme change.
Do not fade a whole badge, row, or container when only its background needs transparency. Do not fade a whole badge, row, or container when only its background needs transparency.
Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors. Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors.
+3 -2
View File
@@ -174,17 +174,18 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
- General offers the interface language through the shared action menu. - General offers the interface language through the shared action menu.
- **Features** lists each native feature in one card: its name, one line of description, and a switch. The page sits between Appearance and Plug-ins, and the `toggle` icon marks it. A failed load shows its cause under the switch in the error color. - **Features** lists each native feature in one card: its name, one line of description, and a switch. The page sits between Appearance and Plug-ins, and the `toggle` icon marks it. A failed load shows its cause under the switch in the error color.
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. A settings section of an off feature shows one line that names Settings → Features. - A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. A settings section of an off feature shows one line that names Settings → Features.
- **Terminal** is a Settings page with the `terminal` icon, after Plug-ins and Browser. It shows only while Terminal is on. **Terminal settings** in the profile menu of the terminal panel opens it. No dialog of the panel holds terminal settings.
- The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme. - The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme.
- Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark. - Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark.
- **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base. - **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base.
- Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance. - Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance.
Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow). Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow), [UI-058](design-decisions.md#ui-058--settings--terminal-and-theme-colors-in-the-terminal).
## Typography and tables ## Typography and tables
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`. - The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting. - Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting in Settings → Terminal.
- Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus. - Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus.
- Tables use shared cell padding and line height. Entering a cell does not change its row height. - Tables use shared cell padding and line height. Entering a cell does not change its row height.
- A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed. - A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
+7 -4
View File
@@ -16,7 +16,7 @@ This guide explains how to work with files, documents, tabs, settings, and the b
| Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) | | Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) |
| Review changes and commit with Git | [Git guide](guides/git.md) | | Review changes and commit with Git | [Git guide](guides/git.md) |
| Turn a built-in feature on or off | [Turn features on or off](#turn-features-on-or-off) | | Turn a built-in feature on or off | [Turn features on or off](#turn-features-on-or-off) |
| Add Terminal or other plugins | [Install and manage plugins](plugins.md) | | Add plugins | [Install and manage plugins](plugins.md) |
| Browse websites | [Use the built-in browser](#use-the-built-in-browser) | | Browse websites | [Use the built-in browser](#use-the-built-in-browser) |
| Run commands or scripts | [Terminal guide](guides/terminal.md) | | Run commands or scripts | [Terminal guide](guides/terminal.md) |
@@ -200,19 +200,22 @@ Settings apply at once to all workspaces on this computer and update all open wi
| --- | --- | | --- | --- |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save | | General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). | | Appearance | Color theme, transparency, background (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Features | Turn Git and Background on or off. See [Turn features on or off](#turn-features-on-or-off). | | Features | Turn Git, Background, and Terminal on or off. See [Turn features on or off](#turn-features-on-or-off). |
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). | | Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
| Browser | Homepage, search engine, profiles, ad blocking, and web data | | Browser | Homepage, search engine, profiles, ad blocking, and web data |
| Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). |
### Turn features on or off ### Turn features on or off
Git and Background are built-in features with an off switch. Open **Settings → Features** and use the switch beside the feature. Git, Background, and Terminal are built-in features with an off switch. Open **Settings → Features** and use the switch beside the feature.
- A feature that is on uses no extra memory until you first use it, for example when you open Source control. Background loads at the start only when you selected a folder or an image. - A feature that is on uses no extra memory until you first use it, for example when you open Source control or the terminal panel. Background loads at the start only when you selected a folder or an image.
- A feature that is off does not load. Its buttons, commands, and tabs do not show. - A feature that is off does not load. Its buttons, commands, and tabs do not show.
- Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first.
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone. - A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on. After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on.
Terminal does the same with the old Terminal plugin, and it copies the terminal settings of that plugin.
Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background). Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background).
Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
+2
View File
@@ -54,6 +54,8 @@
"@tiptap/extension-link": "^3.31.3", "@tiptap/extension-link": "^3.31.3",
"@tiptap/pm": "^3.31.3", "@tiptap/pm": "^3.31.3",
"@tiptap/starter-kit": "^3.31.3", "@tiptap/starter-kit": "^3.31.3",
"@xterm/addon-fit": "0.11.0",
"@xterm/xterm": "6.0.0",
"markdown-it": "^15.0.2", "markdown-it": "^15.0.2",
"mermaid": "^12.0.0" "mermaid": "^12.0.0"
}, },
+4 -4
View File
@@ -66,7 +66,7 @@ A type-only import, such as `import type { PluginApi }`, adds no code to the bun
## Check for features ## Check for features
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.pty`, `api.files`, and `api.workspace.readBytes`. Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.files`, `api.backgrounds`, and `api.workspace.readBytes`.
Make sure that a member exists before you use it. Make sure that a member exists before you use it.
```ts ```ts
@@ -74,8 +74,8 @@ import { hasFeature, requireFeature, requireFeatures, type PluginApi } from "@ru
export function activate(api: PluginApi) { export function activate(api: PluginApi) {
// Stop the activation with one message that names each missing feature. // Stop the activation with one message that names each missing feature.
requireFeatures(api, ["pty", "workspace.readOptional"]); requireFeatures(api, ["files", "workspace.readOptional"]);
const pty = requireFeature(api, "pty"); const files = requireFeature(api, "files");
// Hide a control when the feature is absent. // Hide a control when the feature is absent.
if (hasFeature(api, "ui.showActionMenu")) showMenuButton(); if (hasFeature(api, "ui.showActionMenu")) showMenuButton();
@@ -91,7 +91,7 @@ export function activate(api: PluginApi) {
When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names. When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names.
Its message names each feature and its API path, and tells the user to update RuneStone. For example: Its message names each feature and its API path, and tells the user to update RuneStone. For example:
`This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.` `This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.`
`pluginFeatures` lists all the feature names. The checks examine only whether the member exists. `pluginFeatures` lists all the feature names. The checks examine only whether the member exists.
-29
View File
@@ -20,34 +20,6 @@ export interface PluginDocumentType {
create?: { label: string; defaultName: string; extension: string; contents(): string }; create?: { label: string; defaultName: string; extension: string; contents(): string };
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>; mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
} }
export interface PtyProfile { id: string; title: string; kind: string }
export interface PtyOpenOptions {
/** The workspace root of the window. The host rejects the request when the workspace changed. */
cwd: string;
cols: number;
rows: number;
profile?: string;
/** A start folder other than the workspace root. */
directory?: string;
/** Receives raw terminal output. UTF-8 characters can be split between two calls. */
onData(data: Uint8Array): void;
onExit?(code: number | null): void;
}
export interface PtySession {
readonly id: string;
write(data: string): Promise<void>;
resize(cols: number, rows: number): Promise<void>;
/** Stops the shell. Repeated calls return the same promise. */
close(): Promise<void>;
}
/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */
export interface PtyApi {
readonly version: 1;
profiles(): Promise<PtyProfile[]>;
open(options: PtyOpenOptions): Promise<PtySession>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
export interface FolderGrant { id: string; path: string; name: string } export interface FolderGrant { id: string; path: string; name: string }
export interface FolderEntry { name: string; size: number } export interface FolderEntry { name: string; size: number }
/** Folders outside the workspace that the user granted to this plugin. */ /** Folders outside the workspace that the user granted to this plugin. */
@@ -89,7 +61,6 @@ export interface AssetsApi { read(path: string): Promise<Uint8Array> }
/** Interface parts that the host draws. */ /** Interface parts that the host draws. */
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } } export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
export interface PluginApi { export interface PluginApi {
pty?: PtyApi;
files?: FilesApi; files?: FilesApi;
services?: ServicesApi; services?: ServicesApi;
backgrounds?: BackgroundApi; backgrounds?: BackgroundApi;
-15
View File
@@ -1,16 +1,5 @@
import type { Dispose } from "./api.ts"; import type { Dispose } from "./api.ts";
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
export interface TerminalProps {
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean;
onClose: () => void; onMaximize?: () => void; activeFile?: boolean;
onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
}
export interface TerminalMount {
update(props: TerminalProps): void;
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
dispose: Dispose;
}
/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */ /** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */
export interface Contributions { export interface Contributions {
browser: { browser: {
@@ -21,8 +10,4 @@ export interface Contributions {
/** Opens a web link from a document. False means that the system browser opens it. */ /** Opens a web link from a document. False means that the system browser opens it. */
open(url: string): Promise<boolean>; open(url: string): Promise<boolean>;
}; };
terminal: {
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
};
} }
+1 -3
View File
@@ -1,4 +1,4 @@
import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts"; import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
import type { BackgroundApi } from "./backgrounds.ts"; import type { BackgroundApi } from "./backgrounds.ts";
import type { CompletionApi } from "./completion.ts"; import type { CompletionApi } from "./completion.ts";
@@ -7,7 +7,6 @@ import type { CompletionApi } from "./completion.ts";
* Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed. * Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed.
*/ */
export interface PluginFeatures { export interface PluginFeatures {
pty: PtyApi;
files: FilesApi; files: FilesApi;
services: ServicesApi; services: ServicesApi;
backgrounds: BackgroundApi; backgrounds: BackgroundApi;
@@ -33,7 +32,6 @@ export interface PluginFeatures {
export type PluginFeature = keyof PluginFeatures; export type PluginFeature = keyof PluginFeatures;
const descriptions: { [K in PluginFeature]: string } = { const descriptions: { [K in PluginFeature]: string } = {
pty: "the terminal API",
files: "the folder grant API", files: "the folder grant API",
services: "the plugin service API", services: "the plugin service API",
backgrounds: "the background API", backgrounds: "the background API",
+16
View File
@@ -89,6 +89,12 @@ importers:
'@tiptap/starter-kit': '@tiptap/starter-kit':
specifier: ^3.31.3 specifier: ^3.31.3
version: 3.31.3 version: 3.31.3
'@xterm/addon-fit':
specifier: 0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: 6.0.0
version: 6.0.0
markdown-it: markdown-it:
specifier: ^15.0.2 specifier: ^15.0.2
version: 15.0.2 version: 15.0.2
@@ -750,6 +756,12 @@ packages:
'@upsetjs/[email protected]': '@upsetjs/[email protected]':
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
'@xterm/[email protected]':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
[email protected]: [email protected]:
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
engines: {node: '>=0.4.0'} engines: {node: '>=0.4.0'}
@@ -2095,6 +2107,10 @@ snapshots:
d3-selection: 3.0.0 d3-selection: 3.0.0
d3-transition: 3.0.1([email protected]) d3-transition: 3.0.1([email protected])
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
[email protected]: {} [email protected]: {}
[email protected]: {} [email protected]: {}
+1 -1
View File
@@ -12,7 +12,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */ /** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
export const FEATURE_FOLDERS = ["git", "background"]; export const FEATURE_FOLDERS = ["git", "background", "terminal"];
/** Libraries that only features need. */ /** Libraries that only features need. */
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"]; export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
+4
View File
@@ -42,6 +42,10 @@ export const TABLE = {
terminal: { terminal: {
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` }, plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
nativeKey: "terminal", nativeKey: "terminal",
/**
* Both modes use the same names. Native: the ribbon button comes from the feature switch, and the first click loads
* the Terminal feature and xterm (src/lib/features/TerminalHost.svelte), so the action includes that load.
*/
ribbon: ".plugin-ribbon", ribbon: ".plugin-ribbon",
button: "Terminal", button: "Terminal",
surface: ".xterm", surface: ".xterm",
+1 -1
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url)); const root = fileURLToPath(new URL('../', import.meta.url));
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..'); const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer']; export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer'];
const patterns = { const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g, action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g, svelteMenu: /<ContextMenu\b/g,
-2
View File
@@ -1,2 +0,0 @@
// RuneStone_Terminal imports this path for its smoke test. The helper lives in the shared smoke harness.
export * from "../tests/smoke/_harness/pluginMocks.mjs";
+1 -5
View File
@@ -6,7 +6,7 @@
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1). // After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail. // A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
// A test declares what it needs on a line near the top: // A test declares what it needs on a line near the top:
// // @requires plugin:terminal repo:RuneStone_Git/dist electron // // @requires repo:RuneStone_Project_Management/dist/plugin electron
// The runner skips a test, with the reason, when a requirement is missing. // The runner skips a test, with the reason, when a requirement is missing.
// A test that fails because of a known app defect states it near the top: // A test that fails because of a known app defect states it near the top:
// // @known-issue <the defect> // // @known-issue <the defect>
@@ -67,10 +67,6 @@ async function header(file) {
function missing(requirement) { function missing(requirement) {
const [kind, value = ""] = requirement.split(/:(.*)/s); const [kind, value = ""] = requirement.split(/:(.*)/s);
if (kind === "plugin" && value === "terminal") {
const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist");
return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`;
}
if (kind === "repo") { if (kind === "repo") {
const target = path.join(pluginRepos, value); const target = path.join(pluginRepos, value);
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`; return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
+1
View File
@@ -98,6 +98,7 @@ fn main() {
"pty_profiles", "pty_profiles",
"pty_new_window", "pty_new_window",
"pty_dictation", "pty_dictation",
"pty_running",
]), ]),
), ),
) )
+1
View File
@@ -96,6 +96,7 @@
"allow-pty-profiles", "allow-pty-profiles",
"allow-pty-new-window", "allow-pty-new-window",
"allow-pty-dictation", "allow-pty-dictation",
"allow-pty-running",
"opener:allow-reveal-item-in-dir", "opener:allow-reveal-item-in-dir",
"allow-background-choose-folder", "allow-background-choose-folder",
"allow-background-folder", "allow-background-folder",
+2
View File
@@ -13,6 +13,8 @@
"allow-settings-write", "allow-settings-write",
"allow-settings-migrate", "allow-settings-migrate",
"allow-features-legacy", "allow-features-legacy",
"allow-pty-running",
"allow-pty-profiles",
"core:default", "core:default",
"core:window:allow-close", "core:window:allow-close",
"core:window:allow-minimize", "core:window:allow-minimize",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-running"
description = "Enables the pty_running command without any pre-configured scope."
commands.allow = ["pty_running"]
[[permission]]
identifier = "deny-pty-running"
description = "Denies the pty_running command without any pre-configured scope."
commands.deny = ["pty_running"]
+6 -2
View File
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage}; use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails. /// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 2] = ["runestone.git", "runestone.bg-slideshow"]; pub const LEGACY_PACKAGES: [&str; 3] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal"];
fn check(ids: &[String]) -> Result<()> { fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() { if ids.len() > LEGACY_PACKAGES.len() {
@@ -34,10 +34,14 @@ mod tests {
fn only_the_packages_of_native_features_are_read() { fn only_the_packages_of_native_features_are_read() {
assert!(check(&["runestone.git".into()]).is_ok()); assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok()); assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&["runestone.terminal".into()]).is_ok());
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
assert!(check(&[]).is_ok()); assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] { for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}"); assert!(check(&[id.into()]).is_err(), "{id}");
} }
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into(), "runestone.git".into()]).is_err()); let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.git"].map(String::from);
assert!(too_many.len() > LEGACY_PACKAGES.len());
assert!(check(&too_many).is_err());
} }
} }
+1
View File
@@ -134,6 +134,7 @@ pub fn run() {
pty::pty_profiles, pty::pty_profiles,
pty::pty_new_window, pty::pty_new_window,
pty::pty_dictation, pty::pty_dictation,
pty::pty_running,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while building tauri application") .expect("error while building tauri application")
+2 -2
View File
@@ -20,8 +20,8 @@ use crate::fsutil;
pub const FILE_NAME: &str = "settings.json"; pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1; pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion. /// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
/// `features` holds the switches of the native features. `background` holds the settings of the Background feature. /// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
pub const SECTIONS: [&str; 7] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"]; pub const SECTIONS: [&str; 8] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters. /// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024; pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed"; pub const CHANGED_EVENT: &str = "settings-changed";
+410 -103
View File
@@ -1,24 +1,54 @@
use std::collections::HashMap; //! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::sync::Mutex; use std::sync::Mutex;
use std::thread; use std::thread;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::Serialize; use serde::Serialize;
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId}; use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
use tauri::{AppHandle, Emitter, Manager, State}; use tauri::{AppHandle, Manager, State};
use crate::error::{Error, Result}; use crate::error::{Error, Result};
use crate::workspace::{current_root, WorkspaceState}; use crate::workspace::{current_root, WorkspaceState};
use crate::terminal_platform::find_executable; use crate::terminal_platform::find_executable;
/// The largest output message in bytes.
const BATCH_BYTES: usize = 64 * 1024;
/// The longest time that output waits for more output before it goes to the webview.
const BATCH_WAIT: Duration = Duration::from_millis(8);
/// The number of retired page IDs that each window keeps.
const RETIRED_PAGES: usize = 16;
const NOT_OPEN: &str = "terminal is not open";
const RETIRED_PAGE: &str = "terminal page is no longer active";
pub struct PtyState { pub struct PtyState {
inner: Mutex<HashMap<String, OpenPty>>, inner: Mutex<Sessions>,
}
#[derive(Default)]
struct Sessions {
open: HashMap<String, OpenPty>,
/// The page IDs of each window, by window label.
pages: HashMap<String, Pages>,
}
/// The page loads of one window. Each page load of the frontend makes a new page ID.
#[derive(Default)]
struct Pages {
current: String,
retired: VecDeque<String>,
} }
struct OpenPty { struct OpenPty {
owner: String, owner: String,
/// A unique number for this session. A session ID can come back after a reload.
serial: u64,
integration_file: Option<PathBuf>, integration_file: Option<PathBuf>,
master: Box<dyn MasterPty + Send>, master: Box<dyn MasterPty + Send>,
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>, writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
@@ -33,12 +63,13 @@ impl Drop for OpenPty {
} }
impl PtyState { impl PtyState {
/// Close the window's terminals. Remove them under the lock, then stop the shells outside it. /// Close the window's terminals and forget its pages. Remove the terminals under the lock,
/// then stop the shells outside it.
pub fn close_window(&self, label: &str) { pub fn close_window(&self, label: &str) {
let closed: Vec<OpenPty> = match self.inner.lock() { let closed: Vec<OpenPty> = match self.inner.lock() {
Ok(mut sessions) => { Ok(mut sessions) => {
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect(); sessions.pages.remove(label);
ids.iter().filter_map(|id| sessions.remove(id)).collect() take_window(&mut sessions.open, label)
} }
Err(_) => return, Err(_) => return,
}; };
@@ -55,22 +86,51 @@ impl PtyState {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
inner: Mutex::new(HashMap::new()), inner: Mutex::new(Sessions::default()),
} }
} }
} }
#[derive(Clone, Serialize)] /// Remove the sessions of one window from the map. The caller stops them outside the lock.
pub struct PtyData { fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
pub id: String, let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
// xterm owns UTF-8 decoding so multibyte characters split across reads survive. ids.iter().filter_map(|id| open.remove(id)).collect()
pub data: Vec<u8>,
} }
#[derive(Clone, Serialize)] /// The number of open sessions of all windows.
pub struct PtyExit { fn running(pty: &PtyState) -> Result<usize> {
pub id: String, Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
pub code: Option<u32>, }
/// A page ID has 1 to 64 ASCII letters, digits, and hyphens.
fn check_page(page: &str) -> Result<()> {
if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Err(Error::new("Invalid terminal page ID"));
}
Ok(())
}
/// Apply the page rule to an open request of the window `owner`. A new page is a reload of
/// the window. It retires the current page and returns the sessions of the earlier page.
/// The caller stops them outside the lock. A retired page gets an error, so a late request
/// of an old page cannot close the sessions of the new page.
fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result<Vec<OpenPty>> {
let Some(pages) = sessions.pages.get_mut(owner) else {
sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() });
return Ok(Vec::new());
};
if pages.current == page {
return Ok(Vec::new());
}
if pages.retired.iter().any(|retired| retired == page) {
return Err(Error::new(RETIRED_PAGE));
}
let earlier = std::mem::replace(&mut pages.current, page.to_owned());
pages.retired.push_back(earlier);
while pages.retired.len() > RETIRED_PAGES {
pages.retired.pop_front();
}
Ok(take_window(&mut sessions.open, owner))
} }
/// The destination of the output and the exit status of one terminal session. /// The destination of the output and the exit status of one terminal session.
@@ -79,24 +139,6 @@ trait PtyOutput: Send {
fn exit(&self, code: Option<u32>); fn exit(&self, code: Option<u32>);
} }
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
/// The events go to the window that opened the session. A global `listen` in that window
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
struct EventOutput {
app: AppHandle,
owner: String,
id: String,
}
impl PtyOutput for EventOutput {
fn data(&self, bytes: &[u8]) {
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
}
fn exit(&self, code: Option<u32>) {
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
}
}
/// A channel to the webview that opened the session. Output goes as raw bytes (an /// A channel to the webview that opened the session. Output goes as raw bytes (an
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`. /// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
struct ChannelOutput(Channel<InvokeResponseBody>); struct ChannelOutput(Channel<InvokeResponseBody>);
@@ -110,23 +152,58 @@ impl PtyOutput for ChannelOutput {
} }
} }
/// Use the channel when the caller supplies one. Without a channel, use window events. /// Read the PTY until EOF and send each read to `chunks`.
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> { fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
match channel { let mut buf = vec![0u8; 16 * 1024];
Some(channel) => Box::new(ChannelOutput(channel)),
None => events(),
}
}
/// Send the output until the reader reaches EOF. Then send the exit status.
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
let mut buf = [0u8; 4096];
loop { loop {
match reader.read(&mut buf) { match reader.read(&mut buf) {
Ok(0) | Err(_) => break, Ok(0) | Err(_) => break,
Ok(n) => output.data(&buf[..n]), Ok(n) => {
if chunks.send(buf[..n].to_vec()).is_err() { break; }
} }
} }
}
}
/// Join the output chunks into messages, then send the exit status. A message starts with
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
/// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output
/// and then the exit status.
fn pump(chunks: Receiver<Vec<u8>>, exit: Receiver<Option<u32>>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) {
let max_bytes = max_bytes.max(1);
let mut next: Option<Vec<u8>> = None;
loop {
let mut message = match next.take() {
Some(chunk) => chunk,
None => match chunks.recv() {
Ok(chunk) => chunk,
Err(_) => break,
},
};
let deadline = Instant::now() + wait;
let mut ended = false;
while message.len() < max_bytes {
let now = Instant::now();
if now >= deadline { break; }
match chunks.recv_timeout(deadline - now) {
Ok(chunk) if message.len() + chunk.len() > max_bytes => {
next = Some(chunk);
break;
}
Ok(chunk) => message.extend(chunk),
Err(RecvTimeoutError::Timeout) => break,
Err(RecvTimeoutError::Disconnected) => {
ended = true;
break;
}
}
}
for part in message.chunks(max_bytes) {
output.data(part);
}
if ended { break; }
}
output.exit(exit.recv().ok().flatten()); output.exit(exit.recv().ok().flatten());
} }
@@ -246,7 +323,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
integration_file = Some(rc); integration_file = Some(rc);
} }
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`. // The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
// The Terminal plugin reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path // The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
// cannot contain the escape or bell characters that end the sequence. // cannot contain the escape or bell characters that end the sequence.
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); } "cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); } "node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
@@ -265,8 +342,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
.spawn_command(cmd) .spawn_command(cmd)
.map_err(Error::from_display)?; .map_err(Error::from_display)?;
drop(pair.slave); drop(pair.slave);
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
let session = OpenPty { let session = OpenPty {
owner: owner.into(), owner: owner.into(),
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
integration_file, integration_file,
master: pair.master, master: pair.master,
writer: std::sync::Arc::new(Mutex::new(writer)), writer: std::sync::Arc::new(Mutex::new(writer)),
@@ -284,77 +363,103 @@ pub async fn pty_open(
webview: tauri::Webview, webview: tauri::Webview,
workspace: State<'_, WorkspaceState>, workspace: State<'_, WorkspaceState>,
id: String, id: String,
page: String,
cols: u16, cols: u16,
rows: u16, rows: u16,
cwd: String, cwd: String,
profile: Option<String>, profile: Option<String>,
directory: Option<String>, directory: Option<String>,
channel: Option<JavaScriptChannelId>, channel: JavaScriptChannelId,
) -> Result<()> { ) -> Result<()> {
check_page(&page)?;
let root = current_root(&workspace, window.label())?; let root = current_root(&workspace, window.label())?;
if root.to_string_lossy() != cwd { if root.to_string_lossy() != cwd {
return Err(Error::new("workspace changed before the terminal started")); return Err(Error::new("workspace changed before the terminal started"));
} }
let owner = window.label().to_owned(); let owner = window.label().to_owned();
// A session with a channel sends no `pty-data` or `pty-exit` events. let output = ChannelOutput(channel.channel_on(webview));
let channel = channel.map(|channel| channel.channel_on(webview)); let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await? tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
} }
#[allow(clippy::too_many_arguments)] struct OpenRequest {
fn open(
app: AppHandle,
owner: String, owner: String,
root: PathBuf, page: String,
id: String, id: String,
cols: u16, cols: u16,
rows: u16, rows: u16,
profile: Option<String>, profile: Option<String>,
directory: Option<String>, directory: PathBuf,
channel: Option<Channel<InvokeResponseBody>>, }
) -> Result<()> {
/// Apply the page rule and start the shell under one lock, so two opens cannot race.
fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> {
let pty = app.state::<PtyState>(); let pty = app.state::<PtyState>();
let (left, started) = {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if guard.contains_key(&id) { let left = enter_page(&mut guard, &request.owner, &request.page)?;
return Err(Error::new("terminal already exists")); (left, start(&mut guard, &request))
} };
let directory = directory.map(PathBuf::from).unwrap_or(root); // A reload left these sessions. Stop their shells outside the lock.
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); } drop(left);
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?; let (serial, reader, mut child) = started?;
guard.insert(id.clone(), session);
drop(guard);
let (exit_tx, exit_rx) = std::sync::mpsc::channel(); let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let wait_app = app.clone(); let wait_app = app.clone();
let wait_id = id.clone(); let wait_id = request.id;
thread::spawn(move || { thread::spawn(move || {
let code = child.wait().ok().map(|status| status.exit_code()); let code = child.wait().ok().map(|status| status.exit_code());
// Close ConPTY after the shell exits so the output reader reaches EOF. // Close ConPTY after the shell exits so the output reader reaches EOF.
// A later session can use the same ID, so remove only this session.
let session = wait_app let session = wait_app
.state::<PtyState>() .state::<PtyState>()
.inner .inner
.lock() .lock()
.ok() .ok()
.and_then(|mut sessions| sessions.remove(&wait_id)); .and_then(|mut sessions| match sessions.open.get(&wait_id) {
Some(session) if session.serial == serial => sessions.open.remove(&wait_id),
_ => None,
});
drop(session); drop(session);
let _ = exit_tx.send(code); let _ = exit_tx.send(code);
}); });
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id })); let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
thread::spawn(move || pump(reader, exit_rx, output.as_ref())); thread::spawn(move || read_chunks(reader, chunk_tx));
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
Ok(()) Ok(())
} }
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe, type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
/// and the write then waits. The Terminal plugin waits for each write before the next one.
#[tauri::command] /// Start the shell and insert its session. The caller holds the lock.
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> { fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await? if sessions.open.contains_key(&request.id) {
return Err(Error::new("terminal already exists"));
}
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
let serial = session.serial;
sessions.open.insert(request.id.clone(), session);
Ok((serial, reader, child))
} }
fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> { /// Find a session of the window `owner`. A session of another window gives the same error
/// as a missing session.
fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> {
sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN))
}
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
/// and the write then waits. The Terminal feature waits for each write before the next one.
#[tauri::command]
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &owner, &id, &data)).await?
}
fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
let writer = { let writer = {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?; owned(&guard, owner, id)?.writer.clone()
session.writer.clone()
}; };
// Other terminals stay usable while this write waits. // Other terminals stay usable while this write waits.
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?; let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
@@ -366,10 +471,13 @@ fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
} }
#[tauri::command] #[tauri::command]
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Result<()> { pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
resize(&pty, window.label(), &id, cols, rows)
}
fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?; owned(&guard, owner, id)?
session
.master .master
.resize(PtySize { .resize(PtySize {
rows: rows.max(2), rows: rows.max(2),
@@ -382,19 +490,34 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Res
} }
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output. /// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
/// A missing session and a session of another window are not an error. Neither one closes.
#[tauri::command] #[tauri::command]
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> { pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || { tauri::async_runtime::spawn_blocking(move || {
let pty = app.state::<PtyState>(); let session = close(&app.state::<PtyState>(), &owner, &id)?;
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.remove(&id);
drop(guard);
drop(session); drop(session);
Ok(()) Ok(())
}) })
.await? .await?
} }
/// Remove a session of the window `owner` under the lock. The caller stops it outside the lock.
fn close(pty: &PtyState, owner: &str, id: &str) -> Result<Option<OpenPty>> {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if owned(&guard, owner, id).is_err() {
return Ok(None);
}
Ok(guard.open.remove(id))
}
/// The number of open terminals of all windows. The Settings window asks before Terminal
/// goes off when shells run.
#[tauri::command]
pub fn pty_running(pty: State<PtyState>) -> Result<usize> {
running(&pty)
}
#[tauri::command] #[tauri::command]
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> { pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
let root = current_root(&workspace, window.label())?; let root = current_root(&workspace, window.label())?;
@@ -436,28 +559,111 @@ mod tests {
use std::sync::Arc; use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// Records the window events that a session would send. #[derive(Debug, PartialEq)]
struct FakeEvents(Arc<Mutex<Vec<String>>>); enum Sent {
impl PtyOutput for FakeEvents { Data(Vec<u8>),
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); } Exit(Option<u32>),
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
} }
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) { /// Records the messages that a session sends.
#[derive(Clone, Default)]
struct Recorder(Arc<Mutex<Vec<Sent>>>);
impl PtyOutput for Recorder {
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); }
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(Sent::Exit(code)); }
}
impl Recorder {
fn take(&self) -> Vec<Sent> { std::mem::take(&mut *self.0.lock().unwrap()) }
}
type Pump = (std::sync::mpsc::Sender<Vec<u8>>, std::sync::mpsc::Sender<Option<u32>>, Recorder, thread::JoinHandle<()>);
/// Run the batch loop on its own thread. The test sends the chunks and the exit status.
fn start_pump(max_bytes: usize, wait: Duration) -> Pump {
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
let (exit_tx, exit_rx) = std::sync::mpsc::channel(); let (exit_tx, exit_rx) = std::sync::mpsc::channel();
exit_tx.send(Some(3)).unwrap(); let recorder = Recorder::default();
let output = output(channel, move || Box::new(FakeEvents(events))); let output = recorder.clone();
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref()); let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
(chunk_tx, exit_tx, recorder, handle)
}
fn data_sizes(sent: &[Sent]) -> Vec<usize> {
sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect()
} }
#[test] #[test]
fn a_channel_session_sends_raw_bytes_and_no_window_events() { fn small_chunks_within_the_wait_become_one_message() {
let events = Arc::new(Mutex::new(Vec::new())); let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); }
drop(chunks);
exit.send(Some(0)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]);
}
#[test]
fn output_larger_than_the_limit_becomes_several_messages() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
let mut expected: Vec<u8> = Vec::new();
for index in 0..40u8 {
let chunk = vec![index; 4000];
expected.extend(&chunk);
chunks.send(chunk).unwrap();
}
// One chunk larger than the limit goes in parts.
let large = vec![b'x'; BATCH_BYTES + 100];
expected.extend(&large);
chunks.send(large).unwrap();
drop(chunks);
exit.send(None).unwrap();
handle.join().unwrap();
let sent = recorder.take();
let sizes = data_sizes(&sent);
assert!(sizes.len() > 1, "{sizes:?}");
assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}");
let joined: Vec<u8> = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect();
assert_eq!(joined, expected);
assert_eq!(sent.last(), Some(&Sent::Exit(None)));
}
#[test]
fn a_chunk_after_a_pause_goes_in_a_new_message() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20));
chunks.send(b"first".to_vec()).unwrap();
thread::sleep(Duration::from_millis(300));
chunks.send(b"second".to_vec()).unwrap();
drop(chunks);
exit.send(Some(1)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]);
}
#[test]
fn the_exit_comes_after_all_output() {
let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5));
// The exit status is ready before the output ends.
exit.send(Some(9)).unwrap();
for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); }
drop(chunks);
handle.join().unwrap();
let sent = recorder.take();
assert_eq!(data_sizes(&sent).iter().sum::<usize>(), 100);
assert!(data_sizes(&sent).iter().all(|&size| size <= 16));
assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1));
assert_eq!(sent.last(), Some(&Sent::Exit(Some(9))));
}
#[test]
fn a_channel_session_sends_raw_bytes_then_the_json_exit() {
let received = Arc::new(Mutex::new(Vec::new())); let received = Arc::new(Mutex::new(Vec::new()));
let sink = received.clone(); let sink = received.clone();
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) }); let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
run_pump(Some(channel), events.clone()); let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events"); let (exit_tx, exit_rx) = std::sync::mpsc::channel();
exit_tx.send(Some(3)).unwrap();
read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx);
pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT);
let received = received.lock().unwrap(); let received = received.lock().unwrap();
assert_eq!(received.len(), 2); assert_eq!(received.len(), 2);
match &received[0] { match &received[0] {
@@ -470,11 +676,112 @@ mod tests {
} }
} }
/// Start a real shell for `owner`. A thread reads its output until EOF.
fn shell(owner: &str) -> OpenPty {
let root = std::env::current_dir().unwrap();
let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap();
thread::spawn(move || {
let _ = std::io::copy(&mut reader, &mut std::io::sink());
});
session
}
fn ids(pty: &PtyState) -> Vec<String> {
let mut ids: Vec<String> = pty.inner.lock().unwrap().open.keys().cloned().collect();
ids.sort();
ids
}
#[test] #[test]
fn a_session_without_a_channel_keeps_the_window_events() { fn only_the_owner_window_can_use_a_session() {
let events = Arc::new(Mutex::new(Vec::new())); let pty = PtyState::new();
run_pump(None, events.clone()); pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]); assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "b", "t1").unwrap().is_none());
assert_eq!(ids(&pty), vec!["t1"]);
// A missing session gives the same results.
assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "a", "t2").unwrap().is_none());
write(&pty, "a", "t1", "\r").unwrap();
resize(&pty, "a", "t1", 100, 40).unwrap();
let session = close(&pty, "a", "t1").unwrap();
assert!(session.is_some());
assert!(ids(&pty).is_empty());
drop(session);
}
#[test]
fn a_new_page_closes_the_sessions_of_its_window_only() {
let pty = PtyState::new();
let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page);
// The first page of each window becomes current.
assert!(enter("a", "page-1").unwrap().is_empty());
assert!(enter("b", "page-b").unwrap().is_empty());
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
// A second dock of the same page keeps the sessions.
assert!(enter("a", "page-1").unwrap().is_empty());
assert_eq!(ids(&pty), vec!["a1", "b1"]);
// A reload of window "a" closes its sessions. The session of window "b" stays.
let left = enter("a", "page-2").unwrap();
assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::<Vec<_>>(), vec!["a"]);
drop(left);
assert_eq!(ids(&pty), vec!["b1"]);
// A late open of the old page is refused and closes nothing.
pty.inner.lock().unwrap().open.insert("a2".into(), shell("a"));
assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE));
assert_eq!(ids(&pty), vec!["a2", "b1"]);
// The window forgets its pages when it closes.
pty.close_window("a");
assert_eq!(ids(&pty), vec!["b1"]);
assert!(!pty.inner.lock().unwrap().pages.contains_key("a"));
assert!(enter("a", "page-1").unwrap().is_empty());
pty.close_all();
assert!(ids(&pty).is_empty());
assert!(pty.inner.lock().unwrap().pages.is_empty());
}
#[test]
fn a_window_keeps_a_limited_number_of_retired_pages() {
let mut sessions = Sessions::default();
for index in 0..=RETIRED_PAGES + 4 {
assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty());
}
let pages = &sessions.pages["a"];
assert_eq!(pages.retired.len(), RETIRED_PAGES);
assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4));
assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err());
}
#[test]
fn page_ids_are_checked() {
assert!(check_page("0f3c-9a1b").is_ok());
assert!(check_page(&"a".repeat(64)).is_ok());
for page in ["", "a b", "../page", "page_1", "λ"] {
assert!(check_page(page).is_err(), "{page}");
}
assert!(check_page(&"a".repeat(65)).is_err());
}
#[test]
fn running_counts_the_sessions_of_all_windows() {
let pty = PtyState::new();
assert_eq!(running(&pty).unwrap(), 0);
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
assert_eq!(running(&pty).unwrap(), 2);
pty.close_window("a");
assert_eq!(running(&pty).unwrap(), 1);
pty.close_all();
assert_eq!(running(&pty).unwrap(), 0);
} }
#[test] #[test]
+39
View File
@@ -0,0 +1,39 @@
<script lang="ts">
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
import { onMount } from "svelte";
import { t } from "$lib/i18n";
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
let props: TerminalProps = $props();
let container: HTMLDivElement;
let mounted = $state.raw<TerminalMount>();
let loading = $state(true);
let error = $state("");
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
onMount(() => {
let disposed = false;
ready = terminalInstance().then(instance => {
if (disposed) return undefined;
mounted = instance.mountDock(container, { ...props });
return mounted;
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
return () => {
disposed = true;
const current = mounted;
mounted = undefined;
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
};
});
$effect(() => { mounted?.update({ ...props }); });
/** Run a terminal action. It waits for the first load. */
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
</script>
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
<div class="terminal-host" bind:this={container}></div>
<style>
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
.error { color: var(--rs-error); }
.loading { color: var(--rs-text-dim); }
</style>
+113
View File
@@ -0,0 +1,113 @@
<!--
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
type Profile = { id: string; title: string; kind: string };
const initial = readTerminal();
let settings = $state<TerminalSettings>(initial);
let fontSize = $state<number | undefined>(initial.fontSize);
let scrollback = $state<number | undefined>(initial.scrollback);
let profiles = $state<Profile[]>([]);
let profileNote = $state("");
let message = $state("");
let error = $state("");
let closeMenu = () => {};
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
function read() {
settings = readTerminal();
fontSize = settings.fontSize;
scrollback = settings.scrollback;
}
function save(next: TerminalSettings) {
error = "";
settings = next;
writeTerminal(next).then(() => { message = tr("Changes saved."); })
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
}
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
message = "";
return;
}
save({ ...settings, [key]: value });
}
function profileMenu(event: MouseEvent) {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
}
onMount(() => {
const stop = onTerminalChange(read);
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
else invoke<Profile[]>("pty_profiles").then(found => {
profiles = found;
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
return stop;
});
onDestroy(() => closeMenu());
</script>
<div class="terminal-settings">
<h2>{$t("Terminal")}</h2>
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
<div class="card">
<div class="setting-row">
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
</button>
</div>
<div class="setting-row">
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
</div>
<div class="setting-row">
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
</div>
<div class="setting-row">
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
</div>
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
</div>
<style>
.terminal-settings { min-width: 0; }
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
input[type=number] { width: 96px; }
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
.error { color: var(--rs-error); margin-top: 10px; }
</style>
+11 -1
View File
@@ -4,7 +4,7 @@
import { message, tr } from "../i18n/index.ts"; import { message, tr } from "../i18n/index.ts";
import type { PluginCommand, PluginView } from "../plugins/sdk.ts"; import type { PluginCommand, PluginView } from "../plugins/sdk.ts";
export type FeatureId = "git" | "background"; export type FeatureId = "git" | "background" | "terminal";
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */ /** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
export interface FeatureViewInfo { export interface FeatureViewInfo {
@@ -69,6 +69,16 @@ export const FEATURES: readonly FeatureEntry[] = [
{ id: "pause", title: () => tr("Pause background"), icon: "pause" }, { id: "pause", title: () => tr("Pause background"), icon: "pause" },
], ],
}, },
{
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
defaultOn: true, followsPackage: true,
views: [],
commands: [],
},
]; ];
export function featureEntry(id: FeatureId): FeatureEntry { export function featureEntry(id: FeatureId): FeatureEntry {
+1
View File
@@ -7,6 +7,7 @@ import type { FeatureModule } from "./types.ts";
const imports: Record<FeatureId, () => Promise<FeatureModule>> = { const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
git: () => import("./git/index.ts"), git: () => import("./git/index.ts"),
background: () => import("./background/index.ts"), background: () => import("./background/index.ts"),
terminal: () => import("./terminal/index.ts"),
}; };
const modules = new Map<FeatureId, Promise<FeatureModule>>(); const modules = new Map<FeatureId, Promise<FeatureModule>>();
+15 -3
View File
@@ -1,13 +1,15 @@
// The first start of a version with a new native feature. The switch takes the state of the old plugin package, // The first start of a version with a new native feature. The switch takes the state of the old plugin package,
// or the default of the feature when the feature does not follow its package (`followsPackage`). // or the default of the feature when the feature does not follow its package (`followsPackage`).
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing. // `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`). // The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
// and the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`).
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { readSection, writeSection } from "../settings/store.ts"; import { readSection, writeSection } from "../settings/store.ts";
import { readAppearance } from "../theme/appearance.ts"; import { readAppearance } from "../theme/appearance.ts";
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts"; import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
import { storedSwitches } from "./state.ts"; import { storedSwitches } from "./state.ts";
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts"; import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
/** What the host reports about one old plugin package. */ /** What the host reports about one old plugin package. */
export interface LegacyPlugin { export interface LegacyPlugin {
@@ -42,11 +44,21 @@ const desktopBackground: BackgroundMigrationHost = {
write: writeBackground, write: writeBackground,
}; };
const desktopTerminal: TerminalMigrationHost = {
missing: () => readSection("terminal") === undefined,
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
write: writeTerminal,
};
/** /**
* Give each feature without a stored switch the state of its old package, and make a missing `background` section. * Give each feature without a stored switch the state of its old package, and make a missing `background` or `terminal` section.
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again. * It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
* The `terminal` section needs no package report, so it migrates also then.
*/ */
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground): Promise<FeatureId[]> { export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
terminal: TerminalMigrationHost = desktopTerminal): Promise<FeatureId[]> {
try { await migrateTerminal(terminal); }
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
const current = host.read(); const current = host.read();
const stored = storedSwitches(current); const stored = storedSwitches(current);
const missing = FEATURES.filter(entry => stored[entry.id] === undefined); const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
+3
View File
@@ -68,6 +68,9 @@ export class FeatureSession {
/** Load the module and start the instance now, without a view. Later calls use the same instance. */ /** Load the module and start the instance now, without a view. Later calls use the same instance. */
async start(): Promise<void> { await this.running(); } async start(): Promise<void> { await this.running(); }
/** The instance of this window, for a feature with a surface that is not a view, such as the terminal panel. */
loadInstance(): Promise<FeatureInstance> { return this.running(); }
/** True after the instance started. */ /** True after the instance started. */
get started(): boolean { return this.instance !== undefined; } get started(): boolean { return this.instance !== undefined; }
@@ -0,0 +1,13 @@
<script lang="ts">
// Keeps the panel props as state, so `update` from the host reaches the panel.
import { untrack } from "svelte";
import type { TerminalAction, TerminalProps } from "../terminalHost";
import type { TerminalSessions } from "./sessions";
import TerminalDock from "./TerminalDock.svelte";
let { initial, sessions }: { initial: TerminalProps; sessions: TerminalSessions } = $props();
let dockProps = $state<TerminalProps>(untrack(() => initial));
let dock: TerminalDock;
export function update(value: TerminalProps) { dockProps = value; }
export async function command(action: Exclude<TerminalAction, "toggle">) { await dock.command(action); }
</script>
<TerminalDock bind:this={dock} {...dockProps} {sessions} />
@@ -0,0 +1,290 @@
<script lang="ts">
// The terminal panel: a ribbon, the panes of the active group side by side, and a session rail when more than one session runs.
// A split adds a pane to the group of the active session. Close ends all sessions of the panel, and the next show starts a new one.
import { onMount, tick, untrack } from "svelte";
import { t, tr } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { showActionMenu, type MenuHandle } from "$lib/ui/managedActionMenu";
import type { ActionMenuItem } from "$lib/ui/actionMenu";
import { keys } from "$lib/ui/shortcuts";
import { workspaceRead } from "$lib/workspace/api";
import { TERMINAL_KEYS, type TerminalAction } from "../terminalKeys";
import { onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "../terminalSettings";
import type { TerminalProps } from "../terminalHost";
import { directoryCommand, fileCommand, parseTasks, pickProfile, remember, type ShellProfile, type TerminalControl } from "./model";
import type { TerminalSessions } from "./sessions";
import TerminalPicker from "./TerminalPicker.svelte";
import TerminalPane, { type PaneState } from "./TerminalPane.svelte";
type Session = { id: string; group: string; title: string; state: PaneState; profile: ShellProfile; directory: string; weight: number; command?: string };
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks, onOpenSettings, sessions: shells }:
TerminalProps & { sessions: TerminalSessions } = $props();
let sessions = $state<Session[]>([]);
let profiles = $state<ShellProfile[]>([]);
let settings = $state<TerminalSettings>(readTerminal());
let activeId = $state("");
let loading = $state(true);
let error = $state("");
let railWidth = $state(205);
let picker = $state<Picker | null>(null);
let closing = $state(false);
let restartOnShow = false;
let recentCommands = $state<string[]>([]);
let recentDirectories = $state<string[]>([]);
let menu: MenuHandle | undefined;
let menuAnchor: HTMLElement | undefined;
let profileAnchor: HTMLDivElement;
let moreAnchor: HTMLDivElement;
let panes: HTMLDivElement;
let sequence = 0;
let stopResize: (() => void) | undefined;
let ready: Promise<void> = Promise.resolve();
const controls = new Map<string, TerminalControl>();
const active = $derived(sessions.find(session => session.id === activeId));
const group = $derived(sessions.filter(session => session.group === active?.group));
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
function report(reason: unknown) { error = String(reason); }
function stateLabel(state: PaneState) {
if (state.kind === "exited") return state.code === null ? $t("Exited") : $t("Exited ({code})", { code: state.code });
if (state.kind === "starting") return $t("Starting");
return state.kind === "running" ? $t("Running") : $t("Failed");
}
function defaultProfile() { return pickProfile(profiles, settings.defaultProfile); }
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
if (!profile || closing) return;
const id = crypto.randomUUID();
const next: Session = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: { kind: "starting" }, profile,
directory: split && active ? active.directory : cwd, weight: 1, command };
if (split) for (const member of group) member.weight = 1;
sessions = [...sessions, next]; activeId = id;
recentDirectories = remember(recentDirectories, next.directory);
}
function killSession(id: string) {
const previous = sessions.findIndex(session => session.id === id);
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
sessions = sessions.filter(session => session.id !== id);
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
void tick().then(() => controls.get(activeId)?.focus());
}
async function closeDock() {
if (closing) return;
closing = true;
closeMenu(); picker = null;
try {
await ready;
// Mount the pending panes before their sessions close.
await tick();
const results = await Promise.allSettled(sessions.map(session => shells.close(session.id)));
const failures = results.filter(result => result.status === "rejected");
if (failures.length) throw new Error(failures.map(result => String(result.reason)).join("\n"));
sessions = []; activeId = "";
restartOnShow = true;
onClose();
} catch (reason) { report(reason); }
finally { closing = false; }
}
function select(id: string) { activeId = id; }
function closeMenu() { menu?.close(); menu = undefined; }
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
const same = menu?.open && menuAnchor === anchor;
closeMenu(); if (same) return;
menuAnchor = anchor;
const bounds = anchor.getBoundingClientRect();
menu = showActionMenu({ x: bounds.right - 430, y: bounds.bottom + 4, items, label: name }, shells.signal);
}
function profileMenu() {
showMenu(profileAnchor, [
{ label: tr("New terminal"), icon: "plus", shortcut: keys(TERMINAL_KEYS.new), run: () => addSession() },
{ label: tr("New terminal window"), icon: "external", shortcut: keys(TERMINAL_KEYS.window), run: () => void shells.openWindow().catch(report) },
{ label: tr("Split terminal"), icon: "column", shortcut: keys(TERMINAL_KEYS.split), disabled: !active, run: () => addSession(active?.profile, true) },
{ separator: true },
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? tr("A Node.js REPL with a local inspector. Attach an external debugger to it.") : undefined, run: () => addSession(profile) })),
{ label: tr("Split terminal with profile"), icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
{ separator: true },
{ label: tr("Terminal settings"), icon: "settings", disabled: !onOpenSettings, run: () => onOpenSettings?.() },
{ label: tr("Select the default profile"), icon: "select", run: () => picker = { title: tr("Select the default terminal profile"), items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === defaultProfile()?.id ? tr("Default") : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
{ separator: true },
{ label: tr("Run a task…"), icon: "task", run: () => void runTask() },
{ label: tr("Configure tasks…"), icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
], tr("Terminal profiles"));
}
function persist(next: TerminalSettings) {
settings = { ...next };
void writeTerminal(next).catch(report);
}
async function runFile() {
const target = active;
if (!target || !onRunFile) return;
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
}
function runSelection() {
const text = getSelection();
if (!text) { error = tr("Select text in the editor first."); return; }
controls.get(activeId)?.send(text);
}
function historyPicker(kind: "commands" | "directories") {
const target = active;
if (!target) return;
picker = { title: kind === "commands" ? tr("Run a recent command") : tr("Go to a recent folder"),
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
empty: kind === "commands" ? tr("No commands yet. Shell commands show after the next prompt.") : tr("No folders yet."),
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
}
async function runTask() {
try {
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
picker = { title: tr("Run a task"), items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: tr("No tasks yet. Choose Configure tasks… to add one."), onPick: index => {
const task = tasks[Number(index)];
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
if (!profile) { error = tr("The profile of this task is not installed: {profile}", { profile: task.profile ?? "" }); return; }
addSession(profile, false, task.command, task.label);
} };
} catch (reason) { error = tr("RuneStone cannot read .runestone/tasks.json. Use Configure tasks… to make or change it. {error}", { error: String(reason) }); }
}
function moreMenu() {
showMenu(moreAnchor, [
{ label: tr("Scroll to the previous command"), icon: "up", shortcut: keys(TERMINAL_KEYS.previous), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
{ label: tr("Scroll to the next command"), icon: "down", shortcut: keys(TERMINAL_KEYS.next), disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
{ label: tr("Clear the terminal"), icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
{ label: tr("Run the active file"), icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
{ label: tr("Run selected text"), icon: "select", disabled: !active || !activeFile, run: runSelection },
{ label: tr("Start dictation"), icon: "comment", disabled: !active, title: tr("Start Windows voice typing in the focused terminal"), run: () => { controls.get(activeId)?.focus(); void shells.dictation().catch(report); } },
{ separator: true },
{ label: tr("Go to a recent folder…"), icon: "external", shortcut: keys(TERMINAL_KEYS.directories), disabled: !active, run: () => historyPicker("directories") },
{ label: tr("Run a recent command…"), icon: "task", shortcut: keys(TERMINAL_KEYS.commands), disabled: !active, run: () => historyPicker("commands") },
], tr("Terminal actions"));
}
export async function command(action: Exclude<TerminalAction, "toggle">) {
await ready;
if (action === "new") addSession();
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
else if (action === "window") void shells.openWindow().catch(report);
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
else historyPicker(action);
}
function beginResize(event: PointerEvent, update: (x: number) => void) {
if (event.button !== 0) return;
event.preventDefault(); stopResize?.();
const move = (event: PointerEvent) => update(event.clientX);
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
const stop = () => stopResize?.();
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
}
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
function resizeSplit(event: PointerEvent, session: Session) {
const index = group.indexOf(session), previous = group[index - 1];
if (!previous) return;
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
}
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
onMount(() => {
let disposed = false;
ready = shells.profiles().then(found => {
if (disposed) return;
profiles = found;
if (profiles.length) addSession(); else error = tr("RuneStone found no supported shells on PATH.");
}).catch(report).finally(() => loading = false);
// Settings → Terminal and other windows change the settings. Open sessions take the new font, scrollback, and cursor.
const stopSettings = onTerminalChange(() => { settings = readTerminal(); });
return () => { disposed = true; stopSettings(); closeMenu(); stopResize?.(); };
});
$effect(() => { if (!visible) { closeMenu(); picker = null; } });
$effect(() => {
if (visible) untrack(() => {
if (restartOnShow) { restartOnShow = false; addSession(); }
});
});
</script>
<div class="dock" style:--rail="{railWidth}px">
<header class="ribbon">
<span class="label" title={cwd}>{$t("Terminal")}</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
<div class="actions">
{#if sessions.length === 1 && active}<span class="single-session" title={`${active.title} · ${stateLabel(active.state)}`}>{active.profile.title}</span>{/if}
<IconButton icon="plus" label={$t("New terminal")} disabled={loading || !profiles.length} onclick={() => addSession()} />
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label={$t("Terminal profiles and tasks")} disabled={loading} onclick={profileMenu} /></div>
<IconButton icon="split" label={$t("Split terminal ({shortcut})", { shortcut: keys(TERMINAL_KEYS.split) })} disabled={!active} onclick={() => addSession(active?.profile, true)} />
<div bind:this={moreAnchor}><IconButton icon="more" label={$t("More terminal actions")} onclick={moreMenu} /></div>
<IconButton icon="trash" label={$t("Kill terminal")} disabled={!active} onclick={() => killSession(activeId)} />
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? $t("Restore panel") : $t("Maximize panel")} onclick={onMaximize} />{/if}
<IconButton icon="close" label={standalone ? $t("Close terminal window") : $t("Close terminal (end all sessions)")} disabled={closing} onclick={() => void closeDock()} />
</div>
</header>
{#if error}<div class="error" role="alert"><span>{error}</span><IconButton icon="close" label={$t("Dismiss the terminal error")} onclick={() => error = ""} /></div>{/if}
<div class="body">
<div class="panes" bind:this={panes}>
{#each sessions as session (session.id)}
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings} sessions={shells}
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
onState={state => { session.state = state; if (state.kind === "running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
onCommand={command => recentCommands = remember(recentCommands, command)}
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
{#if session.group === active?.group && group.indexOf(session) > 0}
<div class="split-gutter" role="separator" aria-label={$t("Resize split terminals")} aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
{/if}
</div>
{/each}
{#if !sessions.length}<div class="empty"><p>{loading ? $t("Finding the installed shells…") : $t("No terminal sessions.")}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>{$t("Start a terminal")}</button></div>{/if}
</div>
{#if sessions.length > 1}
<div class="gutter" role="separator" aria-orientation="vertical" aria-label={$t("Resize terminal list")} onpointerdown={resizeRail}></div>
<nav class="rail" aria-label={$t("Terminal list")}>
{#each sessions as session (session.id)}
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${stateLabel(session.state)} · ${session.directory}`} onclick={() => select(session.id)}
onkeydown={event => {
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{stateLabel(session.state)}</small></span></button>
<div class="row-actions">
<IconButton icon="split" label={$t("Split {title}", { title: session.title })} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
<IconButton icon="trash" label={$t("Kill {title} ({shortcut})", { title: session.title, shortcut: keys("Delete") })} onclick={() => killSession(session.id)} />
</div>
</div>
{/each}
</nav>
{/if}
</div>
</div>
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
<style>
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; container-type: inline-size; }
.ribbon { display: flex; flex-wrap: wrap; align-items: center; gap: 0 10px; flex: 0 0 auto; min-height: var(--rs-titlebar-height, 36px); padding: 0 8px; background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
.label { font-size: 13px; color: var(--rs-text-strong); }
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
.actions { flex-wrap: wrap; max-width: 100%; }
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
.body { display: flex; flex: 1; min-height: 0; }
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
.pane.shown { visibility: visible; }
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
.gutter { flex: 0 0 4px; cursor: col-resize; }
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); background: var(--rs-image-sidebar-bg, color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent)); }
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; border-radius: var(--rs-control-radius); }
.item.grouped { border-left-color: var(--rs-border); }
.item.active { background: var(--rs-image-control-hover-bg, color-mix(in srgb, var(--rs-bg-active) 92%, transparent)); border-left-color: var(--rs-accent); }
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; padding: 5px; }
.shell-icon { color: var(--rs-text-dim); }
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
.row-actions { visibility: hidden; }
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
.error { padding: 3px 4px 3px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
.error span { flex: 1; }
.empty button { background: var(--rs-bg-active); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 4px 8px; }
.empty { height: 100%; padding: 20px; color: var(--rs-text-dim); background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent)); }
@container (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
</style>
@@ -0,0 +1,259 @@
<script lang="ts" module>
/** The state of one shell. `code` is the exit code, when the shell gave one. */
export type PaneState = { kind: "starting" | "running" | "failed" } | { kind: "exited"; code: number | null };
</script>
<script lang="ts">
// One xterm and its shell. Input before the shell starts waits in a buffer, xterm's answers to start-up queries included.
// OSC 133 marks the prompts for command scrolling. OSC 633 reports the folder and the last command (src-tauri/src/pty.rs).
import { FitAddon } from "@xterm/addon-fit";
import { Terminal, type IMarker } from "@xterm/xterm";
import { onMount } from "svelte";
import { tr } from "$lib/i18n";
import { terminalShortcut } from "../terminalKeys";
import type { TerminalSettings } from "../terminalSettings";
import { terminalTypography } from "./typography";
import { terminalTheme, watchTerminalAppearance } from "./theme";
import type { ShellProfile, TerminalControl } from "./model";
import type { TerminalSessions } from "./sessions";
type Props = {
id: string;
cwd: string;
active: boolean;
focused: boolean;
profile: ShellProfile;
directory: string;
settings: TerminalSettings;
sessions: TerminalSessions;
onFocus: () => void;
onControl: (control: TerminalControl | null) => void;
onCommand: (command: string) => void;
onDirectory: (directory: string) => void;
onState: (state: PaneState) => void;
};
let { id, cwd, active, focused, profile, directory, settings, sessions, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let focusTerminal: (() => void) | undefined = $state();
let instance = $state.raw<Terminal>();
let resizeTerminal: (() => void) | undefined;
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
$effect(() => {
if (instance) {
instance.options.fontSize = settings.fontSize;
instance.options.scrollback = settings.scrollback;
instance.options.cursorBlink = settings.cursorBlink;
requestAnimationFrame(() => resizeTerminal?.());
}
});
onMount(() => {
if (!host) return;
const theme = terminalTheme(host);
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
const term = new Terminal({
scrollback: settings.scrollback,
...terminalTypography(host),
fontSize: settings.fontSize,
cursorBlink: settings.cursorBlink,
allowProposedApi: true,
allowTransparency: true,
theme,
});
const fit = new FitAddon();
term.loadAddon(fit);
term.open(host);
instance = term;
let disposed = false;
let opened = false;
let exited = false;
const pendingInput: string[] = [];
let writes = Promise.resolve();
const fail = (reason: unknown) => {
if (!disposed) term.writeln(`\r\n${String(reason)}`);
};
let selectionRevision = 0;
const selection = term.onSelectionChange(() => { selectionRevision++; });
const copySelection = (clearAfterCopy = false) => {
const text = term.getSelection();
if (!text) return;
const revision = selectionRevision;
void navigator.clipboard.writeText(text).then(() => {
if (clearAfterCopy && !disposed && selectionRevision === revision) term.clearSelection();
}).catch(fail);
};
const copyOnRightClick = (event: MouseEvent) => {
if (!term.hasSelection()) return;
event.preventDefault();
event.stopPropagation();
copySelection(true);
};
// Copy the selected text before xterm prepares its own context menu.
host.addEventListener("contextmenu", copyOnRightClick, true);
term.attachCustomKeyEventHandler(event => {
const copy = (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "c";
if (copy && (term.hasSelection() || event.shiftKey)) {
if (event.type === "keydown") {
event.preventDefault();
copySelection();
}
return false;
}
return !terminalShortcut(event);
});
const resize = () => {
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
fit.fit();
if (opened && !exited) void sessions.resize(id, term.cols, term.rows).catch(fail);
};
const stopAppearance = watchTerminalAppearance(host, () => {
if (disposed || !host) return;
const theme = terminalTheme(host);
if (host.style.getPropertyValue("--rs-terminal-selection") !== theme.selectionBackground) {
host.style.setProperty("--rs-terminal-selection", theme.selectionBackground!);
}
term.options.theme = theme;
Object.assign(term.options, terminalTypography(host));
resize();
});
resizeTerminal = resize;
focusTerminal = () => { resize(); term.focus(); };
const send = (data: string) => {
if (exited || disposed) return;
if (!opened) { pendingInput.push(data); return; }
writes = writes.then(() => sessions.write(id, data)).catch(fail);
};
const onData = term.onData(send);
let markers: IMarker[] = [];
let prompt: { marker: IMarker; column: number } | undefined;
const promptParser = term.parser.registerOscHandler(133, data => {
if (data === "A") {
const marker = term.registerMarker(0);
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
}
if (data === "B") {
prompt?.marker.dispose();
const marker = term.registerMarker(0);
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
}
return true;
});
const integration = term.parser.registerOscHandler(633, data => {
const separator = data.indexOf(";");
const type = data.slice(0, separator), value = data.slice(separator + 1);
try {
if (type === "Cwd") onDirectory(value);
if (type === "RSCwd" || type === "RSCommand") {
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
}
} catch { /* Ignore shell integration output that is not valid. */ }
return true;
});
// Command Prompt has no history hook, so the pane reads the command line from the screen at Enter.
const keys = term.onKey(({ domEvent }) => {
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
const buffer = term.buffer.active;
let command = "";
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
}
if (command.trim()) onCommand(command);
prompt.marker.dispose(); prompt = undefined;
});
onControl({
focus: () => { resize(); term.focus(); },
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
scrollCommand: direction => {
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
const current = term.buffer.active.viewportY;
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
},
send: (text, execute = true) => {
if (exited) return;
term.paste(text.replace(/\r?\n/g, "\r"));
if (execute) send("\r");
term.focus();
},
});
const start = async () => {
try {
resize();
// The host sends output from the start, because shells and agents can print at once.
await sessions.open(id, {
cwd, cols: term.cols, rows: term.rows, profile: profile.id, directory,
onData: data => { if (!disposed) term.write(data); },
onExit: code => {
if (disposed) return;
exited = true;
onState({ kind: "exited", code });
term.writeln(`\r\n[${code === null ? tr("Process exited") : tr("Process exited with code {code}", { code })}]`);
},
});
opened = true;
if (disposed) { await sessions.close(id); return; }
for (const data of pendingInput.splice(0)) {
writes = writes.then(() => sessions.write(id, data)).catch(fail);
}
if (!exited) onState({ kind: "running" });
resize();
if (active && focused) term.focus();
} catch (reason) {
fail(reason);
if (!disposed) onState({ kind: "failed" });
}
};
void start();
const observer = new ResizeObserver(resize);
observer.observe(host);
return () => {
disposed = true;
focusTerminal = undefined;
instance = undefined;
resizeTerminal = undefined;
onControl(null);
observer.disconnect();
stopAppearance();
onData.dispose();
selection.dispose();
host?.removeEventListener("contextmenu", copyOnRightClick, true);
promptParser.dispose(); integration.dispose(); keys.dispose();
void sessions.close(id).catch(() => {});
term.dispose();
};
});
</script>
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
<style>
.term {
height: 100%;
min-height: 0;
padding: 4px;
background: var(--rs-image-editor-bg, color-mix(in srgb, var(--rs-bg) 90%, transparent));
}
.term :global(.xterm),
.term :global(.xterm-viewport) {
height: 100%;
}
.term :global(.xterm-viewport) {
/* Whole terminal rows can leave a gap above the bottom edge. */
background-color: transparent;
}
/* The DOM renderer blends the selection on its transparent black base first. */
.term :global(.xterm .xterm-selection div) {
background-color: var(--rs-terminal-selection) !important;
}
/* xterm marks selected glyphs as top decorations with opaque fills. */
.term :global(.xterm-rows .xterm-decoration-top) {
background-color: transparent !important;
}
</style>
@@ -0,0 +1,46 @@
<script lang="ts">
// A filter list for tasks, recent commands, recent folders, and profiles. It uses the shared picker rows of menu.css.
import { onMount, tick } from "svelte";
import { t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { keys } from "$lib/ui/shortcuts";
let { title, items, onPick, onClose, empty }: {
title: string; items: { label: string; detail?: string; value: string }[];
onPick: (value: string) => void; onClose: () => void; empty?: string;
} = $props();
let query = $state("");
let selected = $state(0);
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
const listId = $props.id();
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
onMount(() => { dialog.showModal(); input.focus(); });
</script>
<dialog class="rs-picker" bind:this={dialog} oncancel={onClose} aria-label={title}>
<header>{title}<IconButton icon="close" label={$t("Close the list")} onclick={onClose} /></header>
<input bind:this={input} bind:value={query} role="combobox" aria-expanded="true" aria-controls={listId} aria-activedescendant={matches[selected] ? `${listId}-${selected}` : undefined} aria-autocomplete="list" aria-label={title} placeholder={$t("Type to filter…")} oninput={() => selected = 0} onkeydown={event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
}
if (event.key === "Enter") { event.preventDefault(); void pick(matches[selected]?.value); }
}} />
<div class="results" id={listId} role="listbox" aria-label={$t("{title}: choices", { title })}>
{#each matches as item, index}
<button class="rs-picker-row" id={`${listId}-${index}`} role="option" aria-selected={index === selected} data-index={index} onclick={() => void pick(item.value)}><span class="entry-label">{item.label}{#if item.detail}<small class="rs-picker-hint">{item.detail}</small>{/if}</span></button>
{/each}
{#if !matches.length}<p>{query ? $t("No entries match the filter.") : empty ?? $t("No entries yet.")}</p>{/if}
</div>
<footer>{$t("{up} {down} select · {enter} choose · {escape} close", { up: "↑", down: "↓", enter: keys("Enter"), escape: keys("Escape") })}</footer>
</dialog>
<style>
dialog { margin-top: 12vh; width: min(640px, 85vw); }
dialog::backdrop { background: var(--rs-scrim); }
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
input { width: 100%; box-sizing: border-box; padding: var(--rs-menu-row-padding); min-height: var(--rs-menu-row-height); background: var(--rs-bg); color: var(--rs-text-strong); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
.results { max-height: 50vh; overflow: auto; }
.entry-label { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
footer, p { color: var(--rs-text-dim); }
footer { padding: var(--rs-menu-row-padding); border-top: 1px solid var(--rs-border); font-size: var(--rs-settings-description-size); }
</style>
+36
View File
@@ -0,0 +1,36 @@
// The Terminal feature. `loader.ts` imports this module at the first use of a terminal panel:
// the Terminal button, a terminal shortcut, or a terminal window. Settings → Terminal does not load it.
// It starts shells through the `pty_*` commands of src-tauri/src/pty.rs (`transport.ts`).
import { flushSync, mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import type { TerminalInstance, TerminalMount } from "../terminalHost.ts";
import type { FeatureContext } from "../types.ts";
import { TerminalSessions } from "./sessions.ts";
import { desktopTransport } from "./transport.ts";
import TerminalBridge from "./TerminalBridge.svelte";
// The xterm styles load with the feature chunk.
import "@xterm/xterm/css/xterm.css";
export function start(_context: FeatureContext): TerminalInstance {
const sessions = new TerminalSessions(desktopTransport);
const docks = new Set<() => Promise<void>>();
return {
mount() { throw new Error(tr("This view is unavailable.")); },
mountDock(element, props): TerminalMount {
if (sessions.stopped) throw new Error(tr("This feature is off."));
const instance = mount(TerminalBridge, { target: element, props: { initial: props, sessions } });
flushSync();
let stopping: Promise<void> | undefined;
const dispose = () => stopping ??= unmount(instance).then(() => { docks.delete(dispose); });
docks.add(dispose);
return { update: value => instance.update(value), command: action => instance.command(action), dispose };
},
/** Remove the panels, then stop the shells that are left. Panels close their own sessions when they unmount. */
async dispose() {
const results = await Promise.allSettled([...docks].map(dispose => dispose()));
await sessions.closeAll();
const errors = results.filter(result => result.status === "rejected");
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
},
};
}
+63
View File
@@ -0,0 +1,63 @@
// Shell commands, tasks, and history of the terminal panel. Plain functions, so the unit tests run them without a DOM.
import { tr } from "../../i18n/index.ts";
export type ShellKind = "powershell" | "bash" | "cmd" | "node";
/** A shell that `pty_profiles` found (src-tauri/src/pty.rs). */
export type ShellProfile = { id: string; title: string; kind: ShellKind };
/** The controls of one terminal pane for the panel. */
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
/** One task of `.runestone/tasks.json`. */
export type TerminalTask = { label: string; command: string; profile?: string };
/** The profile of a new terminal: the default profile when it exists, then the first shell that is not Node.js. */
export function pickProfile(profiles: readonly ShellProfile[], preferred: string): ShellProfile | undefined {
return profiles.find(profile => profile.id === preferred) || profiles.find(profile => profile.kind !== "node") || profiles[0];
}
/** Quote a path for a shell, so that the shell does not expand it. */
export function quoteShell(value: string, kind: ShellKind): string {
if (/[\r\n\0]/.test(value)) throw new Error(tr("A path cannot contain line breaks or null characters."));
if (kind === "cmd") {
// Command Prompt expands % and ! also between quotes. Refuse the path instead of running another path.
if (/["%!]/.test(value)) throw new Error(tr("Use PowerShell for a path with quotes, % or !."));
return `"${value}"`;
}
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
return `'${value.replaceAll("'", "''")}'`;
}
/** The command that goes to a folder in a shell. */
export function directoryCommand(path: string, kind: ShellKind): string {
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
}
/** The command that runs a file in a shell. The file extension selects the program. */
export function fileCommand(path: string, kind: ShellKind): string {
if (kind === "node") throw new Error(tr("Select a shell terminal to run files. The debug terminal is a Node.js REPL."));
const ext = path.split(".").pop()?.toLowerCase();
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
if (runner === null) throw new Error(tr("RuneStone cannot run this file type. Use Run selected text, or add a task."));
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
}
/** The tasks of `.runestone/tasks.json`. Each task must be valid before the panel offers one. */
export function parseTasks(text: string): TerminalTask[] {
const value = JSON.parse(text);
if (!Array.isArray(value?.tasks)) throw new Error(tr("The tasks file needs a \"tasks\" array."));
return value.tasks.map((task: unknown) => {
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|| ("profile" in task && typeof task.profile !== "string")) throw new Error(tr("Each task needs a label, a command, and an optional profile ID."));
return task as TerminalTask;
});
}
/** Put a value first in a history list without duplicates. The list keeps 100 values. */
export function remember(items: string[], value: string): string[] {
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
}
+112
View File
@@ -0,0 +1,112 @@
// The shell sessions of one Terminal instance. The panes call this layer, and this layer calls the host (`transport.ts`).
// A close waits for the start of its shell, so a close cannot leave a late shell running.
// `closeAll` runs when Terminal goes off or the window closes the feature.
import { tr } from "../../i18n/index.ts";
import type { ShellProfile } from "./model.ts";
/** What a pane asks for when it starts a shell. `id` is the pane ID. The host uses it as the session ID. */
export interface PtyRequest { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }
/** The host commands of the terminal (`pty_*` in src-tauri/src/pty.rs). Tests give a fake transport. */
export interface PtyTransport {
/** Start a shell. `onData` gets the raw output bytes and `onExit` the exit code, from the start on. */
open(request: PtyRequest, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
write(id: string, data: string): Promise<void>;
resize(id: string, cols: number, rows: number): Promise<void>;
close(id: string): Promise<void>;
profiles(): Promise<ShellProfile[]>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
export interface OpenOptions extends Omit<PtyRequest, "id"> {
/** Raw output. A UTF-8 character can be split between two calls. */
onData(data: Uint8Array): void;
onExit?(code: number | null): void;
}
export class TerminalSessions {
private readonly transport: PtyTransport;
private readonly controller = new AbortController();
/** The sessions whose shell started and did not exit. */
private readonly live = new Set<string>();
private readonly opening = new Map<string, Promise<void>>();
private readonly closing = new Map<string, Promise<void>>();
/** Pane IDs that closed. A closed ID cannot start again. */
private readonly closed = new Set<string>();
constructor(transport: PtyTransport) { this.transport = transport; }
/** Aborts when the instance stops. Menus of the panel close then. */
get signal(): AbortSignal { return this.controller.signal; }
get stopped(): boolean { return this.controller.signal.aborted; }
private check() { if (this.stopped) throw new Error(tr("This feature is off.")); }
/** Start a shell for pane `id`. */
open(id: string, options: OpenOptions): Promise<void> {
try {
this.check();
if (this.closed.has(id)) throw new Error(tr("This terminal is closed."));
if (this.live.has(id) || this.opening.has(id)) throw new Error(tr("This terminal is already running."));
} catch (reason) { return Promise.reject(reason); }
let exited = false;
const active = () => !this.closed.has(id) && !this.stopped;
const { onData, onExit, ...request } = options;
const pending = Promise.resolve().then(() => this.transport.open({ id, ...request },
data => { if (active()) onData(data); },
code => {
if (exited) return;
exited = true;
this.live.delete(id);
if (active()) onExit?.(code);
})).then(() => { if (!exited) this.live.add(id); });
this.opening.set(id, pending);
void pending.finally(() => this.opening.delete(id)).catch(() => {});
return pending;
}
private session(id: string) {
this.check();
if (!this.live.has(id)) throw new Error(tr("This terminal is not running."));
}
async write(id: string, data: string): Promise<void> { this.session(id); await this.transport.write(id, data); }
async resize(id: string, cols: number, rows: number): Promise<void> { this.session(id); await this.transport.resize(id, cols, rows); }
/** Stop the shell of pane `id`. Later calls return the same promise until the close ends. */
close(id: string): Promise<void> {
this.closed.add(id);
const pending = this.closing.get(id);
if (pending) return pending;
if (!this.live.has(id) && !this.opening.has(id)) return Promise.resolve();
const close = Promise.resolve(this.opening.get(id)).catch(() => {})
.then(() => this.live.has(id) ? this.transport.close(id) : undefined)
.then(() => { this.live.delete(id); })
.finally(() => this.closing.delete(id));
this.closing.set(id, close);
return close;
}
profiles(): Promise<ShellProfile[]> {
try { this.check(); } catch (reason) { return Promise.reject(reason); }
return this.transport.profiles();
}
openWindow(): Promise<void> {
try { this.check(); } catch (reason) { return Promise.reject(reason); }
return this.transport.openWindow();
}
dictation(): Promise<void> {
try { this.check(); } catch (reason) { return Promise.reject(reason); }
return this.transport.dictation();
}
/** Stop all sessions. Starts that are in progress finish first, then close. Later opens fail. */
async closeAll(): Promise<void> {
this.controller.abort();
await Promise.allSettled([...this.opening.values()]);
const results = await Promise.allSettled([...this.live, ...this.closing.keys()].map(id => this.close(id)));
const errors = results.filter(result => result.status === "rejected");
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
}
}
+77
View File
@@ -0,0 +1,77 @@
// The terminal colors come from the theme tokens. The 16 ANSI colors use the `--rs-ansi-*` tokens of
// src/lib/theme/roles.ts, so the theme editor and custom themes change them. xterm needs hex colors.
import type { ITheme } from "@xterm/xterm";
import { ANSI_COLORS } from "../../theme/roles.ts";
/** The highest alpha of the selection, so the selected text stays readable on every background. */
export const SELECTION_ALPHA = Math.floor(255 * 0.65);
type Key = Exclude<keyof ITheme, "extendedAnsi" | "background">;
const capitalize = (name: string) => name[0].toUpperCase() + name.slice(1);
/** The token of each xterm color, and the highest alpha of the color when it has one. */
export const TERMINAL_TOKENS: readonly { key: Key; token: string; maxAlpha?: number }[] = [
{ key: "foreground", token: "var(--rs-text)" },
{ key: "cursor", token: "var(--rs-accent)" },
{ key: "cursorAccent", token: "var(--rs-bg)" },
{ key: "selectionBackground", token: "var(--rs-selection)", maxAlpha: SELECTION_ALPHA },
{ key: "selectionForeground", token: "var(--rs-selection-text, var(--rs-text))" },
...ANSI_COLORS.map(color => ({ key: color as Key, token: `var(--rs-ansi-${color})` })),
...ANSI_COLORS.map(color => ({ key: `bright${capitalize(color)}` as Key, token: `var(--rs-ansi-bright-${color})` })),
];
/** The xterm theme. `resolve` turns a CSS color into a hex color, with the alpha capped at `maxAlpha`. The background is transparent. */
export function terminalColors(resolve: (css: string, maxAlpha: number) => string): ITheme {
const theme: ITheme = { background: "#00000000" };
for (const { key, token, maxAlpha = 255 } of TERMINAL_TOKENS) theme[key] = resolve(token, maxAlpha);
return theme;
}
/** The xterm theme for the tokens that apply to `element`. */
export function terminalTheme(element: HTMLElement): ITheme {
const probe = document.createElement("span");
probe.style.display = "none";
element.append(probe);
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1;
const context = canvas.getContext("2d", { willReadFrequently: true })!;
try {
return terminalColors((value, maxAlpha) => {
probe.style.color = value;
context.clearRect(0, 0, 1, 1);
const resolved = getComputedStyle(probe).color;
context.fillStyle = resolved;
context.fillRect(0, 0, 1, 1);
const alpha = context.getImageData(0, 0, 1, 1).data[3];
if (maxAlpha < 255) {
// Paint the color opaque, so premultiplied alpha does not change the hue.
context.fillStyle = `rgb(from ${resolved} r g b / 1)`;
context.fillRect(0, 0, 1, 1);
}
const channels = [...context.getImageData(0, 0, 1, 1).data];
channels[3] = Math.min(alpha, maxAlpha);
return "#" + channels.map(byte => byte.toString(16).padStart(2, "0")).join("");
});
} finally {
probe.remove();
}
}
/**
* Run `update` in the next frame after a theme change: the `runestone-theme-changed` event of `applyAppearance`,
* or a change of a class, style, or theme attribute of `element` or its parents. Returns the function that stops it.
*/
export function watchTerminalAppearance(element: HTMLElement, update: () => void): () => void {
let frame = 0;
const queue = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(update);
};
const observer = new MutationObserver(queue);
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
observer.observe(node, { attributes: true, attributeFilter: ["class", "style", "data-theme", "data-palette"] });
}
observer.observe(document.head, { childList: true, subtree: true, characterData: true });
window.addEventListener("runestone-theme-changed", queue);
return () => { observer.disconnect(); window.removeEventListener("runestone-theme-changed", queue); cancelAnimationFrame(frame); };
}
+28
View File
@@ -0,0 +1,28 @@
// The desktop side of the terminal: the `pty_*` commands of src-tauri/src/pty.rs.
// Each shell sends its output over a channel to this webview only. Output arrives as raw bytes (an ArrayBuffer),
// and the exit as `{ exit: code }`. The host checks that each session belongs to the calling window.
import { Channel, invoke } from "@tauri-apps/api/core";
import type { ShellProfile } from "./model.ts";
import type { PtyTransport } from "./sessions.ts";
/**
* The ID of this page load. At the first start in a new page, the host closes the sessions that an earlier page
* of the same window left, for example before a reload. Every panel of this page uses the same ID.
*/
const page = crypto.randomUUID();
export const desktopTransport: PtyTransport = {
open: (request, onData, onExit) => {
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
});
return invoke<void>("pty_open", { ...request, page, channel });
},
write: (id, data) => invoke<void>("pty_write", { id, data }),
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
close: id => invoke<void>("pty_close", { id }),
profiles: () => invoke<ShellProfile[]>("pty_profiles"),
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
dictation: () => invoke<void>("pty_dictation"),
};
+12
View File
@@ -0,0 +1,12 @@
import type { ITerminalOptions } from "@xterm/xterm";
/** The code font of the theme, so the terminal and the code editor use the same font and weight. */
export function terminalTypography(element: HTMLElement): Pick<ITerminalOptions, "fontFamily" | "fontWeight" | "fontWeightBold"> {
const style = getComputedStyle(element);
const weight = Number(style.getPropertyValue("--rs-code-font-weight").trim() || 300);
return {
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
fontWeight: (Number.isFinite(weight) && weight >= 100 && weight <= 900 ? weight : 300) as ITerminalOptions["fontWeight"],
fontWeightBold: 600,
};
}
+2
View File
@@ -0,0 +1,2 @@
// The xterm style sheet. Vite bundles it with the feature chunk. The unit test type check has no Vite types, so it needs this declaration.
declare module "@xterm/xterm/css/xterm.css";
+48
View File
@@ -0,0 +1,48 @@
// The contract between the hosts of the terminal panel (the workbench and the terminal window) and the Terminal feature.
// This file is in the main bundle. It loads no feature code: `terminalInstance` loads the module at first use.
import { featureInstance } from "../plugins/external.ts";
import type { TerminalAction } from "./terminalKeys.ts";
import type { FeatureInstance } from "./types.ts";
export type { TerminalAction } from "./terminalKeys.ts";
/** What the host gives to the terminal panel. */
export interface TerminalProps {
/** The workspace folder. A new terminal starts there. */
cwd: string;
visible: boolean;
maximized?: boolean;
/** True in a terminal window, which has no maximize control. */
standalone?: boolean;
/** The panel closed all its sessions. */
onClose: () => void;
onMaximize?: () => void;
/** True when the active tab is a text file that Run active file can run. */
activeFile?: boolean;
/** Save the active file and return its absolute path, or null. */
onRunFile?: () => Promise<string | null>;
/** The selected text of the editor. */
getSelection?: () => string;
/** Open `.runestone/tasks.json`, and make it first when it does not exist. */
onConfigureTasks?: () => Promise<void>;
/** Open Settings, where Settings → Terminal is. */
onOpenSettings?: () => void;
}
/** One terminal panel in a host element. */
export interface TerminalMount {
update(props: TerminalProps): void;
command(action: Exclude<TerminalAction, "toggle">): Promise<void>;
/** Close the sessions of the panel and remove it. */
dispose(): Promise<void>;
}
/** The instance of the Terminal feature in one window. */
export interface TerminalInstance extends FeatureInstance {
mountDock(element: HTMLElement, props: TerminalProps): TerminalMount;
}
/** Load the Terminal feature if necessary and return its instance in this window. Fails while Terminal is off. */
export async function terminalInstance(): Promise<TerminalInstance> {
return await featureInstance("terminal") as TerminalInstance;
}
+45
View File
@@ -0,0 +1,45 @@
// The shortcuts of the Terminal feature. This file is in the main bundle, because the workbench routes the keys
// and Help lists them while the feature code is not loaded yet.
import { message } from "../i18n/index.ts";
/** The actions of a terminal shortcut. "toggle" shows or hides the terminal panel. */
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
export type TerminalKeyEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">;
/** The terminal action of a key event, or null. Backquote and Digit5 match the physical key on each keyboard layout. */
export function terminalShortcut(event: TerminalKeyEvent): TerminalAction | null {
if (!event.ctrlKey && !event.metaKey) return null;
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
return null;
}
/** The written combination of each action, for menus and Help. `keys()` in `src/lib/ui/shortcuts.ts` gives the label. */
export const TERMINAL_KEYS = {
toggle: "Mod+J",
new: "Mod+Shift+`",
window: "Mod+Shift+Alt+`",
split: "Mod+Shift+5",
previous: "Mod+ArrowUp",
next: "Mod+ArrowDown",
commands: "Mod+Alt+R",
directories: "Mod+G",
} as const satisfies Record<TerminalAction, string>;
/** The Terminal rows of Help. They show only while Terminal is on. */
export const TERMINAL_SHORTCUTS: readonly { label: string; keys: string }[] = [
{ label: message("Show or hide the terminal"), keys: TERMINAL_KEYS.toggle },
{ label: message("New terminal"), keys: TERMINAL_KEYS.new },
{ label: message("New terminal window"), keys: TERMINAL_KEYS.window },
{ label: message("Split terminal"), keys: TERMINAL_KEYS.split },
{ label: message("Scroll to the previous command"), keys: TERMINAL_KEYS.previous },
{ label: message("Scroll to the next command"), keys: TERMINAL_KEYS.next },
{ label: message("Run a recent command"), keys: TERMINAL_KEYS.commands },
{ label: message("Go to a recent folder"), keys: TERMINAL_KEYS.directories },
{ label: message("Copy the selected output"), keys: "Mod+Shift+C" },
];
+76
View File
@@ -0,0 +1,76 @@
// The settings of the Terminal feature: the `terminal` section of the settings file.
// This file is in the main bundle, because Settings → Terminal and the first-start migration need it without xterm.
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
export interface TerminalSettings {
/** The profile of a new terminal. An empty value or an unknown profile selects the first shell that is not Node.js. */
defaultProfile: string;
/** From 9 to 28 pixels. */
fontSize: number;
/** From 100 to 100,000 lines. */
scrollback: number;
cursorBlink: boolean;
}
export const DEFAULT_TERMINAL: Readonly<TerminalSettings> = Object.freeze({ defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true });
export const FONT_SIZE = { min: 9, max: 28 } as const;
export const SCROLLBACK = { min: 100, max: 100000 } as const;
/** The localStorage key of the Terminal plugin. The first start copies it into the `terminal` section and keeps it. */
export const LEGACY_TERMINAL_KEY = "runestone.terminal";
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
const limit = (value: unknown, range: { min: number; max: number }, fallback: number) =>
typeof value === "number" && Number.isFinite(value) ? Math.min(range.max, Math.max(range.min, Math.round(value))) : fallback;
/** Valid settings from any value. Invalid fields take the defaults. */
export function normalizeTerminal(value: unknown): TerminalSettings {
const raw = record(value);
return {
defaultProfile: typeof raw.defaultProfile === "string" ? raw.defaultProfile : DEFAULT_TERMINAL.defaultProfile,
fontSize: limit(raw.fontSize, FONT_SIZE, DEFAULT_TERMINAL.fontSize),
scrollback: limit(raw.scrollback, SCROLLBACK, DEFAULT_TERMINAL.scrollback),
cursorBlink: typeof raw.cursorBlink === "boolean" ? raw.cursorBlink : DEFAULT_TERMINAL.cursorBlink,
};
}
export function readTerminal(): TerminalSettings {
return normalizeTerminal(readSection("terminal"));
}
/** Save the settings. Keys of a newer version stay. */
export function writeTerminal(next: TerminalSettings): Promise<void> {
return writeSection("terminal", { ...record(readSection("terminal")), ...normalizeTerminal(next) });
}
/** Run `listener` after each change of the terminal settings in any window. Returns the function that stops it. */
export function onTerminalChange(listener: () => void): () => void {
return onSettingsChange("terminal", listener);
}
/** The host side of the first-start migration of the `terminal` section. */
export interface TerminalMigrationHost {
/** True when the settings file has no `terminal` section. */
missing(): boolean;
/** The value of the old localStorage key, or null. */
legacy(): string | null;
write(value: TerminalSettings): Promise<void>;
}
/**
* Make the `terminal` section from the localStorage key of the Terminal plugin. The old key stays, so an older version keeps it.
* Without an old key, nothing is written and the defaults apply. Returns the written settings, or null.
*/
export async function migrateTerminal(host: TerminalMigrationHost): Promise<TerminalSettings | null> {
if (!host.missing()) return null;
let raw: string | null;
try { raw = host.legacy(); } catch { return null; }
if (raw === null) return null;
let parsed: unknown;
try { parsed = JSON.parse(raw); } catch { parsed = null; }
const value = normalizeTerminal(parsed);
await host.write(value);
return value;
}
+97
View File
@@ -3563,6 +3563,103 @@ export const messageRows: [string, string, string, string][] = [
["{count} images.", "{count} images.", "{count} 枚の画像。", "{count} 张图像。"], ["{count} images.", "{count} images.", "{count} 枚の画像。", "{count} 张图像。"],
["{count} matches. Type more of the name to see other images.", "{count} résultats. Saisissez une plus grande partie du nom pour voir d’autres images.", "{count} 件一致しました。ほかの画像を表示するには、名前をさらに入力してください。", "{count} 个匹配项。请输入更多名称以查看其他图像。"], ["{count} matches. Type more of the name to see other images.", "{count} résultats. Saisissez une plus grande partie du nom pour voir d’autres images.", "{count} 件一致しました。ほかの画像を表示するには、名前をさらに入力してください。", "{count} 个匹配项。请输入更多名称以查看其他图像。"],
["{name}: skipped {count} unreadable images.", "{name} : {count} images illisibles ignorées.", "{name}: 読み込めない {count} 枚の画像をスキップしました。", "{name}:已跳过 {count} 张无法读取的图像。"], ["{name}: skipped {count} unreadable images.", "{name} : {count} images illisibles ignorées.", "{name}: 読み込めない {count} 枚の画像をスキップしました。", "{name}:已跳过 {count} 张无法读取的图像。"],
// The Terminal feature (src/lib/features/terminal/, Settings → Terminal).
["A Node.js REPL with a local inspector. Attach an external debugger to it.", "Un REPL Node.js avec un inspecteur local. Attachez-y un débogueur externe.", "ローカルインスペクター付きの Node.js REPL です。外部デバッガーを接続してください。", "带本地检查器的 Node.js REPL。请将外部调试器附加到它。"],
["A path cannot contain line breaks or null characters.", "Un chemin ne peut pas contenir de sauts de ligne ni de caractères nuls.", "パスに改行文字やヌル文字を含めることはできません。", "路径不能包含换行符或空字符。"],
["Blink cursor", "Curseur clignotant", "カーソルを点滅", "光标闪烁"],
["Choose a whole number from {min} to {max}.", "Choisissez un nombre entier de {min} à {max}.", "{min} から {max} までの整数を選択してください。", "请选择 {min} 到 {max} 之间的整数。"],
["Clear the terminal", "Effacer le terminal", "ターミナルをクリア", "清除终端"],
["Close terminal (end all sessions)", "Fermer le terminal (terminer toutes les sessions)", "ターミナルを閉じる(すべてのセッションを終了)", "关闭终端(结束所有会话)"],
["Close terminal window", "Fermer la fenêtre du terminal", "ターミナルウィンドウを閉じる", "关闭终端窗口"],
["Close the list", "Fermer la liste", "リストを閉じる", "关闭列表"],
["Configure tasks…", "Configurer les tâches…", "タスクを構成…", "配置任务…"],
["Copy the selected output", "Copier la sortie sélectionnée", "選択した出力をコピー", "复制所选输出"],
["Default", "Par défaut", "既定", "默认"],
["Default profile", "Profil par défaut", "既定のプロファイル", "默认配置文件"],
["Default terminal profile", "Profil de terminal par défaut", "既定のターミナルプロファイル", "默认终端配置文件"],
["Dismiss the terminal error", "Ignorer l’erreur du terminal", "ターミナルのエラーを閉じる", "关闭终端错误"],
["Each task needs a label, a command, and an optional profile ID.", "Chaque tâche nécessite un libellé, une commande et un ID de profil facultatif.", "各タスクにはラベル、コマンド、および任意のプロファイル ID が必要です。", "每个任务都需要标签、命令以及可选的配置文件 ID。"],
["Exited", "Terminé", "終了", "已退出"],
["Exited ({code})", "Terminé ({code})", "終了 ({code})", "已退出({code})"],
["Failed", "Échec", "失敗", "失败"],
["Finding the installed shells…", "Recherche des shells installés…", "インストール済みのシェルを検索中…", "正在查找已安装的 shell…"],
["Font size", "Taille de police", "フォントサイズ", "字体大小"],
["Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.", "La police, l’historique de défilement et le curseur s’appliquent aux terminaux ouverts. Le profil par défaut s’applique aux nouveaux terminaux.", "フォント、スクロールバック、カーソルは開いているターミナルに適用されます。既定のプロファイルは新しいターミナルに適用されます。", "字体、回滚和光标应用于已打开的终端。默认配置文件应用于新终端。"],
["From {min} to {max} pixels.", "De {min} à {max} pixels.", "{min} から {max} ピクセルまで。", "{min} 到 {max} 像素。"],
["Go to a recent folder", "Aller à un dossier récent", "最近のフォルダーに移動", "转到最近的文件夹"],
["Go to a recent folder…", "Aller à un dossier récent…", "最近のフォルダーに移動…", "转到最近的文件夹…"],
["Kill terminal", "Arrêter le terminal", "ターミナルを強制終了", "终止终端"],
["Kill {title} ({shortcut})", "Arrêter {title} ({shortcut})", "{title} を強制終了 ({shortcut})", "终止 {title}({shortcut})"],
["Loading the terminal…", "Chargement du terminal…", "ターミナルを読み込み中…", "正在加载终端…"],
["Maximize panel", "Agrandir le panneau", "パネルを最大化", "最大化面板"],
["More terminal actions", "Autres actions du terminal", "その他のターミナル操作", "更多终端操作"],
["New terminal", "Nouveau terminal", "新しいターミナル", "新建终端"],
["New terminal window", "Nouvelle fenêtre de terminal", "新しいターミナルウィンドウ", "新建终端窗口"],
["No commands yet. Shell commands show after the next prompt.", "Aucune commande pour l’instant. Les commandes du shell apparaissent après la prochaine invite.", "コマンドはまだありません。シェルのコマンドは次のプロンプトの後に表示されます。", "还没有命令。shell 命令会在下一个提示符之后显示。"],
["No entries match the filter.", "Aucune entrée ne correspond au filtre.", "フィルターに一致する項目はありません。", "没有与筛选条件匹配的条目。"],
["No entries yet.", "Aucune entrée pour l’instant.", "項目はまだありません。", "还没有条目。"],
["No folders yet.", "Aucun dossier pour l’instant.", "フォルダーはまだありません。", "还没有文件夹。"],
["No shell", "Aucun shell", "シェルなし", "无 shell"],
["No tasks yet. Choose Configure tasks… to add one.", "Aucune tâche pour l’instant. Choisissez Configurer les tâches… pour en ajouter une.", "タスクはまだありません。[タスクを構成…]を選んで追加してください。", "还没有任务。请选择“配置任务…”来添加任务。"],
["No terminal sessions.", "Aucune session de terminal.", "ターミナルセッションはありません。", "没有终端会话。"],
["Process exited", "Processus terminé", "プロセスが終了しました", "进程已退出"],
["Process exited with code {code}", "Processus terminé avec le code {code}", "プロセスがコード {code} で終了しました", "进程已退出,代码为 {code}"],
["Resize split terminals", "Redimensionner les terminaux divisés", "分割したターミナルのサイズを変更", "调整拆分终端的大小"],
["Resize terminal list", "Redimensionner la liste des terminaux", "ターミナル一覧のサイズを変更", "调整终端列表的大小"],
["Restore panel", "Restaurer le panneau", "パネルを元に戻す", "还原面板"],
["Run a recent command", "Exécuter une commande récente", "最近のコマンドを実行", "运行最近的命令"],
["Run a recent command…", "Exécuter une commande récente…", "最近のコマンドを実行…", "运行最近的命令…"],
["Run a task", "Exécuter une tâche", "タスクを実行", "运行任务"],
["Run a task…", "Exécuter une tâche…", "タスクを実行…", "运行任务…"],
["Run selected text", "Exécuter le texte sélectionné", "選択したテキストを実行", "运行所选文本"],
["Run shells, tasks, and the active file in a panel below the editor or in a separate window.", "Exécutez des shells, des tâches et le fichier actif dans un panneau sous l’éditeur ou dans une fenêtre séparée.", "エディターの下のパネルまたは別のウィンドウで、シェル、タスク、アクティブなファイルを実行します。", "在编辑器下方的面板或单独的窗口中运行 shell、任务和当前文件。"],
["Run the active file", "Exécuter le fichier actif", "アクティブなファイルを実行", "运行当前文件"],
["RuneStone cannot read .runestone/tasks.json. Use Configure tasks… to make or change it. {error}", "RuneStone ne peut pas lire .runestone/tasks.json. Utilisez Configurer les tâches… pour le créer ou le modifier. {error}", "RuneStone は .runestone/tasks.json を読み込めません。[タスクを構成…]で作成または変更してください。{error}", "RuneStone 无法读取 .runestone/tasks.json。请使用“配置任务…”来创建或更改它。{error}"],
["RuneStone cannot run this file type. Use Run selected text, or add a task.", "RuneStone ne peut pas exécuter ce type de fichier. Utilisez Exécuter le texte sélectionné, ou ajoutez une tâche.", "RuneStone はこの種類のファイルを実行できません。[選択したテキストを実行]を使うか、タスクを追加してください。", "RuneStone 无法运行此类文件。请使用“运行所选文本”,或添加任务。"],
["RuneStone could not list the shells: {error}", "RuneStone n’a pas pu lister les shells : {error}", "RuneStone はシェルを一覧表示できませんでした: {error}", "RuneStone 无法列出 shell:{error}"],
["RuneStone found no supported shells on PATH.", "RuneStone n’a trouvé aucun shell pris en charge dans PATH.", "RuneStone は PATH 上にサポートされているシェルを見つけられませんでした。", "RuneStone 在 PATH 中未找到受支持的 shell。"],
["Running", "En cours", "実行中", "正在运行"],
["Scroll to the next command", "Défiler jusqu’à la commande suivante", "次のコマンドまでスクロール", "滚动到下一个命令"],
["Scroll to the previous command", "Défiler jusqu’à la commande précédente", "前のコマンドまでスクロール", "滚动到上一个命令"],
["Scrollback lines", "Lignes d’historique de défilement", "スクロールバックの行数", "回滚行数"],
["Select a shell terminal to run files. The debug terminal is a Node.js REPL.", "Sélectionnez un terminal shell pour exécuter des fichiers. Le terminal de débogage est un REPL Node.js.", "ファイルを実行するにはシェルのターミナルを選択してください。デバッグターミナルは Node.js REPL です。", "请选择 shell 终端来运行文件。调试终端是 Node.js REPL。"],
["Select text in the editor first.", "Sélectionnez d’abord du texte dans l’éditeur.", "先にエディターでテキストを選択してください。", "请先在编辑器中选择文本。"],
["Select the default profile", "Sélectionner le profil par défaut", "既定のプロファイルを選択", "选择默认配置文件"],
["Select the default terminal profile", "Sélectionner le profil de terminal par défaut", "既定のターミナルプロファイルを選択", "选择默认终端配置文件"],
["Split terminal", "Diviser le terminal", "ターミナルを分割", "拆分终端"],
["Split terminal ({shortcut})", "Diviser le terminal ({shortcut})", "ターミナルを分割 ({shortcut})", "拆分终端({shortcut})"],
["Split terminal with profile", "Diviser le terminal avec un profil", "プロファイルを指定してターミナルを分割", "使用配置文件拆分终端"],
["Split {title}", "Diviser {title}", "{title} を分割", "拆分 {title}"],
["Start Windows voice typing in the focused terminal", "Démarrer la saisie vocale Windows dans le terminal actif", "フォーカスのあるターミナルで Windows の音声入力を開始", "在聚焦的终端中启动 Windows 语音输入"],
["Start a terminal", "Démarrer un terminal", "ターミナルを開始", "启动终端"],
["Start dictation", "Démarrer la dictée", "音声入力を開始", "开始听写"],
["Starting", "Démarrage", "開始中", "正在启动"],
["Terminal actions", "Actions du terminal", "ターミナルの操作", "终端操作"],
["Terminal is off. Turn it on in Settings → Features.", "Le terminal est désactivé. Activez-le dans Paramètres → Fonctionnalités.", "ターミナルはオフです。[設定]→[機能]でオンにしてください。", "终端已关闭。请在“设置”→“功能”中将其打开。"],
["Terminal list", "Liste des terminaux", "ターミナル一覧", "终端列表"],
["Terminal profiles", "Profils du terminal", "ターミナルプロファイル", "终端配置文件"],
["Terminal profiles and tasks", "Profils et tâches du terminal", "ターミナルのプロファイルとタスク", "终端配置文件和任务"],
["Terminal sessions will end.", "Les sessions du terminal vont se terminer.", "ターミナルセッションは終了します。", "终端会话将结束。"],
["Terminal settings", "Paramètres du terminal", "ターミナルの設定", "终端设置"],
["The cursor blinks in the focused terminal.", "Le curseur clignote dans le terminal actif.", "フォーカスのあるターミナルでカーソルが点滅します。", "光标在聚焦的终端中闪烁。"],
["The desktop app lists the installed shells.", "L’application de bureau liste les shells installés.", "デスクトップアプリはインストール済みのシェルを一覧表示します。", "桌面应用会列出已安装的 shell。"],
["The lines that a terminal keeps above the screen, from {min} to {max}.", "Les lignes qu’un terminal conserve au-dessus de l’écran, de {min} à {max}.", "ターミナルが画面の上に保持する行数({min} から {max} まで)。", "终端在屏幕上方保留的行数,从 {min} 到 {max}。"],
["The profile of this task is not installed: {profile}", "Le profil de cette tâche n’est pas installé : {profile}", "このタスクのプロファイルはインストールされていません: {profile}", "此任务的配置文件未安装:{profile}"],
["The shell of a new terminal.", "Le shell d’un nouveau terminal.", "新しいターミナルのシェル。", "新终端的 shell。"],
["The tasks file needs a \"tasks\" array.", "Le fichier des tâches nécessite un tableau « tasks ».", "タスクファイルには \"tasks\" 配列が必要です。", "任务文件需要一个 \"tasks\" 数组。"],
["The terminal could not start: {error}", "Le terminal n’a pas pu démarrer : {error}", "ターミナルを開始できませんでした: {error}", "终端无法启动:{error}"],
["This terminal is already running.", "Ce terminal est déjà en cours d’exécution.", "このターミナルはすでに実行中です。", "此终端已在运行。"],
["This terminal is closed.", "Ce terminal est fermé.", "このターミナルは閉じられています。", "此终端已关闭。"],
["This terminal is not running.", "Ce terminal n’est pas en cours d’exécution.", "このターミナルは実行されていません。", "此终端未在运行。"],
["Turn off Terminal", "Désactiver le terminal", "ターミナルをオフにする", "关闭终端"],
["Turn off Terminal?", "Désactiver le terminal ?", "ターミナルをオフにしますか?", "要关闭终端吗?"],
["Type to filter…", "Tapez pour filtrer…", "入力して絞り込み…", "输入以筛选…"],
["Unsaved edits will be discarded.", "Les modifications non enregistrées seront perdues.", "保存されていない編集内容は破棄されます。", "未保存的编辑将被丢弃。"],
["Use PowerShell for a path with quotes, % or !.", "Utilisez PowerShell pour un chemin contenant des guillemets, % ou !.", "引用符、%、! を含むパスには PowerShell を使用してください。", "对于包含引号、% 或 ! 的路径,请使用 PowerShell。"],
["{title}: choices", "{title} : choix", "{title}: 選択肢", "{title}:选项"],
["{up} {down} select · {enter} choose · {escape} close", "{up} {down} sélectionner · {enter} choisir · {escape} fermer", "{up} {down} 選択 · {enter} 決定 · {escape} 閉じる", "{up} {down} 选择 · {enter} 确定 · {escape} 关闭"],
// The native features without the desktop host.
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
]; ];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = { export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+31 -7
View File
@@ -11,6 +11,10 @@
import { FEATURES, type FeatureId } from "$lib/features/catalog"; import { FEATURES, type FeatureId } from "$lib/features/catalog";
import { featureSwitches, setFeature } from "$lib/features/state"; import { featureSwitches, setFeature } from "$lib/features/state";
import { featureErrors } from "$lib/features/loader"; import { featureErrors } from "$lib/features/loader";
import { TERMINAL_SHORTCUTS } from "$lib/features/terminalKeys";
import TerminalSettings from "$lib/features/TerminalSettings.svelte";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { confirm } from "@tauri-apps/plugin-dialog";
import { onMount, untrack, type Snippet } from "svelte"; import { onMount, untrack, type Snippet } from "svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte"; import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
@@ -19,13 +23,16 @@
import { appVersion as version } from "../appVersion"; import { appVersion as version } from "../appVersion";
import { COMMAND_LABELS, OTHER_SHORTCUTS, commandShortcut, shortcutKeys, type WorkbenchCommand } from "./workbenchKeys"; import { COMMAND_LABELS, OTHER_SHORTCUTS, commandShortcut, shortcutKeys, type WorkbenchCommand } from "./workbenchKeys";
import { isMac } from "$lib/ui/shortcuts"; import { isMac } from "$lib/ui/shortcuts";
// Help lists every shortcut: the workbench commands, then the editor and file tree shortcuts. // Help lists every shortcut: the workbench commands, then the editor and file tree shortcuts, then Terminal while it is on.
const shortcutSections = (() => { const shortcutSections = $derived.by(() => {
const general = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).map(command => ({ label: COMMAND_LABELS[command], keys: commandShortcut(command) })).filter(item => item.keys); const terminal = $featureSwitches.terminal;
const general = (Object.keys(COMMAND_LABELS) as WorkbenchCommand[]).filter(command => terminal || command !== "toggle-terminal")
.map(command => ({ label: COMMAND_LABELS[command], keys: commandShortcut(command) })).filter(item => item.keys);
const others = new Map<string, { label: string; keys: string }[]>(); const others = new Map<string, { label: string; keys: string }[]>();
for (const item of OTHER_SHORTCUTS) others.set(item.section, [...(others.get(item.section) ?? []), { label: item.label, keys: shortcutKeys(isMac() && item.macKeys ? item.macKeys : item.keys) }]); for (const item of OTHER_SHORTCUTS) others.set(item.section, [...(others.get(item.section) ?? []), { label: item.label, keys: shortcutKeys(isMac() && item.macKeys ? item.macKeys : item.keys) }]);
if (terminal) others.set("Terminal", TERMINAL_SHORTCUTS.map(item => ({ label: item.label, keys: shortcutKeys(item.keys) })));
return [{ name: "General", items: general }, ...[...others].map(([name, items]) => ({ name, items }))]; return [{ name: "General", items: general }, ...[...others].map(([name, items]) => ({ name, items }))];
})(); });
let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: { let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: {
settings: AppSettings; settings: AppSettings;
@@ -69,7 +76,8 @@
label: tool.title, icon: "settings" as const, label: tool.title, icon: "settings" as const,
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`, keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
}))); })));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase()))); const terminalSection = $derived($featureSwitches.terminal ? [{ id: "terminal" as const, label: $t("Terminal"), icon: "terminal" as const, keywords: "terminal shell profile default font size scrollback lines cursor blink powershell bash cmd" }] : []);
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...terminalSection, ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]); const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id)); const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
@@ -99,8 +107,22 @@
apply({ ...settings, autosaveSeconds: seconds }); apply({ ...settings, autosaveSeconds: seconds });
} }
function changeFeature(id: FeatureId, on: boolean) { /** True when a window runs a shell. The host counts the sessions of all windows. */
async function shellsRunning(): Promise<boolean> {
if (!isTauri()) return false;
try { return await invoke<number>("pty_running") > 0; }
catch { return false; }
}
async function changeFeature(id: FeatureId, on: boolean, input: HTMLInputElement) {
error = ""; error = "";
// Terminal off ends the shells of every window, so ask first, with the words of the close guard of the workbench.
if (id === "terminal" && !on && await shellsRunning()) {
let accepted = false;
try { accepted = await confirm(`${$t("Terminal sessions will end.")}\n${$t("Turn off Terminal?")}`, { title: $t("Turn off Terminal"), kind: "warning" }); }
catch (reason) { error = String(reason); }
if (!accepted) { input.checked = true; return; }
}
setFeature(id, on).then(() => { message = $t("Changes saved."); }) setFeature(id, on).then(() => { message = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; }); .catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
} }
@@ -201,7 +223,7 @@
<p id={`feature-${feature.id}-description`}>{$t(feature.description)}</p> <p id={`feature-${feature.id}-description`}>{$t(feature.description)}</p>
{#if $featureErrors[feature.id]}<p class="error" role="alert">{$t("{name} could not load: {error}", { name: $t(feature.name), error: $featureErrors[feature.id] ?? "" })}</p>{/if} {#if $featureErrors[feature.id]}<p class="error" role="alert">{$t("{name} could not load: {error}", { name: $t(feature.name), error: $featureErrors[feature.id] ?? "" })}</p>{/if}
</div> </div>
<input id={`feature-${feature.id}`} class="rs-switch" type="checkbox" role="switch" aria-describedby={`feature-${feature.id}-description`} checked={$featureSwitches[feature.id]} onchange={event => changeFeature(feature.id, event.currentTarget.checked)} /> <input id={`feature-${feature.id}`} class="rs-switch" type="checkbox" role="switch" aria-describedby={`feature-${feature.id}-description`} checked={$featureSwitches[feature.id]} onchange={event => void changeFeature(feature.id, event.currentTarget.checked, event.currentTarget)} />
</div> </div>
{/each} {/each}
</div> </div>
@@ -211,6 +233,8 @@
<PluginManager /> <PluginManager />
{:else if selected.id === "browser"} {:else if selected.id === "browser"}
<BrowserSlot kind="settings" /> <BrowserSlot kind="settings" />
{:else if selected.id === "terminal"}
<TerminalSettings />
{:else if selectedPlugin} {:else if selectedPlugin}
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key} {#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
{:else} {:else}
+12 -10
View File
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalHost from "$lib/features/TerminalHost.svelte";
import { featureSwitches } from "$lib/features/state";
import { terminalShortcut, type TerminalAction } from "$lib/features/terminalKeys";
import type PluginEditor from "$lib/plugins/PluginEditor.svelte"; import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { featureOfOwner } from "$lib/features/catalog"; import { featureOfOwner } from "$lib/features/catalog";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external"; import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
@@ -14,7 +16,6 @@
import type { ViewMode } from "./ViewModes.svelte"; import type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection"; import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts";
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { confirm, message as dialogMessage } from "@tauri-apps/plugin-dialog"; import { confirm, message as dialogMessage } from "@tauri-apps/plugin-dialog";
@@ -173,9 +174,9 @@
let templateManager = $state(false); let templateManager = $state(false);
let terminalStarted = $state(false); let terminalStarted = $state(false);
let terminalMaximized = $state(false); let terminalMaximized = $state(false);
let terminalDock: TerminalSlot | undefined = $state(); let terminalDock: TerminalHost | undefined = $state();
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); // The Terminal buttons, shortcuts, and command work from the switch alone. The first use loads the feature.
const terminalEnabled = $derived(!!terminalContribution); const terminalEnabled = $derived($featureSwitches.terminal);
const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar")); const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar"));
const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar)); const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar));
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); }); const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
@@ -429,7 +430,7 @@
if (terminalOpen && bottomHeight < 220) bottomHeight = 260; if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
} }
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) { async function terminalAction(action: Exclude<TerminalAction, "toggle">) {
if (!terminalEnabled) return; if (!terminalEnabled) return;
if (!workspace) { error = $t("Open a workspace to start a terminal."); return; } if (!workspace) { error = $t("Open a workspace to start a terminal."); return; }
const started = terminalStarted; const started = terminalStarted;
@@ -965,7 +966,7 @@
void pluginPaneComponents[$pluginView.key]?.openFind(); void pluginPaneComponents[$pluginView.key]?.openFind();
return; return;
} }
const action = pluginHost.get("terminal")?.shortcut(event); const action = terminalEnabled ? terminalShortcut(event) : null;
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock"); const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) { if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
event.preventDefault(); event.preventDefault();
@@ -1248,7 +1249,7 @@
if (closing) return; if (closing) return;
closing = true; closing = true;
try { try {
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n"); const message = [hasDirty ? $t("Unsaved edits will be discarded.") : "", terminalStarted ? $t("Terminal sessions will end.") : ""].filter(Boolean).join("\n");
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) { if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) {
saveDocumentTabs(); saveDocumentTabs();
await getCurrentWindow().destroy(); await getCurrentWindow().destroy();
@@ -1392,7 +1393,7 @@
onCursor={(pane, line, column) => { if (pane.id === documentPanes.active) cursor = { line, column }; }} onCursor={(pane, line, column) => { if (pane.id === documentPanes.active) cursor = { line, column }; }}
onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)} onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
/> />
{#if terminalContribution && terminalStarted} {#if terminalEnabled && terminalStarted}
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) --> <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
<div <div
class="gutter gutter-h" class:terminal-hidden={!terminalOpen} class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
@@ -1408,7 +1409,8 @@
<section class="bottom" class:terminal-hidden={!terminalOpen}> <section class="bottom" class:terminal-hidden={!terminalOpen}>
{#if workspace} {#if workspace}
{#key workspace.root} {#key workspace.root}
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }} <TerminalHost bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
onOpenSettings={() => void openSettings()}
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized} maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile} activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} /> getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
-18
View File
@@ -1,18 +0,0 @@
<script lang="ts">
import { onMount } from "svelte";
import type { Contributions, TerminalProps, TerminalMount, TerminalAction } from "./contracts";
let { contribution, ...props }: TerminalProps & { contribution: Contributions["terminal"] } = $props();
let container: HTMLDivElement;
let mounted = $state.raw<TerminalMount>();
let error = $state("");
onMount(() => {
try { mounted = contribution.mount(container, { ...props }); }
catch (reason) { error = String(reason); }
return () => { void Promise.resolve(mounted?.dispose()).catch(reason => error = String(reason)); mounted = undefined; };
});
$effect(() => { mounted?.update({ ...props }); });
export async function command(action: Exclude<TerminalAction, "toggle">) { await mounted?.command(action); }
</script>
{#if error}<p role="alert">{error}</p>{/if}
<div class="plugin-terminal" bind:this={container}></div>
<style>.plugin-terminal { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }</style>
+1 -1
View File
@@ -1,2 +1,2 @@
// Contribution types are part of the public plugin SDK (packages/plugin-sdk/src/contributions.ts). // Contribution types are part of the public plugin SDK (packages/plugin-sdk/src/contributions.ts).
export type { Contributions, TerminalAction, TerminalMount, TerminalProps } from "./sdk.ts"; export type { Contributions } from "./sdk.ts";
+21 -5
View File
@@ -4,17 +4,17 @@ import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api"; import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
import { ExternalSession, deadline } from "./externalSession"; import { ExternalSession, deadline } from "./externalSession";
import { filesTransport, ptyTransport } from "./nativeServices"; import { filesTransport } from "./nativeServices";
import { pluginAccess, type PluginTool } from "./access"; import { pluginAccess, type PluginTool } from "./access";
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout"; import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
import type { PluginViewOpenOptions } from "./sdk"; import type { PluginViewOpenOptions } from "./sdk";
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk"; import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
import { locale } from "../i18n"; import { locale, tr } from "../i18n";
import { FEATURES, type FeatureEntry } from "../features/catalog"; import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "../features/catalog";
import { FeatureSession } from "../features/session"; import { FeatureSession } from "../features/session";
import { featureSwitches, type FeatureSwitches } from "../features/state"; import { featureSwitches, type FeatureSwitches } from "../features/state";
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../features/launch"; import { LAUNCH_RULES, launchWanted, runsInWindow } from "../features/launch";
import type { FeatureContext } from "../features/types"; import type { FeatureContext, FeatureInstance } from "../features/types";
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] }); export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
export const externalErrors = writable<Record<string, string>>({}); export const externalErrors = writable<Record<string, string>>({});
@@ -104,6 +104,9 @@ const restarted = new Set<string>();
let queue: Promise<void> = Promise.resolve(); let queue: Promise<void> = Promise.resolve();
export function waitForPluginStartup() { return queue; } export function waitForPluginStartup() { return queue; }
let started = false; let started = false;
let markStarted: () => void = () => {};
/** Resolves when `startExternalPlugins` subscribes to the feature switches. A child component can mount before that. */
const whenStarted = new Promise<void>(resolve => { markStarted = resolve; });
let browserWindow = false; let browserWindow = false;
let settingsWindow = false; let settingsWindow = false;
let generation = 0; let generation = 0;
@@ -272,7 +275,6 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
let leased = false; let leased = false;
const session = new ExternalSession(id, { const session = new ExternalSession(id, {
completionTransport, completionTransport,
pty: ptyTransport,
files: filesTransport(id), files: filesTransport(id),
backgrounds: true, backgrounds: true,
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); }, openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
@@ -399,6 +401,19 @@ function syncFeatures(switches: FeatureSwitches) {
launchFeatures(); launchFeatures();
}).catch(reason => pluginServiceError.set(String(reason))); }).catch(reason => pluginServiceError.set(String(reason)));
} }
/**
* The instance of a feature that is on in this window. The first call loads the feature module.
* It waits for the feature switches when the window starts. It fails while the feature is off.
*/
export async function featureInstance(id: FeatureId): Promise<FeatureInstance> {
if (!isTauri()) throw new Error(tr("This feature needs the desktop app."));
const owner = featureEntry(id).owner;
await whenStarted;
if (sessions.get(owner)?.hash !== "feature") await queue;
const loaded = sessions.get(owner);
if (loaded?.hash !== "feature") throw new Error(tr("This feature is off."));
return (loaded.session as FeatureSession).loadInstance();
}
/** Start the instance of each running feature whose launch rule wants it now. */ /** Start the instance of each running feature whose launch rule wants it now. */
function launchFeatures() { function launchFeatures() {
for (const entry of FEATURES) { for (const entry of FEATURES) {
@@ -426,6 +441,7 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
}).catch(reason => report(builtIn.id, reason)); }).catch(reason => report(builtIn.id, reason));
} }
const offFeatures = featureSwitches.subscribe(syncFeatures); const offFeatures = featureSwitches.subscribe(syncFeatures);
markStarted();
const offLaunch = Object.values(LAUNCH_RULES).map(rule => rule.subscribe(launchFeatures)); const offLaunch = Object.values(LAUNCH_RULES).map(rule => rule.subscribe(launchFeatures));
// Feature titles follow the interface language. // Feature titles follow the interface language.
const offLocale = locale.subscribe(() => publish()); const offLocale = locale.subscribe(() => publish());
+2 -54
View File
@@ -4,14 +4,14 @@ import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts"; import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts"; import { backgroundHub } from "./backgrounds.ts";
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts"; import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts"; import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */ /** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & { export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
/** True gives the plugin `api.backgrounds`: the background frames of each target. */ /** True gives the plugin `api.backgrounds`: the background frames of each target. */
openFile?: PluginApi["openFile"]; backgrounds?: boolean; openFile?: PluginApi["openFile"]; backgrounds?: boolean;
completionTransport?: NonNullable<PluginApi["completion"]>["transport"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub; files?: FilesTransport; serviceHub?: ServiceHub;
}; };
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> { export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -37,7 +37,6 @@ export class ExternalSession {
private backgroundSubscriptions = new Set<() => void>(); private backgroundSubscriptions = new Set<() => void>();
private serviceOwner = Symbol('plugin services'); private serviceOwner = Symbol('plugin services');
private serviceSubscriptions = new Set<() => void>(); private serviceSubscriptions = new Set<() => void>();
private ptySessions = new Map<string, () => Promise<void>>();
readonly id: string; readonly id: string;
private services: SessionServices; private services: SessionServices;
private changed: () => void; private changed: () => void;
@@ -65,7 +64,6 @@ export class ExternalSession {
}; };
const api: PluginApi = { const api: PluginApi = {
id: this.id, signal: this.controller.signal, id: this.id, signal: this.controller.signal,
...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}),
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}), ...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub), services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
...(this.services.backgrounds ? { backgrounds: { ...(this.services.backgrounds ? { backgrounds: {
@@ -175,52 +173,6 @@ export class ExternalSession {
this.check(); this.check();
return request().then(value => { this.check(); return value; }); return request().then(value => { this.check(); return value; });
} }
private ptyApi(pty: PtyTransport): PtyApi {
const size = (cols: unknown, rows: unknown) => {
if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers.");
};
const validate = (options: PtyOpenOptions) => {
this.check();
if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function.");
if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd.");
size(options.cols, options.rows);
};
const open = async (options: PtyOpenOptions): Promise<PtySession> => {
const id = crypto.randomUUID();
let closed = false, exited = false, closing: Promise<void> | undefined;
const exit = (code: number | null) => {
if (exited) return;
exited = true; this.ptySessions.delete(id);
if (!closed && !this.stopped) options.onExit?.(code);
};
const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) },
data => { if (!closed && !this.stopped) options.onData(data); }, exit);
// Wait for the start, so that a close cannot leave a late shell running.
const close = () => closing ??= (async () => {
closed = true;
try { await opening; } catch { this.ptySessions.delete(id); return; }
this.ptySessions.delete(id);
await pty.close(id);
})();
this.ptySessions.set(id, close);
try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; }
if (this.stopped) { await close(); this.check(); }
const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); };
return {
id,
write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); },
resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); },
close,
};
};
return {
version: 1,
profiles: () => this.backgroundRequest(() => pty.profiles()),
open: options => { validate(options); return open(options); },
openWindow: () => { this.check(); return pty.openWindow(); },
dictation: () => { this.check(); return pty.dictation(); },
};
}
private filesApi(files: FilesTransport): FilesApi { private filesApi(files: FilesTransport): FilesApi {
const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); }; const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); };
return { return {
@@ -293,10 +245,6 @@ export class ExternalSession {
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); } try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
} }
this.cleanups = []; this.cleanups = [];
// Stop the terminal sessions that the plugin cleanup left open.
for (const close of [...this.ptySessions.values()]) {
try { await deadline(close()); } catch (error) { errors.push(error); }
}
if (errors.length) throw new Error(errors.map(String).join("\n")); if (errors.length) throw new Error(errors.map(String).join("\n"));
})(); })();
return this.stopping; return this.stopping;
+2 -23
View File
@@ -1,26 +1,5 @@
import { Channel, invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import type { FilesTransport, FolderEntry, FolderGrant, PtyProfile, PtyTransport } from "./sdk.ts"; import type { FilesTransport, FolderEntry, FolderGrant } from "./sdk.ts";
/**
* Terminal sessions over a channel to this webview. The output arrives as raw bytes, and no
* `pty-data` or `pty-exit` event goes to other windows. The released Terminal plugin uses the
* events instead, and the host keeps them for sessions without a channel.
*/
export const ptyTransport: PtyTransport = {
open: (request, onData, onExit) => {
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
});
return invoke<void>("pty_open", { ...request, channel });
},
write: (id, data) => invoke<void>("pty_write", { id, data }),
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
close: id => invoke<void>("pty_close", { id }),
profiles: () => invoke<PtyProfile[]>("pty_profiles"),
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
dictation: () => invoke<void>("pty_dictation"),
};
/** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */ /** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */
export function filesTransport(plugin: string): FilesTransport { export function filesTransport(plugin: string): FilesTransport {
+1 -1
View File
@@ -9,7 +9,7 @@ export class ContributionRegistry {
return this.entries.get(key)?.value as Contributions[K] | undefined; return this.entries.get(key)?.value as Contributions[K] | undefined;
} }
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void { register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
if (key !== "terminal" && key !== "browser") throw new Error("Unknown plugin contribution."); if (key !== "browser") throw new Error("Unknown plugin contribution.");
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`); if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
const entry = { owner, value }; const entry = { owner, value };
this.entries.set(key, entry); this.emit(); this.entries.set(key, entry); this.emit();
+1 -11
View File
@@ -1,18 +1,8 @@
// The public plugin API comes from the SDK package (packages/plugin-sdk). Change the public types there. // The public plugin API comes from the SDK package (packages/plugin-sdk). Change the public types there.
// The relative path works in SvelteKit, svelte-check, Vite, and the Node unit tests. // The relative path works in SvelteKit, svelte-check, Vite, and the Node unit tests.
import type { FilesApi, PluginManifest, PtyProfile } from "../../../packages/plugin-sdk/src/index.ts"; import type { FilesApi, PluginManifest } from "../../../packages/plugin-sdk/src/index.ts";
export * from "../../../packages/plugin-sdk/src/index.ts"; export * from "../../../packages/plugin-sdk/src/index.ts";
/** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */
export interface PtyTransport {
open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
write(id: string, data: string): Promise<void>;
resize(id: string, cols: number, rows: number): Promise<void>;
close(id: string): Promise<void>;
profiles(): Promise<PtyProfile[]>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
/** The native side of `FilesApi`, bound to one plugin ID by the host. */ /** The native side of `FilesApi`, bound to one plugin ID by the host. */
export type FilesTransport = Omit<FilesApi, "version">; export type FilesTransport = Omit<FilesApi, "version">;
export type ExternalManifest = PluginManifest; export type ExternalManifest = PluginManifest;
+2 -1
View File
@@ -10,7 +10,7 @@
import { invoke, isTauri } from '@tauri-apps/api/core'; import { invoke, isTauri } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background'] as const; export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background', 'terminal'] as const;
export type SettingsSection = typeof SETTINGS_SECTIONS[number]; export type SettingsSection = typeof SETTINGS_SECTIONS[number];
export type SettingsSections = Partial<Record<SettingsSection, unknown>>; export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
@@ -23,6 +23,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
language: 'runestone.language', language: 'runestone.language',
features: 'runestone.features', features: 'runestone.features',
background: 'runestone.background', background: 'runestone.background',
terminal: 'runestone.terminal',
}; };
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */ /** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
+17 -13
View File
@@ -2,36 +2,40 @@
import { startExternalPlugins } from "$lib/plugins/external"; import { startExternalPlugins } from "$lib/plugins/external";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { t } from "$lib/i18n";
import Workbench from "$lib/layout/Workbench.svelte"; import Workbench from "$lib/layout/Workbench.svelte";
import BrowserWindow from "$lib/layout/BrowserWindow.svelte"; import BrowserWindow from "$lib/layout/BrowserWindow.svelte";
import SettingsWindow from "$lib/layout/SettingsWindow.svelte"; import SettingsWindow from "$lib/layout/SettingsWindow.svelte";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalHost from "$lib/features/TerminalHost.svelte";
import { pluginHost } from "$lib/plugins/registry"; import { featureSwitches } from "$lib/features/state";
import { terminalShortcut } from "$lib/features/terminalKeys";
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow"); const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true"; const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
const settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true"; const settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true";
let dock: TerminalSlot | undefined = $state(); let dock: TerminalHost | undefined = $state();
let error = $state(""); let error = $state("");
const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
onMount(() => startExternalPlugins({ browserWindow })); onMount(() => startExternalPlugins({ browserWindow }));
function keydown(event: KeyboardEvent) { function keydown(event: KeyboardEvent) {
if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return; if (!terminalRoot || !$featureSwitches.terminal || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
const action = terminal?.shortcut(event); const action = terminalShortcut(event);
if (action && action !== "toggle") { event.preventDefault(); void dock?.command(action).catch(reason => error = String(reason)); } if (action && action !== "toggle") { event.preventDefault(); void dock?.command(action).catch(reason => error = String(reason)); }
} }
</script> </script>
<svelte:window onkeydown={keydown} /> <svelte:window onkeydown={keydown} />
{#if terminalRoot} {#if terminalRoot}
<div class="terminal-window"> <div class="terminal-window">
{#if error}<p role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
{#if terminal} {#if $featureSwitches.terminal}
{#key terminal} <TerminalHost bind:this={dock} cwd={terminalRoot} visible standalone
<TerminalSlot bind:this={dock} contribution={terminal} cwd={terminalRoot} visible standalone
onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} /> onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
{/key} {:else}<p class="off">{$t("Terminal is off. Turn it on in Settings → Features.")}</p>{/if}
{:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if}
</div> </div>
{:else if browserWindow}<BrowserWindow /> {:else if browserWindow}<BrowserWindow />
{:else if settingsWindow}<SettingsWindow /> {:else if settingsWindow}<SettingsWindow />
{:else}<Workbench />{/if} {:else}<Workbench />{/if}
<style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style> <style>
.terminal-window { height: 100vh; display: flex; flex-direction: column; }
.error, .off { margin: 0; padding: 12px 16px; }
.error { color: var(--rs-error); }
.off { color: var(--rs-text-dim); }
</style>
+44 -5
View File
@@ -105,11 +105,14 @@ export async function showSavedImage(page) {
* *
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`. * `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
* It cannot use variables from the test file. Pass data through `state`, which must be JSON. * It cannot use variables from the test file. Pass data through `state`, which must be JSON.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`. * `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), pty, settings(section), writeSettings(section, value) }`.
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false. * A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
* *
* Default handlers serve the settings file (`settings_*`), tab transfers (`tab_transfer_*`), and an installed browser engine * Default handlers serve the settings file (`settings_*`), tab transfers (`tab_transfer_*`), an installed browser engine
* (`browser_engine_status`). `commands` can replace them. * (`browser_engine_status`), and the shells of the Terminal feature (`pty_*`). `commands` can replace them.
* The mock shell sends "READY 🪨" and a cursor position query through the channel of `pty_open`, before the open returns.
* `test.pty.output(id, text)` and `test.pty.exit(id, code)` send more to an open session. `pty_running` counts the open
* sessions of all pages of the context.
* All pages of one browser context share their state: the settings file and the offers are in localStorage under * All pages of one browser context share their state: the settings file and the offers are in localStorage under
* test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page. * test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page.
* Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load. * Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load.
@@ -207,7 +210,7 @@ function installMock(options, commands) {
if (target !== pageId) channel.postMessage({ event, payload, target }); if (target !== pageId) channel.postMessage({ event, payload, target });
}; };
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers"; const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"]; const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } }; const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null); const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => { const snapshot = () => {
@@ -224,6 +227,21 @@ function installMock(options, commands) {
broadcast("settings-changed", change); broadcast("settings-changed", change);
return change; return change;
}; };
// The terminal sessions of this page (src-tauri/src/pty.rs). The count of each page is in localStorage, so `pty_running`
// in a Settings page sees the shells of the main page. A page that unloads takes its count with it.
const PTY_COUNTS = "runestone.smoke.pty-sessions";
const channels = new Map();
const countSessions = () => {
const counts = readJson(PTY_COUNTS, {});
if (channels.size) counts[pageId] = channels.size; else delete counts[pageId];
localStorage.setItem(PTY_COUNTS, JSON.stringify(counts));
};
addEventListener("pagehide", () => { channels.clear(); countSessions(); });
const pty = {
channels,
output: (id, text) => channels.get(id)?.onmessage(new TextEncoder().encode(text).buffer),
exit: (id, code) => channels.get(id)?.onmessage({ exit: code }),
};
const offers = () => { const offers = () => {
const list = readJson(TRANSFERS, {}); const list = readJson(TRANSFERS, {});
for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id]; for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id];
@@ -237,6 +255,27 @@ function installMock(options, commands) {
settings_read: () => snapshot(), settings_read: () => snapshot(),
// src-tauri/src/features.rs: no old plugin package of a native feature is installed. // src-tauri/src/features.rs: no old plugin package of a native feature is installed.
features_legacy: () => [], features_legacy: () => [],
// src-tauri/src/pty.rs: one shell. Tests of the terminal replace `pty_profiles` to show more profiles.
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
pty_open: async ({ id, page, channel }) => {
if (!channel || typeof channel.onmessage !== "function") throw "pty_open needs an output channel";
if (typeof page !== "string" || !page) throw "Invalid terminal page ID";
if (channels.has(id)) throw "terminal already exists";
channels.set(id, channel);
countSessions();
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
// Split the emoji between two messages, as a real shell can.
channel.onmessage(data.slice(0, 8).buffer);
channel.onmessage(data.slice(8).buffer);
await new Promise(resolve => setTimeout(resolve, 50));
return null;
},
pty_write: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
pty_resize: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
pty_close: ({ id }) => { channels.delete(id); countSessions(); return null; },
pty_running: () => Object.values(readJson(PTY_COUNTS, {})).reduce((sum, count) => sum + count, 0),
pty_new_window: () => null,
pty_dictation: () => null,
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it. // The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
git_blame: () => null, git_blame: () => null,
// src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these. // src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these.
@@ -277,7 +316,7 @@ function installMock(options, commands) {
}, },
}; };
const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings }; const test = { state: options.state, calls: [], emit, label: options.label, workspace, pty, settings: section => settingsFile()?.[section], writeSettings };
// Look up the test's handlers first. A test can return a Proxy, so do not copy its keys. // Look up the test's handlers first. A test can return a Proxy, so do not copy its keys.
const table = commands ? commands(test) || {} : {}; const table = commands ? commands(test) || {} : {};
window.isTauri = true; window.isTauri = true;
+13 -27
View File
@@ -1,44 +1,30 @@
import { readFile } from "node:fs/promises"; // Installed plugin packages for the smoke tests: the `plugins_*` commands of src-tauri/src/plugins.rs, without plugin code.
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { pluginRepo } from "./index.mjs";
/** An installed package of the old Table Formulas plugin. RuneStone now includes the feature and must not load this code. */ /** An installed package of the old Table Formulas plugin. RuneStone now includes the feature and must not load this code. */
export const oldTableFormulasRow = { export const oldTableFormulasRow = {
manifest: { schemaVersion: 1, id: "runestone.table-formulas", name: "Table Formulas", author: "RuneStone Team", description: "Calculate formulas in Markdown tables.", version: "0.1.3", apiVersion: 1, entry: "main.js", access: "full-app" }, manifest: { schemaVersion: 1, id: "runestone.table-formulas", name: "Table Formulas", author: "RuneStone Team", description: "Calculate formulas in Markdown tables.", version: "0.1.3", apiVersion: 1, entry: "main.js", access: "full-app" },
hash: "old-hash", enabled: true, path: "C:\\AppData\\RuneStone\\plugins\\runestone.table-formulas", error: null, removal: false, hash: "old-hash", enabled: true, path: "C:\AppData\RuneStone\plugins\runestone.table-formulas", error: null, removal: false,
}; };
/** /**
* Load the compiled Terminal package through the production Blob module loader. * Serve `rows` as the installed packages. All pages of a context share them through localStorage, and a change sends
* `extraRows` adds installed rows without code, for example `oldTableFormulasRow`. * `plugins-changed`. Enable, disable, and remove work. `plugins_load` fails, because the rows have no code.
* Call it after `mockTauri`, because it wraps the IPC mock.
*/ */
export async function mockFeaturePlugins(surface, extraRows = []) { export async function mockInstalledPlugins(surface, rows = []) {
// The runner checks the same folder for "@requires plugin:terminal". await surface.addInitScript(rows => {
const root = pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST || pluginRepo("RuneStone_Terminal/dist")) + "/");
const packages = [{
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
code: await readFile(new URL("main.js", root), "utf8"),
css: await readFile(new URL("style.css", root), "base64"),
}];
await surface.addInitScript(({ packages, extraRows }) => {
const key = "test.installed-plugins"; const key = "test.installed-plugins";
const root = "C:\\AppData\\RuneStone\\plugins"; const root = "C:\AppData\RuneStone\plugins";
const defaults = [...packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false })), ...extraRows]; const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(rows));
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults)); const write = next => { localStorage.setItem(key, JSON.stringify(next)); window.__TEST__?.emit("plugins-changed", {}); };
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); }; if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(rows));
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); }); window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
const original = window.__TAURI_INTERNALS__.invoke; const original = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => { window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
if (!command.startsWith("plugins_")) return original(command, args); if (!command.startsWith("plugins_")) return original(command, args);
window.__TEST__?.calls.push({ command, args }); window.__TEST__?.calls.push({ command, args });
if (command === "plugins_snapshot") return { root, plugins: read() }; if (command === "plugins_snapshot") return { root, plugins: read() };
if (command === "plugins_load" || command === "plugins_asset") { if (command === "plugins_load" || command === "plugins_asset") throw new Error(`No code for ${args.id}`);
const item = packages.find(item => item.manifest.id === args.id);
if (!item) throw new Error(`No code for ${args.id}`);
return command === "plugins_load" ? item.code : item.css;
}
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; } if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) }; if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; } if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
@@ -46,5 +32,5 @@ export async function mockFeaturePlugins(surface, extraRows = []) {
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return; if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
throw new Error(`Unhandled plugin IPC: ${command}`); throw new Error(`Unhandled plugin IPC: ${command}`);
}; };
}, { packages, extraRows }); }, rows);
} }
+4 -1
View File
@@ -204,7 +204,10 @@ await runSmoke("features/background", async ({ browser }) => {
await migrated.goto(smokeUrl); await migrated.goto(smokeUrl);
await waitForChange(migrated, ""); await waitForChange(migrated, "");
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" }); assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" });
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true }); // Each feature gets its switch. Background is on, and Git follows its old package (none here).
const switches = await migrated.evaluate(() => window.__TEST__.settings("features"));
assert.equal(switches.background, true);
assert.equal(switches.git, true);
assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1); assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1);
assert.deepEqual(migrated.errors, []); assert.deepEqual(migrated.errors, []);
await migrationContext.close(); await migrationContext.close();
+2 -2
View File
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true }); const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.waitFor(); await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature. // Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true }); assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true });
const settings = await openPage(context, { timeout: 10000 }); const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`); await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
await git.click(); await git.click();
await sourceControl.waitFor({ state: "detached" }); await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true }); assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved."); assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus(); await git.focus();
await settings.keyboard.press("Space"); await settings.keyboard.press("Space");
+474
View File
@@ -0,0 +1,474 @@
// The Terminal feature: lazy load, copy and paste, the theme and the --rs-ansi-* colors, splits, maximize, profiles, history pickers,
// tasks, run file and run selection, Settings → Terminal, the Off prompt, close and reopen, and the terminal window.
// The `pty_*` commands are mocks with channels (tests/smoke/_harness/index.mjs). They do not prove real shell behavior.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
await runSmoke("features/terminal", async ({ browser }) => {
const output = await outputDir("features/terminal");
const shot = name => path.join(output, name);
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await mockTauri(context, {
state: { confirm: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "# Working notes\n\nFirst paragraph.\n",
"src/hello.py": "print('hello')\n",
},
});
test.files = workspace.files;
return {
...workspace,
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }, { id: "git-bash", title: "Git Bash", kind: "bash" }, { id: "node", title: "JavaScript Debug Terminal", kind: "node" }],
settings_open_window: () => null,
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
"plugin:dialog|message": args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return test.state.confirm; },
};
},
});
const page = await openPage(context);
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
const click = name => page.getByRole("button", { name, exact: true }).click();
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
const xtermLoaded = target => target.evaluate(() => performance.getEntriesByType("resource").some(entry => /xterm/i.test(entry.name)));
const appearance = (target, mode) => target.evaluate(async mode => {
const { applyAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ theme: "default", mode });
}, mode);
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
// The Terminal button shows from the static catalog. The feature module and xterm load at the first use.
assert.equal(await xtermLoaded(page), false, "xterm does not load at start");
await click("Terminal");
await waitCount("pty_open", 1);
const open = await page.evaluate(() => window.__TEST__.calls.find(c => c.command === "pty_open").args);
assert.equal(typeof open.page, "string", "Each open sends the page ID");
assert.equal(open.cwd, "C:\\smoke-workspace");
await page.locator(".xterm-rows > div > span").first().waitFor();
assert.equal(await xtermLoaded(page), true);
const terminalFont = await page.locator(".xterm-rows > div > span").first().evaluate(element => {
const style = getComputedStyle(element);
return { family: style.fontFamily, weight: style.fontWeight, size: style.fontSize };
});
assert.equal(terminalFont.weight, "300");
assert.equal(terminalFont.size, "13px");
assert.ok(terminalFont.family.startsWith('"Cascadia Mono"'));
// The input before the open finished includes the answer of xterm to the cursor position query.
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
// Copy: a drag selects without copy, a right-click copies and clears, Ctrl+C copies a selection, and without one it interrupts.
await page.evaluate(() => navigator.clipboard.writeText("before selection"));
const beforeSelection = await writes();
const firstText = await page.locator(".xterm-rows > div > span").first().boundingBox();
await page.mouse.move(firstText.x + 1, firstText.y + firstText.height / 2);
await page.mouse.down();
await page.mouse.move(firstText.x + firstText.width, firstText.y + firstText.height / 2, { steps: 10 });
await page.mouse.up();
assert.ok(await page.locator(".xterm-selection > div").count(), "Mouse drag selects terminal output.");
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "before selection", "Selection does not copy output.");
assert.equal(await writes(), beforeSelection, "Selection does not send input to the shell.");
await page.locator(".term").first().screenshot({ path: shot("terminal-copy-selection.png") });
await page.evaluate(() => {
window.__TEST__.writeText = navigator.clipboard.writeText.bind(navigator.clipboard);
navigator.clipboard.writeText = text => new Promise(resolve => {
window.__TEST__.finishCopy = async () => { await window.__TEST__.writeText(text); resolve(); };
});
});
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
assert.ok(await page.locator(".xterm-selection > div").count(), "Selection stays until the clipboard write succeeds.");
await page.evaluate(() => window.__TEST__.finishCopy());
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
await page.waitForFunction(() => !document.querySelector(".xterm-selection > div"));
assert.equal(await writes(), beforeSelection, "Right-click copy does not send input to the shell.");
await page.evaluate(() => navigator.clipboard.writeText("empty selection"));
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "empty selection", "Right-click without selection keeps the clipboard.");
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
await page.evaluate(() => navigator.clipboard.writeText(""));
const beforeCopy = await writes();
await page.keyboard.press("Control+c");
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
assert.equal(await writes(), beforeCopy, "Copy does not send an interrupt to the shell.");
const beforeInterrupt = await writes();
await page.locator(".xterm-screen").first().click();
await page.keyboard.press("Control+c");
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join("").length > before.length, beforeInterrupt);
assert.equal((await writes()).slice(beforeInterrupt.length), "\u0003", "Ctrl+C without selection interrupts the shell.");
// A denied clipboard write keeps the selection for another try.
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
await page.evaluate(() => { navigator.clipboard.writeText = () => Promise.reject(new Error("Clipboard denied for smoke test")); });
await page.locator(".xterm-screen").first().click({ button: "right" });
await page.getByText("Error: Clipboard denied for smoke test", { exact: true }).waitFor();
assert.ok(await page.locator(".xterm-selection > div").count(), "Failed copy keeps the selection.");
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
// The 16 ANSI colors come from the --rs-ansi-* tokens. A token change reaches the open terminal.
const id = open.id;
await page.evaluate(id => window.__TEST__.pty.output(id, "\x1b[31mANSI-RED\x1b[0m \x1b[94mANSI-BLUE\x1b[0m\r\n"), id);
const colorOf = text => page.evaluate(text => {
const span = [...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text));
return span && getComputedStyle(span).color;
}, text);
await page.waitForFunction(() => [...document.querySelectorAll(".xterm-rows span")].some(node => node.textContent.includes("ANSI-RED")));
const red = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-ansi-red").trim());
assert.ok(red, "The theme defines --rs-ansi-red");
await page.evaluate(() => {
document.documentElement.style.setProperty("--rs-ansi-red", "#12ab34");
document.documentElement.style.setProperty("--rs-ansi-bright-blue", "#3456cd");
});
await page.waitForFunction(() => {
const color = text => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text))).color;
return color("ANSI-RED") === "rgb(18, 171, 52)" && color("ANSI-BLUE") === "rgb(52, 86, 205)";
});
await page.evaluate(() => { for (const name of ["--rs-ansi-red", "--rs-ansi-bright-blue"]) document.documentElement.style.removeProperty(name); });
await page.waitForFunction(() => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes("ANSI-RED"))).color !== "rgb(18, 171, 52)");
assert.notEqual(await colorOf("ANSI-RED"), "rgb(18, 171, 52)");
// Selection colors keep their hue and stay at most 65% opaque, in both themes and at two widths.
for (const theme of ["light", "dark"]) {
await appearance(page, theme);
for (const width of [620, 1440]) {
await page.setViewportSize({ width, height: 1000 });
await page.locator(".xterm-helper-textarea").first().focus();
const text = await (await page.waitForFunction(() => {
const node = [...document.querySelectorAll(".xterm-rows > div > span")].find(node => node.textContent.includes("READY"));
const rect = node?.getBoundingClientRect();
return rect?.width ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null;
})).jsonValue();
await page.mouse.move(text.x + 1, text.y + text.height / 2);
await page.mouse.down();
await page.mouse.move(text.x + text.width, text.y + text.height / 2, { steps: 10 });
await page.mouse.up();
await page.evaluate(() => navigator.clipboard.writeText(""));
await page.keyboard.press("Control+Shift+c");
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
const selectionColor = await page.locator(".xterm-selection > div").first().evaluate(node => getComputedStyle(node).backgroundColor);
const selectionAlpha = Number(selectionColor.match(/rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)\)/)?.[1] ?? 1);
assert.ok(selectionAlpha > 0 && selectionAlpha <= 0.65, `Terminal selection keeps transparency: ${selectionColor}`);
assert.ok(await page.locator(".xterm-rows .xterm-decoration-top").first().evaluate(node => getComputedStyle(node).backgroundColor === "rgba(0, 0, 0, 0)"), "Selected glyph backgrounds stay transparent.");
await page.locator(".term").first().screenshot({ path: shot(`terminal-theme-${theme}-${width}.png`) });
}
}
for (const [source, expected] of [["#ff8000", [255, 128, 0, 0.647]], ["rgba(0, 255, 128, 0.35)", [0, 255, 128, 0.35]]]) {
await page.evaluate(source => document.documentElement.style.setProperty("--rs-selection", source), source);
await page.waitForFunction(expected => {
const channels = getComputedStyle(document.querySelector(".xterm-selection > div")).backgroundColor.match(/[\d.]+/g).map(Number);
return channels.length === 4 && channels.slice(0, 3).every((channel, index) => Math.abs(channel - expected[index]) <= 2) && Math.abs(channels[3] - expected[3]) < 0.005;
}, expected);
}
await page.evaluate(() => document.documentElement.style.removeProperty("--rs-selection"));
// The panel surfaces are translucent, the xterm layers are transparent, and the ribbon controls fit at 620 pixels.
const surfaces = () => page.evaluate(() => {
const alpha = color => {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1;
const context = canvas.getContext("2d");
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
return context.getImageData(0, 0, 1, 1).data[3] / 255;
};
return Object.fromEntries([".ribbon", ".term", ".xterm", ".xterm-viewport", ".rail", ".pane-label"].map(selector => {
const element = document.querySelector(`.dock ${selector}`);
if (!element) return [selector, null];
const style = getComputedStyle(element);
return [selector, { alpha: alpha(style.backgroundColor), opacity: style.opacity }];
}));
});
for (const mode of ["light", "dark"]) {
await appearance(page, mode);
await settle(page);
const colors = await surfaces();
// The ribbon and the panes use the translucent surface tokens, so a background image shows through them.
assert.ok(colors[".ribbon"].alpha > 0.5 && colors[".ribbon"].alpha < 1, `ribbon ${colors[".ribbon"].alpha}`);
assert.ok(colors[".term"].alpha > 0.5 && colors[".term"].alpha < 1, `term ${colors[".term"].alpha}`);
assert.equal(colors[".xterm"].alpha, 0);
assert.equal(colors[".xterm-viewport"].alpha, 0);
assert.equal(colors[".ribbon"].opacity, "1");
assert.equal(await page.locator(".bottom").evaluate(element => getComputedStyle(element).backgroundColor), "rgba(0, 0, 0, 0)");
for (const width of [620, 1440]) {
await page.setViewportSize({ width, height: 800 });
await page.locator(".xterm-helper-textarea").first().focus();
await settle(page);
await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).focus();
await page.getByRole("tooltip", { name: "Terminal profiles and tasks", exact: true }).waitFor();
const ribbonBounds = await page.locator(".dock .ribbon").boundingBox();
for (const button of await page.locator(".dock .ribbon button").all()) {
const bounds = await button.boundingBox();
assert.ok(bounds.x >= ribbonBounds.x && bounds.x + bounds.width <= ribbonBounds.x + ribbonBounds.width + 1);
assert.ok(bounds.width >= 28 && bounds.height >= 28);
}
await page.screenshot({ path: shot(`terminal-translucent-${mode}-${width}.png`) });
}
}
// Splits, maximize, hide and show without a close, profiles, and kill.
await page.setViewportSize({ width: 1440, height: 1000 });
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
const adjacent = await page.getByRole("button", { name: "New terminal", exact: true }).evaluate(button => { const buttons = [...button.closest(".actions").querySelectorAll("button")]; return buttons[buttons.indexOf(button) + 1]?.getAttribute("aria-label"); });
assert.equal(adjacent, "Terminal profiles and tasks");
await click("Split terminal (Ctrl+Shift+5)");
await waitCount("pty_open", 2);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 1);
assert.equal(await page.locator(".pane.shown").count(), 2);
const original = await page.locator(".pane.shown").first().boundingBox();
await click("Maximize panel");
const enlarged = await page.locator(".pane.shown").first().boundingBox();
assert.ok(enlarged.height > original.height + 100);
assert.equal(await count("pty_close"), 0);
await page.screenshot({ path: shot("terminal-splits.png") });
await click("Restore panel");
await page.keyboard.press("Control+j");
assert.equal(await count("pty_close"), 0);
await page.keyboard.press("Control+j");
assert.equal(await count("pty_open"), 2);
await click("Terminal profiles and tasks");
const splitProfile = page.getByRole("menuitem", { name: "Split terminal with profile", exact: true });
await splitProfile.focus();
await page.keyboard.press("ArrowRight");
const profileSubmenu = page.getByRole("menu", { name: "Split terminal with profile", exact: true });
assert(await profileSubmenu.getByRole("menuitem", { name: "PowerShell", exact: true }).evaluate(node => document.activeElement === node));
await page.keyboard.press("ArrowLeft");
assert(await splitProfile.evaluate(node => document.activeElement === node));
await page.keyboard.press("Escape");
assert(await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).evaluate(node => document.activeElement === node));
await click("Terminal profiles and tasks");
await page.screenshot({ path: shot("terminal-profiles.png") });
await menu("Command Prompt");
await waitCount("pty_open", 3);
assert.equal(await page.locator(".pane.shown").count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "cmd");
await page.keyboard.press("Control+Shift+5");
await waitCount("pty_open", 4);
assert.equal(await page.locator(".pane.shown").count(), 2);
await click("Kill terminal");
await waitCount("pty_close", 1);
assert.equal(await page.locator(".pane.shown").count(), 1);
// OSC 633 and 133 shell integration fills the history pickers.
await page.evaluate(() => {
const id = window.__TEST__.calls.filter(c => c.command === "pty_open")[2].args.id;
const data = `\x1b]633;RSCommand;${btoa("echo history-check")}\x07\x1b]633;RSCwd;${btoa("C:\\two words")}\x07\x1b]133;A\x07C:\\two words>\x1b]133;B\x07`;
window.__TEST__.pty.output(id, data);
});
await click("More terminal actions");
assert(await page.getByRole("menuitem", { name: "Run the active file", exact: true }).isDisabled());
assert(await page.getByRole("menuitem", { name: "Run selected text", exact: true }).isDisabled());
await page.screenshot({ path: shot("terminal-actions.png") });
await menu("Run a recent command… Ctrl+Alt+R");
await page.getByRole("dialog").getByRole("option", { name: "echo history-check" }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo history-check")));
await page.keyboard.press("Control+g");
await page.getByRole("dialog").getByRole("option", { name: "C:\\two words" }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes('cd /d "C:\\two words"')));
// Settings → Terminal opens Settings. The page does not load xterm, and its changes reach the open panel.
await click("Terminal profiles and tasks");
await menu("Terminal settings");
await waitCount("settings_open_window", 1);
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
const dialog = settings.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("button", { name: "Terminal", exact: true }).click();
await dialog.getByRole("heading", { name: "Terminal", exact: true }).waitFor();
assert.equal(await xtermLoaded(settings), false, "Settings → Terminal does not load xterm");
const fontSize = dialog.getByLabel("Font size", { exact: true });
assert.equal(await fontSize.inputValue(), "13");
await fontSize.fill("40");
await fontSize.press("Enter");
await fontSize.blur();
await dialog.getByText("Choose a whole number from 9 to 28.", { exact: true }).waitFor();
await fontSize.fill("16");
await fontSize.blur();
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.fontSize === 16);
await page.waitForFunction(() => getComputedStyle(document.querySelector(".pane.shown .xterm-rows > div > span")).fontSize === "16px");
for (const mode of ["light", "dark"]) {
await appearance(settings, mode);
for (const width of [1152, 360]) {
await settings.setViewportSize({ width, height: width === 360 ? 640 : 815 });
await settle(settings);
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `No horizontal scroll at ${width} pixels`);
await settings.screenshot({ path: shot(`settings-terminal-${mode}-${width}.png`) });
}
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
const profileMenu = settings.getByRole("menu", { name: "Default terminal profile", exact: true });
const current = profileMenu.getByRole("menuitemradio", { name: "PowerShell", exact: true });
assert.equal(await current.getAttribute("aria-checked"), "true");
assert.equal(await profileMenu.getByRole("menuitemradio", { name: "JavaScript Debug Terminal", exact: true }).count(), 0, "The debug terminal is not a default");
const bounds = await profileMenu.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 640);
await settings.screenshot({ path: shot(`settings-terminal-profile-${mode}-360.png`) });
await settings.keyboard.press("End");
assert(await profileMenu.getByRole("menuitemradio", { name: "Git Bash", exact: true }).evaluate(node => document.activeElement === node));
await settings.keyboard.press("Escape");
assert(await dialog.getByRole("button", { name: "Default profile", exact: true }).evaluate(node => document.activeElement === node));
}
await settings.setViewportSize({ width: 1152, height: 815 });
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
await settings.getByRole("menuitemradio", { name: "Git Bash", exact: true }).click();
await dialog.getByRole("switch", { name: "Blink cursor", exact: true }).uncheck();
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.defaultProfile === "git-bash" && window.__TEST__.settings("terminal")?.cursorBlink === false);
await page.bringToFront();
await click("New terminal");
await waitCount("pty_open", 5);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "git-bash");
// Tasks from .runestone/tasks.json, with the shared picker rows at 360 pixels in both themes.
await page.evaluate(() => window.__TEST__.files.set(".runestone/tasks.json", JSON.stringify({ tasks: [{ label: "Smoke task", command: "echo task-ok", profile: "powershell" }] })));
await click("Terminal profiles and tasks");
await menu("Run a task…");
for (const mode of ["light", "dark"]) {
await appearance(page, mode);
await page.setViewportSize({ width: 360, height: 640 });
const row = page.getByRole("option", { name: "Smoke task echo task-ok" });
const measurements = await row.evaluate(node => {
const css = getComputedStyle(node);
const root = getComputedStyle(document.documentElement);
return { fontSize: css.fontSize, minHeight: css.minHeight, padding: css.padding, radius: css.borderRadius,
tokenFont: root.getPropertyValue("--rs-menu-font-size").trim(), tokenHeight: root.getPropertyValue("--rs-menu-row-height").trim(),
tokenRadius: root.getPropertyValue("--rs-control-radius").trim(), tokenPadding: root.getPropertyValue("--rs-menu-row-padding").trim() };
});
assert.equal(measurements.fontSize, measurements.tokenFont);
assert.equal(measurements.minHeight, measurements.tokenHeight);
assert.equal(measurements.radius, measurements.tokenRadius);
assert.equal(measurements.padding, measurements.tokenPadding);
await page.screenshot({ path: shot(`terminal-task-picker-${mode}-360.png`) });
}
await page.setViewportSize({ width: 1440, height: 1000 });
const taskQuery = page.getByRole("combobox", { name: "Run a task", exact: true });
await taskQuery.fill("no-such-task");
await page.getByText("No entries match the filter.", { exact: true }).waitFor();
assert.equal(await page.getByRole("option").count(), 0);
await taskQuery.fill("Smoke task");
const taskOption = page.getByRole("option", { name: "Smoke task echo task-ok" });
assert.equal(await taskQuery.getAttribute("aria-activedescendant"), await taskOption.getAttribute("id"));
await taskQuery.press("Enter");
await waitCount("pty_open", 6);
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
// Run selected text and run the active file. The editor keeps its selection while the menu takes focus.
// The shell owns its control keys, so the test opens the file from a new tab.
await click("New tab (Ctrl+T)");
await page.getByRole("button", { name: /^Find file/ }).click();
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).first().click();
const editor = page.locator(".cm-content").first();
await editor.waitFor();
const editorFont = await editor.evaluate(element => ({ family: getComputedStyle(element).fontFamily, weight: getComputedStyle(element).fontWeight }));
assert.equal(editorFont.weight, terminalFont.weight, "The terminal uses the code font weight");
assert.ok(editorFont.family.startsWith(terminalFont.family.split(",")[0]), "The terminal uses the code font");
await editor.click();
await page.keyboard.press("Control+a");
await click("More terminal actions");
await menu("Run selected text");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("print('hello')")));
await click("More terminal actions");
await menu("Run the active file");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("python 'C:\\smoke-workspace\\src\\hello.py'")));
await click("Terminal profiles and tasks");
await menu("New terminal window Ctrl+Alt+Shift+`");
await waitCount("pty_new_window", 1);
await click("More terminal actions");
await menu("Start dictation");
await waitCount("pty_dictation", 1);
await click("More terminal actions");
await menu("Clear the terminal");
assert.equal(await count("pty_close"), 1);
// Kill down to one session and none, start again, the new and window shortcuts, then close and a fresh reopen.
await page.setViewportSize({ width: 880, height: 600 });
await page.screenshot({ path: shot("terminal-narrow.png") });
for (let remaining = 5; remaining > 1; remaining--) await click("Kill terminal");
await waitCount("pty_close", 5);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
await click("Kill terminal");
await waitCount("pty_close", 6);
await click("Start a terminal");
await waitCount("pty_open", 7);
await page.locator(".pane.shown .xterm-helper-textarea").focus();
await page.keyboard.press("Control+Shift+Backquote");
await waitCount("pty_open", 8);
await page.keyboard.press("Control+Shift+Alt+Backquote");
await waitCount("pty_new_window", 2);
const opens = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").map(c => c.args.id));
await click("Close terminal (end all sessions)");
await waitCount("pty_close", opens.length);
const closedIds = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").map(c => c.args.id));
assert.deepEqual([...closedIds].sort(), [...opens].sort());
await page.keyboard.press("Control+j");
await waitCount("pty_open", opens.length + 1);
const freshId = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.id);
assert.equal(opens.includes(freshId), false);
// The new shell takes the focus when it starts. Wait for that before the focus moves to the close button.
await page.waitForFunction(id => window.__TEST__.calls.some(c => c.command === "pty_resize" && c.args.id === id), freshId);
await appearance(page, "light");
await settle(page);
await page.getByRole("button", { name: "Close terminal (end all sessions)", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close terminal (end all sessions)", exact: true }).waitFor();
await page.screenshot({ path: shot("terminal-close-light-narrow-focus.png") });
await page.keyboard.press("Enter");
await waitCount("pty_close", opens.length + 1);
await page.keyboard.press("Control+Shift+Backquote");
await waitCount("pty_open", opens.length + 2);
assert.equal(await page.locator(".pane.shown").count(), 1);
// Off asks first while a shell runs. Cancel keeps the shells. OK ends them and removes the controls.
await settings.bringToFront();
await dialog.getByRole("button", { name: "Features", exact: true }).click();
const terminalSwitch = dialog.getByRole("switch", { name: "Terminal", exact: true });
await terminalSwitch.click();
await settings.waitForFunction(() => window.__TEST__.state.prompts?.length === 1);
await settings.waitForFunction(() => document.querySelector("#feature-terminal").checked);
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), ["Terminal sessions will end.\nTurn off Terminal?"]);
assert.equal(await terminalSwitch.isChecked(), true, "Cancel keeps Terminal on");
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), true);
const closesBefore = await count("pty_close");
await settings.evaluate(() => { window.__TEST__.state.confirm = "Ok"; });
await terminalSwitch.click();
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_close").length > before, closesBefore);
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), false);
await page.getByRole("button", { name: "Terminal", exact: true }).waitFor({ state: "detached" });
assert.equal(await dialog.getByRole("button", { name: "Terminal", exact: true }).count(), 0, "Settings → Terminal hides while Terminal is off");
for (const mode of ["light", "dark"]) {
await appearance(settings, mode);
await settings.setViewportSize({ width: 360, height: 640 });
await settle(settings);
await settings.screenshot({ path: shot(`features-terminal-off-${mode}-360.png`) });
}
// Without prompts, an Off with no shell needs no question.
await terminalSwitch.check();
await page.getByRole("button", { name: "Terminal", exact: true }).first().waitFor();
await settings.evaluate(() => { window.__TEST__.state.prompts = []; });
await terminalSwitch.uncheck();
await settings.waitForFunction(() => window.__TEST__.settings("features").terminal === false);
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), []);
await terminalSwitch.check();
assert.deepEqual([...page.errors, ...settings.errors], []);
await settings.close();
// The terminal window: one session, no workspace open, the exit code from the channel, and close.
await page.goto(`${smokeUrl}/?terminalWindow=C%3A%5Csmoke-workspace`);
await page.locator(".xterm").waitFor();
await waitCount("pty_open", 1);
assert.equal(await count("workspace_open"), 0);
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
assert.equal(await page.getByRole("button", { name: "Maximize panel", exact: true }).count(), 0);
await page.screenshot({ path: shot("terminal-window.png") });
await page.evaluate(() => window.__TEST__.pty.exit(window.__TEST__.calls.find(c => c.command === "pty_open").args.id, 3));
await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("[Process exited with code 3]"));
await click("Close terminal window");
await waitCount("plugin:window|destroy", 1);
assert.equal(await count("pty_close"), 0, "The host removed the exited shell, so the close needs no host call");
assert.deepEqual(page.errors, []);
console.log("PASS: terminal lazy load, copy, ANSI tokens, selection, splits, profiles, history, Settings → Terminal, tasks, run file, Off prompt, close and reopen, and the terminal window.");
}, { timeout: 30000 });
+1 -4
View File
@@ -1,10 +1,8 @@
// Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px. // Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px.
// @requires plugin:terminal
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs"; import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/windowControls", async ({ page }) => { await runSmoke("layout/windowControls", async ({ page }) => {
const output = await outputDir("layout/windowControls"); const output = await outputDir("layout/windowControls");
@@ -20,8 +18,7 @@ await runSmoke("layout/windowControls", async ({ page }) => {
"plugin:dialog|message": () => test.state.confirm, "plugin:dialog|message": () => test.state.confirm,
}), }),
}); });
// The Terminal button belongs to the terminal plug-in (src/lib/layout/Workbench.svelte:1305). // The Terminal button belongs to the Terminal feature, which is on by default (src/lib/features/catalog.ts).
await mockFeaturePlugins(page);
const called = command => page.evaluate(command => window.__TEST__.calls.some(call => call.command === command), command); const called = command => page.evaluate(command => window.__TEST__.calls.some(call => call.command === command), command);
const config = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/tauri.conf.json"), "utf8")); const config = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/tauri.conf.json"), "utf8"));
+1 -18
View File
@@ -1,10 +1,8 @@
// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts. // Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
// @requires plugin:terminal
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs"; import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/workbench", async ({ page }) => { await runSmoke("layout/workbench", async ({ page }) => {
const output = await outputDir("layout/workbench"); const output = await outputDir("layout/workbench");
@@ -21,33 +19,18 @@ await runSmoke("layout/workbench", async ({ page }) => {
}, },
}); });
Object.assign(test, { files: workspace.files, root: workspace.root }); Object.assign(test, { files: workspace.files, root: workspace.root });
// The terminal plug-in opens shells through these commands. // The Terminal feature opens its shells through the default `pty_*` handlers of the harness.
const pty = {};
for (const command of ["pty_write", "pty_resize", "pty_close"]) pty[command] = () => {};
return { return {
...workspace, ...workspace,
...pty,
workspace_write: args => { workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args); return workspace.workspace_write(args);
}, },
workspace_search: () => [], workspace_search: () => [],
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
pty_open: async args => {
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
// A Terminal plugin that uses api.pty passes a channel and gets raw bytes. Released versions listen for events.
if (args.channel) setTimeout(() => { args.channel.onmessage(data.slice(0, 8).buffer); args.channel.onmessage(data.slice(8).buffer); }, 0);
else {
test.emit("pty-data", { id: args.id, data: [...data.slice(0, 8)] });
test.emit("pty-data", { id: args.id, data: [...data.slice(8)] });
}
await new Promise(resolve => setTimeout(resolve, 50));
},
"plugin:dialog|message": () => "Cancel", "plugin:dialog|message": () => "Cancel",
}; };
}, },
}); });
await mockFeaturePlugins(page);
async function quickOpen(name) { async function quickOpen(name) {
await page.keyboard.press("Control+p"); await page.keyboard.press("Control+p");
+25 -31
View File
@@ -1,10 +1,10 @@
// Feature lifecycle: the built-in Table formulas setting and the Terminal plug-in turn off, persist, reopen across windows, and uninstall without restoration. // Feature lifecycle: the built-in Table formulas setting and the native Terminal feature turn off, persist, and turn on again across windows.
// An old Table Formulas package stays inactive and shows that the feature is built in. // Terminal off asks first while a shell runs, and then ends the shells of each window.
// @requires plugin:terminal // An old Table Formulas package stays inactive, shows that the feature is built in, and uninstalls without restoration.
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import path from 'node:path'; import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs'; import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { mockFeaturePlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs'; import { mockInstalledPlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs';
await runSmoke('plugins/lifecycle', async ({ browser }) => { await runSmoke('plugins/lifecycle', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
@@ -32,24 +32,12 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
test.emit('workspace-event', { root: ws.root, kind: 'modify', paths: [rel] }); test.emit('workspace-event', { root: ws.root, kind: 'modify', paths: [rel] });
}, },
settings_open_window: () => null, settings_open_window: () => null,
pty_profiles: () => [{ id: 'powershell', title: 'PowerShell', kind: 'powershell' }], // Terminal off asks first while a shell runs (src/lib/layout/SettingsDialog.svelte).
pty_open: async ({ id, channel }) => { 'plugin:dialog|message': args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return 'Ok'; },
const data = new TextEncoder().encode('READY 🪨\r\n\x1b[6n');
// A Terminal plugin that uses api.pty passes a channel and gets raw bytes. Released versions listen for events.
if (channel) setTimeout(() => { channel.onmessage(data.slice(0, 8).buffer); channel.onmessage(data.slice(8).buffer); }, 0);
else {
test.emit('pty-data', { id, data: [...data.slice(0, 8)] });
test.emit('pty-data', { id, data: [...data.slice(8)] });
}
await new Promise(resolve => setTimeout(resolve, 50));
},
pty_write: () => null,
pty_resize: () => null,
pty_close: () => null,
}; };
}, },
}); });
await mockFeaturePlugins(context, [oldTableFormulasRow]); await mockInstalledPlugins(context, [oldTableFormulasRow]);
const output = await outputDir('plugins/lifecycle'); const output = await outputDir('plugins/lifecycle');
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n'; const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table'); const table = page.locator('.live-writer table');
@@ -122,29 +110,38 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await oldPackage.getByText('Included with RuneStone', { exact: true }).waitFor(); await oldPackage.getByText('Included with RuneStone', { exact: true }).waitFor();
await oldPackage.getByText(/Table Formulas is now built in\. You can remove this old package\./).waitFor(); await oldPackage.getByText(/Table Formulas is now built in\. You can remove this old package\./).waitFor();
assert(await oldPackage.getByRole('switch').isDisabled(), 'The old package cannot be enabled'); assert(await oldPackage.getByRole('switch').isDisabled(), 'The old package cannot be enabled');
assert.equal(await switchFor('Terminal').count(), 0, 'Terminal is a feature, not a plugin');
await dialog.getByRole('button', { name: 'Features', exact: true }).click();
await switchFor('Terminal').uncheck(); await switchFor('Terminal').uncheck();
await page.waitForFunction(ptyCalled, 'pty_close'); await page.waitForFunction(ptyCalled, 'pty_close');
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings.png') }); const prompts = await settingsPage.evaluate(() => window.__TEST__.state.prompts);
assert.deepEqual(prompts, ['Terminal sessions will end.\nTurn off Terminal?'], 'Terminal off asks first while a shell runs');
assert.equal(await settingsPage.evaluate(() => window.__TEST__.settings('features').terminal), false);
await settingsPage.screenshot({ path: path.join(output, 'features-terminal-off.png') });
await closeSettings(); await closeSettings();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
const opened = await count('pty_open'); const opened = await count('pty_open');
await page.keyboard.press('Control+j'); await page.keyboard.press('Control+j');
await page.keyboard.press('Control+Shift+Backquote');
assert.equal(await count('pty_open'), opened); assert.equal(await count('pty_open'), opened);
await page.reload(); await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor(); await page.getByText('smoke-workspace', { exact: true }).waitFor();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
await settings(); await settings('Features');
assert(!await switchFor('Terminal').isChecked()); assert(!await switchFor('Terminal').isChecked());
assert.equal(await dialog.getByRole('button', { name: 'Terminal', exact: true }).count(), 0, 'Settings → Terminal shows only while Terminal is on');
const standalone = await openPage(context); const standalone = await openPage(context);
await standalone.goto(smokeUrl + '?terminalWindow=C%3A%5Csmoke-workspace'); await standalone.goto(smokeUrl + '?terminalWindow=C%3A%5Csmoke-workspace');
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor(); await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
await switchFor('Terminal').check(); await switchFor('Terminal').check();
await standalone.locator('.xterm').waitFor(); await standalone.locator('.xterm').waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_open'); await standalone.waitForFunction(ptyCalled, 'pty_open');
await dialog.getByRole('button', { name: 'Terminal', exact: true }).waitFor();
await switchFor('Terminal').uncheck(); await switchFor('Terminal').uncheck();
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor(); await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_close'); await standalone.waitForFunction(ptyCalled, 'pty_close');
assert.equal((await settingsPage.evaluate(() => window.__TEST__.state.prompts)).length, 1, 'The shell of the terminal window gives a prompt too');
page.errors.push(...standalone.errors); page.errors.push(...standalone.errors);
await standalone.close(); await standalone.close();
await switchFor('Terminal').check(); await switchFor('Terminal').check();
@@ -156,17 +153,14 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await quickOpen('formulas.md'); await quickOpen('formulas.md');
await settings(); await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0); assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
for (const name of ['Terminal', 'Table Formulas']) {
await idle(); await idle();
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click(); await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name: 'Table Formulas', exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true }); const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Table Formulas?', exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await confirmation.waitFor({ state: 'hidden' }); await confirmation.waitFor({ state: 'hidden' });
await switchFor(name).waitFor({ state: 'detached' }); await switchFor('Table Formulas').waitFor({ state: 'detached' });
}
await closeSettings(); await closeSettings();
await page.waitForFunction(() => !document.querySelector('.xterm')); assert.equal(await page.locator('.xterm').count(), 1, 'The package removal does not touch the Terminal feature');
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
assert.equal(await table.locator('.md-table-formula').innerText(), '8', 'Removing the old package keeps the built-in formulas'); assert.equal(await table.locator('.md-table-formula').innerText(), '8', 'Removing the old package keeps the built-in formulas');
await page.reload(); await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor(); await page.getByText('smoke-workspace', { exact: true }).waitFor();
@@ -181,5 +175,5 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
console.log([...page.errors, ...settingsPage.errors]); console.log([...page.errors, ...settingsPage.errors]);
throw error; throw error;
} }
console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.'); console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, Terminal off with a prompt, persistence, shortcuts, the terminal window, removal, and no automatic restoration.');
}); });
-3
View File
@@ -1,8 +1,6 @@
// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo. // Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo.
// @requires plugin:terminal
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs"; import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("tables/navigation", async ({ page }) => { await runSmoke("tables/navigation", async ({ page }) => {
await mockTauri(page, { await mockTauri(page, {
@@ -12,7 +10,6 @@ await runSmoke("tables/navigation", async ({ page }) => {
return workspace; return workspace;
}, },
}); });
await mockFeaturePlugins(page);
// Add a file after the workspace opens, as an external change would. // Add a file after the workspace opens, as an external change would.
const addFile = (name, text) => page.evaluate(({ name, text }) => { const addFile = (name, text) => page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text); window.__TEST__.files.set(name, text);
+19 -13
View File
@@ -5,6 +5,7 @@ import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/feature
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts"; import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts"; import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts"; import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts"; import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts"; import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts"; import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
@@ -29,12 +30,12 @@ test("each feature keeps the ID of its old plugin package as its owner ID", () =
}); });
test("switches keep known booleans only, and missing keys take the default", () => { test("switches keep known booleans only, and missing keys take the default", () => {
assert.deepEqual(storedSwitches({ git: false, terminal: true, other: "yes" }), { git: false }); assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {}); assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {}); assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true, background: true }); assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true });
assert.deepEqual(switchesFrom({ git: false, background: false }), { git: false, background: false }); assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false }), { git: false, background: false, terminal: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true }); assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true });
}); });
test("an installed package gives its state, and without a package the default applies", () => { test("an installed package gives its state, and without a package the default applies", () => {
@@ -57,6 +58,11 @@ function presentBackground(): BackgroundMigrationHost {
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } }; return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
} }
/** A terminal host with a section already present. */
function presentTerminal(): TerminalMigrationHost {
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
}
test("the migration asks only for features without a switch, and keeps other keys", async () => { test("the migration asks only for features without a switch, and keeps other keys", async () => {
const writes: unknown[] = []; const writes: unknown[] = [];
const asked: string[][] = []; const asked: string[][] = [];
@@ -65,10 +71,10 @@ test("the migration asks only for features without a switch, and keeps other key
write: async (value: unknown) => { writes.push(value); }, write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; }, legacy: async (ids: string[]) => { asked.push(ids); return packages; },
}); });
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground()), ["git"]); assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]); assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, background: false, git: false }]); assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true }, []), presentBackground()), []); assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true }, []), presentBackground(), presentTerminal()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read."); assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1); assert.equal(writes.length, 1);
}); });
@@ -78,17 +84,17 @@ test("a missing background section asks for the slideshow package and makes the
const switches: unknown[] = []; const switches: unknown[] = [];
const sections: BackgroundSettings[] = []; const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } }; const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } }; const host = { read: () => ({ git: true, background: false, terminal: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background), []); assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]); assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay."); assert.deepEqual(switches, [], "Stored switches stay.");
assert.equal(sections.length, 1); assert.equal(sections.length, 1);
assert.equal(sections[0].source, "image"); assert.equal(sections[0].source, "image");
// Both migrations together ask once for both packages. // Both migrations together ask once for both packages.
asked.length = 0; asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background); await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal());
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow"]]); assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal"]]);
assert.deepEqual(switches, [{ git: true, background: true }]); assert.deepEqual(switches, [{ git: true, background: true, terminal: true }]);
}); });
test("a failed package read writes nothing, so the next start tries again", async () => { test("a failed package read writes nothing, so the next start tries again", async () => {
@@ -97,7 +103,7 @@ test("a failed package read writes nothing, so the next start tries again", asyn
console.error = () => {}; console.error = () => {};
try { try {
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } }; const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background); const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal());
assert.deepEqual(result, []); assert.deepEqual(result, []);
assert.deepEqual(writes, []); assert.deepEqual(writes, []);
} finally { console.error = error; } } finally { console.error = error; }
+269
View File
@@ -0,0 +1,269 @@
// The Terminal feature: the catalog entry, the shell commands and tasks, the shortcuts, the session lifecycle,
// the theme map, the settings section, and the first-start migration of the plugin settings.
import { test } from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { migrateFeatures } from "../../../src/lib/features/migration.ts";
import { TERMINAL_KEYS, TERMINAL_SHORTCUTS, terminalShortcut, type TerminalAction } from "../../../src/lib/features/terminalKeys.ts";
import { DEFAULT_TERMINAL, migrateTerminal, normalizeTerminal, type TerminalMigrationHost, type TerminalSettings } from "../../../src/lib/features/terminalSettings.ts";
import { directoryCommand, fileCommand, parseTasks, pickProfile, quoteShell, remember, type ShellProfile } from "../../../src/lib/features/terminal/model.ts";
import { TerminalSessions, type PtyRequest, type PtyTransport } from "../../../src/lib/features/terminal/sessions.ts";
import { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts";
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.ts";
test("Terminal keeps the ID of the Terminal plugin and follows its package", () => {
const terminal = featureEntry("terminal");
assert.equal(terminal.owner, "runestone.terminal");
assert.equal(featureOfOwner("runestone.terminal")?.id, "terminal");
assert.equal(terminal.defaultOn, true);
assert.equal(terminal.followsPackage, true);
assert.deepEqual(terminal.views, []);
assert.deepEqual(terminal.commands, []);
});
test("paths are shell-quoted without evaluating metacharacters", () => {
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
assert.equal(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
assert.equal(directoryCommand("C:\\two words", "bash"), "cd -- 'C:/two words'");
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"), /PowerShell/);
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"), /line breaks/);
});
test("run file selects a runner and refuses documents that do not run", () => {
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
assert.equal(fileCommand("D:\\tools\\app.exe", "powershell"), "& 'D:\\tools\\app.exe'");
assert.equal(fileCommand("D:\\tools\\build.cmd", "cmd"), 'cmd /c "D:\\tools\\build.cmd"');
assert.throws(() => fileCommand("notes.md", "powershell"), /cannot run this file type/);
assert.throws(() => fileCommand("app.js", "node"), /Node\.js REPL/);
});
test("the tasks file must be valid before the panel offers a task", () => {
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
for (const text of ["{}", "null", '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text), text);
});
test("history puts the newest value first, has no duplicates, and keeps 100 values", () => {
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
assert.deepEqual(remember(["one"], " "), ["one"]);
});
test("a new terminal takes the default profile, then the first shell that is not Node.js", () => {
const profiles: ShellProfile[] = [{ id: "node", title: "JavaScript Debug Terminal", kind: "node" }, { id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }];
assert.equal(pickProfile(profiles, "cmd")?.id, "cmd");
assert.equal(pickProfile(profiles, "")?.id, "powershell");
assert.equal(pickProfile(profiles, "missing")?.id, "powershell");
assert.equal(pickProfile([profiles[0]], "")?.id, "node");
assert.equal(pickProfile([], ""), undefined);
});
/** A key event for a written combination such as "Mod+Shift+`". Mod is Ctrl. */
function press(combination: string) {
const parts = combination.split("+");
const key = parts.pop()!;
const has = (name: string) => parts.includes(name);
const code = key === "`" ? "Backquote" : /^\d$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key;
return { ctrlKey: has("Mod") || has("Ctrl"), metaKey: false, altKey: has("Alt"), shiftKey: has("Shift"), code, key: key.length === 1 ? key.toLowerCase() : key };
}
test("physical key shortcuts tell new, split, window, and hide apart", () => {
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
assert.equal(terminalShortcut(key), "new");
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
assert.equal(terminalShortcut({ ...key, ctrlKey: false, metaKey: true, shiftKey: false }), "toggle", "Cmd works as Ctrl on macOS.");
assert.equal(terminalShortcut({ ...key, ctrlKey: false }), null);
// Each combination that menus and Help show gives its own action.
for (const [action, combination] of Object.entries(TERMINAL_KEYS)) assert.equal(terminalShortcut(press(combination)), action as TerminalAction, combination);
assert.ok(TERMINAL_SHORTCUTS.every(row => row.label && row.keys && !/Ctrl/.test(row.keys)), "Help rows use Mod, so macOS shows Cmd.");
});
/** A fake host. `hold()` makes the next open wait for `release()`. */
function fakeTransport() {
const calls: string[] = [];
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
let holding: Promise<void> = Promise.resolve();
let release: () => void = () => {};
let failClose = false;
const transport: PtyTransport = {
open: async (request: PtyRequest, data, exit) => {
calls.push(`open:${request.id}:${request.profile ?? ""}:${request.directory ?? ""}`);
outputs.set(request.id, { data, exit });
await holding;
},
write: async (id, data) => { calls.push(`write:${id}:${data}`); },
resize: async (id, cols, rows) => { calls.push(`resize:${id}:${cols}x${rows}`); },
close: async id => { calls.push(`close:${id}`); if (failClose) throw new Error("close failed"); },
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
openWindow: async () => { calls.push("window"); },
dictation: async () => { calls.push("dictation"); },
};
return {
transport, calls, outputs,
hold() { holding = new Promise(resolve => { release = resolve; }); },
release: () => release(),
failClose(value: boolean) { failClose = value; },
};
}
const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
const options = (output: string[] = [], exits: (number | null)[] = []) => ({ cwd: "C:\\work", cols: 80, rows: 24, onData: (data: Uint8Array) => output.push(text(data)), onExit: (code: number | null) => exits.push(code) });
test("sessions deliver their own output, write, resize, and close once", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
assert.deepEqual(await sessions.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
const output: string[] = [];
await sessions.open("a", { ...options(output), profile: "pwsh", directory: "C:\\work\\src" });
await sessions.open("b", options());
assert.deepEqual(host.calls.slice(0, 2), ["open:a:pwsh:C:\\work\\src", "open:b::"]);
host.outputs.get("a")!.data(new TextEncoder().encode("ready"));
await sessions.write("a", "dir\r");
await sessions.resize("a", 100, 30);
assert.deepEqual(output, ["ready"]);
assert.deepEqual(host.calls.slice(-2), ["write:a:dir\r", "resize:a:100x30"]);
await assert.rejects(sessions.open("a", options()), /already running/);
await Promise.all([sessions.close("a"), sessions.close("a")]);
assert.equal(host.calls.filter(call => call === "close:a").length, 1);
await assert.rejects(sessions.write("a", "x"), /not running/);
host.outputs.get("a")!.data(new TextEncoder().encode("late"));
assert.deepEqual(output, ["ready"], "A closed pane gets no more output.");
await assert.rejects(sessions.open("a", options()), /closed/);
await assert.rejects(sessions.write("missing", "x"), /not running/);
await sessions.openWindow();
await sessions.dictation();
assert.deepEqual(host.calls.slice(-2), ["window", "dictation"]);
});
test("a close waits for the start of its shell, and a closed pane cannot start", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
host.hold();
const start = sessions.open("starting", options());
const close = sessions.close("starting");
assert.equal(sessions.close("starting"), close, "A second close returns the same promise.");
await Promise.resolve();
assert.deepEqual(host.calls, ["open:starting::"]);
host.release();
await Promise.all([start, close]);
assert.deepEqual(host.calls, ["open:starting::", "close:starting"]);
await sessions.close("not-started");
await assert.rejects(sessions.open("not-started", options()), /closed/);
assert.equal(host.calls.length, 2);
});
test("an exited shell needs no close, and a failed close can be tried again", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
const exits: (number | null)[] = [];
await sessions.open("exits", options([], exits));
host.outputs.get("exits")!.exit(3);
host.outputs.get("exits")!.exit(4);
assert.deepEqual(exits, [3], "The exit reaches the pane one time.");
await assert.rejects(sessions.write("exits", "x"), /not running/);
await sessions.close("exits");
assert.equal(host.calls.includes("close:exits"), false);
await sessions.open("writer", options());
host.failClose(true);
await assert.rejects(sessions.close("writer"), /close failed/);
host.failClose(false);
await sessions.close("writer");
assert.equal(host.calls.filter(call => call === "close:writer").length, 2);
});
test("closeAll stops every shell, also one that is starting, and later calls fail", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
await sessions.open("one", options());
host.hold();
const late = sessions.open("late", options());
const stopping = sessions.closeAll();
assert.equal(sessions.signal.aborted, true);
host.release();
await late;
await stopping;
assert.deepEqual(host.calls.filter(call => call.startsWith("close:")).sort(), ["close:late", "close:one"]);
await assert.rejects(sessions.open("again", options()), /This feature is off/);
await assert.rejects(sessions.profiles(), /This feature is off/);
await assert.rejects(sessions.openWindow(), /This feature is off/);
});
test("the terminal colors come from the theme tokens, with the 16 ANSI colors from --rs-ansi-*", () => {
const asked: [string, number][] = [];
const theme = terminalColors((css, maxAlpha) => { asked.push([css, maxAlpha]); return css; });
assert.equal(theme.background, "#00000000", "The panel surface shows through the terminal.");
assert.equal(theme.foreground, "var(--rs-text)");
assert.equal(theme.cursor, "var(--rs-accent)");
assert.equal(theme.cursorAccent, "var(--rs-bg)");
assert.equal(theme.selectionBackground, "var(--rs-selection)");
assert.deepEqual(asked.find(([css]) => css === "var(--rs-selection)"), ["var(--rs-selection)", SELECTION_ALPHA]);
assert.equal(SELECTION_ALPHA, 165);
for (const color of ANSI_COLORS) {
const bright = `bright${color[0].toUpperCase()}${color.slice(1)}` as keyof typeof theme;
assert.equal(theme[color], `var(--rs-ansi-${color})`);
assert.equal(theme[bright], `var(--rs-ansi-bright-${color})`);
}
assert.equal(TERMINAL_TOKENS.filter(item => item.token.startsWith("var(--rs-ansi-")).length, 16);
assert.ok(asked.filter(([css]) => css !== "var(--rs-selection)").every(([, alpha]) => alpha === 255), "Only the selection has an alpha cap.");
});
test("the terminal settings section has valid values and its own old key", () => {
assert.ok((SETTINGS_SECTIONS as readonly string[]).includes("terminal"));
assert.equal(LEGACY_KEYS.terminal, "runestone.terminal");
assert.deepEqual(normalizeTerminal(undefined), DEFAULT_TERMINAL);
assert.deepEqual(normalizeTerminal(["x"]), DEFAULT_TERMINAL);
assert.deepEqual(normalizeTerminal({ defaultProfile: "cmd", fontSize: 40, scrollback: 5, cursorBlink: false, future: 1 }),
{ defaultProfile: "cmd", fontSize: 28, scrollback: 100, cursorBlink: false });
assert.deepEqual(normalizeTerminal({ defaultProfile: 3, fontSize: 2, scrollback: 250000, cursorBlink: "no" }),
{ defaultProfile: "", fontSize: 9, scrollback: 100000, cursorBlink: true });
assert.equal(normalizeTerminal({ fontSize: 14.6 }).fontSize, 15);
assert.equal(normalizeTerminal({ fontSize: Number.NaN }).fontSize, 13);
});
function terminalHost(missing: boolean, legacy: string | null | (() => never)): TerminalMigrationHost & { written: TerminalSettings[] } {
const written: TerminalSettings[] = [];
return { written, missing: () => missing, legacy: () => typeof legacy === "function" ? legacy() : legacy, write: async value => { written.push(value); } };
}
test("the first start copies the plugin settings into the terminal section once", async () => {
const plugin = JSON.stringify({ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
const copy = terminalHost(true, plugin);
assert.deepEqual(await migrateTerminal(copy), { defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
assert.deepEqual(copy.written, [{ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false }]);
const present = terminalHost(false, plugin);
assert.equal(await migrateTerminal(present), null);
assert.deepEqual(present.written, [], "An existing section stays.");
const none = terminalHost(true, null);
assert.equal(await migrateTerminal(none), null);
assert.deepEqual(none.written, [], "Without the old key, the defaults apply and nothing is written.");
const damaged = terminalHost(true, "{not json");
assert.deepEqual(await migrateTerminal(damaged), DEFAULT_TERMINAL);
const blocked = terminalHost(true, () => { throw new Error("storage is blocked"); });
assert.equal(await migrateTerminal(blocked), null);
});
test("the feature migration copies the terminal settings also when the package report fails", async () => {
const error = console.error;
console.error = () => {};
try {
const terminal = terminalHost(true, JSON.stringify({ fontSize: 20 }));
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
const host = { read: () => undefined, write: async () => { throw new Error("not asked"); }, legacy: async () => { throw new Error("no host"); } };
assert.deepEqual(await migrateFeatures(host, background, terminal), []);
assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]);
} finally { console.error = error; }
});
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
const writes: unknown[] = [];
const host = { read: () => ({ git: true, background: true }), write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]);
assert.deepEqual(writes, [{ git: true, background: true, terminal: false }]);
});
+1 -77
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts"; import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts"; import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ServiceHub } from "../../../src/lib/plugins/services.ts"; import { ServiceHub } from "../../../src/lib/plugins/services.ts";
import type { FilesTransport, PluginApi, PtyTransport } from "../../../src/lib/plugins/sdk.ts"; import type { FilesTransport, PluginApi } from "../../../src/lib/plugins/sdk.ts";
const base: SessionServices = { const base: SessionServices = {
workspace: { list: async () => [], read: async () => "", write: async () => {} }, workspace: { list: async () => [], read: async () => "", write: async () => {} },
@@ -17,82 +17,6 @@ async function start(id: string, services: Partial<SessionServices>) {
return { api, session }; return { api, session };
} }
function fakePty() {
const calls: unknown[][] = [];
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
let release: (() => void) | undefined;
const transport: PtyTransport & { hold(): void } = {
hold() { let done!: () => void; const wait = new Promise<void>(resolve => { done = resolve; }); release = done; holding = wait; },
open: async (request, data, exit) => { calls.push(["open", request]); outputs.set(request.id, { data, exit }); await holding; },
write: async (id, data) => { calls.push(["write", id, data]); },
resize: async (id, cols, rows) => { calls.push(["resize", id, cols, rows]); },
close: async id => { calls.push(["close", id]); },
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
openWindow: async () => { calls.push(["window"]); },
dictation: async () => { calls.push(["dictation"]); },
};
let holding: Promise<void> = Promise.resolve();
return { transport, calls, outputs, release: () => release?.() };
}
test("terminal sessions deliver their own output and close when the plugin stops", async () => {
const pty = fakePty();
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
assert.equal(api.pty!.version, 1);
assert.deepEqual(await api.pty!.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
const received: string[] = [];
const exits: (number | null)[] = [];
const first = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh", onData: data => received.push(new TextDecoder().decode(data)), onExit: code => exits.push(code) });
const second = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
assert.notEqual(first.id, second.id);
assert.deepEqual(pty.calls[0], ["open", { id: first.id, cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh" }]);
pty.outputs.get(first.id)!.data(new TextEncoder().encode("ready"));
await first.write("dir\r");
await first.resize(100, 30);
assert.deepEqual(received, ["ready"]);
assert.deepEqual(pty.calls.slice(-2), [["write", first.id, "dir\r"], ["resize", first.id, 100, 30]]);
assert.throws(() => first.resize(0, 30), /positive integers/);
// An exited session needs no close at shutdown.
pty.outputs.get(first.id)!.exit(0);
assert.deepEqual(exits, [0]);
await session.stop();
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", second.id]]);
pty.outputs.get(second.id)!.data(new TextEncoder().encode("late"));
assert.deepEqual(received, ["ready"]);
assert.throws(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }), /disabled/);
assert.throws(() => api.pty!.openWindow(), /disabled/);
assert.throws(() => second.write("x"), /disabled/);
// Close stays safe after shutdown and is not repeated.
await second.close();
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
});
test("a terminal session that starts after shutdown is closed", async () => {
const pty = fakePty();
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
pty.transport.hold();
const opening = api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
const stopping = session.stop();
pty.release();
await assert.rejects(opening, /disabled/);
await stopping;
const id = (pty.calls[0][1] as { id: string }).id;
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", id]]);
});
test("a closed terminal session rejects input and closes once", async () => {
const pty = fakePty();
const { api } = await start("org.test.terminal", { pty: pty.transport });
const output: string[] = [];
const terminal = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: data => output.push(String(data.length)) });
await Promise.all([terminal.close(), terminal.close()]);
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
assert.throws(() => terminal.write("x"), /closed/);
pty.outputs.get(terminal.id)!.data(new Uint8Array([1]));
assert.deepEqual(output, []);
await assert.rejects(Promise.resolve().then(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24 } as never)), /onData/);
});
test("folder grant calls check shutdown before and after the native request", async () => { test("folder grant calls check shutdown before and after the native request", async () => {
const calls: unknown[][] = []; const calls: unknown[][] = [];
let finish: ((value: unknown) => void) | undefined; let finish: ((value: unknown) => void) | undefined;
+15 -14
View File
@@ -5,9 +5,9 @@ import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts"; import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
import type { Contributions } from "../../../src/lib/plugins/contracts.ts"; import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
// A small test-only package. It contributes a feature, as the optional plugins do. // A small test-only package. It contributes the browser, as the built-in browser module does.
const terminal: Contributions["terminal"] = { mount: () => ({ update() {}, command() {}, dispose() {} }), shortcut: () => null }; const browser: Contributions["browser"] = { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => false };
const activate = (api: PluginApi) => { api.contribute("terminal", terminal); }; const activate = (api: PluginApi) => { api.contribute("browser", browser); };
const services = { const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} }, workspace: { list: async () => [], read: async () => "", write: async () => {} },
@@ -37,23 +37,24 @@ test("optional workspace creation and reads stop when the plugin is disabled", a
assert.equal(files.size, 1); assert.equal(files.size, 1);
}); });
test("core starts without optional features and package contributions end with their session", async () => { test("core starts without optional features and package contributions end with their session", async () => {
assert.equal(pluginHost.get("terminal"), undefined); assert.equal(pluginHost.get("browser"), undefined);
const registry = new ContributionRegistry(); const registry = new ContributionRegistry();
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry); const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await session.start({ activate }); await session.start({ activate });
assert.equal(registry.get("terminal"), terminal); assert.equal(registry.get("browser"), browser);
await session.stop(); await session.stop();
assert.equal(registry.get("terminal"), undefined); assert.equal(registry.get("browser"), undefined);
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry); const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await next.start({ activate }); await next.start({ activate });
assert.equal(registry.get("terminal"), terminal); assert.equal(registry.get("browser"), browser);
await next.stop(); await next.stop();
assert.equal(registry.get("terminal"), undefined); assert.equal(registry.get("browser"), undefined);
}); });
test("unknown contribution keys are rejected", () => { test("unknown contribution keys are rejected", () => {
const registry = new ContributionRegistry(); const registry = new ContributionRegistry();
for (const key of ["tableFormulas", "git"]) assert.throws(() => registry.register("old", key as keyof Contributions, terminal as never), /Unknown plugin contribution/); // `terminal` was a contribution until the Terminal feature became native.
for (const key of ["tableFormulas", "git", "terminal"]) assert.throws(() => registry.register("old", key as keyof Contributions, browser as never), /Unknown plugin contribution/);
}); });
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => { test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
@@ -62,13 +63,13 @@ test("package contribution conflicts preserve the first owner and revoke access
const second = new ExternalSession("second", services, () => {}, () => {}, registry); const second = new ExternalSession("second", services, () => {}, () => {}, registry);
let api!: PluginApi; let api!: PluginApi;
await first.start({ activate(value) { api = value; activate(api); } }); await first.start({ activate(value) { api = value; activate(api); } });
const contribution = registry.get("terminal"); const contribution = registry.get("browser");
await assert.rejects(second.start({ activate }), /already registered/); await assert.rejects(second.start({ activate }), /already registered/);
await second.stop(); await second.stop();
assert.equal(registry.get("terminal"), contribution); assert.equal(registry.get("browser"), contribution);
api.onDispose(() => { api.onDispose(() => {
assert.equal(registry.get("terminal"), undefined); assert.equal(registry.get("browser"), undefined);
assert.throws(() => api.contribute("terminal", contribution!), /disabled/); assert.throws(() => api.contribute("browser", contribution!), /disabled/);
}); });
await first.stop(); await first.stop();
}); });
@@ -82,5 +83,5 @@ test("partial activation and failed cleanup cannot retain feature contributions"
throw new Error("Activation failed"); throw new Error("Activation failed");
} }), /Activation failed/); } }), /Activation failed/);
await assert.rejects(session.stop(), /Cleanup failed/); await assert.rejects(session.stop(), /Cleanup failed/);
assert.equal(registry.get("terminal"), undefined); assert.equal(registry.get("browser"), undefined);
}); });
+12 -12
View File
@@ -15,8 +15,7 @@ import type { ActionMenuItem as HostMenuItem } from "../../../src/lib/ui/actionM
import type { MenuOptions as HostMenuOptions } from "../../../src/lib/ui/managedActionMenu.ts"; import type { MenuOptions as HostMenuOptions } from "../../../src/lib/ui/managedActionMenu.ts";
import type { ActionMenuItem, ActionMenuOptions } from "../../../packages/plugin-sdk/src/index.ts"; import type { ActionMenuItem, ActionMenuOptions } from "../../../packages/plugin-sdk/src/index.ts";
// The host menu files must match the copies in the Terminal plugin (scripts/menuSurfaceAudit.mjs), so they keep // The host menu files keep their own menu types. `pnpm check` fails when those types and the SDK types differ.
// their own menu types. `pnpm check` fails when those types and the SDK types differ.
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const sameMenuTypes: [Same<HostMenuItem, ActionMenuItem>, Same<HostMenuOptions, ActionMenuOptions>] = [true, true]; const sameMenuTypes: [Same<HostMenuItem, ActionMenuItem>, Same<HostMenuOptions, ActionMenuOptions>] = [true, true];
@@ -40,15 +39,17 @@ test("feature checks find optional members, and missing members give an update m
assert.equal(hasFeature(api, "workspace.readBytes"), true); assert.equal(hasFeature(api, "workspace.readBytes"), true);
assert.equal(hasFeature(api, "services"), true); assert.equal(hasFeature(api, "services"), true);
assert.equal(hasFeature(api, "workspace.subscribe"), false); assert.equal(hasFeature(api, "workspace.subscribe"), false);
assert.equal(hasFeature(api, "pty"), false); assert.equal(hasFeature(api, "files"), false);
assert.deepEqual(missingFeatures(api, ["pty", "workspace.readBytes", "settings.subscribe"]), ["pty", "settings.subscribe"]); assert.deepEqual(missingFeatures(api, ["files", "workspace.readBytes", "settings.subscribe"]), ["files", "settings.subscribe"]);
assert.equal(requireFeature(api, "services"), (api as unknown as { services: unknown }).services); assert.equal(requireFeature(api, "services"), (api as unknown as { services: unknown }).services);
assert.throws(() => requireFeature(api, "pty"), (error: unknown) => error instanceof MissingFeatureError assert.throws(() => requireFeature(api, "files"), (error: unknown) => error instanceof MissingFeatureError
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "pty" && error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "files"
&& error.message === "This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature."); && error.message === "This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.");
assert.throws(() => requireFeatures(api, ["pty", "files", "workspace.readBytes"]), { assert.throws(() => requireFeatures(api, ["files", "backgrounds", "workspace.readBytes"]), {
message: "This plugin needs the terminal API (api.pty) and the folder grant API (api.files). Update RuneStone to a version that has these features.", message: "This plugin needs the folder grant API (api.files) and the background API (api.backgrounds). Update RuneStone to a version that has these features.",
}); });
// The terminal API (api.pty) left the SDK when Terminal became a native feature.
assert.throws(() => hasFeature(api, "pty" as never), TypeError);
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"])); assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError); assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)"); assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)");
@@ -63,10 +64,9 @@ test("a required function stays bound to its parent object", async () => {
}); });
test("the current host gives every SDK feature when all services are present", async () => { test("the current host gives every SDK feature when all services are present", async () => {
const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} };
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} }; const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
const { api, session } = await hostApi({ const { api, session } = await hostApi({
pty, files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {}, files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} }, workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
settings: { ...base.settings, subscribe: () => () => {} }, settings: { ...base.settings, subscribe: () => () => {} },
}, true); }, true);
@@ -78,7 +78,7 @@ test("the host without optional services lacks only the features that depend on
const { api, session } = await hostApi({}); const { api, session } = await hostApi({});
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [ assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
"backgrounds", "closeView", "completion.transport", "files", "backgrounds", "closeView", "completion.transport", "files",
"openFile", "pty", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe", "openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe", "workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
]); ]);
await session.stop(); await session.stop();
+2 -1
View File
@@ -66,5 +66,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
test('Every section has one old key', () => { test('Every section has one old key', () => {
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them. // `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']); // `runestone.terminal` is the key of the Terminal plugin. The first start of the Terminal feature copies it into the file.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings', 'runestone.terminal']);
}); });