Initial RuneStone project

This commit is contained in:
Knotty Wyvern
2026-09-26 01:25:42 -07:00
commit bdc15e952d
190 changed files with 25986 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
src-tauri/target
src-tauri/gen
.idea
/.audit
+7
View File
@@ -0,0 +1,7 @@
{
"recommendations": [
"svelte.svelte-vscode",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"svelte.enable-ts-plugin": true
}
+63
View File
@@ -0,0 +1,63 @@
# RuneStone project instructions
## Documentation
Keep the README focused on the project, its usefulness, setup, help, and maintainers.
Keep agent instructions in this file. Put detailed usage, development notes, and
product plans in `docs/`, with links from the README.
Keep the roadmap visual and organized around goals, user outcomes, and milestones.
Keep detailed capability lists and design constraints in the product scope reference.
## UI work: prefer meaningful icons
Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI.
Apply them automatically without requiring the user to repeat them.
- Favor recognizable icons for actions, navigation, menus, and settings categories.
Help users recognize functions without relying only on English vocabulary.
Use icons to save space and reduce clutter.
- Pair icons with concise visible labels when the meaning could be ambiguous.
Keep labels that help users learn or distinguish functions.
- Use icon-only controls for familiar actions in compact spaces.
Give them accessible names, tooltips on hover and keyboard focus, and comfortable click targets.
- Reuse existing icon components and artwork. Keep the same icon for the same function.
Maintain consistent sizing and stroke weight.
- Do not force icons onto every setting, label, or explanation.
Use text alone when no clear icon exists. Omit decoration that does not improve understanding.
Recognition and accessibility take priority over fitting more controls on screen.
- Use Obsidian's settings pattern as a reference: icons with labels in navigation,
readable text and ordinary controls in detailed settings.
For UI reviews, check changed controls against these rules.
## UI work: use rounded corners
Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI.
Apply them automatically without requiring the user to repeat them.
- Use rounded corners consistently for controls and navigation highlights, including file and folder selections.
Compact controls and navigation rows share `--rs-control-radius`.
Selection outlines use `--rs-item-selection-radius`.
- Round exposed selection corners while keeping adjacent selected rows joined.
Do not add rounded gaps or selection borders on shared edges.
- Apply the same treatment to hover, active, and selected navigation states.
- Tables inside documents are the exception: keep grids, cells, and cell selection outlines square.
Table toolbar and menu controls still use rounded corners.
## UI work: outline only the outer boundary of a selection
Apply these rules whenever designing, implementing, modifying, or reviewing selection UI.
Apply them automatically without requiring the user to repeat them.
- Adjacent selected rows or cells share one highlighted region.
Highlight only its exposed perimeter. Omit selection borders on shared internal edges.
Apply this to navigation rows, table cells, lists, and grids.
- Use the shared `--rs-item-selection-*` theme values for fill, border color, and border width.
Use table-cell selection as the fill and outline reference, with rounded exposed corners outside document tables.
- Separate groups, divided by unselected items or physical gaps, retain separate outlines.
A single selected item gets a complete outline.
- Determine adjacency from visible layout order, including sorting and expanded tree branches.
At indentation changes, preserve exposed edges and omit the portions shared by selected rows.
- Keep the fill continuous within each selected region.
Ordinary table grid lines can remain, but must not become highlighted selection borders inside the region.
- Check single items, contiguous ranges, separated selections, and nested rows.
+73
View File
@@ -0,0 +1,73 @@
# RuneStone
A desktop workspace for writing and code.
RuneStone brings Markdown notes, scripts, images, and a terminal into one window.
Open a folder and work with the files already inside it.
## Why RuneStone?
Notes and code often belong to the same project. RuneStone keeps them together,
so you can write an explanation, edit a script, and run it in the same workspace.
Your documents stay as ordinary files on disk. You can open them in other editors
and use your own tools to manage them. Workspace settings live separately in `.runestone/`.
## Features
- **Markdown writing:** Live formatting, source editing, split view, and read view.
- **Code editing:** A source editor for scripts, with file navigation and workspace search.
- **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams.
- **Tables:** Editable Markdown tables with formulas for calculations.
- **Terminals:** Multiple shell sessions, split panes, and commands beside your documents.
- **File handling:** Autosave every five seconds and controls to resolve changes from other tools.
## Project status
RuneStone is under development, with Windows as its first target.
**Plugin support is planned and is not available yet.** Git controls, language servers,
session restoration, and crash recovery are also pending.
The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones.
The [user guide](docs/user-guide.md) covers current features and limitations.
## Get started
RuneStone runs on Windows 10 and 11 (64-bit). There is no public installer download yet.
If you have a supplied installer:
1. Open `RuneStone_<version>_x64-setup.exe`.
2. Follow the setup steps.
3. Open **RuneStone** from the Windows Start menu.
4. Use the folder button to open a workspace or create one.
The installer sets up RuneStone for your Windows account. You do not need a terminal or developer tools.
If Microsoft Edge WebView2 is missing, setup downloads and installs it, which needs an internet connection.
Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save.
See the [installation guide](docs/installation.md) for setup help, updates, and removal.
To run from source, see the [development guide](docs/development.md#run-from-source).
## Documentation
Documentation lives in this repository:
- [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts.
- [Installation guide](docs/installation.md): Windows setup and troubleshooting.
- [Development guide](docs/development.md): Build tools, source setup, and tests.
- [Release guide](docs/releases.md): Build and package the Windows installer.
- [Roadmap](docs/roadmap.md): Product direction, goals, and milestones.
## Contributing
Contributions can include code, documentation, reproducible bug reports, and feature proposals.
Read the [development guide](docs/development.md) for the build and test workflow,
and the [product scope](docs/product-scope.md) for detailed capabilities and boundaries.
Bug reports should include the operating system, steps to reproduce the problem,
the expected result, and any error message.
## Maintainer
[kwyvern-gh](https://github.com/kwyvern-gh)
+72
View File
@@ -0,0 +1,72 @@
# Development guide
[Back to RuneStone](../README.md)
## Stack
RuneStone uses Tauri 2 and Rust for the desktop host.
The interface uses Svelte 5, TypeScript, and Vite.
CodeMirror handles live Markdown editing, Monaco handles source editing, and xterm handles terminals.
Windows is the first target. The older WriterHost component remains unused.
See the setup steps below to install dependencies and run the desktop app.
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md).
## Run from source
These steps are for developers. App users can use the [Windows installer](installation.md).
### Requirements
- Node.js 22.12 or later and pnpm
- A current stable Rust toolchain
- Microsoft C++ Build Tools and Microsoft Edge WebView2 on Windows
Use the [Tauri prerequisites guide](https://v2.tauri.app/start/prerequisites/) to install the Windows build tools and Rust toolchain.
1. Download or clone this repository.
2. Open a terminal in the repository folder.
3. Run `pnpm install --frozen-lockfile`.
4. Run `pnpm tauri dev`.
5. Use the folder button in the app to open a workspace or create one.
See the [release guide](releases.md) to build a Windows installer.
## Checks
Run these commands from the repository folder:
```sh
pnpm check
pnpm test
pnpm build
cargo test --manifest-path src-tauri/Cargo.toml --lib --offline
```
The offline Rust command requires cached dependencies. Omit `--offline` if Cargo needs to download them.
`pnpm build` builds the frontend. Use `pnpm tauri build` to build the desktop app.
The Rust tests cover real terminal shells, working directories, Unicode output,
resizing, exit status, and session termination. Native terminal tests launch each
detected shell profile and check shell prompt integration.
## Browser smoke tests
The browser tests use the real interface with mocked desktop communication.
They do not replace native desktop tests.
1. Install Playwright, or set `PLAYWRIGHT_MODULE` to a shared Playwright package.
2. Start the frontend with `pnpm dev`.
3. In a second terminal, run a smoke script, such as `node scripts/workbench.smoke.mjs`.
Set `CHROME_PATH` if you need to select an installed browser executable.
| Script | Coverage |
| --- | --- |
| `scripts/workbench.smoke.mjs` | The Svelte, Monaco, and xterm interface |
| `scripts/terminal.smoke.mjs` | Terminal groups, single-session layout, menus, profiles, history, tasks, settings, and editor actions |
| `scripts/images.smoke.mjs` | Image drops, clipboard imports, source editing, zoom, undo, failed writes, and tab changes during imports |
| `scripts/imageNavigation.smoke.mjs` | Navigator pointer drags, hidden image source, selection, context actions, inline/reference images, and drag cancellation |
Additional smoke scripts live in `scripts/`.
+47
View File
@@ -0,0 +1,47 @@
# Installation guide
[Back to RuneStone](../README.md)
## Install on Windows
RuneStone supports Windows 10 and 11 on 64-bit Intel and AMD computers.
The installer contains the app and its interface. You do not need developer tools or a terminal.
There is no public download yet. Get the setup file from the maintainer who supplied your release.
1. Save `RuneStone_<version>_x64-setup.exe` to your Downloads folder.
2. Double-click the file.
3. Follow the setup steps.
4. Open **RuneStone** from the Windows Start menu.
5. Use the folder button to open a workspace or create one.
Keep the default installation folder unless you need a different location.
Setup installs the app for your Windows account and adds a Start menu shortcut.
If WebView2 is missing, setup downloads and installs it. Keep your internet connection active until setup finishes.
## Update RuneStone
1. Save your open documents.
2. Close all RuneStone windows.
3. Open the installer for the newer version.
4. Follow the setup steps.
The installer replaces the app. Your workspace files stay in their current folders.
Setup blocks older versions from replacing a newer version.
## Remove RuneStone
1. Open **Settings > Apps > Installed apps** in Windows 11, or **Apps & features** in Windows 10.
2. Find **RuneStone**.
3. Select **Uninstall**.
Your workspace folders contain your notes, scripts, images, and workspace settings.
Keep these folders outside the app installation folder. Removing the app leaves these separate folders in place.
## Setup help
- **WebView2 download fails:** Restore your internet connection, then run the installer again.
- **Windows shows an unknown publisher:** Current local builds are unsigned. Check the file source with the maintainer before you proceed.
- **The app cannot open a workspace:** Use the folder button to choose a folder that your Windows account can access.
The [user guide](user-guide.md) explains the app controls.
The [release guide](releases.md) explains how maintainers build and distribute installers.
+87
View File
@@ -0,0 +1,87 @@
# Product scope
[Back to RuneStone](../README.md)
This reference preserves intended capabilities and design constraints. Some features already exist.
See the [roadmap](roadmap.md) for goals and milestones, and the [user guide](user-guide.md) for current behavior and limitations.
The planned design keeps the core active and adds optional features through first-party plugins. Plugin support is not implemented yet.
## Workspace and files
- Open one folder as the workspace.
- Keep notes, scripts, and images in the same tree.
- Honor `.gitignore` in the navigator.
- Watch the folder for changes. Poll when the path is a network drive.
- Prefer a local Git clone. Do not treat a live network share as the sync path.
- Store display order, pins, bookmarks, and plugin settings in `.runestone/`.
- Open an existing Obsidian folder as files plus wiki links. Ignore `.obsidian`.
## Writer and IDE
- Use one editor engine for notes and code.
- Switch chrome between Writer and IDE. Autodetect from the file type. Allow a per-file override.
- Writer chrome uses wrapped text, a document preview, and image hover previews.
- IDE chrome uses line numbers, a minimap, and a terminal dock.
- Left-click a file in the navigation pane to open it in the current tab; middle-click to open it in a new tab. Tabs with unsaved edits stay open. Already-open files select their existing tab. Close a tab with the close control or the middle mouse button.
- Support Markdown, Python, JavaScript, TypeScript, JSON, YAML, TOML, and shell at first.
- Parse CommonMark, GFM tasks and tables, YAML frontmatter, wiki links, and tags.
## Navigator
- Show a left activity bar with Files, Search, and Bookmarks.
- Click the active item again to hide the sidebar.
- Right-click empty space to create a folder or a note.
- Right-click a file for copy, bookmark, path copy, reveal, pin, rename, and delete.
- Drag files and folders to move them or to set display order.
- Save display order. Do not reorder inodes for sort.
- Show a ribbon with new file, new folder, sort, and collapse all or expand all.
## Panes
- Show an outline of headings and symbols on the right. Allow collapse.
- Show a minimap of the open buffer.
- Open a terminal whose working directory is the workspace root.
- Allow more than one terminal. Add a session and kill that session from a rail on the right of the dock.
- Show a document preview that renders Markdown images.
## Plugins
Plugin support is pending. The plan is to ship extra features as first-party plugins with an on or off toggle. A marketplace is outside the planned scope.
Planned plugins enabled by default:
- Git. Status, stage, commit, pull, push, log, and diff. Use the system `git` binary.
- Sort. Per-folder order, pin, and hide. Flexplorer is a reference for behavior, not a source of code.
Planned plugins disabled by default:
- Projects. Kanban is the first view. Calendar and Gantt share the same task index.
- Graph. Draw wiki-link edges from the file index.
- Canvas. Store `.canvas` files in JSON Canvas 1.0.
- Browser. Open a page in an in-app webview. Block ads with EasyList and EasyPrivacy.
Kanban boards are Markdown files. Headings are columns. Task list items are cards.
## Later work
- Background Git for people who do not want to run Git by hand. Timed commit, pull, and push. A history limit is not designed yet.
- Extend the existing live Markdown preview. See the [user guide](user-guide.md) for current behavior.
- Language servers for diagnostics and go-to-definition.
- Wiki-link jump and backlinks from a rebuildable index.
- A command palette for every command.
## Out of scope
- A plugin marketplace or third-party loader
- Obsidian or VS Code plugin compatibility
- Cloud sync, live collaboration, or mobile
- A debugger or a full IDE
- Auto-commit on save
## Architecture goals
Dark is the primary theme.
Privileged operations belong in Rust: disk access, file watching, search, Git, terminal sessions, and adblock matching.
Git and adblock matching belong to planned plugins.
+69
View File
@@ -0,0 +1,69 @@
# Release guide
[Back to RuneStone](../README.md)
## Build the Windows installer
Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source).
The commands below use the checked-in dependency versions.
```sh
pnpm install --frozen-lockfile
pnpm check
pnpm test
pnpm build:installer
```
The last command builds the interface, compiles the release app, and creates an NSIS setup executable.
The first build needs internet access to download the packaging tools and the WebView2 bootstrapper.
Find the installer in:
```text
src-tauri/target/release/bundle/nsis/RuneStone_<version>_x64-setup.exe
```
Distribute this setup file. Users do not need the repository, a local server, or build tools.
Build output stays outside version control.
## Installer settings
Tauri automatically merges `src-tauri/tauri.windows.conf.json` into the base configuration on Windows.
This file selects NSIS for ordinary `pnpm tauri build` commands too.
It uses the existing RuneStone icon and installs the app for the current Windows account.
Tauri supplies the setup screens, Start menu shortcut, launch option, and uninstaller.
The installer includes the WebView2 bootstrapper.
If WebView2 is missing, setup downloads the runtime. An existing runtime needs no setup download.
The configuration blocks version downgrades.
It does not register document types or start RuneStone when Windows starts.
See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options.
## Prepare a release
1. Set the same version in `package.json`, `src-tauri/Cargo.toml`, and `src-tauri/tauri.conf.json`.
2. Update `src-tauri/Cargo.lock` with Cargo if the package version changed.
3. Run the checks and build command above.
4. Test the installer on a clean Windows account with the checks below.
5. Attach the setup file and release notes to the repository release or your chosen download page.
Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity.
No public download location or automatic release upload is configured yet.
After you publish an installer, add its download link to the README.
Local installers are unsigned until the maintainer configures Windows code signing.
Use [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) before public distribution.
## Installer checks
| Check | Expected result |
| --- | --- |
| Install on an account without Node.js or Rust | Setup completes and RuneStone opens |
| Install without WebView2, with internet access | Setup installs the runtime and RuneStone opens |
| Open RuneStone from the Start menu | The app opens without a terminal or development server |
| Create a workspace outside the installation folder | Notes save and reopen |
| Install a newer version | Setup updates the app and preserves workspace files |
| Try to install an older version | Setup blocks the downgrade |
| Remove RuneStone through Windows Settings | The app and shortcuts disappear, and the separate workspace remains |
These checks require a Windows test account or virtual machine. A successful build alone does not confirm them.
+59
View File
@@ -0,0 +1,59 @@
# Product roadmap
[Back to RuneStone](../README.md)
**Goal:** Make RuneStone a dependable place to write, understand, and run a project
while keeping its files portable and under the user's control.
## Direction
This is a proposed progression from the existing editor to a broader workspace.
No release dates are assigned.
```mermaid
flowchart LR
accTitle: RuneStone product direction
accDescr: First make daily work dependable, then help users understand connected projects, then let users choose optional workflows.
daily("1. Trust daily work<br/>Write, run, and resume")
understand("2. Understand the project<br/>Follow ideas and code")
adapt("3. Choose your workflow<br/>Add only the tools you need")
daily --> understand --> adapt
```
## 1. Trust daily work
**Objective:** Make RuneStone dependable enough to serve as the everyday home for notes and scripts.
The current editor, local files, autosave, and terminals provide the foundation.
Session restoration and crash recovery would let users resume work after an interruption.
**Milestone:** A user can write a note, run its companion script, restart the app,
and resume the workspace with recoverable edits.
## 2. Understand the project
**Objective:** Help users move from a question to the related notes and code without losing context.
Reliable note links and backlinks would connect explanations.
Code navigation and diagnostics would help users understand the scripts those explanations describe.
**Milestone:** A user can follow a note to related material, locate a code definition,
and identify a reported code problem within the workspace.
## 3. Choose your workflow
**Objective:** Support different ways of working while keeping the core editor simple.
Plugin support is pending. A first-party plugin foundation would let users choose
optional tools for version history, organization, planning, and visual exploration.
**Milestone:** A user can enable a first-party plugin, use it with workspace files,
and disable it while retaining access to those files in the core editor.
## Why this order?
Reliable daily work establishes trust. Better navigation then helps users understand larger projects.
Optional workflows build on that foundation while preserving a focused core.
Detailed capabilities and boundaries live in the [product scope](product-scope.md).
The [user guide](user-guide.md) describes what works today.
+145
View File
@@ -0,0 +1,145 @@
# User guide
[Back to RuneStone](../README.md)
Current features and limitations as of September 2026.
## Workspace, editing, and terminals
- The folder button and Ctrl+O open recent workspaces, with the current workspace
marked and full paths shown. The list remembers the 20 most recently opened
folders across restarts. Open another folder from the bottom of the menu, or
choose New workspace to create and open a named folder in a chosen location.
Existing folders are never overwritten. Opening or creating a workspace opens
a new window, keeping the current window's documents and terminals in place.
- Markdown's writing layout is one continuous document with live formatting.
Type freely, press Enter to continue, and use arrow keys or select across lines.
The active line reveals its raw Markdown, including link destinations and task
markers. Other lines show formatting. Checkboxes stay beside their item text. Clicking one updates the Markdown and completed items are struck through.
Ctrl+click follows links. There is no formatting toolbar.
Ctrl+E switches to the IDE source editor; Split and Read remain available.
Writing edits update the shared source model without converting through HTML,
preserving Markdown syntax, frontmatter and Windows line endings. Mermaid code,
tables and images preview inline. Table cells can be edited directly.
- Click a note's title in Writing to rename its file. Enter or leaving the field
saves the name; Escape cancels. The folder and Markdown extension are preserved,
and renaming keeps the note's contents and editing history.
- Drag a workspace image from the navigator into a Markdown editor to insert a
relative link to the existing file. An “Insert image” hint marks the editor;
Escape cancels the drag. Dropping files from the system file explorer or pasting
images copies them into `attachments/` with unique filenames. Undo removes the
inserted links while keeping the image files.
In Writing, image Markdown stays hidden until **Edit image source** is pressed. The image remains visible while editing. Hide it again with the same button,
Escape, or by moving the cursor away. Click an image to select it, then
right-click or press Shift+F10 for copy image, copy Markdown, swap image, remove
image, zoom, edit source, open in a new tab, copy path, and show in Explorer.
Remove image or Delete removes only that embed from the note and supports undo.
Zoom supports fit, magnification and Escape to close, including in Split and Read.
- Right-click Markdown text in writing or source mode (or press Shift+F10) for
note/external links, selection search, extraction, formatting, and clipboard
actions. Format includes bold, italic, strike, highlight, code, math, comments,
and clear formatting. Paragraph applies lists, tasks, headings 1–6, body text,
or quotes to the selected lines. Insert adds footnotes, tables, callouts,
horizontal rules, code blocks, and math blocks as Markdown source. Use arrow
keys to navigate submenus and Escape to return to editing. Obsidian Bases are
not supported.
- Tables keep readable column widths and render `<br>` as cell line breaks.
Hover beside a table's right edge to add a column, or below its bottom edge to
add a row. Clicking a cell edits its contents. Wide tables scroll within the document.
Grips appear on hover or keyboard focus above columns and beside body rows.
Drag a grip to reorder: a preview follows the pointer, the source row/column
stays highlighted, and a line marks the drop position. Drag near an edge
to scroll, or press Escape to cancel. Focus a grip and use arrow keys to move it.
Row moves keep the Markdown header fixed. Columns carry their alignment with them.
Drag across cells or Shift+click to select a rectangle, then right-click for
cut/copy/paste, bold, italic, strikethrough, highlight, code, math, comment,
clear formatting, alignment, clear cells, and delete cells. Clipboard shortcuts,
Ctrl+B/I, Shift+arrow selection, and undo/redo work on the selected cells.
TSV or Markdown tables paste as a grid and expand the table when needed.
Alignment applies to selected columns, as required by Markdown. Clear empties
contents; Delete removes complete selected rows/columns, or shifts a partial
selection left. Math stores inline `$…$` syntax. Comments use `%%…%%` and are
hidden in Read mode. Each operation can be undone in one step.
Right-clicking text within a cell preserves the selected words and offers note
links, external links, workspace search, extraction to a new note, formatting,
rich/plain-text paste, and Select all. Extraction saves the selected Markdown
in a new file and replaces the selection with a note link. Undo restores the
original text without deleting the new note. Row and Column submenus insert,
move, duplicate, and delete at the clicked cell. Column moves keep alignment. Sorting is stable and natural (2 before 10), leaves blanks last, and keeps the
header fixed. Context-menu actions and table edge buttons have matching icons.
- Table formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`,
`=SUM(B2:B10)`, or `=ROUND(B2/3, 2)`. Columns use A, B, …, AA. Row 1 is
the header, so the first data row is 2. References stay inside the current table.
Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`.
Functions include SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND.
Separate function arguments with commas: `=AVERAGE(B2,C2)` averages two cells.
A colon selects a range: `=AVERAGE(B2:C2)`.
Aggregates ignore text and blank cells. Arithmetic treats blank cells as zero.
Results recalculate in Writing, Split, and Read. Click a result to edit its
formula; Enter commits it and Tab moves to the next cell. The Formulas control
below each table explains the syntax, and the active cell shows its address.
Invalid formulas, missing cells, and circular references display error labels.
Markdown stores the formula itself, so other apps display readable source.
Use code formatting or `\=` to keep formula-like text literal. References are
positional: copying, inserting, deleting, sorting, or moving cells does not
rewrite addresses. Cross-table references and automatic fill are not supported.
- Tabs retain their editor models, undo history, cursor and scroll state while open.
- Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file.
- Changed notes and scripts autosave every 5 seconds, including background tabs.
Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts
and unavailable files preserve your edits for resolution instead of overwriting.
- The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks,
code blocks and reference images. Frontmatter sits in a collapsed Properties
section. Wiki links, note callouts and locally rendered Mermaid diagrams are
supported in Writing, Split and Read. Diagram source remains available to copy. Invalid diagrams show a message and their source. Toolbar icons show tooltips
on hover or keyboard focus; Split view stacks vertically in narrow panes.
- Ctrl+P finds files by path. Ctrl+N creates a note or script at a workspace-relative
path. Ctrl+S saves. Ctrl+Shift+F opens workspace search; Ctrl+F searches the editor.
- Ctrl+` or Ctrl+J shows or hides the terminal, preserving sessions and scrollback.
New Terminal (Ctrl+Shift+`) creates an independent shell; Split (Ctrl+Shift+5)
adds a resizable pane in the active group and inherits its current directory/profile.
The terminal list appears only when multiple sessions exist. Kill terminates a
session; Delete does the same while a terminal-list entry has focus. Maximize
and Restore change the panel size without restarting shells.
- The dropdown immediately beside New Terminal offers installed PowerShell,
PowerShell 7, Git Bash, Command Prompt, and Bash profiles, a default-profile
picker, terminal settings, tasks, and separate terminal windows
(Ctrl+Shift+Alt+`). Font size, scrollback, cursor blinking, and default profile
persist locally. New terminals inherit the app environment, including PATH.
- More terminal actions clears scrollback, runs selected editor text, or saves
and runs the active script. Supported runners include Python, JavaScript,
PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes
must be installed. Recent-command (Ctrl+Alt+R) and directory (Ctrl+G) pickers
work while the terminal is focused. Ctrl+Up/Down navigates prompt markers.
History is kept in memory for the current dock; PowerShell/Bash report commands
after completion, while Command Prompt captures submitted text at its prompt.
- Configure Tasks creates/opens `.runestone/tasks.json`. Its `tasks` array contains
objects with `label`, `command`, and an optional `profile` ID (`powershell`,
`pwsh`, `git-bash`, `cmd`, or `bash`). Run Task starts the chosen command in its
own terminal at the workspace root. Tasks run only when explicitly selected.
- JavaScript Debug Terminal starts a Node.js REPL with a local inspector on an
available port. Attach an external debugger using the printed address.
RuneStone does not provide VS Code's debugger or automatic debug attachment.
Start Dictation invokes Windows voice typing (Win+H) in the focused terminal;
Windows microphone/voice-typing configuration is required. Other platforms
use their operating system's dictation shortcut.
- Closing a detached terminal window terminates its sessions. Switching workspace
closes detached terminal windows and ends the old workspace's sessions.
- File watching reloads clean buffers after an agent or another application changes
them. Dirty buffers display a conflict with the disk version and explicit choices
to use it, keep local edits, or save a copy. Missing files retain their open buffer.
- Saves compare the current disk text with the saved baseline, prepare a complete
temporary file, then replace the destination. This prevents known stale saves and
truncation on failed writes. It does not lock out other processes. Concurrent tools
can still write between the last comparison and replacement.
- Closing a dirty tab, switching workspaces, and closing the desktop window prompt
before discarding edits or terminating terminal sessions.
- `.git`, `.obsidian`, `.runestone`, and temporary save files are hidden from the
navigator/search. Directory symlinks are not traversed by the navigator.
## Limitations
Vault-wide wiki-link resolution, backlinks and math rendering still need work.
Git UI, language servers, plugins, persistent tab restoration and crash recovery
are not implemented. Unsaved buffers and terminals last for the current app
session only.
+63
View File
@@ -0,0 +1,63 @@
---
title: Project field notes
tags: [workspace, design]
---
# Project field notes
A place for the thinking that happens around the code. Keep your research,
implementation notes, and scripts together, with room to read and a terminal
close at hand.
## A calmer place to work
Good notes need a clear rhythm: **strong headings**, comfortable paragraphs,
and enough space to see how ideas relate. Use `project/config.ts` for a small
code reference, or follow a [[notes/welcome|related note]] without losing context.
> [!tip] Keep context close
> Write down the reason for a change alongside the script that implements it.
> Your future self gets both the decision and the details.
### From idea to implementation
1. Capture the question in a note.
- Link the relevant research.
- Keep examples beside the explanation.
2. Open the script and try the smallest useful change.
3. Run it in the project terminal.
## Working checklist
- [x] Keep notes and code in the same workspace
- [x] Preserve Markdown exactly as written
- [ ] Review the next iteration
- [ ] Check a narrow split view
- [ ] Record what changed
## At a glance
| Surface | Purpose | Shortcut |
| :--- | :--- | ---: |
| Notes | Decisions, research, and working drafts | `Ctrl N` |
| Editor | Scripts and source files | `Ctrl P` |
| Terminal | Run commands in the project directory | `Ctrl` + backtick |
### A small example
```python
from pathlib import Path
workspace = Path.cwd()
for note in workspace.rglob("*.md"):
print(note.relative_to(workspace))
```
Code keeps its indentation and punctuation. Text such as `**bold**` inside a
code span stays literal, while **bold** in a paragraph is formatted.
> The best workspace helps you return to a thought as easily as you return to a file.
---
One project, with room for both the explanation and the implementation.
+31
View File
@@ -0,0 +1,31 @@
{
"pins": [],
"bookmarks": [],
"order": {
"notes": [
"inbox.md",
"projects"
],
"notes/projects": [],
"": [
".runestone",
"src",
"notes",
"tools",
"folder"
],
"folder": [
"screenshot10.png",
"screenshot11.png",
"screenshot12.png",
"screenshot7.png",
"test.md",
"screenshot6.png",
"screenshot5.png",
"screenshot4.png",
"screenshot8.png",
"screenshot3.png",
"screenshot2.png"
]
}
}
+5
View File
@@ -0,0 +1,5 @@
# Inbox
This is a sample note. Link to [[projects/alpha]].
- [ ] First task
+3
View File
@@ -0,0 +1,3 @@
# Alpha
Back to [[inbox]].
+6
View File
@@ -0,0 +1,6 @@
def greet(name: str) -> str:
return f"hello, {name}"
if __name__ == "__main__":
print(greet("runestone"))
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
echo "workspace ready"
+58
View File
@@ -0,0 +1,58 @@
{
"name": "runestone",
"version": "0.1.0",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"build:installer": "tauri build --bundles nsis -- --locked",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri",
"test": "node --experimental-strip-types --test scripts/*.spec.ts"
},
"license": "MIT",
"dependencies": {
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.12.4",
"@codemirror/search": "^6.7.2",
"@codemirror/state": "^6.7.5",
"@codemirror/view": "^6.43.12",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.7.3",
"@tauri-apps/plugin-opener": "^2",
"@tiptap/core": "^3.31.3",
"@tiptap/extension-highlight": "^3.31.3",
"@tiptap/extension-image": "^3.31.3",
"@tiptap/extension-link": "^3.31.3",
"@tiptap/extension-subscript": "^3.31.3",
"@tiptap/extension-superscript": "^3.31.3",
"@tiptap/extension-table": "^3.31.3",
"@tiptap/extension-table-cell": "^3.31.3",
"@tiptap/extension-table-header": "^3.31.3",
"@tiptap/extension-table-row": "^3.31.3",
"@tiptap/extension-task-item": "^3.31.3",
"@tiptap/extension-task-list": "^3.31.3",
"@tiptap/pm": "^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",
"mermaid": "^12.0.0",
"monaco-editor": "^0.56.0"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.65.1",
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"@tauri-apps/cli": "^2",
"svelte": "^5.56.3",
"svelte-check": "^4.6.0",
"typescript": "~6.0.3",
"vite": "^8.0.16"
}
}
+2678
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import test from "node:test";
import { detectChrome, extensionOf, treeFileParts } from "../src/lib/workspace/chrome.ts";
import { monacoChrome } from "../src/lib/editor/monacoChrome.ts";
test("markdown files open in writing chrome", () => {
assert.equal(detectChrome("notes/inbox.md"), "Writing");
assert.equal(detectChrome("README.markdown"), "Writing");
});
test("scripts open in ide chrome", () => {
assert.equal(detectChrome("src/hello.py"), "Ide");
assert.equal(detectChrome("tools/setup.sh"), "Ide");
assert.equal(detectChrome("Makefile"), "Ide");
});
test("writing chrome wraps and hides line numbers", () => {
assert.equal(monacoChrome("Writing").wordWrap, "on");
assert.equal(monacoChrome("Writing").lineNumbers, "off");
assert.equal(monacoChrome("Writing").minimap.enabled, false);
});
test("ide chrome shows line numbers and no wrap", () => {
assert.equal(monacoChrome("Ide").wordWrap, "off");
assert.equal(monacoChrome("Ide").lineNumbers, "on");
assert.equal(monacoChrome("Ide").minimap.enabled, true);
});
test("extensionOf reads the last suffix", () => {
assert.equal(extensionOf("a/b.c.py"), "py");
assert.equal(extensionOf(".gitignore"), "");
});
test("treeFileParts splits a display name from its extension", () => {
assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" });
assert.deepEqual(treeFileParts("chrome_extensions.json"), {
label: "chrome_extensions",
ext: "json",
});
assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" });
});
+348
View File
@@ -0,0 +1,348 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { Documents } from "../src/lib/workspace/documents.ts";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(done => resolve = done);
return { promise, resolve };
}
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
function setup() {
const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]);
const io = {
read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; },
write: async (path: string, contents: string, expected: string) => {
if (disk.get(path) !== expected) throw new Error("conflict");
disk.set(path, contents);
},
image: async () => "data:image/png;base64,",
kind: () => "text" as const,
chrome: () => "Writing" as const,
};
const docs = new Documents(io, () => {});
return { docs, disk, io };
}
test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "keep my edits");
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
assert.equal(first.kind, "empty");
assert.equal(second.kind, "empty");
assert.notEqual(first.relPath, second.relPath);
assert.equal(note.contents, "keep my edits");
docs.select(first.relPath);
docs.close(first.relPath);
assert.equal(docs.active, second);
docs.close(note.relPath);
io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); };
io.write = async () => { assert.fail("empty tabs must not write disk"); };
docs.edit(second.id, "ignored");
await docs.refresh();
await docs.save(second.id);
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(docs.dirty, false);
assert.equal(second.diskError, undefined);
docs.close(second.relPath);
assert.equal(docs.activePath, null);
});
test("opening a file fills the active empty tab in place and failed reads preserve it", async () => {
const { docs } = setup();
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
docs.select(first.relPath);
await assert.rejects(docs.open(entry("missing.md")), /missing/);
assert.equal(docs.active, first);
await docs.open(entry("note.md"));
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]);
docs.select(second.relPath);
await docs.open(entry("note.md"));
assert.equal(docs.buffers.length, 2);
assert.equal(docs.activePath, "note.md");
});
test("a new empty tab stays selected when an earlier file read finishes", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.newTab();
const blank = docs.active!;
gate.resolve("note");
await pending;
assert.equal(docs.active, blank);
assert.equal(docs.buffers.length, 2);
});
test("clean buffers follow agent edits; dirty buffers retain both versions", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
disk.set("note.md", "agent version");
await docs.refresh();
assert.equal(docs.active?.contents, "agent version");
docs.edit(docs.active!.id, "my version");
disk.set("note.md", "agent version 2");
await docs.refresh();
assert.equal(docs.active?.contents, "my version");
assert.equal(docs.active?.diskContents, "agent version 2");
await assert.rejects(docs.save(docs.active!.id), /Resolve/);
docs.resolve(docs.active!.id, false);
await docs.save(docs.active!.id);
assert.equal(disk.get("note.md"), "my version");
});
test("typing during a save remains unsaved", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first edit");
const pending = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "second edit");
gate.resolve();
await pending;
assert.equal(disk.get("note.md"), "first edit");
assert.equal(docs.active!.saved, "first edit");
assert.equal(docs.active!.contents, "second edit");
assert.equal(docs.dirty, true);
});
test("concurrent saves serialize and finish at the latest edit", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first");
const first = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "latest");
const second = docs.save(docs.active!.id);
const third = docs.save(docs.active!.id);
gate.resolve();
await Promise.all([first, second, third]);
assert.equal(disk.get("note.md"), "latest");
assert.equal(docs.dirty, false);
});
test("latest navigation wins even when earlier reads finish later", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
const read = io.read;
io.read = path => path === "note.md" ? gate.promise : read(path);
const first = docs.open(entry("note.md"));
await docs.open(entry("script.py"));
gate.resolve("note");
await first;
assert.equal(docs.activePath, "script.py");
});
test("duplicate opens share one document and do not lose edits", async () => {
const { docs } = setup();
await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]);
assert.equal(docs.buffers.length, 1);
docs.edit(docs.active!.id, "unsaved");
await docs.open(entry("script.py"));
await docs.open(entry("note.md"));
assert.equal(docs.active!.contents, "unsaved");
});
test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => {
const { docs, disk } = setup();
disk.set("third.md", "third");
await docs.open(entry("note.md"));
await docs.open(entry("script.py"), "new");
docs.select("note.md");
await docs.open(entry("third.md"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "third.md");
await docs.open(entry("script.py"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "script.py");
});
test("current-tab navigation preserves edits made while the next file is loading", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.edit(note.id, "keep these edits");
gate.resolve("script");
await pending;
assert.equal(docs.buffers.length, 2);
assert.equal(note.contents, "keep these edits");
assert.equal(docs.activePath, "script.py");
});
test("failed current-tab navigation keeps the active document", async () => {
const { docs } = setup();
await docs.open(entry("note.md"), "current");
await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/);
assert.equal(docs.buffers.length, 1);
assert.equal(docs.activePath, "note.md");
});
test("a late current-tab read cannot replace a more recently selected tab", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.select("note.md");
gate.resolve("script");
await pending;
assert.equal(docs.activePath, "note.md");
assert.equal(docs.buffers[0].relPath, "note.md");
});
test("removed files retain text and block accidental recreation", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "precious text");
disk.delete("note.md");
await docs.refresh();
assert.equal(docs.active!.contents, "precious text");
assert.match(docs.active!.diskError!, /unavailable/);
await assert.rejects(docs.save(docs.active!.id));
});
test("disposing a workspace ignores late open results", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.dispose(); gate.resolve("late");
await pending;
assert.equal(docs.buffers.length, 0);
});
test("renaming a folder preserves document identity and dirty state", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const id = docs.active!.id;
docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md");
assert.equal(docs.activePath, "notes/moved.md");
assert.equal(docs.active!.id, id);
assert.equal(docs.dirty, true);
});
test("autosave writes changed background tabs once and skips clean or reverted text", async () => {
const { docs, io, disk } = setup();
const writes: string[] = [];
const write = io.write;
io.write = async (...args) => { writes.push(args[0]); await write(...args); };
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "background edit");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "temporary edit");
docs.edit(docs.active!.id, docs.active!.saved);
assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] });
assert.equal(disk.get("note.md"), "background edit");
await docs.autosave();
await docs.save(note.id);
assert.deepEqual(writes, ["note.md"]);
});
test("autosave skips in-flight saves and preserves edits for the next pass", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
let writes = 0;
io.write = async (...args) => { writes++; await gate.promise; await write(...args); };
docs.edit(docs.active!.id, "first");
const pending = docs.autosave();
await Promise.resolve();
docs.edit(docs.active!.id, "still typing");
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
gate.resolve();
await pending;
assert.equal(writes, 1);
assert.equal(disk.get("note.md"), "first");
assert.equal(docs.dirty, true);
await docs.autosave();
assert.equal(writes, 2);
assert.equal(disk.get("note.md"), "still typing");
});
test("autosave skips known conflicts and unavailable files", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
disk.set("note.md", "external edit");
disk.delete("script.py");
await docs.refresh();
io.write = async () => { assert.fail("blocked files must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(note.contents, "my note");
assert.equal(note.diskContents, "external edit");
assert.equal(docs.active!.contents, "my script");
assert.equal(docs.dirty, true);
});
test("an autosave failure preserves edits, saves other files, and can be retried", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
const write = io.write;
io.write = async (...args) => {
if (args[0] === "note.md") throw new Error("disk full");
await write(...args);
};
const result = await docs.autosave();
assert.deepEqual(result.saved, ["script.py"]);
assert.equal(result.failed[0].path, "note.md");
assert.match(String(result.failed[0].error), /disk full/);
assert.equal(note.saved, "original");
assert.equal(note.contents, "my note");
assert.equal(disk.get("script.py"), "my script");
io.write = write;
await docs.autosave();
assert.equal(disk.get("note.md"), "my note");
assert.equal(docs.dirty, false);
});
test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "my note");
disk.set("note.md", "external edit");
const result = await docs.autosave();
assert.equal(result.failed.length, 1);
assert.equal(disk.get("note.md"), "external edit");
assert.equal(docs.active!.contents, "my note");
assert.equal(docs.dirty, true);
});
test("closed documents and disposed workspaces are not autosaved", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "discarded");
docs.close("note.md");
io.write = async () => { assert.fail("discarded edits must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "disposed");
docs.dispose();
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
});
+15
View File
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { fenceOpenText, headingMarkText } from "../src/lib/editor/headingMarks.ts";
test("heading marks match the heading level", () => {
assert.equal(headingMarkText(1), "#");
assert.equal(headingMarkText(3), "###");
assert.equal(headingMarkText(6), "######");
});
test("fence open marks include the language", () => {
assert.equal(fenceOpenText(""), "```");
assert.equal(fenceOpenText("js"), "```js");
assert.equal(fenceOpenText(" pp "), "```pp");
});
+209
View File
@@ -0,0 +1,209 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>';
files.set("images/picture (#1).svg", btoa(svg));
files.set("images/replacement.svg", btoa(svg));
files.set("notes/welcome.md", "Above.\n\nBelow.\n");
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_write_bytes") {
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
if (window.__TEST__.failWrite) throw new Error("Image write failed");
files.set(args.rel, args.base64); return;
}
if (command === "workspace_read_data_url") {
if (!files.has(args.rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + files.get(args.rel);
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
async function dragFromTree(selector = ".cm-content", cancel = false) {
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
await page.mouse.move(from.x + 60, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
await page.getByText("Insert image", { exact: true }).waitFor();
assert.equal(await page.locator(".image-drop-target").count(), 1);
if (cancel) await page.keyboard.press("Escape");
await page.mouse.up();
}
async function imageMenu() {
await page.locator(".md-image-frame").first().click({ button: "right" });
await page.getByRole("menu", { name: "Image actions" }).waitFor();
}
try {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).click();
await writer();
await page.locator('[data-tree-rel="images"]').click();
await dragFromTree();
await page.locator(".md-image-frame img").waitFor();
const linked = await source();
assert.ok(linked.startsWith("![](../images/picture%20%28%231%29.svg)\n\nAbove."), linked);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => ["workspace_write_bytes", "workspace_rename"].includes(c.command)).length), 0);
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
// Neither caret movement nor selection exposes an image's Markdown.
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: 0, head: 38 } }));
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
await page.locator(".md-image-frame img").click();
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Image actions" }).waitFor();
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
await page.screenshot({ path: ".audit/image-context-menu.png" });
await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click();
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "![](../images/picture%20%28%231%29.svg)");
await imageMenu();
await page.getByRole("menuitem", { name: "Copy image", exact: true }).click();
await page.waitForFunction(async () => (await navigator.clipboard.read()).some(item => item.types.includes("image/png")));
await imageMenu();
await page.getByRole("menuitem", { name: "Show in Explorer", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "workspace_reveal" && c.args.rel === "images/picture (#1).svg"));
await imageMenu();
await page.getByRole("menuitem", { name: "Remove image", exact: true }).click();
assert.ok(!(await source()).includes("picture%20"));
assert.ok(await page.evaluate(() => window.__TEST__.files.has("images/picture (#1).svg")));
await page.keyboard.press("Control+z");
assert.equal(await source(), linked);
await page.locator(".md-image-frame").hover();
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
await page.locator(".cm-line").filter({ hasText: "picture%20" }).waitFor();
assert.equal(await page.locator(".md-image-frame img").count(), 1);
await page.getByRole("button", { name: "Hide image source", exact: true }).click();
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
await imageMenu();
await page.getByRole("menuitem", { name: "Swap image…", exact: true }).click();
await page.getByRole("textbox", { name: "Image path relative to this note, or https URL" }).fill("../images/replacement.svg");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.waitForFunction(() => window.__CM__.state.doc.toString().includes("replacement.svg"));
assert.equal(await page.locator(".cm-line").filter({ hasText: "replacement.svg" }).count(), 0);
await imageMenu();
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
await page.getByRole("tab", { name: "replacement.svg", exact: true }).waitFor();
await page.getByRole("tab", { name: /welcome.md/ }).click();
await writer();
const beforeCancel = await source();
await dragFromTree(".cm-content", true);
assert.equal(await source(), beforeCancel);
assert.equal(await page.locator(".image-drop-target").count(), 0);
// Inline images remain independently selectable without hiding adjacent prose.
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "Before ![](../images/replacement.svg) between ![[../images/replacement.svg]] after.\n" }, selection: { anchor: 0 } });
});
await page.waitForFunction(() => document.querySelectorAll(".md-image-frame").length === 2);
assert.ok((await page.locator(".cm-content").innerText()).includes("Before"));
assert.ok(!(await page.locator(".cm-content").innerText()).includes("![]"));
await page.locator(".md-image-frame img").nth(1).click();
await page.keyboard.press("Delete");
assert.equal(await source(), "Before ![](../images/replacement.svg) between after.\n");
await page.keyboard.press("Control+z");
assert.ok((await source()).includes("![[../images/replacement.svg]]"));
// Reference-image editing affects only the selected embed, not its definition.
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "![Reference][pic]\n\nBelow.\n\n[pic]: ../images/replacement.svg\n" }, selection: { anchor: 0 } });
});
await page.locator(".md-image-frame").hover();
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
await page.locator(".cm-line").filter({ hasText: "![Reference]" }).waitFor();
await page.keyboard.press("Escape");
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
// The same navigator drag works in the source editor.
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await dragFromTree(".monaco-editor .view-lines");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0);
assert.deepEqual(errors, []);
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
} catch (error) {
await page.screenshot({ path: ".audit/image-navigation-failure.png" });
console.error(errors); throw error;
} finally { await browser.close(); }
+248
View File
@@ -0,0 +1,248 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_write_bytes") {
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
if (window.__TEST__.failWrite) throw new Error("Image write failed");
files.set(args.rel, args.base64); return;
}
if (command === "workspace_read_data_url") {
if (!files.has(args.rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + files.get(args.rel);
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function openNote(name = "welcome.md") {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator(".cm-content").waitFor();
}
async function source() {
return page.evaluate(() => window.__CM__.state.doc.toString());
}
async function save() {
await page.keyboard.press("Control+s");
await page.waitForTimeout(100);
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
}
async function drop(count = 1, selector = ".cm-content") {
await page.locator(selector).evaluate((element, count) => {
const data = new DataTransfer();
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
}, count);
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } });
});
const original = await source();
const acceptsDrag = await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg"));
const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data });
element.dispatchEvent(event); return event.defaultPrevented;
});
assert.ok(acceptsDrag);
await drop(2);
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2);
await page.locator(".md-image-frame img").first().waitFor();
assert.equal(await page.locator(".md-image-frame img").count(), 2);
const inserted = await source();
assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor");
const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]);
assert.notEqual(paths[0], paths[1]);
assert.ok(paths.every(path => path.startsWith("../attachments/")));
assert.equal(await save(), inserted);
// Selecting and editing Markdown leaves the image visible and updates its alt text.
await page.locator(".md-image-frame").first().hover();
await page.getByRole("button", { name: "Edit image source", exact: true }).first().click();
assert.equal(await page.locator(".md-image-frame img").count(), 2);
assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0])));
await page.evaluate(() => {
const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2;
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
});
await page.locator('img[alt="Edited alt"]').waitFor();
await page.screenshot({ path: ".audit/images-editing.png" });
await page.locator(".md-image-frame").first().hover();
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
const zoom = page.getByRole("dialog", { name: "Image zoom" });
await zoom.waitFor();
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
await page.screenshot({ path: ".audit/images-zoom.png" });
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("dialog").count(), 0);
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in");
// Undo the alt edit and the complete drop as separate operations.
await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
assert.equal(await source(), original);
await page.keyboard.press("Control+y");
assert.equal(await source(), inserted);
// Type and move the cursor during a slow import; the drop follows its original position.
await page.evaluate(() => { window.__TEST__.delay = true; });
await drop();
await page.waitForFunction(() => !!window.__TEST__.resume);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } });
window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null;
});
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3);
assert.ok((await source()).startsWith("Typed while saving.\n\n![]"));
// Typed local image paths load without changing views, including wiki syntax.
await page.evaluate(path => {
window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]);
const view = window.__CM__;
view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } });
}, "../attachments/typed.svg");
await page.locator('img[alt="Wiki image"]').waitFor();
await save();
await page.getByRole("button", { name: "Read", exact: true }).click();
await page.locator(".md-page .md-image-frame").first().hover();
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
await page.keyboard.press("Escape");
// Source mode uses the same drop flow; the batch is one undo step.
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
window.__MONACO__ = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
});
const sourceBefore = await page.evaluate(() => window.__MONACO__.getValue());
await drop(2, ".monaco-editor .view-lines");
await page.waitForFunction(() => (window.__MONACO__.getValue().match(/!\[\]/g) || []).length === 5);
await page.keyboard.press("Control+z");
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore);
await page.keyboard.press("Control+y");
assert.equal((await save()).match(/!\[\]/g).length, 5);
// A failed write leaves source unchanged and surfaces an error.
const beforeFailure = await page.evaluate(() => window.__MONACO__.getValue());
await page.evaluate(() => { window.__TEST__.failWrite = true; });
await drop(1, ".monaco-editor .view-lines");
await page.getByText("Image write failed", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure);
await page.evaluate(() => { window.__TEST__.failWrite = false; });
// File drops over a rendered widget are handled by the editor's capture listener.
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await drop(1, ".md-image-frame img >> nth=0");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6);
// Switching tabs while a write is pending cannot insert into the new document.
await page.evaluate(() => { window.__TEST__.delay = true; });
await drop();
await page.waitForFunction(() => !!window.__TEST__.resume);
await openNote("second.md");
await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); });
await page.waitForTimeout(100);
assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/"));
// Clipboard images are inserted and remain a single undo operation too.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'], "pasted.svg", { type: "image/svg+xml" }));
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
});
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
assert.deepEqual(errors, []);
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
} catch (error) {
await page.screenshot({ path: ".audit/images-failure.png" });
console.error(errors);
throw error;
} finally { await browser.close(); }
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../src/lib/workspace/media.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../src/lib/editor/imageDrop.ts";
test("same-name image imports receive distinct safe attachment paths", () => {
const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG")));
assert.equal(paths.size, 100);
assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path)));
});
test("protected file drags and files without MIME metadata are recognized", () => {
assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true);
assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false);
const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }];
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
});
test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");
assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, ["![](a.png)"]), "![](a.png)\n\n");
});
test("pending image drops follow intervening edits instead of the current caret", () => {
let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] });
const id = Symbol();
state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state;
state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state;
assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 });
});
test("navigator image links are relative and encode Markdown and URL punctuation", () => {
assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "![](../../images/a%20%28%231%29.png)");
assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "![](photo.png)");
assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "![](%E6%97%A5%E6%9C%AC%E8%AA%9E/photo%25.png)");
});
test("image source is explicitly activated, tracks edits, and hides on leaving", () => {
let state = EditorState.create({ doc: "![](a.png)\n\nText", extensions: [imageSource] });
state = state.update({ selection: { anchor: 0, head: 10 } }).state;
assert.equal(state.field(imageSource), null);
state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state;
state = state.update({ changes: { from: 2, insert: "Alt" } }).state;
assert.deepEqual(state.field(imageSource), { from: 0, to: 13 });
state = state.update({ selection: { anchor: state.doc.length } }).state;
assert.equal(state.field(imageSource), null);
});
test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => {
const source = "`![](code.png)`\n\nText ![alt](<a b.png>) and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n![](code.png)\n```";
assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["![alt](<a b.png>)", "![[a b.png|Photo]]", "![ref][photo]"]);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { languageFor } from "../src/lib/editor/languageFor.ts";
test("markdown files use the markdown language", () => {
assert.equal(languageFor("notes/inbox.md"), "markdown");
assert.equal(languageFor("README.markdown"), "markdown");
});
test("python and scripts use their languages", () => {
assert.equal(languageFor("src/hello.py"), "python");
assert.equal(languageFor("tools/setup.sh"), "shell");
});
test("unknown extensions are plaintext", () => {
assert.equal(languageFor("Makefile"), "plaintext");
assert.equal(languageFor("notes/data.bin"), "plaintext");
});
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownBlocks, markdownFences } from "../src/lib/workspace/markdownBlocks.ts";
test("fenced block with a language is one fence", () => {
assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [
{ type: "text", line: "hi" },
{ type: "fence", lang: "js", body: "const x = 1" },
{ type: "text", line: "bye" },
]);
});
test("fenced block without a language keeps an empty lang", () => {
assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [
{ type: "fence", lang: "", body: "HUGE" },
]);
});
test("inline backticks stay on a text line", () => {
assert.deepEqual(markdownBlocks("say `HUGE` now"), [
{ type: "text", line: "say `HUGE` now" },
]);
});
test("a fence opened and closed on one line is a fence", () => {
assert.deepEqual(markdownBlocks("```this was a triumph```"), [
{ type: "fence", lang: "", body: "this was a triumph" },
]);
});
test("closed fence body is the copy payload", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [
{ lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 },
]);
});
test("one-line fence body excludes ticks", () => {
assert.deepEqual(markdownFences("```this was a triumph```"), [
{ lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 },
]);
});
test("unclosed fence is not MdFence", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []);
});
test("markdownBlocks fence body matches markdownFences", () => {
const src = "hi\n```js\nconst x = 1\n```\nbye";
const block = markdownBlocks(src).find((row) => row.type === "fence");
const fence = markdownFences(src)[0];
assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1");
assert.equal(fence.body, "const x = 1");
assert.equal(fence.lang, "js");
assert.equal(fence.openLine, 2);
assert.equal(fence.closeLine, 4);
});
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../src/lib/editor/markdownCommands.ts";
const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to);
test("inline formatting toggles without losing surrounding prose or the selected text", () => {
for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) {
const source = "before words after", selection = { from: 7, to: 12 };
const edit = formatText(source, selection, format), changed = apply(source, edit);
assert.equal(changed.slice(edit.anchor, edit.head), "words");
assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format);
assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format);
}
assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** ");
assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***");
const empty = formatText("", { from: 0, to: 0 }, "bold");
assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2);
});
test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => {
const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code");
assert.equal(edit.insert, "``a ` b``");
assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source);
assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source);
const rich = "**bold**\r\n==mark== and \\*literal\\*";
assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*");
assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold");
});
test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => {
const source = "before\r\n - [x] first\r\n 2. second\r\nafter";
const selected = { from: source.indexOf("first"), to: source.indexOf("after") };
assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter");
assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter");
assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three");
assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] ");
assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two");
});
test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => {
const source = "left right", selection = { from: 5, to: 10 };
for (const kind of ["table", "rule"] as const) {
const result = apply(source, insertBlock(source, selection, kind));
assert.ok(result.startsWith(source + "\n\n"));
}
const code = insertBlock("```", { from: 0, to: 3 }, "code");
assert.equal(code.insert, "````\n```\n````\n\n");
const table = insertBlock("", { from: 0, to: 0 }, "table");
assert.equal(table.insert.slice(table.anchor, table.head), "Column 1");
assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n");
});
test("footnotes get unique references, retain the document tail, and select the definition", () => {
const source = "One[^1] and words.\n\n[^1]: existing\n";
const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote");
const changed = apply(source, edit);
assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n");
assert.equal(changed.slice(edit.anchor, edit.head), "words");
});
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { findMarkdownLinks, wikiCandidates } from "../src/lib/workspace/markdownLinks.ts";
test("markdown links skip image embeds", () => {
const links = findMarkdownLinks("See [alpha](notes/a.md) and ![shot](pic.png)");
assert.deepEqual(links, [
{ kind: "md", from: 4, to: 23, label: "alpha", target: "notes/a.md" },
]);
});
test("wikilinks skip image embeds", () => {
const links = findMarkdownLinks("Go [[projects/alpha|Alpha]] and ![[screenshot.png]]");
assert.deepEqual(links, [
{
kind: "wiki",
from: 3,
to: 27,
label: "Alpha",
target: "projects/alpha",
},
]);
});
test("wikiCandidates add .md for a bare name", () => {
assert.deepEqual(wikiCandidates("alpha"), ["alpha.md", "notes/alpha.md", "alpha"]);
});
import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts";
test("links resolve relative to notes, including parent paths and encoded spaces", () => {
assert.deepEqual(linkCandidates("notes/project/inbox.md", "../other%20note.md", "md"), ["notes/other note.md"]);
assert.deepEqual(linkCandidates("notes/inbox.md", "ideas", "wiki"), ["notes/ideas.md", "notes/ideas", "ideas.md", "ideas"]);
assert.deepEqual(linkCandidates("notes/inbox.md", "../../secret", "md"), []);
assert.deepEqual(linkCandidates("notes/inbox.md", "javascript:alert(1)", "md"), []);
});
+207
View File
@@ -0,0 +1,207 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const source = "First paragraph.\n\nSecond paragraph.\n";
await page.evaluate(async value => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
editor.setValue(value);
editor.setSelection(new monaco.Selection(1, 1, 1, 6)); editor.focus();
}, source);
const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await page.keyboard.press("Shift+F10");
await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await waitForText(source);
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10"); await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Italic", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Heading 2", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("## First paragraph."));
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+End");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Table", exact: true }).click();
await page.locator(".live-writer table").waitFor();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
// Mouse invocation must preserve the selection, too.
await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } });
await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Highlight", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph."));
await page.keyboard.press("Control+End");
await page.locator(".writer-highlight").waitFor();
assert.equal(await page.locator(".writer-highlight").textContent(), "First");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+End");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await page.screenshot({ path: ".audit/markdown-insert-menu.png" });
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 760, height: 600 });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
await writer.focus();
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).focus();
await page.keyboard.press("ArrowRight");
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list");
const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox();
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600);
await page.screenshot({ path: ".audit/markdown-paragraph-menu.png" });
await page.keyboard.press("ArrowLeft");
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click();
await page.getByRole("textbox", { name: "External link URL" }).fill("https://example.com/a(b)");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a%28b%29) paragraph."));
await page.keyboard.press("Control+z");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click();
await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[[/notes/extracted.md|First]] paragraph."));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/extracted.md")), "First\n");
await page.keyboard.press("Control+z");
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate(() => navigator.clipboard.writeText("Pasted"));
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Pasted paragraph."));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("Pasted paragraph."));
await page.evaluate(() => { navigator.clipboard.readText = () => new Promise(resolve => { window.__finishPaste = resolve; }); });
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
await writer.focus(); await page.keyboard.press("End"); await page.keyboard.type(" kept");
await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); });
assert.ok(!(await writer.textContent()).includes("STALE"));
assert.ok((await writer.textContent()).includes("kept"));
assert.deepEqual(errors, []);
console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards.");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
await page.screenshot({ path: ".audit/markdown-menu-failure.png" });
throw error;
} finally { await browser.close(); }
+93
View File
@@ -0,0 +1,93 @@
import assert from "node:assert/strict";
import test from "node:test";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts";
import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts";
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
assert.equal(extractedCellMarkdown([
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
{ type: "hardBreak" },
{ type: "text", text: "<br>", marks: [{ type: "code" }] },
]), "**Title**\n`<br>`");
});
test("table column insertion retains alignment and existing cell contents", () => {
assert.equal(appendTableColumn(table), "| Ticker | Notes | |\n| :--- | ---: | --- |\n| IBKR.US | First<br>Second | |");
});
test("table row insertion keeps existing source byte-for-byte", () => {
assert.equal(appendTableRow(table + "\n\n"), table + "\n| | |\n\n");
});
test("table edits preserve CRLF and optional outer pipes", () => {
const source = "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n";
assert.equal(appendTableRow(source), "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n| | |\r\n");
assert.equal(appendTableColumn(source), "| Name | Link | |\r\n| --- | :---: | --- |\r\n| One | [note](note.md) | |\r\n");
});
test("escaped pipes in text, wiki aliases, and inline code stay inside cells", () => {
const source = "| One | Two |\n| --- | --- |\n| [[note\\|Alias]] | `a\\|b` and text\\|value |";
const parsed = parseMarkdownTable(source)!;
assert.equal(parsed.rows[2].cells.length, 2);
const changed = appendTableColumn(source);
assert.ok(changed.includes("| [[note\\|Alias]] | `a\\|b` and text\\|value | |"));
for (const row of parsed.rows) for (const cell of row.cells) assert.equal(source.slice(cell.from, cell.to), cell.text);
});
test("adding columns pads short rows without losing extra source cells", () => {
const source = "| A | B |\n| --- | --- |\n| short |\n| a | b | extra |";
assert.equal(appendTableColumn(source), "| A | B | |\n| --- | --- | --- |\n| short | | |\n| a | b | | extra |");
});
test("table controls handle header-only and single-column tables", () => {
assert.equal(appendTableRow("| Header |\n| --- |"), "| Header |\n| --- |\n| |");
assert.equal(parseMarkdownTable(appendTableColumn("| Header |\n| --- |"))?.columns, 2);
});
test("invalid tables are unchanged", () => {
for (const source of ["Just text", "| A | B |\n| --- |", "| A |\n| not a delimiter |"] ) {
assert.equal(parseMarkdownTable(source), null);
assert.equal(appendTableColumn(source), source);
assert.equal(appendTableRow(source), source);
}
});
test("editing one cell preserves padding, alignment, other cells and CRLF", () => {
const source = " | Name | Notes |\r\n | :--- | ---: |\r\n | One | first<br />~~old~~ |\r\n\r\nTail";
assert.equal(replaceTableCell(source, 2, 1, "next<br>line\\|pipe"), source.replace("first<br />~~old~~", "next<br>line\\|pipe"));
assert.equal(replaceTableCell(source, 0, 0, "Title"), source.replace("Name", "Title"));
assert.equal(replaceTableCell(source, 1, 0, "bad"), source);
assert.equal(replaceTableCell(source, 2, 1, "break\nrow"), source);
});
test("editing an empty or omitted cell does not overwrite its neighbor", () => {
assert.equal(replaceTableCell("| A | B |\n| --- | --- |\n| short |", 2, 1, "new"), "| A | B |\n| --- | --- |\n| short | new |");
const source = "| A | B |\n| --- | --- |\n| | value |";
assert.equal(replaceTableCell(source, 2, 0, "new"), source.replace("| | value", "| new| value"));
});
test("rich cell serialization retains breaks, formatting, links and literal punctuation", () => {
const text = tableCellMarkdown({ type: "doc", content: [{ type: "paragraph", content: [
{ type: "text", text: "old", marks: [{ type: "strike" }] },
{ type: "hardBreak" },
{ type: "text", text: "bold", marks: [{ type: "bold" }] },
{ type: "text", text: " | *literal* <br> & value" },
{ type: "hardBreak" },
{ type: "text", text: "a|`b", marks: [{ type: "code" }] },
{ type: "text", text: "note", marks: [{ type: "link", attrs: { href: "note.md", "data-kind": "wiki" } }] },
{ type: "text", text: "web", marks: [{ type: "link", attrs: { href: "https://example.com/a(b)" } }] },
] }, { type: "paragraph", content: [{ type: "text", text: "Pasted paragraph" }] }] });
const source = `| A |\n| --- |\n| ${text} |`;
assert.equal(parseMarkdownTable(source)?.rows[2].cells.length, 1);
const html = renderMarkdownHtml(source, new Map());
assert.ok(html.includes("<s>old</s>"));
assert.ok(html.includes("<strong>bold</strong>"));
assert.ok(html.includes("| *literal* &lt;br&gt; &amp; value"));
assert.ok(html.includes("<code>a|`b</code>"));
assert.ok(html.includes('href="note.md" data-kind="wiki"'));
assert.ok(html.includes('href="https://example.com/a(b)"'));
assert.equal((html.match(/<br>/g) || []).length, 3);
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
findMarkdownImages,
isImagePath,
isRemoteImage,
resolveImageRel,
} from "../src/lib/workspace/media.ts";
test("image paths are detected by extension", () => {
assert.equal(isImagePath("screenshot.png"), true);
assert.equal(isImagePath("notes/photo.JPEG"), true);
assert.equal(isImagePath("notes/inbox.md"), false);
});
test("markdown image syntax is parsed", () => {
const found = findMarkdownImages("See ![alt](../shot.png) and ![[screenshot.png|Hero]]");
assert.equal(found.length, 2);
assert.equal(found[0].src, "../shot.png");
assert.equal(found[0].kind, "md");
assert.equal(found[1].src, "screenshot.png");
assert.equal(found[1].alt, "Hero");
assert.equal(found[1].kind, "wiki");
});
test("image paths resolve from the note folder", () => {
assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png");
assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png");
});
test("remote images stay as URLs", () => {
assert.equal(isRemoteImage("https://example.com/a.png"), true);
assert.equal(isRemoteImage("screenshot.png"), false);
});
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
test("headings and inline marks become markdown", () => {
const html =
"<h1>Heading 1</h1><h2>Heading 2</h2><p>hello <strong>bold</strong> and <code>code</code></p>";
assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`");
});
test("fences keep language and body", () => {
const html = '<pre class="md-code" data-lang="js"><code class="language-js">const x = 1</code></pre>';
assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```");
});
test("wiki and markdown links become markdown", () => {
const html =
'<p>see <a class="wiki" href="projects/alpha" data-kind="wiki">projects/alpha</a> and <a href="notes/a.md" data-kind="md">label</a></p>';
assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)");
});
test("wiki image uses data-md-kind", () => {
const html =
'<p><img src="data:image/png;base64,xx" alt="screenshot.png" data-md-src="screenshot.png" data-md-kind="wiki" /></p>';
assert.equal(htmlToMarkdown(html), "![[screenshot.png]]");
});
test("strike super and sub become markdown", () => {
const html = "<p><s>old</s> x<sup>2</sup> a<sub>n</sub></p>";
assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~");
});
test("gfm table becomes markdown", () => {
const html =
"<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>";
assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |");
});
test("checked task item becomes a checkbox line", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>done</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [x] done");
});
test("unchecked task item becomes an empty checkbox", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="false"><p>todo</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [ ] todo");
});
test("italic highlight math and comment become markdown", () => {
const html =
'<p><em>hi</em> <mark>glow</mark> <span data-math="1">x^2</span> <span data-comment="1">note</span></p>';
assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%");
});
test("blockquote and numbered list become markdown", () => {
const html = "<blockquote><p>said</p></blockquote><ol><li>one</li><li>two</li></ol>";
assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two");
});
+103
View File
@@ -0,0 +1,103 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
const render = (text: string) => renderMarkdownHtml(text, new Map());
test("writing sections retain exact source ranges and document-wide references", () => {
const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n';
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source);
assert.equal(sections.length, 4);
assert.match(sections[2].html, /<ul>[\s\S]*<ul>/);
assert.match(sections[3].html, /href="https:\/\/example.com"/);
const paragraph = sections[3];
const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end);
assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start));
});
test("writing exposes empty and reference-only documents for editing", () => {
for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) {
assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]);
}
});
test("Mermaid fences render diagram containers with escaped, copyable source", () => {
const html = render('```mermaid\nflowchart LR\n A["<script>bad</script>"] --> B\n```');
assert.match(html, /class="md-mermaid"/);
assert.match(html, /aria-label="Mermaid diagram"/);
assert.match(html, /<summary>Diagram source<\/summary>/);
assert.match(html, /&lt;script&gt;bad&lt;\/script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.doesNotMatch(render('```js\nconst x = 1;\n```'), /md-mermaid/);
});
test("reader joins soft-wrapped lines and preserves paragraph boundaries", () => {
assert.equal(render("First line\ncontinues here.\n\nSecond paragraph."), "<p>First line\ncontinues here.</p>\n<p>Second paragraph.</p>\n");
assert.match(render("Hard break \nnext line"), /Hard break<br>\nnext line/);
});
test("reader preserves nested lists, ordered starts and multi-paragraph items", () => {
const html = render("7. Parent\n - Nested **item**\n - Other\n8. Next\n\n Another paragraph.\n");
assert.match(html, /<ol start="7">/);
assert.match(html, /<li>\n<p>Parent<\/p>\n<ul>\n<li>Nested <strong>item<\/strong><\/li>/);
assert.match(html, /<p>Next<\/p>\n<p>Another paragraph\.<\/p>/);
});
test("reader renders aligned tables and read-only nested tasks", () => {
const html = render("| Left | Right |\n| :--- | ---: |\n| **a** | 2 |\n\n- [x] Done\n - [ ] Nested\n");
assert.match(html, /class="md-table-scroll"><table>/);
assert.match(html, /<th style="text-align:right">Right<\/th>/);
assert.equal((html.match(/type="checkbox" disabled/g) || []).length, 2);
assert.equal((html.match(/ checked>/g) || []).length, 1);
assert.doesNotMatch(html, /\[x\]|\[ \]/);
});
test("reader keeps code literal and escapes embedded HTML", () => {
const html = render('```js\nconst text = "[[note]] **bold** <script>alert(1)</script>";\n```\n\n`[[literal]]`\n\n<img src=x onerror=alert(1)>');
assert.match(html, /aria-label="Copy code"/);
assert.match(html, /\[\[note\]\] \*\*bold\*\* &lt;script&gt;/);
assert.match(html, /<code>\[\[literal\]\]<\/code>/);
assert.doesNotMatch(html, /<script>|<img|class="wiki"|<strong>/);
});
test("table cell line breaks render without enabling arbitrary HTML", () => {
const html = render('| Notes |\n| --- |\n| First<br>Second<BR />Third<br/>Fourth |');
assert.match(html, /First<br>\nSecond<br>\nThird<br>\nFourth/);
assert.doesNotMatch(html, /&lt;br/i);
assert.match(render('`<br>`'), /<code>&lt;br&gt;<\/code>/);
assert.doesNotMatch(render('<br onclick="alert(1)">'), /<br /);
});
test("frontmatter is collapsed separately from document headings", () => {
const html = render("\uFEFF---\r\ntitle: Notes\r\ntags: [work]\r\n---\r\n# Document\n");
assert.match(html, /^<details class="md-properties"><summary>Properties<\/summary><pre>title: Notes/);
assert.match(html, /<h1>Document<\/h1>/);
assert.doesNotMatch(html, /<h2>|<hr>|details[^>]*open/);
assert.match(render("---\n\nOrdinary rule"), /^<hr>/);
});
test("wiki links, aliases and reference images retain their targets", () => {
const source = 'See [[notes/one|First note]] and [second](second.md).\n\n![A **diagram**][diagram]\n\n![[assets/screenshot.png|Screenshot]]\n\n[diagram]: assets/my%20diagram.png "Diagram"\n';
const urls = new Map([['assets/my%20diagram.png', 'data:image/png;base64,AA=='], ['assets/screenshot.png', 'data:image/png;base64,BB==']]);
const html = renderMarkdownHtml(source, urls);
assert.match(html, /href="notes\/one" data-kind="wiki" class="wiki">First note/);
assert.match(html, /href="second.md" data-kind="md"/);
assert.match(html, /alt="A diagram"/);
assert.match(html, /data-md-kind="wiki"/);
assert.deepEqual(markdownImages(source + '\n`![[ignored.png]]`\n\n```\n![also ignored](x.png)\n```'), ['assets/my%20diagram.png', 'assets/screenshot.png']);
});
test("reader rejects executable links and image URL injection", () => {
const html = render('[bad](javascript:alert%281%29) [[javascript:alert(1)]] ![bad](javascript:alert%281%29)');
assert.doesNotMatch(html, /<a |<img /);
const image = renderMarkdownHtml('![[safe.png]]', new Map([['safe.png', 'javascript:alert(1)']]));
assert.match(image, /Image unavailable/);
});
test("note callouts separate their title from the Markdown body", () => {
const html = render('> [!tip] Keep context close\n> Use **notes** beside code.\n>\n> A second paragraph.');
assert.match(html, /class="md-callout" data-callout="tip"/);
assert.match(html, /class="md-callout-title">Keep context close<\/strong>Use <strong>notes<\/strong>/);
assert.match(html, /<p>A second paragraph\.<\/p>/);
});
+66
View File
@@ -0,0 +1,66 @@
import assert from "node:assert/strict";
import test from "node:test";
import { planRename, planTitleRename, planMarkdownTitleRename } from "../src/lib/workspace/renamePath.ts";
test("rename in a folder keeps the parent", () => {
assert.deepEqual(planRename("notes/a.md", "b.md"), {
action: "rename",
to: "notes/b.md",
});
});
test("same name is a no-op", () => {
assert.deepEqual(planRename("notes/a.md", "a.md"), { action: "noop" });
});
test("path separators are rejected", () => {
assert.deepEqual(planRename("notes/a.md", "foo/bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
assert.deepEqual(planRename("notes/a.md", "foo\\bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
});
test("empty name is rejected", () => {
assert.deepEqual(planRename("notes/a.md", " "), {
action: "error",
message: "Name is empty",
});
});
test("root file rename stays at the root", () => {
assert.deepEqual(planRename("inbox.md", "todo.md"), {
action: "rename",
to: "todo.md",
});
});
test("title rename keeps the existing extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello"), {
action: "rename",
to: "notes/hello.md",
});
assert.deepEqual(planTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
});
test("title rename keeps a typed extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello.txt"), {
action: "rename",
to: "notes/hello.txt",
});
});
test("writing titles preserve Markdown extensions and allow dots in names", () => {
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "Release 1.2"), { action: "rename", to: "notes/Release 1.2.md" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.MD", " Renamed.md "), { action: "rename", to: "notes/Renamed.MD" });
assert.deepEqual(planMarkdownTitleRename("inbox.markdown", "Renamed"), { action: "rename", to: "Renamed.markdown" });
assert.deepEqual(planMarkdownTitleRename("inbox.mdown", "Renamed"), { action: "rename", to: "Renamed.mdown" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md.md", "inbox.md"), { action: "noop" });
for (const name of ["", " ", ".md", "../escape", "folder/note", "folder\\note"]) {
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
}
});
+158
View File
@@ -0,0 +1,158 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function openNote(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("button", { name: "Rename note", exact: true }).waitFor();
}
const title = page.getByRole("button", { name: "Rename note", exact: true });
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote("welcome.md");
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
await writer.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved text");
await editTitle("Release 1.2");
await input.press("Enter");
await renamed("notes/Release 1.2.md");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
await page.locator('.tree').getByText("notes", { exact: true }).click();
await page.locator('.tree').getByText("Release 1.2", { exact: true }).waitFor();
await writer.click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
await editTitle("Cancelled");
await input.press("Escape");
await renamed("notes/Release 1.2.md");
assert.equal(await input.isVisible(), false);
// Keyboard activation and filename errors stay outside Markdown editing.
await title.focus(); await title.press("Enter");
await input.fill(" "); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "Name is empty" }).waitFor();
await input.fill("folder/note"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "path separator" }).waitFor();
await input.fill("second"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
assert.equal(await input.inputValue(), "second");
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
await input.fill("Renamed.md"); await input.press("Tab");
await renamed("notes/Renamed.md");
await page.mouse.move(10, 10);
await page.screenshot({ path: ".audit/rename-title.png" });
// A pending rename belongs to its original document even if the tab changes.
await page.evaluate(() => { window.__TEST__.delayRename = true; });
await editTitle("Background"); await input.press("Enter");
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
await page.locator('.tree').getByText("second", { exact: true }).click();
await renamed("notes/second.md");
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
await renamed("notes/second.md");
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
await renamed("notes/Background.md");
// Disk reload after rename must not restore the old displayed title.
await page.evaluate(() => {
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
});
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
assert.ok((await title.innerText()).startsWith("Background"));
assert.deepEqual(errors, []);
console.log("PASS: inline filename rename, folder/extension preservation, tabs/tree, contents and undo, Enter/blur/Escape, validation/collisions, tab switching during rename, and reload (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
await page.screenshot({ path: ".audit/rename-title-failure.png" });
throw error;
} finally { await browser.close(); }
+148
View File
@@ -0,0 +1,148 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function open(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
}
async function settle() {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function roundTrip(selector, label) {
const scroller = page.locator(selector);
const position = async (top) => label === 'IDE'
? page.evaluate(async top => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
if (top !== undefined) editor.setScrollTop(top, 1);
return editor.getScrollTop();
}, top)
: scroller.evaluate((el, top) => {
if (top !== undefined) el.scrollTop = top;
return el.scrollTop;
}, top);
await scroller.waitFor({ state: 'visible' });
await settle();
await position(1800);
await settle();
const first = await position();
assert.ok(first > 1000, `${label}: first document is scrollable`);
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
await position(650);
await settle();
const second = await position();
for (let repeat = 0; repeat < 2; repeat++) {
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
await page.getByRole('tab', { name, exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
const actual = await position();
assert.ok(Math.abs(actual - expected) < 5, `${label}: ${name} expected ${expected}, got ${actual}`);
}
}
console.log(`PASS: ${label} retains independent tab scroll positions`);
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(() => {
for (const name of ['scroll-a.md', 'scroll-b.md']) {
window.__TEST__.files.set(name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join(''));
}
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['scroll-a.md', 'scroll-b.md'] });
});
await open('scroll-b.md');
await open('scroll-a.md');
if (await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).count()) {
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
}
await roundTrip('.cm-scroller', 'Writing');
await page.getByRole('button', { name: 'Read', exact: true }).click();
await roundTrip('.md-page', 'Reading');
await page.getByRole('button', { name: 'Split', exact: true }).click();
await roundTrip('.md-page', 'Split preview');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
await roundTrip('.monaco-scrollable-element', 'IDE');
assert.deepEqual(errors, []);
} catch (error) {
console.error('Browser errors:', errors);
console.error((await page.locator('body').innerText()).slice(-2000));
throw error;
} finally { await browser.close(); }
+234
View File
@@ -0,0 +1,234 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
const headers = () => table.locator('th').allTextContents();
async function grip(axis, index) {
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
await handle.scrollIntoViewIfNeeded();
const rect = await handle.boundingBox();
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
await page.mouse.down();
}
async function target(axis, index, after = false) {
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
}
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('drag.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
}, source);
await quickOpen('drag.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
const firstGrip = page.locator('.table-drag-row[data-index="1"]');
await firstGrip.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '1');
assert.equal(await page.locator('.table-drag-row[data-index="2"]').evaluate(el => getComputedStyle(el).opacity), '0');
await page.mouse.move(5, 5);
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '0');
await grip('row', 1);
assert.equal(await page.locator('.table-drag-preview').count(), 0);
await target('row', 2, true);
const preview = page.locator('.table-drag-preview');
await preview.waitFor();
assert.match(await preview.innerText(), /Alpha/);
assert.equal(await preview.getAttribute('aria-hidden'), 'true');
assert.equal(await preview.evaluate(el => getComputedStyle(el).pointerEvents), 'none');
const initialPreview = await preview.boundingBox();
await target('row', 4, true);
assert.ok((await preview.boundingBox()).y > initialPreview.y + 20);
assert.equal(await preview.locator('.table-drag-preview-label').innerText(), 'Row 2 → 5');
assert.equal(await table.locator('.is-cell-selected').count(), 3);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-row.png' });
await page.mouse.up();
assert.equal(await preview.count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| Delta | 40 | Four |\n| Alpha'));
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await page.keyboard.press('Control+y');
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await grip('row', 4); await target('row', 1); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await target('column', 2, true);
assert.deepEqual(await preview.locator('tr').allTextContents(), ['Name', 'Alpha', 'Beta', 'Gamma', 'Delta']);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-column.png' });
await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| ---: | :---: | :--- |'));
await grip('column', 2); await target('column', 0); await page.mouse.up();
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Cancel, out-of-table drop, and click without a drag must not change source.
await grip('row', 1); await target('row', 4, true); await page.keyboard.press('Escape'); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('row', 1); await page.mouse.move(5, 5, { steps: 5 }); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// The focused grip offers the same operation to keyboard users.
// Tab into the handle, rather than leaving mouse focus on it.
await page.locator('.table-add-row').focus();
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 1');
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-column[data-index="0"]')).opacity === '1');
await page.keyboard.press('ArrowRight');
assert.deepEqual(await headers(), ['Value', 'Name', 'Notes']);
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 2');
await page.keyboard.press('ArrowLeft');
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Editing a cell before dragging must commit its latest contents.
await table.locator('tbody tr').first().locator('td').first().click();
await page.keyboard.press('Control+End'); await page.keyboard.type(' edited');
await grip('row', 1); await target('row', 4, true); await page.mouse.up();
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha edited']);
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha edited', 'Beta', 'Gamma', 'Delta']);
// Keep column handles aligned when a narrow table viewport scrolls.
await page.setViewportSize({ width: 760, height: 700 });
await table.locator('th').first().scrollIntoViewIfNeeded();
await grip('column', 0);
const viewport = await page.locator('.writer-table .md-table-scroll').boundingBox();
await page.mouse.move(viewport.x + viewport.width - 2, viewport.y + 15, { steps: 8 });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft > 0; });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft + el.clientWidth >= el.scrollWidth - 2; });
await target('column', 2, true); await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await page.screenshot({ path: '.audit/table-drag-narrow.png' });
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await page.evaluate(() => {
window.__TEST__.files.set('long.md', '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n');
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
});
await quickOpen('long.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
const first = await table.locator('tr').nth(1).boundingBox();
await page.mouse.move(first.x + 20, scroller.y + scroller.height - 5, { steps: 8 });
await page.waitForFunction(() => {
const last = document.querySelector('.live-writer table tbody tr:last-child').getBoundingClientRect();
const viewport = document.querySelector('.live-writer .cm-scroller').getBoundingClientRect();
return last.bottom < viewport.bottom - 20;
});
await target('row', 30, true);
await page.mouse.up();
assert.equal((await rows()).at(-1), 'Item 1');
assert.equal((await rows())[0], 'Item 2');
await page.keyboard.press('Control+z');
assert.equal((await rows())[0], 'Item 1');
await grip('row', 2); await target('row', 3, true);
await page.locator('.table-drag-row[data-index="2"]').dispatchEvent('pointercancel');
await page.mouse.up();
assert.equal((await rows())[1], 'Item 2');
assert.equal(await page.locator('.is-table-dragging').count(), 0);
assert.equal(await preview.count(), 0);
assert.deepEqual(errors, []);
console.log('PASS: hover/focus grips, pointer-following previews and cleanup, row/column drag in both directions, indicators, alignment, undo/redo, cancellation, keyboard movement, active edits, horizontal and vertical auto-scroll.');
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: '.audit/table-drag-failure.png' });
throw error;
} finally { await browser.close(); }
+187
View File
@@ -0,0 +1,187 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
const result = (r, c) => cell(r, c).locator('.md-table-formula');
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('formulas.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
}, source);
await quickOpen('formulas.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await table.waitFor();
assert.equal(await result(1, 3).innerText(), '9.5');
assert.equal(await result(3, 3).innerText(), '17.5');
await cell(1, 3).click();
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
await edit.fill('=AVERAGE(B2+C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 19');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2,C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2:C2)');
await page.keyboard.press('Enter');
await cell(1, 1).click();
await edit.fill('5');
assert.equal(await result(1, 3).innerText(), '7.5');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Tab');
await cell(1, 3).click();
assert.equal(await edit.innerText(), '=AVERAGE(B2:C2)');
assert.match(await page.locator('.table-formula-status').innerText(), /D2/);
await edit.fill('=B2*C2');
await page.keyboard.press('Enter');
assert.equal(await result(1, 3).innerText(), '50');
assert.equal(await result(3, 3).innerText(), '58');
assert.match(await save(), /\| =B2\*C2 \|/);
await cell(1, 3).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=AVERAGE(B2:C2)');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Control+y');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=B2*C2');
assert.equal(await result(3, 3).innerText(), '58');
await cell(2, 3).click();
await edit.fill('=D3');
await page.keyboard.press('Enter');
assert.equal(await result(2, 3).innerText(), '#CYCLE!');
assert.equal(await result(3, 3).innerText(), '#CYCLE!');
await cell(2, 3).click();
await edit.fill('=AVERAGE(B3:C3)');
await page.keyboard.press('Tab');
await cell(3, 1).click();
await edit.fill('=SUM(B2:B3)');
await page.keyboard.press('Enter');
assert.equal(await result(3, 1).innerText(), '12');
const saved = await save();
assert.match(saved, /=SUM\(B2:B3\)/);
assert.doesNotMatch(saved, /\\=/);
// Footer controls share one normal-flow block aligned to the table at any width.
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await cell(3, 1).click();
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer.png' });
await page.setViewportSize({ width: 850, height: 1000 });
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer-narrow.png' });
await page.locator('.table-formula-help summary').click();
assert.equal(await page.locator('.table-formula-help').getAttribute('open'), '');
await checkFooter();
await page.setViewportSize({ width: 1440, height: 1000 });
await page.screenshot({ path: '.audit/table-formulas.png' });
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Split']) {
await page.getByRole('button', { name: mode, exact: true }).click();
const preview = page.locator('.md-page table').first();
await preview.waitFor();
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
}
assert.deepEqual(errors, []);
console.log('PASS: live recalculation, raw formula editing, Enter/Tab, undo/redo, cycle recovery, Markdown saves, help, remount, Read, and Split');
} finally { await browser.close(); }
+92
View File
@@ -0,0 +1,92 @@
import assert from "node:assert/strict";
import test from "node:test";
import { cellAddress, evaluateTableFormulas } from "../src/lib/editor/tableFormulas.ts";
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
for (const separator of [",", ":"]) {
const result = evaluate(`=${name}(B2${separator}C2)`);
assert.equal(result.text, separate);
}
const result = evaluate(`=${name}(B2+C2)`);
assert.equal(result.text, combined);
}
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
});
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
for (const [formula, result] of [
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
]) assert.equal(calculate(formula), result, formula);
});
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
const results = evaluateTableFormulas([
["Name", "Appearance", "Cha", "Combined"],
["First", "9", "10", "=AVERAGE(B2:C2)"],
["Second", "7", "9", "=SUM(B3,C3)/2"],
["Total", "", "=B4+1", "=SUM(D2:D3)"],
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
]);
assert.equal(results[1][3]?.text, "9.5");
assert.equal(results[2][3]?.text, "8");
assert.equal(results[3][3]?.text, "17.5");
assert.equal(results[3][2]?.text, "1");
assert.equal(results[4][1]?.text, "5");
assert.equal(results[4][2]?.text, "3");
assert.equal(results[4][3]?.text, "5.83");
assert.equal(results[5][1]?.text, "35");
assert.equal(results[5][2]?.text, "8");
assert.equal(results[5][3]?.text, "35");
assert.equal(results[0][0], null);
assert.equal(cellAddress(1, 26), "AA2");
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
});
test("errors are visible, propagated, bounded, and never executed", () => {
for (const [formula, result] of [
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
]) assert.equal(calculate(formula), result, formula);
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
});
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
const html = renderMarkdownHtml(source, new Map());
assert.match(html, /aria-label="=AVERAGE\(A2:B2\) → 9.5">9.5<\/span>/);
assert.match(html, /aria-label="=A2\*B2 → 3">3<\/span>/);
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections.map(s => source.slice(s.start, s.end)).join(""), source);
assert.equal(sections.map(s => s.html).join(""), html);
const literal = renderMarkdownHtml("=1+2\n\n| A | B | C |\n| --- | --- | --- |\n| `=1+2` | \\=1+2 | ==highlight== |", new Map());
assert.doesNotMatch(literal, /md-table-formula/);
assert.match(literal, /<mark>highlight<\/mark>/);
const hostile = renderMarkdownHtml('| A |\n| --- |\n| ="<img src=x onerror=alert(1)>" |', new Map());
assert.doesNotMatch(hostile, /<img/);
assert.match(hostile, /#ERROR!/);
});
test("editing keeps formulas readable and code or explicit escapes literal", () => {
const doc = (text: string, marks?: { type: string }[]) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text, marks }] }] });
assert.equal(tableCellMarkdown(doc("=SUM($B$2:C2)*50%")), "=SUM($B$2:C2)*50%");
assert.equal(tableCellMarkdown(doc("\\=1+2")), "\\=1+2");
assert.equal(tableCellMarkdown(doc("=1+2", [{ type: "code" }])), "`=1+2`");
});
+324
View File
@@ -0,0 +1,324 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
async function expectCell(r, c) {
await page.waitForFunction(({ r, c }) => {
const active = document.activeElement;
const cell = active?.closest('th, td');
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
}, { r, c });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function at(r, c, edge = 'End') {
await cell(r, c).click();
// ProseMirror guards native selections at the start for 200ms after focus.
await page.waitForTimeout(220);
await page.keyboard.press(`Control+${edge}`);
await expectCell(r, c);
}
async function arrow(key, r, c) {
await page.keyboard.press(key);
await expectCell(r, c);
}
async function expectProse(after) {
await page.waitForFunction(after => {
const content = document.querySelector('.live-writer .cm-content');
const table = content?.querySelector('table');
const caret = document.getSelection()?.focusNode;
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
}, after);
}
async function caret() {
return edit.evaluate(el => {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
range.setEnd(selection.focusNode, selection.focusOffset);
return { offset: range.toString().length, selected: selection.toString() };
});
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('navigation.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['navigation.md'] });
}, source);
await quickOpen('navigation.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await table.waitFor();
// Reproduce the reported right-arrow escape, including formula destinations.
await at(1, 0);
await arrow('ArrowRight', 1, 1);
assert.equal((await caret()).offset, 0);
await arrow('ArrowRight', 1, 1);
assert.equal((await caret()).offset, 1);
await arrow('ArrowRight', 1, 1);
await arrow('ArrowRight', 1, 2);
assert.equal(await edit.innerText(), '=B2*2');
assert.equal((await caret()).offset, 0);
await arrow('ArrowLeft', 1, 1);
assert.equal((await caret()).offset, 2);
await arrow('ArrowLeft', 1, 1);
assert.equal((await caret()).offset, 1);
// Repeated native arrows can arrive before selectionchange is delivered.
await at(1, 1, 'Home');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await expectCell(1, 2);
assert.equal((await caret()).offset, 0);
// Row wrapping, empty cells, and header/body transitions.
await at(1, 2);
await arrow('ArrowRight', 2, 0);
await arrow('ArrowLeft', 1, 2);
await at(2, 0);
await arrow('ArrowRight', 2, 1);
await arrow('ArrowRight', 2, 2);
await arrow('ArrowLeft', 2, 1);
await arrow('ArrowUp', 1, 1);
await arrow('ArrowUp', 0, 1);
await arrow('ArrowDown', 1, 1);
await arrow('ArrowDown', 2, 1);
// Exit in all four directions, without adding rows or changing existing prose.
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await expectProse(false);
await at(0, 1, 'Home');
await page.keyboard.press('ArrowUp');
await expectProse(false);
await at(3, 2);
await page.keyboard.press('ArrowRight');
await expectProse(true);
await at(3, 1);
await page.keyboard.press('ArrowDown');
await expectProse(true);
assert.equal(await table.locator('tr').count(), 4);
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('navigation.md')), source);
// Reverse each exit using only the keyboard. Horizontal entry starts at the
// first/last cell; vertical entry uses the nearest column of the edge row.
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await expectProse(false);
await arrow('ArrowRight', 0, 0);
assert.equal((await caret()).offset, 0);
await at(0, 1, 'Home');
await page.keyboard.press('ArrowUp');
await expectProse(false);
await arrow('ArrowDown', 0, 0);
await at(3, 2);
await page.keyboard.press('ArrowRight');
await expectProse(true);
await page.keyboard.press('ArrowLeft');
await arrow('ArrowLeft', 3, 2);
assert.equal((await caret()).offset, 3);
await at(3, 1);
await page.keyboard.press('ArrowDown');
await expectProse(true);
await page.keyboard.press('ArrowUp');
await arrow('ArrowUp', 3, 0);
// Preserve the vertical goal column when crossing an empty prose line.
for (const after of [false, true]) {
await page.evaluate(async after => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.live-writer .cm-content'));
const EditorSelection = view.state.selection.constructor;
const table = view.dom.querySelector('table');
const preview = table.closest('.writer-preview');
const from = view.posAtDOM(preview);
const end = view.state.doc.toString().indexOf('\n\nAfter.');
const x = table.rows[0].cells[1].getBoundingClientRect().left + 20;
const goal = x - view.contentDOM.getBoundingClientRect().left;
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(after ? end + 1 : from - 1, 0, undefined, goal)]) });
view.focus();
}, after);
await arrow(after ? 'ArrowUp' : 'ArrowDown', after ? 3 : 0, 1);
}
// Ordinary prose cursor movement and extending a selection must stay in the
// outer editor, even when the selection crosses the whole table.
await page.locator('.cm-line').filter({ hasText: 'Before.' }).click();
await page.keyboard.press('Home');
await page.keyboard.press('ArrowRight');
await expectProse(false);
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Shift+ArrowDown');
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// Text selection and word navigation remain within the current editor.
await at(1, 0);
await arrow('Shift+ArrowLeft', 1, 0);
assert.equal((await caret()).selected, 'a');
await arrow('ArrowRight', 1, 0);
assert.equal((await caret()).selected, '');
await arrow('Control+ArrowLeft', 1, 0);
assert.equal((await caret()).offset, 0);
// Up/down traverse visual lines before crossing to another row.
await at(3, 0, 'Home');
await arrow('ArrowDown', 3, 0);
assert.ok((await caret()).offset > 0);
await arrow('ArrowUp', 3, 0);
await arrow('ArrowUp', 2, 0);
await at(2, 0);
await arrow('ArrowDown', 3, 0);
assert.ok((await caret()).offset <= 3, 'Down enters the first line');
// A wrapped cell also retains ordinary vertical caret movement.
await at(3, 1);
await edit.fill('A long sentence that wraps onto multiple visual lines in a narrow table cell.');
await page.keyboard.press('Control+Home');
await arrow('ArrowDown', 3, 1);
assert.ok((await caret()).offset > 0 && (await caret()).offset < (await edit.innerText()).length, 'Down moves into the next visual line');
await arrow('ArrowUp', 3, 1);
assert.equal((await caret()).offset, 0);
await page.keyboard.press('Control+End');
await page.keyboard.press('ArrowDown');
await expectProse(true);
// Edits commit when navigating; formulas update and undo restores the source.
await at(1, 1);
await edit.fill('15');
await arrow('ArrowRight', 1, 2);
await arrow('ArrowDown', 2, 2);
assert.equal(await cell(1, 2).locator('.md-table-formula').innerText(), '30');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('navigation.md').includes('| Alpha | 15 | =B2*2 |'));
await at(1, 1);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '12');
await page.keyboard.press('Control+y');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '15');
await page.keyboard.press('Tab');
await expectCell(1, 2);
await page.keyboard.press('Shift+Tab');
await expectCell(1, 1);
await page.keyboard.press('Escape');
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// A table at the document boundary still offers somewhere to type outside it.
const loneTable = '| Name |\n| --- |\n| Value |';
for (const [key, after] of [['ArrowLeft', false], ['ArrowUp', false], ['ArrowRight', true], ['ArrowDown', true]]) {
const name = `${key}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: loneTable });
await quickOpen(name);
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await table.waitFor();
await at(after ? 1 : 0, 0, after ? 'End' : 'Home');
await page.keyboard.press(key);
await expectProse(after);
const reverse = { ArrowLeft: 'ArrowRight', ArrowUp: 'ArrowDown', ArrowRight: 'ArrowLeft', ArrowDown: 'ArrowUp' }[key];
// Exiting added two newlines, so first cross the outer empty line.
await page.keyboard.press(reverse);
await arrow(reverse, after ? 1 : 0, 0);
await page.keyboard.press(`Control+${after ? 'End' : 'Home'}`);
await page.keyboard.press(key);
await expectProse(after);
await page.keyboard.type('Outside.');
await page.keyboard.press('Control+s');
const expected = after ? `${loneTable}\n\nOutside.` : `\nOutside.\n${loneTable}`;
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
}
assert.deepEqual(errors, []);
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, save, undo/redo, Tab and Escape');
} catch (error) {
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
throw error;
} finally { await browser.close(); }
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { alignTableCells, clipboardCells, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts";
import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts";
import { renderMarkdownHtml, plainInlineMarkdown } from "../src/lib/workspace/noteHtml.ts";
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
const source = "| A | B | C |\r\n| --- | :---: | ---: |\r\n| one | two | three |\r\n| four | five | six |\r\n\r\nTail";
const range = { anchor: { row: 2, column: 1 }, head: { row: 1, column: 0 } };
test("reversed rectangular selections only change selected cells and preserve CRLF", () => {
const changed = formatTableCells(source, range, "bold");
assert.equal(changed, source.replace("one", "**one**").replace("two", "**two**").replace("four", "**four**").replace("five", "**five**"));
assert.equal(formatTableCells(changed, range, "bold"), source);
assert.equal(formatTableCells(source.replace("one", "**one**"), range, "bold"), changed);
assert.equal(copyTableCells(source, range), "one\ttwo\nfour\tfive");
assert.equal(alignTableCells(source, range, "left"), source.replace("| --- | :---: | ---: |", "| :--- | :--- | ---: |"));
});
test("all formats render and clear without interpreting escaped punctuation", () => {
const cell = { anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } };
for (const [format, html] of [["bold", "<strong>one</strong>"], ["italic", "<em>one</em>"], ["strike", "<s>one</s>"], ["highlight", "<mark>one</mark>"], ["code", "<code>one</code>"], ["math", 'class="md-inline-math">one</span>'], ["comment", 'class="md-inline-comment">one</span>']] as const) {
const changed = formatTableCells(source, cell, format);
assert.ok(renderMarkdownHtml(changed, new Map()).includes(html), format);
assert.equal(formatTableCells(changed, cell, "clear"), source);
}
assert.equal(plainInlineMarkdown("**bold** ==*highlight*== ~~strike~~ `a|b`<br>\\*literal\\*"), "bold highlight strike a\\|b<br>\\*literal\\*");
assert.equal(plainInlineMarkdown("**Photo** ![alt](image.png)"), "Photo ![alt](<image.png>)");
assert.ok(renderMarkdownHtml("`==not highlighted==` \\==literal\\==", new Map()).includes("<code>==not highlighted==</code>"));
for (const type of ["highlight", "math", "comment"]) {
const text = tableCellMarkdown({ type: "text", text: "a|b", marks: [{ type }] });
assert.equal(parseMarkdownTable(`| H |\n| --- |\n| ${text} |`)?.rows[2].cells.length, 1);
}
});
test("clipboard accepts Markdown and quoted TSV without splitting escaped pipes", () => {
assert.deepEqual(clipboardCells('"a\tb"\t"line 1\nline 2"\r\n"say ""hi"""\tx|y\r\n'), [["a\tb", "line 1<br>line 2"], ['say "hi"', "x\\|y"]]);
assert.deepEqual(clipboardCells("| A | B |\n| --- | --- |\n| a\\|b | `code` |"), [["A", "B"], ["a\\|b", "`code`"]]);
const pasted = pasteTableCells(source, range, "value");
assert.equal(copyTableCells(pasted, range), "value\tvalue\nvalue\tvalue");
const large = pasteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 2, column: 2 } }, "a\tb\nc\td");
assert.equal(parseMarkdownTable(large)?.columns, 4);
assert.equal(parseMarkdownTable(large)?.rows.length, 5);
assert.ok(large.endsWith("\r\n\r\nTail"));
assert.equal(copyTableCells(large, { anchor: { row: 2, column: 2 }, head: { row: 3, column: 3 } }), "a\tb\nc\td");
});
test("clear preserves structure; delete removes whole rows/columns or shifts partial cells", () => {
assert.equal(copyTableCells(mapTableCells(source, range, () => ""), range), "\t\n\t");
assert.equal(copyTableCells(deleteTableCells(source, range), range), "three\t\nsix\t");
const rows = deleteTableCells(source, { anchor: { row: 1, column: 0 }, head: { row: 1, column: 2 } });
assert.equal(parseMarkdownTable(rows)?.rows.length, 3);
assert.ok(rows.includes("four")); assert.ok(!rows.includes("one"));
const columns = deleteTableCells(source, { anchor: { row: 0, column: 1 }, head: { row: 2, column: 1 } });
assert.equal(parseMarkdownTable(columns)?.columns, 2);
assert.ok(columns.includes("| one | three |"));
const header = deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 0, column: 2 } });
assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |"));
assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail");
});
+69
View File
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import test from "node:test";
import { changeTableStructure, moveTableAxis, sortTableColumn } from "../src/lib/editor/tableStructure.ts";
import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts";
const source = "| Name | Value |\r\n| :--- | ---: |\r\n| Zebra | `2` |\r\n| **Apple** | 10 |\r\n| apple | 3 |\r\n| | 1 |\r\n\r\nTail";
const values = (text: string) => parseMarkdownTable(text)!.rows.map(row => row.cells.map(cell => cell.text));
test("dragging rows across multiple positions preserves raw Markdown, header, CRLF and suffix", () => {
const moved = moveTableAxis(source, "row", 1, 4);
assert.deepEqual(values(moved).slice(2).map(row => row[0]), ["**Apple**", "apple", "", "Zebra"]);
assert.ok(moved.includes("| Zebra | `2` |\r\n\r\nTail"));
assert.equal(moveTableAxis(moved, "row", 4, 1), source);
for (const [from, to] of [[0, 2], [2, 0], [1, 5], [-1, 2], [1, 1], [1.5, 2], [1, NaN]]) {
assert.equal(moveTableAxis(source, "row", from, to), source);
}
});
test("dragging columns carries alignment and rich contents across ragged rows", () => {
const text = " | A | B | C |\r\n | :--- | :---: | ---: |\r\n | a\\|b | **bold**<br>line | [[note]] | extra |\r\n | short |\r\n\r\nTail";
const moved = moveTableAxis(text, "column", 0, 2);
assert.deepEqual(values(moved), [["B", "C", "A"], [":---:", "---:", ":---"], ["**bold**<br>line", "[[note]]", "a\\|b", "extra"], ["", "", "short"]]);
assert.ok(moved.endsWith("\r\n\r\nTail"));
assert.deepEqual(values(moveTableAxis(moved, "column", 2, 0)).slice(0, 3), values(text).slice(0, 3));
assert.equal(moveTableAxis(text, "column", 0, 3), text);
assert.equal(moveTableAxis("| H |\n| --- |", "column", 0, 0), "| H |\n| --- |");
assert.equal(moveTableAxis("invalid", "row", 1, 2), "invalid");
});
test("row insertion, movement and duplication preserve header, raw cells and CRLF", () => {
const inserted = changeTableStructure(source, "row", 1, "before");
assert.equal(inserted, source.replace("| Zebra", "| | |\r\n| Zebra"));
assert.equal(changeTableStructure(source, "row", 0, "after"), inserted);
assert.equal(changeTableStructure(source, "row", 0, "before"), source);
const moved = changeTableStructure(source, "row", 2, "previous");
assert.equal(moved, source.replace("| Zebra | `2` |\r\n| **Apple** | 10 |", "| **Apple** | 10 |\r\n| Zebra | `2` |"));
assert.equal(changeTableStructure(moved, "row", 1, "next"), source);
assert.equal(changeTableStructure(source, "row", 1, "previous"), source);
assert.equal(changeTableStructure(source, "row", 0, "next"), source);
assert.equal(changeTableStructure(source, "row", 4, "next"), source);
assert.equal(changeTableStructure(source, "row", 1, "duplicate"), source.replace("| Zebra | `2` |", "| Zebra | `2` |\r\n| Zebra | `2` |"));
assert.ok(changeTableStructure(source, "row", 1, "delete").endsWith("\r\n\r\nTail"));
});
test("column movement and duplication carry header, contents and alignment together", () => {
const moved = changeTableStructure(source, "column", 1, "previous");
assert.deepEqual(values(moved), values(source).map(row => row.toReversed()));
assert.deepEqual(values(changeTableStructure(moved, "column", 0, "next")), values(source));
assert.deepEqual(values(changeTableStructure(source, "column", 0, "duplicate")), values(source).map(row => [row[0], ...row]));
assert.deepEqual(values(changeTableStructure(source, "column", 1, "before")), values(source).map((row, i) => [row[0], i === 1 ? "---" : "", row[1]]));
assert.deepEqual(values(changeTableStructure(source, "column", 1, "delete")), values(source).map(row => [row[0]]));
assert.equal(changeTableStructure(source, "column", 0, "previous"), source);
assert.equal(changeTableStructure(source, "column", 1, "next"), source);
});
test("sort uses visible text and natural numbers, is stable, leaves blanks last and header intact", () => {
assert.deepEqual(values(sortTableColumn(source, 0)).slice(2).map(row => row[0]), ["**Apple**", "apple", "Zebra", ""]);
assert.deepEqual(values(sortTableColumn(source, 0, true)).slice(2).map(row => row[0]), ["Zebra", "**Apple**", "apple", ""]);
assert.deepEqual(values(sortTableColumn(source, 1)).slice(2).map(row => row[1]), ["1", "`2`", "3", "10"]);
const sorted = sortTableColumn(source, 1, true);
assert.ok(sorted.startsWith("| Name | Value |\r\n| :--- | ---: |"));
assert.ok(sorted.includes("| Zebra | `2` |"));
assert.ok(sorted.endsWith("\r\n\r\nTail"));
});
test("header-only, ragged and single-column tables remain valid through operations", () => {
const header = "| H |\n| --- |";
assert.equal(changeTableStructure(header, "row", 0, "duplicate"), header + "\n| H |");
assert.equal(changeTableStructure(header, "column", 0, "delete"), "");
assert.equal(changeTableStructure(header, "row", 0, "delete"), "");
assert.equal(sortTableColumn(header, 0), header);
const ragged = "| A | B |\n| --- | --- |\n| short |\n| a\\|b | two | extra |";
assert.deepEqual(values(changeTableStructure(ragged, "column", 1, "previous"))[3], ["two", "a\\|b", "extra"]);
assert.equal(changeTableStructure("invalid", "row", 0, "after"), "invalid");
});
+195
View File
@@ -0,0 +1,195 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return []; if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "pty_profiles") return [{ 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" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
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(""));
try {
await page.goto("http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await click("Terminal");
await waitCount("pty_open", 1);
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: ".audit/terminal-splits.png" });
await click("Restore panel");
await click("Hide terminal (sessions keep running)");
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");
await page.screenshot({ path: ".audit/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 prompt integration reaches 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__.emit("pty-data", { id, data: [...new TextEncoder().encode(data)] });
});
await click("More terminal actions");
await page.screenshot({ path: ".audit/terminal-actions.png" });
await menu("Run Recent Command… Ctrl+Alt+R");
await page.getByRole("dialog").getByRole("button", { 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("button", { name: "C:\\two words" }).click();
assert.ok((await writes()).includes('cd /d "C:\\two words"'));
await click("Terminal profiles and tasks");
await menu("Configure Terminal Settings");
await page.getByLabel("Font size", { exact: true }).fill("16");
await page.getByLabel("Default profile", { exact: true }).selectOption("git-bash");
await click("Save settings");
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");
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.terminal")).fontSize), 16);
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 Task…");
await page.getByRole("dialog").getByRole("button", { name: "Smoke task echo task-ok" }).click();
await waitCount("pty_open", 6);
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
// Capture selected source while the terminal menu takes focus.
await page.getByRole("button", { name: /Find a file/ }).click();
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).click();
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(e => e.getDomNode()?.isConnected);
editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 15 });
});
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 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+Shift+Alt+`");
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 Terminal");
assert.equal(await count("pty_close"), 1);
await page.setViewportSize({ width: 880, height: 600 });
await page.screenshot({ path: ".audit/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 page.screenshot({ path: ".audit/terminal-single.png" });
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);
await page.goto("http://127.0.0.1:1420/?terminalWindow=C%3A%5Csmoke-workspace");
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("navigation", { name: "Terminal list" }).count(), 0);
await page.screenshot({ path: ".audit/terminal-window.png" });
assert.deepEqual(errors, []);
console.log("PASS: split groups, profile selection, maximize/restore/hide, shell history, directory quoting, settings persistence, tasks, editor selection/file execution, window/dictation IPC, and narrow layout.");
} catch (error) { console.log("errors", errors, "writes", await writes());
await page.screenshot({ path: ".audit/terminal-failure.png" });
throw error;
} finally { await browser.close(); }
+39
View File
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import test from "node:test";
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../src/lib/terminal/model.ts";
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.throws(() => quoteShell("C:\\%PATH%", "cmd"));
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"));
});
test("run file selects a runner and rejects non-executable documents", () => {
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.throws(() => fileCommand("notes.md", "powershell"));
assert.throws(() => fileCommand("app.js", "node"));
});
test("task config validates every entry before offering execution", () => {
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
for (const text of ['{}', '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text));
});
test("history deduplicates most recent entries and is bounded", () => {
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("physical key shortcuts distinguish new, split, window, and hide", () => {
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);
});
+120
View File
@@ -0,0 +1,120 @@
import assert from "node:assert/strict";
import test from "node:test";
import { dropHint, dropPlaceAt, planDrop, uniqueName } from "../src/lib/workspace/treeDrop.ts";
function kids(map: Record<string, string[]>) {
return (parent: string) => map[parent] ?? [];
}
test("same-folder drop before a sibling reorders and keeps the name", () => {
const plan = planDrop(
"notes/b.md",
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
"before",
kids({ notes: ["a.md", "b.md"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "notes",
names: ["b.md", "a.md"],
});
});
test("same-folder drop after a sibling inserts after that sibling", () => {
const plan = planDrop(
"notes/a.md",
{ name: "b.md", rel_path: "notes/b.md", kind: "file" },
"after",
kids({ notes: ["a.md", "b.md"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "notes",
names: ["b.md", "a.md"],
});
});
test("drop inside the parent folder is a no-op", () => {
const plan = planDrop(
"notes/a.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ notes: ["a.md", "b.md"], "": ["notes"] }),
);
assert.deepEqual(plan, { action: "noop" });
});
test("drop before a sibling folder reorders instead of moving inside", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"before",
kids({ "": ["inbox.md", "notes"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "",
names: ["inbox.md", "notes"],
});
});
test("drop onto self is a no-op", () => {
const plan = planDrop(
"notes/a.md",
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
"before",
kids({ notes: ["a.md"] }),
);
assert.deepEqual(plan, { action: "noop" });
});
test("drop inside another folder moves under that folder", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ "": ["inbox.md", "notes"], notes: ["a.md"] }),
);
assert.deepEqual(plan, {
action: "move",
from: "inbox.md",
to: "notes/inbox.md",
fromParent: "",
toParent: "notes",
destName: "inbox.md",
orderFrom: ["notes"],
orderTo: ["a.md", "inbox.md"],
});
});
test("drop into a folder that already has the name picks a unique name", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ "": ["inbox.md", "notes"], notes: ["inbox.md"] }),
);
assert.equal(plan.action, "move");
if (plan.action === "move") {
assert.equal(plan.to, "notes/inbox 2.md");
assert.equal(plan.destName, "inbox 2.md");
}
});
test("uniqueName skips taken numbered suffixes", () => {
assert.equal(uniqueName(["alpha.md", "alpha 2.md"], "alpha.md"), "alpha 3.md");
});
test("dropPlaceAt splits a file row in half and a folder row into three bands", () => {
assert.equal(dropPlaceAt("file", 0.2), "before");
assert.equal(dropPlaceAt("file", 0.8), "after");
assert.equal(dropPlaceAt("folder", 0.1), "before");
assert.equal(dropPlaceAt("folder", 0.5), "inside");
assert.equal(dropPlaceAt("folder", 0.9), "after");
});
test("dropHint names the landing", () => {
assert.equal(dropHint("notes", "inside"), "Into notes");
assert.equal(dropHint("inbox.md", "before"), "Before inbox.md");
assert.equal(dropHint("inbox.md", "after"), "After inbox.md");
});
+122
View File
@@ -0,0 +1,122 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(rows => rows.map(row => row.dataset.treeRel));
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await row('notes').waitFor();
await row('notes').click();
await row('notes/second.md').waitFor();
assert.deepEqual(await selected(), ['notes']);
await row('notes/second.md').click({ modifiers: ['Control'] });
await row('src').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
assert.equal(await page.getByRole('tab').count(), 0);
await row('notes').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
await row('notes/second.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md']);
await row('src').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md', 'src']);
await page.keyboard.press('F2');
assert.equal(await page.locator('.tree .rename').count(), 0);
await row('notes/welcome.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md']);
await row('notes/second.md').click();
assert.deepEqual(await selected(), ['notes/second.md']);
await page.getByRole('tab', { name: /second/ }).waitFor();
await row('notes/second.md').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), []);
await row('src').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Control'] });
await page.keyboard.press('F2');
assert.equal(await page.locator('.tree .rename').inputValue(), 'src');
await page.keyboard.press('Escape');
await row('notes/second.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes/second.md', 'notes/welcome.md', 'src']);
const colors = await page.locator('.tree .row.selected').evaluateAll(rows => rows.map(row => getComputedStyle(row).backgroundColor));
assert.equal(new Set(colors).size, 1);
await page.screenshot({ path: '.audit/tree-selection.png' });
await page.getByRole('button', { name: 'Collapse all', exact: true }).click();
assert.deepEqual(await selected(), ['src']);
await row('notes').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'src']);
await row('notes').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Shift', 'Control'] });
assert.deepEqual(await selected(), ['notes', 'src']);
assert.deepEqual(errors, []);
console.log('Tree selection browser checks passed.');
} finally { await browser.close(); }
+87
View File
@@ -0,0 +1,87 @@
import assert from "node:assert/strict";
import test from "node:test";
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type TreeSelection } from "../src/lib/workspace/treeSelection.ts";
import type { TreeEntry } from "../src/lib/workspace/types.ts";
const entry = (rel_path: string, kind: "file" | "folder" = "file"): TreeEntry => ({ rel_path, name: rel_path.split("/").pop()!, kind });
const children = {
"": [entry("notes", "folder"), entry("src", "folder"), entry("z.md")],
notes: [entry("notes/b.md"), entry("notes/a.md"), entry("notes/nested", "folder")],
"notes/nested": [entry("notes/nested/c.md")],
src: [entry("src/main.ts")],
};
const visible = visibleTreePaths(children, new Set(["notes", "notes/nested"]));
const empty = (): TreeSelection => ({ paths: new Set(), anchor: null });
test("selection outlines omit shared edges and close around gaps and single rows", () => {
const rows = ["a.md", "b.md", "c.md", "d.md", "e.md"];
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "b.md", "c.md", "e.md"]))], [
["a.md", { top: null, bottom: 0 }],
["b.md", { top: 0, bottom: 0 }],
["c.md", { top: 0, bottom: null }],
["e.md", { top: null, bottom: null }],
]);
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "c.md", "e.md"]))].map(([, edges]) => edges),
Array.from({ length: 3 }, () => ({ top: null, bottom: null })));
});
test("nested selection outlines retain only exposed indentation steps in visible order", () => {
const edges = treeSelectionEdges(visible, new Set(visible));
assert.deepEqual(edges.get("notes"), { top: null, bottom: 1 });
assert.deepEqual(edges.get("notes/b.md"), { top: 0, bottom: 0 });
assert.deepEqual(edges.get("notes/nested"), { top: 0, bottom: 1 });
assert.deepEqual(edges.get("notes/nested/c.md"), { top: 0, bottom: 0 });
assert.deepEqual(edges.get("src"), { top: 2, bottom: 0 });
assert.deepEqual(edges.get("z.md"), { top: 0, bottom: null });
const collapsed = visibleTreePaths(children, new Set());
assert.deepEqual([...treeSelectionEdges(collapsed, new Set(visible))], [
["notes", { top: null, bottom: 0 }], ["src", { top: 0, bottom: 0 }], ["z.md", { top: 0, bottom: null }],
]);
});
test("visible order preserves custom sorting and only visits expanded folders", () => {
assert.deepEqual(visible, ["notes", "notes/b.md", "notes/a.md", "notes/nested", "notes/nested/c.md", "src", "z.md"]);
assert.deepEqual(visibleTreePaths(children, new Set()), ["notes", "src", "z.md"]);
});
test("Ctrl-click toggles files and folders independently; plain click replaces the selection", () => {
const first = selectTreePath(empty(), "notes", visible);
const added = selectTreePath(first, "z.md", visible, { ctrlKey: true });
assert.deepEqual([...added.paths], ["notes", "z.md"]);
assert.deepEqual([...first.paths], ["notes"]);
const removed = selectTreePath(added, "notes", visible, { ctrlKey: true });
assert.deepEqual([...removed.paths], ["z.md"]);
assert.deepEqual([...selectTreePath(removed, "z.md", visible, { ctrlKey: true }).paths], []);
assert.deepEqual([...selectTreePath(added, "src", visible).paths], ["src"]);
});
test("Shift-click selects an inclusive range in both directions across files and folders", () => {
const first = selectTreePath(empty(), "notes/b.md", visible);
const forward = selectTreePath(first, "src", visible, { shiftKey: true });
assert.deepEqual([...forward.paths], visible.slice(1, 6));
const reverse = selectTreePath(selectTreePath(empty(), "src", visible), "notes/b.md", visible, { shiftKey: true });
assert.deepEqual([...reverse.paths], visible.slice(1, 6));
});
test("repeated Shift-click keeps the anchor and shrinks or reverses the range", () => {
const first = selectTreePath(empty(), "notes/a.md", visible);
const extended = selectTreePath(first, "z.md", visible, { shiftKey: true });
const shrunk = selectTreePath(extended, "notes/nested", visible, { shiftKey: true });
assert.deepEqual([...shrunk.paths], ["notes/a.md", "notes/nested"]);
assert.equal(shrunk.anchor, "notes/a.md");
assert.deepEqual([...selectTreePath(shrunk, "notes", visible, { shiftKey: true }).paths], visible.slice(0, 3));
});
test("Ctrl+Shift adds a range and Command-click supports the same toggle behavior", () => {
let selection = selectTreePath(empty(), "z.md", visible);
selection = selectTreePath(selection, "notes/b.md", visible, { metaKey: true });
selection = selectTreePath(selection, "notes/nested", visible, { ctrlKey: true, shiftKey: true });
assert.deepEqual([...selection.paths], ["z.md", "notes/b.md", "notes/a.md", "notes/nested"]);
assert.deepEqual([...selectTreePath(selection, "z.md", visible, { metaKey: true }).paths], ["notes/b.md", "notes/a.md", "notes/nested"]);
});
test("a missing or hidden anchor makes Shift-click select only the clicked row", () => {
assert.deepEqual(selectTreePath(empty(), "src", visible, { shiftKey: true }), { paths: new Set(["src"]), anchor: "src" });
const hidden = selectTreePath(empty(), "notes/b.md", visible);
assert.deepEqual(selectTreePath(hidden, "z.md", ["notes", "src", "z.md"], { shiftKey: true }), { paths: new Set(["z.md"]), anchor: "z.md" });
});
+84
View File
@@ -0,0 +1,84 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const state = { maximized: false, confirm: "Cancel", calls: [] };
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
state.calls.push(command);
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return null;
if (command === "plugin:window|is_maximized") return state.maximized;
if (command === "plugin:window|toggle_maximize") { state.maximized = !state.maximized; emit("tauri://resize", { width: 1400, height: 900 }); return; }
if (command === "plugin:window|minimize" || command === "plugin:window|destroy") return;
if (command === "plugin:window|close") { emit("tauri://close-requested"); return; }
if (command === "plugin:dialog|message") return state.confirm;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { state, emit };
});
try {
const config = JSON.parse(await readFile(new URL("../src-tauri/tauri.conf.json", import.meta.url), "utf8"));
assert.equal(config.app.windows[0].decorations, false);
const capability = JSON.parse(await readFile(new URL("../src-tauri/capabilities/default.json", import.meta.url), "utf8"));
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
}
await page.goto(process.env.SMOKE_URL || "http://localhost:1420");
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).click();
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
// Native maximize/restore (e.g. double-clicking the drag region) updates the button too.
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert.ok(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|minimize")));
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:dialog|message"));
assert.equal(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|destroy")), false);
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:window|destroy"));
await page.getByRole("button", { name: "Terminal", exact: true }).click();
for (const width of [1400, 880]) {
await page.setViewportSize({ width, height: 900 });
const layout = await page.evaluate(() => {
const header = document.querySelector(".header").getBoundingClientRect();
const controls = [...document.querySelectorAll(".header button")].map(el => el.getBoundingClientRect());
return { height: header.height, top: header.top, fits: controls.every(rect => rect.x >= 0 && rect.right <= innerWidth && rect.y >= header.y && rect.bottom <= header.bottom), drag: document.querySelector(".window-drag-space").getBoundingClientRect().width };
});
assert.equal(layout.height, 36);
assert.equal(layout.top, 0);
assert.ok(layout.fits);
assert.ok(layout.drag >= 40);
await page.screenshot({ path: `.audit/window-controls-${width}.png` });
}
assert.deepEqual(errors, []);
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
} finally { await browser.close(); }
+798
View File
@@ -0,0 +1,798 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const original = await contents();
assert.ok(original.startsWith("---\ntitle:"));
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Added in source.");
await waitForText(original + "Added in source.");
await quickOpen("hello.py");
await page.getByRole("tab", { name: /welcome\.md/ }).click();
await focusEditor();
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source.");
await page.keyboard.press("Control+y");
await waitForText(original + "Added in source.");
await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await page.getByRole("button", { name: "Split", exact: true }).click();
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".monaco-host").isVisible());
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await waitForText("# Agent update\n");
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Local edit");
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await page.getByRole("button", { name: "Keep my edits" }).waitFor();
assert.equal(await contents(), "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Keep my edits" }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
await page.screenshot({ path: ".audit/core-rebuild-terminal.png" });
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
await page.getByRole("button", { name: "New terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
await page.screenshot({ path: ".audit/core-rebuild.png" });
await page.evaluate(text => {
window.__TEST__.files.set("reader-showcase.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
const read = page.getByRole("button", { name: "Read", exact: true });
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-pressed"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".monaco-host").isVisible(), false);
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
assert.equal(await page.locator(".reading ol > li").count(), 3);
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
assert.equal(await page.locator(".reading input:checked").count(), 2);
assert.equal(await page.locator(".md-properties").getAttribute("open"), null);
assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes"));
const surface = await page.locator(".reading").boundingBox();
assert.ok(surface.width <= 741);
await page.mouse.move(700, 980);
await page.screenshot({ path: ".audit/reader-mode.png" });
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
await page.getByRole("button", { name: "Copy code", exact: true }).click();
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
await page.screenshot({ path: ".audit/reader-details.png" });
await page.setViewportSize({ width: 1000, height: 900 });
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: ".audit/reader-narrow.png" });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.getByRole("button", { name: "Split", exact: true }).click();
await page.waitForFunction(() => {
const host = document.querySelector(".monaco-host");
const rendered = host?.querySelector(".monaco-editor");
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
});
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
await page.screenshot({ path: ".audit/reader-split.png" });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.setViewportSize({ width: 1440, height: 1000 });
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
await page.screenshot({ path: ".audit/reader-split-wide.png" });
await page.getByRole("button", { name: "Edit", exact: true }).click();
assert.equal(await contents(), showcase);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await page.getByRole("button", { name: "Read", exact: true }).focus();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" });
// Continuous live Markdown: only active lines reveal source; checkboxes
// remain inline and update the original file without HTML serialization.
const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n';
await page.evaluate(text => {
window.__TEST__.files.set("writing.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
}, writingSource);
await quickOpen("writing.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0);
await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 });
await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor();
const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." });
await paragraph.click();
await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor();
await page.keyboard.press("Home");
await page.keyboard.type("New ");
await page.keyboard.press("Control+s");
const editedSource = writingSource.replace("A **formatted**", "New A **formatted**");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await writer.waitFor();
await paragraph.click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("First new paragraph.");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("**Second new paragraph.**");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("Third new paragraph.");
assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1);
await page.keyboard.press("Home");
await page.keyboard.press("Shift+ArrowUp");
await page.keyboard.press("Shift+ArrowUp");
assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph."));
await page.keyboard.press("Backspace");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph."));
assert.ok(await writer.evaluate(el => el.contains(document.activeElement)));
// Link syntax becomes editable on a normal click, without opening the link.
await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click();
await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor();
await page.keyboard.press("End");
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.keyboard.type("[Project link](https://example.com/new)");
await page.keyboard.press("ArrowDown");
await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor();
const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" });
const checkbox = task.getByRole("checkbox");
assert.ok(await task.evaluate(line => {
const box = line.querySelector('input').getBoundingClientRect();
const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft'));
const range = document.createRange(); range.selectNode(text);
const label = range.getBoundingClientRect();
return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left;
}));
await checkbox.click();
await task.locator('.writer-completed').waitFor();
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
await task.locator('.writer-completed').click();
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.keyboard.type('- [ ] Revised task');
await page.keyboard.press("ArrowUp");
await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
await page.locator(".live-writer .md-diagram svg").waitFor();
await page.screenshot({ path: ".audit/writing-continuous.png" });
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.evaluate(() => {
window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
});
await quickOpen("crlf.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
await page.keyboard.press("Home");
await page.keyboard.type("Changed ");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n");
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await writer.waitFor();
await page.keyboard.type("One");
await page.keyboard.press("Enter");
await page.keyboard.type("Two");
await page.keyboard.press("Enter");
await page.keyboard.type("Three");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.getByRole("tab", { name: "crlf.md", exact: true }).click();
await page.getByRole("tab", { name: "blank.md", exact: true }).click();
await writer.waitFor();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree");
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.keyboard.press("Control+f");
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+a");
await page.keyboard.type("- [ ] First task");
await page.keyboard.press("Enter");
await page.keyboard.type("Second task");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task");
await page.evaluate(() => {
window.__TEST__.files.set("blank.md", "Fresh disk version\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] });
});
await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor();
await page.keyboard.press("Control+z");
assert.ok((await writer.innerText()).includes("Fresh disk version"));
const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.<br>Keep listings consistent.<br>Introduce automated investing.<br>Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;<br>- Trading |\n\nAfter the table.\n';
await page.evaluate(text => {
window.__TEST__.files.set("tables.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["tables.md"] });
}, tableSource);
await page.setViewportSize({ width: 1440, height: 1000 });
await quickOpen("tables.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
const table = page.locator('.live-writer table');
await table.waitFor();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
const tableHeading = page.locator('.live-writer .writer-heading');
await tableHeading.click();
assert.equal(await tableHeading.innerText(), '# Table layout');
await table.locator('tbody tr').first().locator('td').first().click();
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
assert.equal(await table.locator('th').count(), 5);
assert.equal(await table.locator('tbody tr').count(), 2);
assert.equal(await table.locator('br').count(), 4);
assert.ok(!(await table.innerText()).includes('<br>'));
assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100)));
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
await table.locator('td').first().hover();
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-column.png' });
await addColumn.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
await addRow.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-row.png' });
await addRow.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |'));
assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2);
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource);
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+y');
await table.locator('th').last().click();
const cellEditor = page.locator('.writer-cell-editor');
await cellEditor.waitFor();
assert.equal(await table.locator('th').count(), 6);
assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0);
await page.keyboard.type('New column');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column'));
await page.keyboard.press('Tab');
assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count());
await page.keyboard.press('Shift+Tab');
assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count());
await table.locator('tbody tr').first().locator('td').nth(4).click();
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
await page.keyboard.press('Control+End');
await page.keyboard.press('Enter');
await page.keyboard.type('Plain | pipe and *stars*');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
assert.equal(await table.locator('th').count(), 6);
await page.screenshot({ path: '.audit/writing-table-cell-edit.png' });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
await cellEditor.waitFor();
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain'));
await page.keyboard.press('Escape');
await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click();
const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md'));
await table.locator('tbody tr').first().locator('td').nth(4).click();
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit);
await table.locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Tab');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4);
await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.getByRole('button', { name: 'Read', exact: true }).click();
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
assert.equal(await page.locator('.md-page table br').count(), 5);
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('selection-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
window.__TEST__.clipboard = '';
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
writeText: async text => { window.__TEST__.clipboard = text; },
readText: async () => window.__TEST__.clipboard,
} });
}, selectionTable);
await quickOpen('selection-table.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const selectedTable = page.locator('.live-writer table');
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
await page.mouse.move(fromCell.x + 15, fromCell.y + 15);
await page.mouse.down();
await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 });
await page.mouse.up();
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
await page.screenshot({ path: '.audit/table-cell-selection-menu.png' });
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
await page.keyboard.press('Control+i');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0);
assert.equal(await selectedTable.locator('strong').count(), 4);
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
async function cellAction(name, formatted = false) {
await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' });
if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
}
await cellAction('Clear formatting', true);
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
await cellAction('Copy');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive');
await cellAction('Cut');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
await cellAction('Paste');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await cellAction('Align centre');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) {
await cellAction(name, true);
await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector);
await cellAction('Clear formatting', true);
}
// Native clipboard events must operate on the rectangle, including one-step undo.
await page.locator('.writer-table').evaluate(el => {
const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
});
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red');
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three');
assert.equal(await selectedTable.locator('th').count(), 3);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await page.keyboard.press('Control+a');
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9);
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0);
await page.keyboard.press('Control+z');
await selectedTable.waitFor();
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) {
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
await selectedCell(1, 0).click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Escape');
assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`);
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await cellAction('Clear formatting', true);
}
const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('table-actions.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
}, actionsSource);
await quickOpen('table-actions.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const actionTable = page.locator('.live-writer table');
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
async function actionItem(label, group, r = 1, c = 0) {
await actionCell(r, c).click({ button: 'right' });
if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover();
await page.getByRole('menuitem', { name: label, exact: true }).click();
}
async function saveActionSource() {
await page.keyboard.press('Control+s');
return page.evaluate(() => window.__TEST__.files.get('table-actions.md'));
}
async function undoAction() {
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource);
}
for (const [label, group, r, c, rows, columns] of [
['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2],
['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1],
]) {
await actionItem(label, group, r, c);
assert.equal(await actionTable.locator('tr').count(), rows, label);
assert.equal(await actionTable.locator('th').count(), columns, label);
await undoAction();
}
await actionItem('Move row down', 'Row');
assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group');
await undoAction();
await actionItem('Move row up', 'Row', 2);
assert.equal(await actionCell(1, 0).innerText(), 'Apple');
await undoAction();
await actionItem('Move column right', 'Column');
assert.equal(await actionCell(0, 0).innerText(), 'Value');
assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right');
await undoAction();
await actionItem('Move column left', 'Column', 1, 1);
assert.equal(await actionCell(0, 0).innerText(), 'Value');
await undoAction();
await actionItem('Sort by column (A to Z)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']);
await undoAction();
await actionItem('Sort by column (Z to A)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']);
await undoAction();
await actionCell(0, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled());
assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled());
await page.keyboard.press('Escape');
async function selectBrokers() {
await actionCell(1, 0).click();
await page.keyboard.press('Control+Home');
for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight');
for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers');
}
await selectBrokers();
await actionCell(1, 0).click({ button: 'right' });
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-row-menu.png' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-column-menu.png' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
await page.keyboard.press('ArrowRight');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
await page.keyboard.press('ArrowLeft');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column');
await page.keyboard.press('Escape');
await actionItem('Bold', 'Format');
assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers');
assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group'));
await actionItem('Add external link');
await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1');
assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Add link');
await page.getByRole('dialog').locator('input').fill('notes/second');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Search for “Brokers”');
await page.getByPlaceholder('Search files and notes').waitFor();
assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers');
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers'));
await selectBrokers();
await actionItem('Extract current selection…');
await page.getByRole('dialog').locator('input').fill('extracted-brokers.md');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n');
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md');
await page.keyboard.press('Control+z');
await selectBrokers();
await page.evaluate(() => { window.__TEST__.clipboard = '<b>literal</b>\nnext'; });
await actionItem('Paste as plain text');
assert.ok((await saveActionSource()).includes('Interactive &lt;') || (await saveActionSource()).includes('Interactive \\<b\\>literal\\</b\\><br>next'));
assert.equal(await actionCell(1, 0).locator('b').count(), 0);
await page.keyboard.press('Control+z');
await selectBrokers();
await page.evaluate(() => {
navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? '<em>Rich paste</em>' : 'Rich paste'], { type }) }];
});
await actionItem('Paste');
await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste');
await page.keyboard.press('Control+z');
await page.evaluate(() => { delete navigator.clipboard.read; });
await selectBrokers();
await actionItem('Copy');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
await actionItem('Cut');
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Select all');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group');
await page.setViewportSize({ width: 800, height: 600 });
await actionCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
assert.ok(await page.locator('.table-cell-menu, .table-cell-submenu:not([hidden])').evaluateAll(panels => panels.every(panel => {
const rect = panel.getBoundingClientRect(); return rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight;
})));
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
const richTable = '| Name | Notes |\r\n| :--- | ---: |\r\n| Untouched | ~~Old~~ **bold** [link](https://example.com) ![attachment](missing.png)<br />Next |\r\n| Short |\r\n';
await page.evaluate(text => {
window.__TEST__.files.set('rich-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
}, richTable);
await quickOpen('rich-table.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
await richCell.click();
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable);
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited'));
const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md'));
assert.ok(richSaved.includes('| Untouched |'));
assert.ok(richSaved.includes('~~Old~~'));
assert.ok(richSaved.includes('**bold**'));
assert.ok(richSaved.includes('https://example.com'));
assert.ok(richSaved.includes('![attachment](<missing.png>)'));
assert.ok(richSaved.includes('<br>Next edited'));
assert.ok(!/(?<!\r)\n/.test(richSaved));
await page.keyboard.press('Escape');
await richCell.click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' again');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Next edited again'));
const shortCell = page.locator('.live-writer tbody tr').last().locator('td').last();
await shortCell.click();
await cellEditor.evaluate(el => {
const data = new DataTransfer(); data.setData('text/plain', 'Pasted | text\nSecond line');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
});
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Pasted \\| text<br>Second line'));
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+b');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('**Pasted \\| text**'));
assert.equal(await page.locator('.live-writer th').count(), 2);
// Physical mouse coordinates below tall block widgets must resolve to the
// visible line, including immediately adjacent heading/body lines.
const longTable = '| Ticker | Name | Notes |\n| --- | --- | --- |\n' +
Array.from({ length: 14 }, (_, index) => `| STOCK${index} | Company ${index} | First note<br>Second note<br>Third note |`).join('\n');
const hitTestSource = `# Listed\n\n${longTable}\n\n# Tier 1\nTier one body directly below heading.\n\n${longTable}\n\n## Tier 2\nTier two body directly below heading.\n`;
await page.evaluate(text => {
window.__TEST__.files.set('table-hit-testing.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
}, hitTestSource);
await quickOpen('table-hit-testing.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
async function clickRenderedLine(locator, expected) {
await locator.scrollIntoViewIfNeeded();
const rect = await locator.boundingBox();
assert.ok(rect);
await page.mouse.click(rect.x + 45, rect.y + rect.height * .7);
const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent);
assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`);
}
async function checkLinesAfterTables() {
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
for (const [heading, body] of [
['# Tier 1', 'Tier one body directly below heading.'],
['## Tier 2', 'Tier two body directly below heading.'],
]) {
const tables = page.locator('.live-writer .writer-table');
await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded();
await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading);
await page.keyboard.press('End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading);
await page.keyboard.press('Control+z');
await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body);
}
}
await page.setViewportSize({ width: 1440, height: 1000 });
await checkLinesAfterTables();
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Control+End');
for (let line = 0; line < 4; line++) {
await page.keyboard.press('Enter');
await page.keyboard.type('A newly added line changes the table height.');
}
await checkLinesAfterTables();
await page.setViewportSize({ width: 1000, height: 900 });
await checkLinesAfterTables();
await page.screenshot({ path: '.audit/table-cursor-position.png' });
assert.deepEqual(errors, []);
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md")));
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
await page.screenshot({ path: ".audit/core-rebuild-failure.png" });
throw error;
} finally { await browser.close(); }
+122
View File
@@ -0,0 +1,122 @@
// Run against pnpm dev; use PLAYWRIGHT_MODULE for a shared Playwright installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1100, height: 800 } });
const errors = [];
page.on("pageerror", err => errors.push(err.message));
await page.addInitScript(() => {
window.isTauri = true;
let current = "D:\\Notes";
let recent = [current, "D:\\Writing\\Notes", "D:\\Missing"];
let picked = null;
let contents = "Original note";
const calls = [];
const windows = [];
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "workspace_last_path") return current;
if (command === "workspace_recent") return recent;
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
if (command === "workspace_read") { if (args.rel === "note.txt") return contents; throw "File not found"; }
if (command === "workspace_write") { contents = args.contents; return; }
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "plugin:dialog|open") return picked;
if (command === "plugin:dialog|message") return "Cancel";
if (command === "workspace_new") {
if (args.name === "Existing") throw "A file or folder with that name already exists.";
const root = args.parent + "\\" + args.name;
recent = [root, ...recent]; windows.push(root);
return;
}
if (command === "workspace_open_window") {
if (args.path.endsWith("Missing")) throw "folder does not exist";
windows.push(args.path);
recent = [args.path, ...recent.filter(p => p !== args.path)];
return;
}
if (command === "workspace_open") {
if (args.path.endsWith("Missing")) throw "folder does not exist";
current = args.path; recent = [current, ...recent.filter(p => p !== current)];
return { root: current, name: current.split("\\").pop(), watch_mode: "native" };
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [] };
});
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco;
window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected).setValue("My pending edit");
});
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
await trigger.click();
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
await page.screenshot({ path: ".audit/workspaces-menu.png" });
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
await menu.getByRole("button").filter({ hasText: "Current" }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
await page.keyboard.press("Control+o");
await menu.getByRole("button").filter({ hasText: "Missing" }).click();
await menu.getByRole("alert").filter({ hasText: "folder does not exist" }).waitFor();
await menu.getByRole("button", { name: "Open another folder…" }).click();
assert(await menu.isVisible(), "Cancelling folder picker keeps history available");
await menu.getByRole("button").filter({ hasText: "D:\\Writing\\Notes" }).click();
await menu.waitFor({ state: "hidden" });
assert.equal(await page.locator(".ws").textContent(), "Notes");
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes"]);
await trigger.click();
await page.evaluate(() => window.__TEST__.pick("D:\\Other"));
await menu.getByRole("button", { name: "Open another folder…" }).click();
await menu.waitFor({ state: "hidden" });
assert.equal(await page.locator(".ws").textContent(), "Notes");
await trigger.click();
await menu.getByRole("button", { name: "New workspace…" }).click();
const dialog = page.getByRole("dialog", { name: "New workspace", exact: true });
assert(await dialog.getByRole("button", { name: "Create workspace", exact: true }).isDisabled());
await dialog.getByLabel("Workspace name").fill("Existing");
await page.evaluate(() => window.__TEST__.pick("D:\\Projects"));
await dialog.getByRole("button", { name: "Browse…" }).click();
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
await dialog.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
await dialog.getByLabel("Workspace name").fill("Fresh notes");
await page.screenshot({ path: ".audit/workspaces-create.png" });
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
await dialog.waitFor({ state: "hidden" });
assert.equal(await page.locator(".ws").textContent(), "Notes");
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes", "D:\\Other", "D:\\Projects\\Fresh notes"]);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|message").length), 0);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected)?.getValue()), "My pending edit");
assert(await page.getByRole("tab", { name: /note\.txt/ }).isVisible());
await trigger.click();
await page.keyboard.press("End");
assert.equal(await page.locator(":focus").textContent(), " Open another folder…");
await page.keyboard.press("Escape");
await menu.waitFor({ state: "hidden" });
await page.evaluate(() => window.__TEST__.clear());
await trigger.click();
await menu.getByText("No recent workspaces yet.").waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
await menu.waitFor({ state: "hidden" });
assert.deepEqual(errors, []);
console.log("Workspace smoke passed: history, opening and creating in new windows, original workspace preserved, cancellation, errors, keyboard and empty state.");
} finally { await browser.close(); }
+244
View File
@@ -0,0 +1,244 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
copySelection,
cutSelection,
pasteClipboard,
writerContextItems,
} from "../src/lib/editor/writerMenu.ts";
type Harness = {
selected: string;
inTable: boolean;
deleted: boolean;
focused: boolean;
inserted: string | null;
dispatched: boolean;
};
function fakeEditor(init?: { selected?: string; inTable?: boolean }) {
const harness: Harness = {
selected: init?.selected ?? "",
inTable: init?.inTable ?? false,
deleted: false,
focused: false,
inserted: null,
dispatched: false,
};
const tr = {
insertText(text: string) {
harness.inserted = text;
return tr;
},
};
const chainApi = {
focus() {
harness.focused = true;
return chainApi;
},
deleteSelection() {
harness.deleted = true;
return chainApi;
},
run() {
return true;
},
};
const editor = {
isActive(name: string) {
return name === "table" && harness.inTable;
},
chain() {
return chainApi;
},
state: {
selection: { from: 0, to: harness.selected.length },
doc: {
textBetween() {
return harness.selected;
},
},
tr,
},
view: {
dispatch() {
harness.dispatched = true;
},
},
};
return { editor, harness };
}
function withClipboard(
impl: { writeText?: (text: string) => Promise<void>; readText?: () => Promise<string> },
run: () => Promise<void>,
): Promise<void> {
const previous = Object.getOwnPropertyDescriptor(globalThis, "navigator");
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: { clipboard: impl },
});
return run().finally(() => {
if (previous) {
Object.defineProperty(globalThis, "navigator", previous);
} else {
Reflect.deleteProperty(globalThis, "navigator");
}
});
}
function actionLabels(items: ReturnType<typeof writerContextItems>): string[] {
const labels: string[] = [];
for (const item of items) {
if (item.kind === "action") {
labels.push(item.label);
} else if (item.kind === "group") {
for (const sub of item.items) {
if (sub.kind === "action") {
labels.push(sub.label);
}
}
}
}
return labels;
}
test("paste inserts clipboard text without parsing tags", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{ readText: async () => "<b>bold</b>" },
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.focused, true);
assert.equal(harness.dispatched, true);
assert.equal(harness.inserted, "<b>bold</b>");
});
test("paste swallows clipboard errors", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{
readText: async () => {
throw new Error("denied");
},
},
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.dispatched, false);
assert.equal(harness.inserted, null);
});
test("cut keeps the selection when clipboard write fails", async () => {
const { editor, harness } = fakeEditor({ selected: "gone" });
await withClipboard(
{
writeText: async () => {
throw new Error("denied");
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(harness.deleted, false);
});
test("copy swallows clipboard errors", async () => {
const { editor } = fakeEditor({ selected: "keep" });
let attempted = false;
await withClipboard(
{
writeText: async () => {
attempted = true;
throw new Error("denied");
},
},
async () => {
await copySelection(editor as never);
},
);
assert.equal(attempted, true);
});
test("cut writes selected text then deletes it", async () => {
const { editor, harness } = fakeEditor({ selected: "clip" });
let written = "";
await withClipboard(
{
writeText: async (text) => {
written = text;
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(written, "clip");
assert.equal(harness.deleted, true);
});
test("table row and column actions disable outside a table", () => {
const { editor } = fakeEditor({ inTable: false });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, true);
assert.equal(byLabel.get("Delete table")?.disabled, true);
});
test("table row and column actions enable inside a table", () => {
const { editor } = fakeEditor({ inTable: true });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, false);
assert.equal(byLabel.get("Delete table")?.disabled, false);
});
test("style and format actions cover the requested commands", () => {
const { editor } = fakeEditor();
const labels = actionLabels(writerContextItems(editor as never));
for (const label of [
"Cut",
"Copy",
"Paste",
"Heading 1",
"Heading 6",
"Body",
"Quote",
"Bullet list",
"Numbered list",
"Task list",
"Bold",
"Italic",
"Strikethrough",
"Highlight",
"Code",
"Math",
"Comment",
"Clear formatting",
"Insert table",
]) {
assert.equal(labels.includes(label), true, label);
}
assert.equal(labels.includes("Superscript"), false);
assert.equal(labels.includes("Subscript"), false);
});
+7
View File
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
+5395
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "runestone"
version = "0.1.0"
description = "Writing workspace plus script editor"
authors = ["you"]
edition = "2021"
[lib]
name = "runestone_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2.0.20"
notify = "8.2.0"
ignore = "0.4.33"
dunce = "1.0.5"
tauri-plugin-dialog = "2.7.3"
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
base64 = "0.23.1"
portable-pty = "0.9.0"
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true
+33
View File
@@ -0,0 +1,33 @@
fn main() {
tauri_build::try_build(
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"workspace_open",
"workspace_open_window",
"workspace_last_path",
"workspace_recent",
"workspace_new",
"workspace_list",
"workspace_read",
"workspace_write",
"workspace_create",
"workspace_rename",
"workspace_delete",
"workspace_read_data_url",
"workspace_write_bytes",
"workspace_copy",
"workspace_abs_path",
"workspace_reveal",
"workspace_search",
"pty_open",
"pty_write",
"pty_resize",
"pty_close",
"pty_profiles",
"pty_new_window",
"pty_dictation",
]),
),
)
.expect("failed to run tauri-build");
}
+41
View File
@@ -0,0 +1,41 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main", "workspace-*", "terminal-*"],
"permissions": [
"core:default",
"core:window:allow-destroy",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-start-dragging",
"opener:default",
"dialog:default",
"allow-workspace-open",
"allow-workspace-open-window",
"allow-workspace-last-path",
"allow-workspace-recent",
"allow-workspace-new",
"allow-workspace-list",
"allow-workspace-read",
"allow-workspace-write",
"allow-workspace-create",
"allow-workspace-rename",
"allow-workspace-delete",
"allow-workspace-read-data-url",
"allow-workspace-write-bytes",
"allow-workspace-copy",
"allow-workspace-abs-path",
"allow-workspace-reveal",
"allow-workspace-search",
"allow-pty-open",
"allow-pty-write",
"allow-pty-resize",
"allow-pty-close",
"allow-pty-profiles",
"allow-pty-new-window",
"allow-pty-dictation",
"opener:allow-reveal-item-in-dir"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-close"
description = "Enables the pty_close command without any pre-configured scope."
commands.allow = ["pty_close"]
[[permission]]
identifier = "deny-pty-close"
description = "Denies the pty_close command without any pre-configured scope."
commands.deny = ["pty_close"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-dictation"
description = "Enables the pty_dictation command without any pre-configured scope."
commands.allow = ["pty_dictation"]
[[permission]]
identifier = "deny-pty-dictation"
description = "Denies the pty_dictation command without any pre-configured scope."
commands.deny = ["pty_dictation"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-new-window"
description = "Enables the pty_new_window command without any pre-configured scope."
commands.allow = ["pty_new_window"]
[[permission]]
identifier = "deny-pty-new-window"
description = "Denies the pty_new_window command without any pre-configured scope."
commands.deny = ["pty_new_window"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-open"
description = "Enables the pty_open command without any pre-configured scope."
commands.allow = ["pty_open"]
[[permission]]
identifier = "deny-pty-open"
description = "Denies the pty_open command without any pre-configured scope."
commands.deny = ["pty_open"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-profiles"
description = "Enables the pty_profiles command without any pre-configured scope."
commands.allow = ["pty_profiles"]
[[permission]]
identifier = "deny-pty-profiles"
description = "Denies the pty_profiles command without any pre-configured scope."
commands.deny = ["pty_profiles"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-resize"
description = "Enables the pty_resize command without any pre-configured scope."
commands.allow = ["pty_resize"]
[[permission]]
identifier = "deny-pty-resize"
description = "Denies the pty_resize command without any pre-configured scope."
commands.deny = ["pty_resize"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-write"
description = "Enables the pty_write command without any pre-configured scope."
commands.allow = ["pty_write"]
[[permission]]
identifier = "deny-pty-write"
description = "Denies the pty_write command without any pre-configured scope."
commands.deny = ["pty_write"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-abs-path"
description = "Enables the workspace_abs_path command without any pre-configured scope."
commands.allow = ["workspace_abs_path"]
[[permission]]
identifier = "deny-workspace-abs-path"
description = "Denies the workspace_abs_path command without any pre-configured scope."
commands.deny = ["workspace_abs_path"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-copy"
description = "Enables the workspace_copy command without any pre-configured scope."
commands.allow = ["workspace_copy"]
[[permission]]
identifier = "deny-workspace-copy"
description = "Denies the workspace_copy command without any pre-configured scope."
commands.deny = ["workspace_copy"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-create"
description = "Enables the workspace_create command without any pre-configured scope."
commands.allow = ["workspace_create"]
[[permission]]
identifier = "deny-workspace-create"
description = "Denies the workspace_create command without any pre-configured scope."
commands.deny = ["workspace_create"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-delete"
description = "Enables the workspace_delete command without any pre-configured scope."
commands.allow = ["workspace_delete"]
[[permission]]
identifier = "deny-workspace-delete"
description = "Denies the workspace_delete command without any pre-configured scope."
commands.deny = ["workspace_delete"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-last-path"
description = "Enables the workspace_last_path command without any pre-configured scope."
commands.allow = ["workspace_last_path"]
[[permission]]
identifier = "deny-workspace-last-path"
description = "Denies the workspace_last_path command without any pre-configured scope."
commands.deny = ["workspace_last_path"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-list"
description = "Enables the workspace_list command without any pre-configured scope."
commands.allow = ["workspace_list"]
[[permission]]
identifier = "deny-workspace-list"
description = "Denies the workspace_list command without any pre-configured scope."
commands.deny = ["workspace_list"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-new"
description = "Enables the workspace_new command without any pre-configured scope."
commands.allow = ["workspace_new"]
[[permission]]
identifier = "deny-workspace-new"
description = "Denies the workspace_new command without any pre-configured scope."
commands.deny = ["workspace_new"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-open"
description = "Enables the workspace_open command without any pre-configured scope."
commands.allow = ["workspace_open"]
[[permission]]
identifier = "deny-workspace-open"
description = "Denies the workspace_open command without any pre-configured scope."
commands.deny = ["workspace_open"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-open-window"
description = "Enables the workspace_open_window command without any pre-configured scope."
commands.allow = ["workspace_open_window"]
[[permission]]
identifier = "deny-workspace-open-window"
description = "Denies the workspace_open_window command without any pre-configured scope."
commands.deny = ["workspace_open_window"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-read"
description = "Enables the workspace_read command without any pre-configured scope."
commands.allow = ["workspace_read"]
[[permission]]
identifier = "deny-workspace-read"
description = "Denies the workspace_read command without any pre-configured scope."
commands.deny = ["workspace_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-read-data-url"
description = "Enables the workspace_read_data_url command without any pre-configured scope."
commands.allow = ["workspace_read_data_url"]
[[permission]]
identifier = "deny-workspace-read-data-url"
description = "Denies the workspace_read_data_url command without any pre-configured scope."
commands.deny = ["workspace_read_data_url"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-recent"
description = "Enables the workspace_recent command without any pre-configured scope."
commands.allow = ["workspace_recent"]
[[permission]]
identifier = "deny-workspace-recent"
description = "Denies the workspace_recent command without any pre-configured scope."
commands.deny = ["workspace_recent"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-rename"
description = "Enables the workspace_rename command without any pre-configured scope."
commands.allow = ["workspace_rename"]
[[permission]]
identifier = "deny-workspace-rename"
description = "Denies the workspace_rename command without any pre-configured scope."
commands.deny = ["workspace_rename"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-reveal"
description = "Enables the workspace_reveal command without any pre-configured scope."
commands.allow = ["workspace_reveal"]
[[permission]]
identifier = "deny-workspace-reveal"
description = "Denies the workspace_reveal command without any pre-configured scope."
commands.deny = ["workspace_reveal"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-search"
description = "Enables the workspace_search command without any pre-configured scope."
commands.allow = ["workspace_search"]
[[permission]]
identifier = "deny-workspace-search"
description = "Denies the workspace_search command without any pre-configured scope."
commands.deny = ["workspace_search"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-write"
description = "Enables the workspace_write command without any pre-configured scope."
commands.allow = ["workspace_write"]
[[permission]]
identifier = "deny-workspace-write"
description = "Denies the workspace_write command without any pre-configured scope."
commands.deny = ["workspace_write"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-write-bytes"
description = "Enables the workspace_write_bytes command without any pre-configured scope."
commands.allow = ["workspace_write_bytes"]
[[permission]]
identifier = "deny-workspace-write-bytes"
description = "Denies the workspace_write_bytes command without any pre-configured scope."
commands.deny = ["workspace_write_bytes"]
+52
View File
@@ -0,0 +1,52 @@
mod pty;
mod workspace;
use pty::PtyState;
use tauri::Manager;
use workspace::WorkspaceState;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.manage(WorkspaceState::new())
.manage(PtyState::new())
.invoke_handler(tauri::generate_handler![
workspace::workspace_open,
workspace::workspace_open_window,
workspace::workspace_last_path,
workspace::workspace_recent,
workspace::workspace_new,
workspace::workspace_list,
workspace::workspace_read,
workspace::workspace_write,
workspace::workspace_create,
workspace::workspace_rename,
workspace::workspace_delete,
workspace::workspace_read_data_url,
workspace::workspace_write_bytes,
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
workspace::workspace_search,
pty::pty_open,
pty::pty_write,
pty::pty_resize,
pty::pty_close,
pty::pty_profiles,
pty::pty_new_window,
pty::pty_dictation,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
app.state::<PtyState>().close_window(label);
app.state::<WorkspaceState>().close_window(label);
}
if matches!(event, tauri::RunEvent::Exit) {
app.state::<PtyState>().close_all();
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
runestone_lib::run()
}
+503
View File
@@ -0,0 +1,503 @@
use std::collections::HashMap;
use std::io::{Read, Write};
use std::sync::Mutex;
use std::thread;
use std::path::{Path, PathBuf};
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};
use crate::workspace::{current_root_path, WorkspaceError, WorkspaceState};
type PtyResult<T> = Result<T, WorkspaceError>;
fn err(msg: impl Into<String>) -> WorkspaceError {
WorkspaceError::from_message(msg)
}
pub struct PtyState {
inner: Mutex<HashMap<String, OpenPty>>,
}
struct OpenPty {
owner: String,
integration_file: Option<PathBuf>,
master: Box<dyn MasterPty + Send>,
writer: Mutex<Box<dyn Write + Send>>,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
}
impl Drop for OpenPty {
fn drop(&mut self) {
let _ = self.killer.kill();
if let Some(path) = &self.integration_file { let _ = std::fs::remove_file(path); }
}
}
impl PtyState {
pub fn close_window(&self, label: &str) {
if let Ok(mut sessions) = self.inner.lock() {
sessions.retain(|_, session| session.owner != label);
}
}
pub fn close_all(&self) {
let sessions = self
.inner
.lock()
.ok()
.map(|mut sessions| std::mem::take(&mut *sessions));
drop(sessions);
}
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
}
}
}
#[derive(Clone, Serialize)]
pub struct PtyData {
pub id: String,
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
pub data: Vec<u8>,
}
#[derive(Clone, Serialize)]
pub struct PtyExit {
pub id: String,
pub code: Option<u32>,
}
type ShellProcess = (
OpenPty,
Box<dyn Read + Send>,
Box<dyn portable_pty::Child + Send + Sync>,
);
#[derive(Clone, Serialize)]
pub struct ShellProfile {
id: String,
title: String,
kind: String,
#[serde(skip)]
executable: PathBuf,
}
fn find_executable(name: &str) -> Option<PathBuf> {
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
.map(|dir| dir.join(name)).find(|path| path.is_file())
}
#[tauri::command]
pub fn pty_profiles() -> Vec<ShellProfile> {
let candidates = if cfg!(windows) {
vec![("powershell", "PowerShell", "powershell", "powershell.exe"),
("pwsh", "PowerShell 7", "powershell", "pwsh.exe"),
("cmd", "Command Prompt", "cmd", "cmd.exe"),
("node", "JavaScript Debug Terminal", "node", "node.exe")]
} else {
vec![("bash", "Bash", "bash", "bash"), ("pwsh", "PowerShell", "powershell", "pwsh"),
("node", "JavaScript Debug Terminal", "node", "node")]
};
let mut profiles: Vec<_> = candidates.into_iter().filter_map(|(id, title, kind, exe)| {
find_executable(exe).map(|executable| ShellProfile { id: id.into(), title: title.into(), kind: kind.into(), executable })
}).collect();
if cfg!(windows) {
let mut paths = Vec::new();
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
if let Some(base) = std::env::var_os(variable) {
paths.push(PathBuf::from(&base).join("Git/bin/bash.exe"));
paths.push(PathBuf::from(base).join("Programs/Git/bin/bash.exe"));
}
}
if let Some(git) = find_executable("git.exe") {
if let Some(base) = git.parent().and_then(Path::parent) { paths.push(base.join("bin/bash.exe")); }
}
if let Some(executable) = paths.into_iter().find(|path| path.is_file()) {
profiles.insert(1.min(profiles.len()), ShellProfile { id: "git-bash".into(), title: "Git Bash".into(), kind: "bash".into(), executable });
}
}
profiles
}
// Prompt hooks report executed commands and directories rather than recording keystrokes
// (which could include passwords entered into a child application).
const POWERSHELL_INTEGRATION: &str = r#"
$global:__rsHistory = -1
$global:__rsOriginalPrompt = $function:prompt
function global:prompt {
$esc = [char]27; $bel = [char]7
$h = Get-History -Count 1
if ($h -and $h.Id -ne $global:__rsHistory) {
$global:__rsHistory = $h.Id
$b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($h.CommandLine))
[Console]::Write("${esc}]633;RSCommand;${b}${bel}")
}
$b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($pwd.Path))
[Console]::Write("${esc}]633;RSCwd;${b}${bel}${esc}]133;A${bel}")
$p = if ($global:__rsOriginalPrompt) { & $global:__rsOriginalPrompt } else { "PS $pwd> " }
"${p}${esc}]133;B${bel}"
}
"#;
const BASH_INTEGRATION: &str = r#"__rs_prompt() {
local entry
entry="$(HISTTIMEFORMAT= builtin history 1)"
if [[ "$entry" != "$__rs_last_history" ]]; then
__rs_last_history="$entry"
entry="$(printf '%s' "$entry" | sed 's/^ *[0-9]* *//')"
[[ -n "$entry" ]] && printf '\033]633;RSCommand;%s\007' "$(printf '%s' "$entry" | base64 | tr -d '\r\n')"
fi
printf '\033]633;RSCwd;%s\007\033]133;A\007' "$(printf '%s' "$(pwd -W 2>/dev/null || printf '%s' "$PWD")" | base64 | tr -d '\r\n')"
}
__rs_last_history="$(HISTTIMEFORMAT= builtin history 1)"
PROMPT_COMMAND=("${PROMPT_COMMAND[@]}" __rs_prompt)
PS1="${PS1}"'\[\e]133;B\a\]'
"#;
fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: &str) -> PtyResult<ShellProcess> {
let system = native_pty_system();
let pair = system
.openpty(PtySize {
rows: rows.max(2),
cols: cols.max(2),
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| err(e.to_string()))?;
let profiles = pty_profiles();
let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id))
.ok_or_else(|| err("The selected shell is not installed. Select another terminal profile."))?;
let mut cmd = CommandBuilder::new(&selected.executable);
let mut integration_file = None;
match selected.kind.as_str() {
"powershell" => { cmd.args(["-NoLogo", "-NoExit", "-Command", POWERSHELL_INTEGRATION]); }
"bash" => {
// Use a private integration rc file; the user's bashrc still runs first.
let directory = std::env::temp_dir().join("runestone-shell");
std::fs::create_dir_all(&directory)?;
static NEXT_RC: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let sequence = NEXT_RC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let rc = directory.join(format!("bashrc-{}-{sequence}", std::process::id()));
std::fs::write(&rc, format!("[[ -f ~/.bashrc ]] && source ~/.bashrc\n{BASH_INTEGRATION}"))?;
cmd.args(["--init-file", &rc.to_string_lossy().replace('\\', "/"), "-i"]);
integration_file = Some(rc);
}
"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"]); }
_ => return Err(err("Unsupported shell profile")),
}
cmd.cwd(&root);
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
let reader = pair
.master
.try_clone_reader()
.map_err(|e| err(e.to_string()))?;
let writer = pair.master.take_writer().map_err(|e| err(e.to_string()))?;
let child = pair
.slave
.spawn_command(cmd)
.map_err(|e| err(e.to_string()))?;
drop(pair.slave);
let session = OpenPty {
owner: owner.into(),
integration_file,
master: pair.master,
writer: Mutex::new(writer),
killer: child.clone_killer(),
};
Ok((session, reader, child))
}
#[tauri::command]
pub fn pty_open(
app: AppHandle,
window: tauri::Window,
workspace: State<WorkspaceState>,
pty: State<PtyState>,
id: String,
cols: u16,
rows: u16,
cwd: String,
profile: Option<String>,
directory: Option<String>,
) -> PtyResult<()> {
let root = current_root_path(&workspace, window.label())?;
if root.to_string_lossy() != cwd {
return Err(err("workspace changed before the terminal started"));
}
let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
if guard.contains_key(&id) {
return Err(err("terminal already exists"));
}
let directory = directory.map(PathBuf::from).unwrap_or(root);
if !directory.is_dir() { return Err(err("Terminal working directory does not exist")); }
let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), window.label())?;
guard.insert(id.clone(), session);
drop(guard);
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let wait_app = app.clone();
let wait_id = id.clone();
thread::spawn(move || {
let code = child.wait().ok().map(|status| status.exit_code());
// Close ConPTY after the shell exits so the output reader reaches EOF.
let session = wait_app
.state::<PtyState>()
.inner
.lock()
.ok()
.and_then(|mut sessions| sessions.remove(&wait_id));
drop(session);
let _ = exit_tx.send(code);
});
let app_reader = app.clone();
let reader_id = id.clone();
thread::spawn(move || {
let mut buf = [0u8; 4096];
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let data = buf[..n].to_vec();
let _ = app_reader.emit(
"pty-data",
PtyData {
id: reader_id.clone(),
data,
},
);
}
Err(_) => break,
}
}
let code = exit_rx.recv().ok().flatten();
let _ = app_reader.emit(
"pty-exit",
PtyExit {
id: reader_id,
code,
},
);
});
Ok(())
}
#[tauri::command]
pub fn pty_write(pty: State<PtyState>, id: String, data: String) -> PtyResult<()> {
let guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?;
let mut writer = session.writer.lock().map_err(|_| err("pty writer lock"))?;
writer
.write_all(data.as_bytes())
.map_err(|e| err(e.to_string()))?;
writer.flush().ok();
Ok(())
}
#[tauri::command]
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> PtyResult<()> {
let guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?;
session
.master
.resize(PtySize {
rows: rows.max(2),
cols: cols.max(2),
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| err(e.to_string()))?;
Ok(())
}
#[tauri::command]
pub fn pty_close(pty: State<PtyState>, id: String) -> PtyResult<()> {
let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let session = guard.remove(&id);
drop(guard);
drop(session);
Ok(())
}
#[tauri::command]
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> PtyResult<()> {
let root = current_root_path(&workspace, window.label())?;
if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(err("Invalid window ID")); }
let mut url = tauri::Url::parse("http://localhost/").map_err(|e| err(e.to_string()))?;
url.query_pairs_mut().append_pair("terminalWindow", &root.to_string_lossy());
let label = format!("terminal-{id}");
if app.get_webview_window(&label).is_some() { return Err(err("Terminal window already exists")); }
workspace.bind_terminal(&label, root)?;
let result = tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into()))
.title("RuneStone — Terminal").inner_size(1000.0, 650.0).min_inner_size(500.0, 300.0).build()
.map_err(|e| err(e.to_string()));
if result.is_err() { workspace.close_window(&label); }
result?;
Ok(())
}
#[tauri::command]
pub fn pty_dictation() -> PtyResult<()> {
#[cfg(windows)]
{
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN};
// The frontend focuses xterm before invoking Windows voice typing.
unsafe {
keybd_event(VK_LWIN as u8, 0, 0, 0);
keybd_event(b'H', 0, 0, 0);
keybd_event(b'H', 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_LWIN as u8, 0, KEYEVENTF_KEYUP, 0);
}
Ok(())
}
#[cfg(not(windows))]
{ Err(err("Use your operating system's dictation shortcut with the terminal focused.")) }
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
#[test]
fn installed_profiles_start_and_report_shell_prompts() {
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
for profile in pty_profiles() {
eprintln!("Checking {}", profile.title);
let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, Some(&profile.id), "profile-test").unwrap();
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let mut buffer = [0u8; 4096];
while let Ok(n) = reader.read(&mut buffer) {
if n == 0 || tx.send(buffer[..n].to_vec()).is_err() { break; }
}
});
let deadline = Instant::now() + Duration::from_secs(15);
let mut bytes = Vec::new();
let mut sent = false;
loop {
if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) {
bytes.extend(chunk);
if bytes.windows(4).any(|w| w == b"\x1b[6n") {
session.writer.lock().unwrap().write_all(b"\x1b[1;1R").unwrap();
// Avoid answering this same query more than once.
for i in 0..bytes.len().saturating_sub(3) { if &bytes[i..i+4] == b"\x1b[6n" { bytes[i] = b' '; } }
}
}
let output = String::from_utf8_lossy(&bytes);
let ready = if profile.kind == "node" { output.contains("Debugger listening") && output.contains('>') } else { output.contains("\x1b]133;B") };
if ready && !sent {
let command = match profile.kind.as_str() {
"powershell" => "Write-Output ('RS_' + 'PROFILE_OK')\r",
"bash" => "printf 'RS_%s\\n' PROFILE_OK\r",
"cmd" => "echo RS_PROFILE_OK\r",
_ => "console.log('RS_' + 'PROFILE_OK')\r",
};
session.writer.lock().unwrap().write_all(command.as_bytes()).unwrap();
sent = true;
}
let history = profile.kind != "powershell" && profile.kind != "bash" || output.contains("\x1b]633;RSCommand;");
if sent && output.contains("RS_PROFILE_OK") && history { break; }
if Instant::now() > deadline {
let _ = child.kill();
panic!("{} failed integration: {output}", profile.title);
}
}
drop(session);
}
}
#[test]
fn real_shell_runs_in_project_and_drains_output_on_exit() {
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, None, "test").unwrap();
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let mut buf = [0u8; 4096];
while let Ok(n) = reader.read(&mut buf) {
if n == 0 {
break;
}
if tx.send(buf[..n].to_vec()).is_err() {
break;
}
}
});
session
.master
.resize(PtySize {
rows: 40,
cols: 100,
pixel_width: 0,
pixel_height: 0,
})
.unwrap();
let command = if cfg!(windows) {
"(Get-Location).Path; [Console]::WriteLine([char]0x03BB); exit 7\r\n"
} else {
"pwd; printf '\\316\\273\\n'; exit 7\n"
};
session
.writer
.lock()
.unwrap()
.write_all(command.as_bytes())
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let mut bytes = Vec::new();
let status = loop {
if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) {
// A real xterm answers cursor-position queries from PSReadLine.
if chunk.windows(4).any(|window| window == b"\x1b[6n") {
session
.writer
.lock()
.unwrap()
.write_all(b"\x1b[1;1R")
.unwrap();
}
bytes.extend(chunk);
}
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if Instant::now() >= deadline {
child.kill().unwrap();
panic!("shell failed to exit: {}", String::from_utf8_lossy(&bytes));
}
};
drop(session);
loop {
match rx.recv_timeout(Duration::from_secs(5)) {
Ok(chunk) => bytes.extend(chunk),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(_) => panic!("PTY reader did not reach EOF after shell exit"),
}
}
let output = String::from_utf8(bytes).expect("terminal output must be UTF-8");
assert_eq!(status.exit_code(), 7);
assert!(
output.contains(root.to_string_lossy().as_ref()),
"wrong working directory: {output}"
);
assert!(output.contains('λ'), "Unicode output missing: {output}");
}
#[test]
fn dropping_a_session_terminates_its_shell() {
let root = std::env::current_dir().unwrap();
let (session, mut reader, mut child) = spawn_shell(&root, 80, 24, None, "test").unwrap();
thread::spawn(move || {
let _ = std::io::copy(&mut reader, &mut std::io::sink());
});
drop(session);
let deadline = Instant::now() + Duration::from_secs(5);
while child.try_wait().unwrap().is_none() {
assert!(Instant::now() < deadline, "shell survived session disposal");
thread::sleep(Duration::from_millis(30));
}
}
}

Some files were not shown because too many files have changed in this diff Show More