Compare commits

...
Author SHA1 Message Date
aiongg 44e40fd606 Merge pull request #5013 from davidmann4/feat/agents-open-window
feat(automation): agents, control channel and confinement the same as in every Craft app (MCP batch)
2026-12-05 02:37:01 -05:00
David MannandClaude Opus 5.5 4baabc6dd3 fix(automation): queued agent input claims only a draft it opens or changes
While an agent's queued input is applied, a cell draft becomes the agent's
only when that input opened it or changed its text; a pointer move over
the person's open draft leaves it theirs (test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 17:18:16 +01:00
David MannandClaude Opus 5.5 c26b7a975c fix(automation): a refused agent request leaves the person's draft theirs
Draft ownership moves to the agent only when its request opens the draft
or changes its text; a refused or read-only request leaves the person's
draft unrestricted (test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 17:05:13 +01:00
David MannandClaude Opus 5.5 abe329dabf fix(automation): a draft an agent opens directly is its edit too
`ui.edit.begin` / `ui.edit.text` from an agent open or change a cell draft
without queued input; that draft now keeps the agent's folders as well, so
AutoSave keeps the change inside them whoever commits it. The person's own
drafts are autosaved as before (test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:50:44 +01:00
David MannandClaude Opus 5.5 acae69ffa9 fix(automation): name the agent snapshot types (clippy type_complexity)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:15:13 +01:00
David MannandClaude Opus 5.5 d9bd8a8334 fix(automation): an agent's open draft stays its edit; root options need a folder
- A cell draft an agent's input opened or typed into keeps that agent's
  folders: when anyone commits it later, AutoSave keeps the change inside
  them.
- `gridcraft --automation-read-root` / `--automation-write-root` without a
  folder (last, or followed by another option) refuses the launch instead
  of falling back to the agent folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:08:41 +01:00
David MannandClaude Opus 5.5 d4534b7ce4 test(automation): AutoSave after an agent's typed input, through real UI passes
The desktop app's frame confinement moves into SheetApp::with_agent_input,
so the test runs the same code: an agent types into the grid, the text is
applied by later raw-input and UI passes, and AutoSave writes nothing
outside the agent folders while the input is applied and after the queue
has emptied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 15:53:46 +01:00
Dylan M. Taylor fe6195d207 Merge pull request #5081 from storytold/docs/freebsd-15-1-requirement
docs: document FreeBSD 15.1 minimum for prebuilt packages
2026-12-04 09:48:56 -05:00
David MannandClaude Opus 5.5 3e080a17fd feat(automation): one control server and one confinement rule, as in every Craft app
- `--control` runs the framework's control server for the whole run
  (AgentLink::from_launch), confined to the agent folders or to the
  desktop app's --automation-read-root / --automation-write-root.
  GridCraft's own server, its first-line token and per-port token files
  are gone; the token is agent-control.token (or GRIDCRAFT_CONTROL_TOKEN).
- `send`, `mcp` and `mcp --connect` authenticate the window with the
  challenge handshake and never replay a request (#4573, #5000).
- A session without a window grants each folder's direction only: with
  no folder it opens and saves nothing (the --in file is opened first).
- macOS: gridcraft-cli ships inside GridCraft.app (folded in from #5015).
- #2739 review findings: the FIFO test moves into mod tests and requires
  its fixture, the new-save mode test meets the same umask as the save,
  a destination another save published meanwhile counts as existing, and
  the permission rows say what the code does.

Closes #445, closes #2172, closes #2174, closes #4573, closes #5000,
closes #5016

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:37:42 +01:00
David MannandClaude Opus 5.5 9e9e52b0e0 packaging(macos): the bundle comment claims only what the CLI does today
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:13:02 +01:00
David MannandClaude Opus 5.5 8bb34047aa packaging(macos): ship gridcraft-cli inside GridCraft.app
The ArtCraft Launcher registers an app for agents only when its CLI sits
beside the app's executable, and the CLI starts the app through
LaunchServices from inside the bundle. Copy gridcraft-cli into
Contents/MacOS and sign it as nested code before the bundle is sealed.
The separate CLI zip stays.

Refs #5012, #221

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:13:02 +01:00
David MannandClaude Opus 5.5 e93be7cdbf fix(automation): agent screenshots are written through the write folder
An agent's screenshot path was checked when the request was admitted and
the PNG written later by name, so an entry replaced in between could
redirect it. The pending shot now keeps the agent's folders, and the PNG
goes through the engine's confined writer relative to the write folder
it opened. A test covers AutoSave after an agent's queued input, both
while it is pending and after the queue empties.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 13:33:14 +01:00
David MannandClaude Opus 5.5 d37c5a70ea fix(automation): let the workbook snapshots go once an agent's queued input is applied
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:09:35 +01:00
David MannandClaude Opus 5.5 0ab181731c fix(automation): AutoSave writes an agent's changes only inside its folders
A workbook an agent changed, through a request or through input it
queued, keeps that agent's folders until it is saved: AutoSave runs
inside them, so an agent's edit to a workbook the person opened elsewhere
waits for the person's own Save instead of being written by a later pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:51:19 +01:00
David MannandClaude Opus 5.5 f444f0c420 fix(automation): agent input, folder answers and the no-folder case stay confined
- Input an agent queues (ui.key, ui.click, ui.text) is applied in later
  frames; until it is gone those frames run with the agent folders, so an
  agent's Ctrl+S or an edit on the Agents page can't save outside or widen
  them.
- The window answers agent_folders from the roots it really opened (null
  for a folder it couldn't use) instead of the CLI reading the settings.
- Agents let in with no usable folder get roots that grant nothing, not an
  unconfined session.
- `--when-closed` without a settings folder is an error instead of a
  silent headless session.
- Docs: command-line roots apply to sessions without a window
  (`--headless` in the examples).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:35:48 +01:00
David MannandClaude Opus 5.5 848e8e49d4 feat(automation): agents in the open window through the ArtCraft Launcher's switch
While the launcher's AI agents switch names GridCraft (behind the suite's
AI-MCP flag), the open window serves agents with the shared link host
(craft_automation::agents::AgentLink): a loopback control server, the token
in the settings folder and agent-connection.json, started, moved and
stopped without a restart, a stale file removed at start. Plain
`gridcraft-cli mcp` finds the window on every tool call through the shared
craft_control::agents::Live and authenticates it with the challenge
handshake before anything derived from the token is sent; otherwise it
serves a session without a window, following the closed-app choice.

- Agent requests run GridCraft's own control methods, confined to the agent
  folders (Documents/ArtCraft/Agents/GridCraft for an empty setting) with
  the file_access roots from #2739; a screenshot outside the write folder is
  refused, and agents can't change the agent settings.
- File > Options shows the shared Agents page; `options.agents` reads and
  saves the settings (agents.json, read by the CLI).
- New `agent_folders` MCP tool; `--headless` and `--when-closed`;
  `--connect` keeps working one release with a deprecation line.
- `--control` keeps its own channel for the run (#5016 moves it later).

Closes #5012

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:12:30 +01:00
David MannandClaude Opus 5.5 3b8d41c27f WIP: agents in the open window through the ArtCraft Launcher's switch (#5012)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:08:38 +01:00
David Mann e4cdee3997 Merge branch 'pr-2739' into feat/agents-open-window 2026-12-02 22:08:10 +01:00
ro-legal-docx 391448abed MCP: confine file access to a user-selected folder
Rebased from ab58fe3973701421d51b964b4b9450e46f22c952.
2026-11-28 08:56:10 +02:00
44 changed files with 3427 additions and 1160 deletions
Generated
+196 -6
View File
@@ -155,6 +155,12 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "ambient-authority"
version = "0.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
[[package]]
name = "android-activity"
version = "0.6.1"
@@ -698,6 +704,36 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "cap-primitives"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
dependencies = [
"ambient-authority",
"fs-set-times",
"io-extras",
"io-lifetimes 3.0.1",
"ipnet",
"maybe-owned",
"rustix 1.1.6",
"rustix-linux-procfs",
"windows-sys 0.61.2",
"winx",
]
[[package]]
name = "cap-std"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
dependencies = [
"cap-primitives",
"io-extras",
"io-lifetimes 3.0.1",
"rustix 1.1.6",
]
[[package]]
name = "cc"
version = "1.6.0"
@@ -1031,6 +1067,16 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-ai-agents"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
dependencies = [
"dirs",
"serde",
"serde_json",
]
[[package]]
name = "craft-appkit"
version = "0.1.0"
@@ -1049,6 +1095,31 @@ dependencies = [
"rustix 1.1.6",
]
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"base64 0.23.1",
"craft-behavior",
"craft-control",
"craft-host",
"craft-keymap",
"craft-platform",
"craft-theme",
"craft-ui",
"egui",
"getrandom 0.3.4",
"hmac 0.12.1",
"log",
"png 0.17.16",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.21",
"web-time",
]
[[package]]
name = "craft-behavior"
version = "0.1.0"
@@ -1085,6 +1156,21 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-ai-agents",
"craft-atomic",
"craft-flags",
"dirs",
"getrandom 0.3.4",
"log",
"serde",
"serde_json",
]
[[package]]
name = "craft-csv"
version = "0.1.0"
@@ -1113,6 +1199,16 @@ dependencies = [
"serde",
]
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-atomic",
"dirs",
"toml_edit",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -1235,7 +1331,7 @@ dependencies = [
"craft-zip",
"flate2",
"getrandom 0.3.4",
"hmac",
"hmac 0.13.0",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
@@ -1263,7 +1359,7 @@ dependencies = [
"craft-cfb",
"craft-xml",
"getrandom 0.3.4",
"hmac",
"hmac 0.13.0",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
@@ -1872,6 +1968,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer 0.10.4",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
@@ -2539,6 +2636,17 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fs-set-times"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix 1.1.6",
"windows-sys 0.59.0",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -2853,13 +2961,15 @@ version = "0.20.0"
dependencies = [
"arboard",
"chrono",
"craft-automation",
"craft-control",
"craft-nightly",
"craft-print",
"craft-ui",
"craft-update",
"eframe",
"egui",
"fmv-macos-events",
"getrandom 0.4.3",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
@@ -2904,6 +3014,7 @@ dependencies = [
name = "gridcraft-cli"
version = "0.20.0"
dependencies = [
"craft-control",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
@@ -2939,8 +3050,10 @@ dependencies = [
name = "gridcraft-engine"
version = "0.20.0"
dependencies = [
"cap-std",
"craft-csv",
"craft-gridcraft-format",
"getrandom 0.4.3",
"gridcraft-calc",
"gridcraft-chart",
"gridcraft-core",
@@ -2955,6 +3068,7 @@ dependencies = [
"log",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.21",
"unicode-segmentation",
"web-time",
@@ -2992,7 +3106,11 @@ dependencies = [
name = "gridcraft-mcp"
version = "0.20.0"
dependencies = [
"craft-automation",
"craft-control",
"craft-mcp-server",
"craft-ui",
"egui",
"gridcraft-engine",
"log",
"serde_json",
@@ -3046,7 +3164,9 @@ dependencies = [
name = "gridcraft-ui-egui"
version = "0.20.0"
dependencies = [
"craft-automation",
"craft-behavior",
"craft-control",
"craft-host",
"craft-keymap",
"craft-print",
@@ -3244,6 +3364,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "hmac"
version = "0.13.0"
@@ -3671,7 +3800,7 @@ dependencies = [
"byteorder-lite",
"moxcms",
"num-traits",
"png",
"png 0.18.1",
"tiff",
"zune-core",
"zune-jpeg",
@@ -3711,6 +3840,28 @@ dependencies = [
"rustversion",
]
[[package]]
name = "io-extras"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.59.0",
]
[[package]]
name = "io-lifetimes"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
[[package]]
name = "io-lifetimes"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -4061,6 +4212,12 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "maybe-owned"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "md-5"
version = "0.10.6"
@@ -4161,7 +4318,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"png",
"png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
@@ -5114,6 +5271,19 @@ dependencies = [
"time",
]
[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "png"
version = "0.18.1"
@@ -5788,6 +5958,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustix-linux-procfs"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
dependencies = [
"once_cell",
"rustix 1.1.6",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -6785,7 +6965,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
"png",
"png 0.18.1",
"tiny-skia-path 0.12.0",
]
@@ -8082,6 +8262,16 @@ version = "0.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
[[package]]
name = "winx"
version = "0.36.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.59.0",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
+5
View File
@@ -54,6 +54,11 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
# Agents in the open window: the ArtCraft Launcher's switch, the connection file and the CLI's live
# client (`craft-control`, feature `agents`), and the app's link host, control server and Agents page
# (`craft-automation`, features `agents` and `ui`).
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
# foundation
+2 -2
View File
@@ -172,8 +172,8 @@ so a Nightly run never touches the stable app's settings, prefs or logs.
## For agents: MCP, CLI and the control channel
```sh
claude mcp add gridcraft -- gridcraft-cli mcp # headless MCP server
gridcraft-cli mcp --connect 7979 # MCP bridged to a running window
gridcraft-cli mcp # MCP server: the open window while AI agents are on
gridcraft-cli mcp --headless # MCP server without a window
gridcraft-cli eval '=XLOOKUP("b",{"a","b"},{1,2})' # → 2
gridcraft-cli run --sample budget --cmd 'home.bold={"range":"B4:F4"}' --out budget.xlsx
gridcraft-cli cat budget.xlsx --range B4:F15 # aligned text table
+21
View File
@@ -136,6 +136,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | What landed |
|---|---|
| 2026-12-02 | Agents in the open window: while the ArtCraft Launcher's AI agents switch names GridCraft, plain `gridcraft-cli mcp` reaches the open window by itself (no port or token in the client's configuration; the window proves it holds the token first), confined to the agent folders; File › Options › Agents shows the link and the folders, the `agent_folders` tool names them, and `--headless` / `--when-closed` choose a session without a window; `--connect` is deprecated (#5012) |
| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) |
| 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) |
| 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `<controls>` and VML), alongside the form controls GridCraft keeps unchanged |
@@ -392,3 +393,23 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-10 | minor | Checked against the alpha gate (six core workflows pass): stays alpha |
| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; progress docs restructured; detail moved to `docs/` |
| 2026-10-07 | major | First estimates: catalog 89%, functions ~93%, depth ~65%, ~35 h to alpha, ~215 h to full parity |
## Contribution #2739 — scoped notes
> **Last updated:** 2026-11-15 · These notes describe this contribution. The mainline assessment and progress tables above are retained verbatim from `1d0b311b4a94`. The contribution does not revise the mainline readiness estimates.
The behavior described in these scoped notes applies to this branch and supersedes corresponding older baseline statements above. Dated rows below record the contribution history, rather than adding a new claim of general parity.
### Contribution progress
| Date | What changed |
|---|---|
| 2026-11-05 | Native file-I/O confinement: a new save requests mode 0644 and the process umask applies, rather than forcing owner-only access; over an existing file whose group can't be kept, the replacement keeps its owner-only temporary mode; the directory-handle confinement policy is unchanged. |
| 2026-10-27 | MCP can confine file I/O to operator-selected read/write folders; initial `--in`, generic commands and atomic-save paths are covered (#445, #2172) |
### Contribution revision history
| Date | Change | Summary |
|---|---|---|
| 2026-11-05 | trivial | new native saves request mode 0644 before the umask; when an existing file's group can't be kept, the replacement keeps its owner-only temporary mode instead of restoring the old owner and other bits; synthetic regression, no readiness change |
+2
View File
@@ -17,6 +17,8 @@ path = "src/main.rs"
gridcraft-sandbox = { workspace = true }
gridcraft-engine = { workspace = true }
gridcraft-mcp = { workspace = true }
# `mcp`: the closed-app choice and starting the desktop app beside the CLI.
craft-control = { workspace = true, features = ["agents"] }
serde_json = { workspace = true }
log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
+145 -30
View File
@@ -9,7 +9,8 @@
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--in FILE | --sample NAME]
//! [--automation-read-root DIR] [--automation-write-root DIR]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
//! gridcraft-cli version | --version
@@ -49,7 +50,11 @@ const USAGE: &str = "usage:
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--in FILE | --sample NAME]
[--automation-read-root DIR] [--automation-write-root DIR]
the open GridCraft window while AI agents may use it (ArtCraft Launcher ›
Settings › AI agents), otherwise a session without a window; --headless,
--in and --sample always use one
gridcraft-cli send <port> <method> [json]
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
whether this system confines programs (no program: a confined self-test)
@@ -558,31 +563,100 @@ fn functions(args: &[String]) -> Result<(), String> {
Ok(())
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
/// The stderr line `mcp --connect` prints: the flag works for one more release.
const CONNECT_DEPRECATED: &str = "gridcraft-cli: --connect is deprecated and will be removed in a later release; plain `gridcraft-cli mcp` finds the open GridCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
/// Validate MCP arguments without opening files, connecting or starting a server.
fn mcp_args(args: &[String]) -> Result<Args, String> {
let a = Args::parse(args, &["connect", "in", "sample", "automation-read-root", "automation-write-root", "when-closed"], &["headless"])?;
a.no_extra(0)?;
let backend: Box<dyn Backend> = match a.opt("connect") {
Some(c) => {
let addr = control_addr(c);
Box::new(
Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
)
for option in ["automation-read-root", "automation-write-root"] {
if a.opts.iter().filter(|(name, _)| name == option).count() > 1 {
return Err(format!("--{option} may be given only once"));
}
None => {
let session = match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
if a.opt(option) == Some("") {
return Err(format!("--{option} must name an existing directory"));
}
}
if a.opt("connect").is_some() && (a.opt("automation-read-root").is_some() || a.opt("automation-write-root").is_some()) {
return Err("automation roots require headless MCP; --connect cannot enforce them in the desktop app".into());
}
if a.opt("connect").is_some() && (a.has("headless") || a.opt("when-closed").is_some()) {
return Err("--connect names a `gridcraft --control` app itself; --headless and --when-closed are for plain `mcp`".into());
}
if let Some(choice) = a.opt("when-closed") {
if craft_control::agents::WhenAppClosed::parse(choice).is_none() {
return Err(format!("--when-closed must be launch, headless or error, not `{choice}`"));
}
if a.has("headless") || a.opt("in").is_some() || a.opt("sample").is_some() {
return Err("--when-closed is for the open window; --headless, --in and --sample never reach it".into());
}
}
Ok(a)
}
/// `mcp`: the open GridCraft window while the person lets agents use it, found through its
/// connection file on every tool call, otherwise a headless session (`gridcraft_mcp::agents`).
/// `--headless` (or `--in`/`--sample`, which name a headless workbook) always runs headless.
/// `--connect PORT|HOST:PORT` drives an app started with `gridcraft --control PORT` (deprecated).
/// JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::agents::{LiveBackend, LiveConfig};
use gridcraft_mcp::{Backend, Headless, Server};
let a = mcp_args(args)?;
let read_root = a.opt("automation-read-root");
let write_root = a.opt("automation-write-root");
let roots = gridcraft_engine::file_access::AutomationRoots::new(read_root.map(std::path::Path::new), write_root.map(std::path::Path::new))?;
let headless_only = a.has("headless") || a.opt("in").is_some() || a.opt("sample").is_some();
let settings_dir = gridcraft_mcp::agents::settings_dir();
let backend: Box<dyn Backend> = match (a.opt("connect"), settings_dir) {
(Some(c), _) => {
eprintln!("{CONNECT_DEPRECATED}");
Box::new(gridcraft_mcp::agents::control_window(c)?)
}
(None, Some(dir)) if !headless_only => {
let mut cfg = LiveConfig::new(dir);
cfg.when_closed = a.opt("when-closed").and_then(craft_control::agents::WhenAppClosed::parse);
cfg.read_root = read_root.map(std::path::PathBuf::from);
cfg.write_root = write_root.map(std::path::PathBuf::from);
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft_control::agents::launcher(&cli, gridcraft_mcp::agents::APP_EXE));
Box::new(LiveBackend::new(cfg))
}
(None, None) if !headless_only && a.opt("when-closed").is_some() => {
return Err("no settings folder (APPDATA or HOME is not set), so the open GridCraft window can't be found; use --headless for a session without a window"
.into());
}
(None, _) => {
// As in every Craft app: each automation root grants that direction of file access and
// an omitted one denies it, so with neither the session opens and saves nothing. With
// roots, they apply before --in, and to worker threads as well as calls arriving over
// MCP; without them, the --in file the command names is opened before that.
let open_session = || -> Result<Session, String> {
Ok(match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
})
};
Box::new(Headless::with_session(session))
let (session, roots) = match roots {
Some(roots) => {
if !gridcraft_engine::file_access::confine_process(roots.clone()) {
return Err("automation roots were already configured for this process".into());
}
(open_session()?, roots)
}
None => {
let session = open_session()?;
let none = gridcraft_engine::file_access::AutomationRoots::none();
gridcraft_engine::file_access::confine_process(none.clone());
(session, none)
}
};
Box::new(Headless::with_session(session).with_automation_roots(Some(roots)))
}
};
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
@@ -591,9 +665,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
/// `send PORT METHOD [JSON]`: one control-channel request to a running `gridcraft --control` app.
fn send(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Remote, control_addr};
use gridcraft_mcp::Backend;
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
let params: Value = match args.get(2) {
@@ -603,10 +677,7 @@ fn send(args: &[String]) -> Result<(), String> {
if let Some(x) = args.get(3) {
return Err(format!("unexpected argument `{x}`"));
}
let addr = control_addr(port);
let mut r = Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
let v = r.call(method, params)?;
let v = gridcraft_mcp::agents::control_window(port)?.call(method, params)?;
outln!("{}", pretty(&v));
Ok(())
}
@@ -665,6 +736,50 @@ mod tests {
);
}
/// Root parsing is independent of the filesystem and never starts a server.
#[test]
fn mcp_root_arguments_are_independent() {
for (flags, read, write) in [
(vec![], None, None),
(vec!["--automation-read-root", "/selected"], Some("/selected"), None),
(vec!["--automation-write-root=/selected/out"], None, Some("/selected/out")),
(vec!["--automation-read-root=/selected", "--automation-write-root", "/selected/out"], Some("/selected"), Some("/selected/out")),
(vec!["--automation-read-root", "/selected", "--automation-write-root", "/selected"], Some("/selected"), Some("/selected")),
] {
let args: Vec<String> = flags.iter().map(|s| s.to_string()).collect();
let parsed = mcp_args(&args).unwrap();
assert_eq!(parsed.opt("automation-read-root"), read);
assert_eq!(parsed.opt("automation-write-root"), write);
}
}
/// Invalid policy options fail before a backend or process policy is installed.
#[test]
fn mcp_root_arguments_reject_alias_and_invalid_combinations() {
for flags in [
vec!["--root", "/selected"],
vec!["--root=/selected"],
vec!["--automation-read-root", "/selected", "--automation-read-root", "/other"],
vec!["--automation-write-root=/selected/out", "--automation-write-root=/other"],
vec!["--automation-read-root", ""],
vec!["--automation-write-root="],
vec!["--automation-read-root"],
vec!["--automation-write-root"],
vec!["--connect", "7979", "--automation-read-root", "/selected"],
vec!["--connect", "7979", "--automation-write-root", "/selected/out"],
// The closed-app choice names one of three, and only plain `mcp` reaches a window.
vec!["--when-closed", "later"],
vec!["--when-closed", "launch", "--headless"],
vec!["--when-closed", "headless", "--in", "book.xlsx"],
vec!["--connect", "7979", "--headless"],
vec!["--connect", "7979", "--when-closed", "error"],
vec!["--headless=yes"],
] {
let args: Vec<String> = flags.iter().map(|s| s.to_string()).collect();
assert!(mcp_args(&args).is_err(), "{flags:?}");
}
}
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
+13 -1
View File
@@ -129,7 +129,19 @@ fn commands_and_functions() {
#[test]
fn mcp_over_stdio() {
let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
// The suite's AI-MCP flag off (an empty flags file): plain `mcp` lets no agent into a window
// and serves a session without one, whatever this machine's launcher allows.
let flags = tmpdir("mcp-flags").join("flags.toml");
std::fs::write(&flags, "").unwrap();
let mut child = bin()
.arg("mcp")
.env("CRAFT_FLAGS_FILE", &flags)
.env_remove("CRAFT_FLAGS")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
{
let stdin = child.stdin.as_mut().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
@@ -0,0 +1,51 @@
//! Real CLI startup checks; all synthetic fixtures are retained.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::PathBuf;
use std::process::{Command, Stdio};
fn base(label: &str) -> PathBuf {
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let p = std::env::temp_dir().join(format!("gridcraft-cli-confinement-{label}-{}-{stamp}", std::process::id()));
std::fs::create_dir_all(p.join("allowed")).unwrap();
std::fs::create_dir_all(p.join("outside")).unwrap();
std::fs::write(p.join("allowed/in.csv"), "inside,7\n").unwrap();
std::fs::write(p.join("outside/in.csv"), "outside,91\n").unwrap();
p
}
fn run(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).stdin(Stdio::null()).output().unwrap()
}
#[test]
fn folder_confinement_cli_checks_initial_in_before_reading() {
let p = base("startup");
let root = p.join("allowed");
let outside = p.join("outside/in.csv");
let inside = root.join("in.csv");
let denied = run(&["mcp", "--automation-read-root", root.to_str().unwrap(), "--in", outside.to_str().unwrap()]);
assert!(!denied.status.success());
assert!(String::from_utf8_lossy(&denied.stderr).contains("outside the read root"));
let allowed = run(&["mcp", "--automation-read-root", root.to_str().unwrap(), "--in", inside.to_str().unwrap()]);
assert!(allowed.status.success(), "{}", String::from_utf8_lossy(&allowed.stderr));
let inline = format!("--automation-read-root={}", root.display());
assert!(run(&["mcp", &inline, "--in", inside.to_str().unwrap()]).status.success());
}
#[test]
fn folder_confinement_cli_rejects_ambiguous_or_unenforceable_configuration() {
let p = base("options");
let root = p.join("allowed");
let r = root.to_str().unwrap();
for args in [
vec!["mcp", "--automation-read-root", r, "--automation-read-root", r],
vec!["mcp", "--automation-write-root", r, "--automation-write-root", r],
vec!["mcp", "--connect", "7979", "--automation-read-root", r],
vec!["mcp", "--automation-read-root", ""],
vec!["mcp", "--automation-read-root"],
vec!["mcp", "--automation-read-root", "--sample", "sales"],
] {
let o = run(&args);
assert!(!o.status.success(), "{args:?}");
}
assert!(!run(&["mcp", "--automation-read-root", p.join("missing").to_str().unwrap()]).status.success());
assert!(!run(&["mcp", "--automation-read-root", root.join("in.csv").to_str().unwrap()]).status.success());
}
+1
View File
@@ -1,4 +1,5 @@
//! The crate's integration tests, one module per file, built as one test binary.
mod cli;
mod folder_confinement;
mod sandbox;
mod text_to_columns_quotes;
+5 -2
View File
@@ -39,8 +39,11 @@ craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
gridcraft-mcp = { workspace = true }
# The control channel's token (OS random numbers); already in the tree.
getrandom = "0.4"
# Agents in the open window: the ArtCraft Launcher's switch and the stale connection file.
craft-control = { workspace = true, features = ["agents"] }
# `--control`: the framework's control server and its token, the ones the agents link runs.
craft-automation = { workspace = true, features = ["agents", "ui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
+2 -9
View File
@@ -11,15 +11,8 @@ use std::ffi::OsString;
use std::path::PathBuf;
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
match platform {
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
_ => env("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft")),
}
// Shared with `gridcraft-cli mcp`, which finds the open window's agent connection there.
gridcraft_mcp::agents::settings_dir_for(platform, env)
}
/// The folder the settings and the log files live in.
-503
View File
@@ -1,503 +0,0 @@
//! Localhost JSON-lines control server. Each connection may send many requests; each line
//! `{"id":…, "method":…, "params":…}` gets one reply line `{"id":…, "ok":…, …}`.
//!
//! The first line of a connection must authenticate with the app's token (#777; see
//! `gridcraft_mcp::control_auth`). A connection that doesn't, or later sends a line that isn't
//! JSON, is answered once and closed.
//!
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
use gridcraft_mcp::control_auth;
use gridcraft_ui_egui::ControlRequest;
use serde_json::{Value as Json, json};
const MAX_LINE: usize = 64 * 1024 * 1024;
/// How long a new connection may take to send its token, in total.
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
/// How many connections may be waiting to authenticate at once. Anyone on the machine can
/// connect without the token, so past this a new connection is closed before anything is read:
/// each waiting one holds a thread and a socket.
const MAX_PENDING_AUTH: usize = 16;
/// How the server treats connections that haven't authenticated yet.
#[derive(Clone, Copy)]
struct AuthLimits {
timeout: Duration,
max_pending: usize,
}
const AUTH_LIMITS: AuthLimits = AuthLimits { timeout: AUTH_TIMEOUT, max_pending: MAX_PENDING_AUTH };
/// A connection that is still waiting to authenticate; dropping it frees its place.
struct Pending(Arc<AtomicUsize>);
impl Pending {
/// A place among the `max` waiting connections, or `None` when they are all taken.
fn claim(waiting: &Arc<AtomicUsize>, max: usize) -> Option<Pending> {
waiting.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok()?;
Some(Pending(Arc::clone(waiting)))
}
}
impl Drop for Pending {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
/// The secret of this run: the one the user chose (`--control-token`, `GRIDCRAFT_CONTROL_TOKEN`),
/// else 256 random bits from the operating system, written to a file only the user can read.
fn make_token(port: u16, chosen: Option<String>) -> std::io::Result<String> {
if let Some(t) = chosen.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) {
if t.len() < control_auth::MIN_TOKEN_LEN {
return Err(std::io::Error::other(format!("the control token must have at least {} characters", control_auth::MIN_TOKEN_LEN)));
}
eprintln!("gridcraft: control channel on 127.0.0.1:{port} requires the token you set (clients: GRIDCRAFT_CONTROL_TOKEN)");
return Ok(t);
}
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| std::io::Error::other(format!("no random numbers for the control token: {e}")))?;
let token = control_auth::hex(&bytes);
let path = control_auth::write_token_file(port, &token)?;
eprintln!("gridcraft: control channel on 127.0.0.1:{port}; its token is in {} (gridcraft-cli reads it)", path.display());
Ok(token)
}
pub fn start(port: u16, chosen_token: Option<String>, ctx: egui::Context) -> std::io::Result<Receiver<ControlRequest>> {
let listener = TcpListener::bind(("127.0.0.1", port))?;
let token: Arc<str> = make_token(port, chosen_token)?.into();
let rx = serve_listener(listener, token, ctx)?;
log::info!("control channel listening on 127.0.0.1:{port}");
Ok(rx)
}
/// Accept connections on `listener`; requests arrive on the returned receiver.
fn serve_listener(listener: TcpListener, token: Arc<str>, ctx: egui::Context) -> std::io::Result<Receiver<ControlRequest>> {
serve_listener_with(listener, token, ctx, AUTH_LIMITS)
}
fn serve_listener_with(listener: TcpListener, token: Arc<str>, ctx: egui::Context, limits: AuthLimits) -> std::io::Result<Receiver<ControlRequest>> {
let (tx, rx) = channel();
let waiting = Arc::new(AtomicUsize::new(0));
std::thread::Builder::new().name("control".into()).spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else {
// Out of sockets or handles: wait for some to free instead of spinning on the error.
std::thread::sleep(Duration::from_millis(50));
continue;
};
// Dropping the stream closes it before anything is read.
let Some(place) = Pending::claim(&waiting, limits.max_pending) else { continue };
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
let _ =
std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx, limits.timeout, Some(place)));
}
})?;
Ok(rx)
}
/// Read the connection's first line (at most [`control_auth::MAX_AUTH_LINE`] bytes, within
/// `timeout` in total) and check the token. `true` when the peer may go on.
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
fn authenticate(reader: &mut BufReader<TcpStream>, out: &mut TcpStream, token: &str, timeout: Duration) -> bool {
let deadline = Instant::now().checked_add(timeout).unwrap_or_else(Instant::now);
let mut first = Vec::new();
let read = read_auth_line(reader, &mut first, deadline);
let verdict = match (read, std::str::from_utf8(&first)) {
(Ok(()), Ok(line)) if line.ends_with('\n') => control_auth::check_first_line(line, token),
_ => Err(json!({"ok": false, "error": "authentication required"})),
};
let allowed = verdict.is_ok();
let reply = verdict.unwrap_or_else(|e| e);
let _ = writeln!(out, "{reply}");
let _ = reader.get_ref().set_read_timeout(None);
allowed
}
/// Read the first line, at most [`control_auth::MAX_AUTH_LINE`] bytes, by `deadline`.
///
/// The timeout goes on the handle the reader reads: on Windows a `try_clone` of the stream keeps
/// its own, so one set on the writing half never fired (a silent peer held its thread forever).
/// It is shortened before every read, so a peer sending one byte at a time can't stretch it.
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
fn read_auth_line(reader: &mut BufReader<TcpStream>, line: &mut Vec<u8>, deadline: Instant) -> std::io::Result<()> {
let max = control_auth::MAX_AUTH_LINE;
while line.len() < max && line.last() != Some(&b'\n') {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(std::io::ErrorKind::TimedOut.into());
}
reader.get_ref().set_read_timeout(Some(left))?;
let buf = reader.fill_buf()?;
if buf.is_empty() {
break;
}
let room = max.saturating_sub(line.len());
let take = buf.iter().take(room).position(|b| *b == b'\n').map_or(buf.len().min(room), |i| i + 1);
line.extend(buf.iter().take(take));
reader.consume(take);
}
Ok(())
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| e.to_string())?;
if n == 0 {
return Ok(false);
}
if buf.last() == Some(&b'\n') {
buf.pop();
return Ok(true);
}
if buf.len() > max {
return Err(format!("request too large (over {max} bytes); closing the connection"));
}
// Last line without a newline, then end of stream.
Ok(true)
}
/// One request line, parsed.
enum Line {
Request {
id: Json,
method: String,
params: Json,
},
Blank,
/// Not a request: reply with this error and close the connection.
Reject(String),
}
fn parse_line(bytes: &[u8]) -> Line {
let Ok(text) = std::str::from_utf8(bytes) else {
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
let text = text.trim();
if text.is_empty() {
return Line::Blank;
}
if is_http_request_line(text) {
return Line::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
}
let msg = match serde_json::from_str::<Json>(text) {
Ok(v) => v,
Err(e) => return Line::Reject(format!("invalid JSON ({e}); expected one JSON request object per line; closing the connection")),
};
let Some(obj) = msg.as_object() else {
return Line::Reject("not a control request (expected a JSON object); closing the connection".into());
};
let Some(method) = obj.get("method").and_then(Json::as_str) else {
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
};
Line::Request {
id: obj.get("id").cloned().unwrap_or(Json::Null),
method: method.to_string(),
params: obj.get("params").cloned().unwrap_or(json!({})),
}
}
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
fn is_http_request_line(text: &str) -> bool {
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context, auth_timeout: Duration, place: Option<Pending>) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let mut reader = BufReader::new(read);
let allowed = authenticate(&mut reader, &mut out, token, auth_timeout);
// Authenticated or refused, the connection no longer counts as waiting.
drop(place);
if !allowed {
return;
}
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => break,
// The peer is gone before sending a line: nobody to tell.
Err(_) if buf.is_empty() => break,
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Request { id, method, params } => {
let (req, rx) = ControlRequest::new(method, params);
let state = std::sync::Arc::clone(&req.state);
if tx.send(req).is_err() {
break;
}
// Wake the UI thread: egui only runs frames when something happens.
ctx.request_repaint();
let mut reply = rx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| {
// Give up on the request as well as on its reply. While it is still
// queued this keeps it from running late -- the client was told it had
// failed, and an agent that retried after the error ran it twice (#1914);
// if the app had already started it, its outcome is unknown instead.
if ControlRequest::abandon(&state) {
json!({"ok": false, "error": "timed out waiting for the UI (is the window minimised?)"})
} else {
json!({"ok": false, "error": "timed out waiting for the UI, which had already started the request, so it may still finish; its outcome is unknown"})
}
});
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
}
if writeln!(out, "{reply}").is_err() {
break;
}
continue;
}
},
};
// The connection closes either way; a peer that can't read the reason loses nothing.
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject}));
break;
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
/// Authenticate a new connection, send `input`, and read reply lines (after the
/// authentication reply) until the server closes it.
fn exchange(addr: std::net::SocketAddr, input: &[u8]) -> Vec<Json> {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
c.write_all(input).unwrap();
// A read timeout ends the list too: the server kept the connection open.
let mut replies: Vec<Json> = BufReader::new(c).lines().map_while(Result::ok).map(|l| serde_json::from_str(&l).unwrap()).collect();
assert_eq!(replies.first().map(|r| r["ok"].clone()), Some(json!(true)), "{replies:?}");
replies.remove(0);
replies
}
fn serve_on_loopback() -> (std::net::SocketAddr, Receiver<ControlRequest>) {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
(addr, serve_listener(listener, TOKEN.into(), egui::Context::default()).unwrap())
}
/// A browser can POST to the port: its request line closes the connection before the JSON
/// line in its body is read, so nothing is dispatched.
#[test]
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
let (addr, rx) = serve_on_loopback();
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nContent-Type: text/plain\r\n\r\n\
{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"cell.set\",\"params\":{\"cell\":\"A1\",\"input\":\"x\"}}}\n";
let replies = exchange(addr, http);
assert_eq!(replies.len(), 1, "{replies:?}");
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
assert!(rx.try_recv().is_err(), "the body was dispatched");
}
#[test]
fn a_line_that_is_not_a_request_closes_the_connection() {
let (addr, rx) = serve_on_loopback();
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true}));
}
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
c.write_all(b"{\"id\":1,\"method\":\"a\"}\r\n\n{\"id\":2,\"method\":\"b\"}\n").unwrap();
let mut r = BufReader::new(c);
let mut auth_reply = String::new();
r.read_line(&mut auth_reply).unwrap();
for id in [1, 2] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Json>(&line).unwrap()["id"], id, "{line}");
}
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
let mut input = junk.to_vec();
input.extend_from_slice(b"{\"id\":2,\"method\":\"b\"}\n");
let replies = exchange(addr, &input);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
}
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
assert!(is_http_request_line("PRI * HTTP/2.0"));
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
}
#[test]
fn an_overlong_line_is_refused_without_reading_the_rest() {
let mut buf = Vec::new();
let long = [b'x'; 100];
let mut input: &[u8] = &long;
assert!(read_bounded_line(&mut input, &mut buf, 10).is_err());
assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread");
}
/// A server on a loopback port with a stand-in UI that echoes each method.
fn spawn() -> std::net::SocketAddr {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
}
});
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default(), AUTH_TIMEOUT, None));
}
});
addr
}
fn lines(addr: std::net::SocketAddr, send: &str) -> Vec<Json> {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(send.as_bytes()).unwrap();
// Replies up to the server closing the connection.
BufReader::new(c).lines().map_while(Result::ok).map(|l| serde_json::from_str(&l).unwrap()).collect()
}
#[test]
fn the_token_opens_the_connection() {
let addr = spawn();
let auth = control_auth::auth_line(1, TOKEN);
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{auth}\n{{\"id\":2,\"method\":\"ping\"}}\n").as_bytes()).unwrap();
let mut r = BufReader::new(c);
let mut line = String::new();
r.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Json>(&line).unwrap()["ok"], json!(true));
line.clear();
r.read_line(&mut line).unwrap();
let v: Json = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].clone(), v["result"].clone()), (json!(2), json!("ping")));
}
#[test]
fn anything_but_the_token_first_closes_the_connection() {
let addr = spawn();
let wrong = control_auth::auth_line(1, "ffffffffffffffffffffffffffffffff");
for first in [wrong.as_str(), "{\"id\":1,\"method\":\"app.save\",\"params\":{\"path\":\"/tmp/x\"}}", "POST / HTTP/1.1", ""] {
// The second request is never served: one refusal, then end of stream.
let got = lines(addr, &format!("{first}\n{{\"id\":2,\"method\":\"ping\"}}\n"));
assert_eq!(got.len(), 1, "{first}: {got:?}");
assert_eq!(got[0]["ok"], json!(false), "{first}");
}
}
#[test]
fn an_unparsable_line_after_auth_closes_the_connection() {
let addr = spawn();
let auth = control_auth::auth_line(1, TOKEN);
let got = lines(addr, &format!("{auth}\nnot json\n{{\"id\":3,\"method\":\"ping\"}}\n"));
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got[1]["ok"], json!(false));
}
/// Whether the server closed `c` (end of stream, or a refusal and then end of stream) within
/// `within`, and how long it took.
#[allow(clippy::disallowed_methods)] // a native-only test of the desktop app
fn closed_within(c: TcpStream, within: Duration) -> (bool, Duration) {
let start = Instant::now();
c.set_read_timeout(Some(within)).unwrap();
let mut r = BufReader::new(c);
let mut line = String::new();
loop {
line.clear();
match r.read_line(&mut line) {
Ok(0) => return (true, start.elapsed()),
Ok(_) => continue,
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => return (false, start.elapsed()),
Err(_) => return (true, start.elapsed()),
}
}
}
/// The token deadline is for the whole first line: neither a silent peer nor one sending a
/// byte at a time keeps the connection (and its thread) past it.
#[test]
fn a_silent_or_slow_peer_is_closed_at_the_auth_deadline() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let limits = AuthLimits { timeout: Duration::from_millis(300), max_pending: MAX_PENDING_AUTH };
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
let silent = TcpStream::connect(addr).unwrap();
let mut slow = TcpStream::connect(addr).unwrap();
let mut drip = slow.try_clone().unwrap();
std::thread::spawn(move || {
for b in control_auth::auth_line(1, TOKEN).bytes() {
if drip.write_all(&[b]).is_err() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
});
let (closed, took) = closed_within(silent, Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "silent peer kept for {took:?}");
let (closed, took) = closed_within(slow.try_clone().unwrap(), Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "byte-at-a-time peer kept for {took:?}");
let _ = slow.flush();
}
/// Peers without the token can't pile up threads: past the cap a new connection is closed at
/// once, and a waiting one that authenticates frees its place.
#[test]
fn connections_waiting_to_authenticate_are_capped() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let limits = AuthLimits { timeout: Duration::from_secs(20), max_pending: 2 };
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
let mut first = TcpStream::connect(addr).unwrap();
let _second = TcpStream::connect(addr).unwrap();
std::thread::sleep(Duration::from_millis(200));
let (closed, took) = closed_within(TcpStream::connect(addr).unwrap(), Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "a third waiting connection was kept");
first.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
first.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
let mut reply = String::new();
BufReader::new(first.try_clone().unwrap()).read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "{reply}");
std::thread::sleep(Duration::from_millis(200));
let mut next = TcpStream::connect(addr).unwrap();
next.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
next.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
let mut reply = String::new();
BufReader::new(next).read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "a freed place was not reused: {reply}");
}
#[test]
fn a_chosen_token_must_be_long_enough() {
assert!(make_token(1, Some("short".into())).is_err());
assert_eq!(make_token(1, Some(format!(" {TOKEN} "))).unwrap(), TOKEN);
}
}
+131 -19
View File
@@ -1,11 +1,15 @@
//! GridCraft desktop app.
//!
//! Usage: `gridcraft [--control <port> [--control-token <token>]] [--sample <name>] [files…]`
//! Usage: `gridcraft [--control <port> [--control-token <token>] [--automation-read-root <dir>]
//! [--automation-write-root <dir>]] [--sample <name>] [files…]`
//!
//! `--control <port>` (or `GRIDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control
//! server: `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
//! The first line of each connection must carry the token (`docs/control-protocol.md`).
//! See `gridcraft_ui_egui::control` and `docs/control-protocol.md` for the methods.
//! `--control <port>` (or `GRIDCRAFT_CONTROL_PORT`) serves the framework's loopback control server
//! for the whole run (`craft_automation::server`, the one agents reach through the ArtCraft
//! Launcher's switch): `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`,
//! after the challenge handshake with the token in `agent-control.token` in the settings folder
//! (or `--control-token` / `GRIDCRAFT_CONTROL_TOKEN`, 64 hex characters). Its file commands are
//! confined to the agent folders, or to the automation roots given. See `gridcraft_ui_egui::control`
//! and `docs/control-protocol.md` for the methods.
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -16,7 +20,6 @@ mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(any(target_os = "windows", target_os = "macos", test))]
mod graphics;
mod launch_profile;
@@ -64,9 +67,13 @@ impl eframe::App for App {
}
apple_events::poll(&self.apple_events, &mut self.app, ctx);
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
self.app.close_path(ctx);
// While input an agent sent is being applied, the passes run with the agent folders.
let windows = &mut self.windows;
self.app.with_agent_input(|app| {
app.logic(ctx);
windows.logic(app, ctx);
app.close_path(ctx);
});
}
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
@@ -81,7 +88,8 @@ impl eframe::App for App {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.windows.show(&mut self.app, ui);
let windows = &mut self.windows;
self.app.with_agent_input(|app| windows.show(app, ui));
}
fn on_exit(&mut self) {
print::finish_pending_jobs();
@@ -114,6 +122,60 @@ fn config_dir() -> Option<std::path::PathBuf> {
app_dirs::config_dir()
}
/// Agents in the open window (`gridcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
/// names GridCraft, the window serves agents on loopback and publishes the connection in its
/// settings folder, where `gridcraft-cli mcp` finds it. A connection file a crashed run left is
/// removed first. `settings` false (`GRIDCRAFT_NO_PREFS`) reads and saves no agent settings.
fn agents_for(ctx: &egui::Context, settings: bool) -> gridcraft_ui_egui::agents::Agents {
use gridcraft_mcp::agents::{LAUNCHER_APP_ID, read_settings, write_settings};
let dir = config_dir().filter(|_| settings);
if let Some(dir) = &dir {
craft_control::agents::remove_stale_connection(dir);
}
let switch = craft_control::agents::AgentSwitch::watch(LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let save_dir = dir.clone();
let save: gridcraft_ui_egui::agents::SaveFn = Box::new(move |s| match &save_dir {
Some(d) => write_settings(d, s).map_err(|e| format!("couldn't save the agent settings in {}: {e}", d.display())),
None => Err("this run keeps no settings (GRIDCRAFT_NO_PREFS)".into()),
});
let saved = dir.as_deref().map(read_settings).unwrap_or_default();
let version = format!("GridCraft {}", env!("GRIDCRAFT_BUILT_VERSION"));
gridcraft_ui_egui::agents::Agents::new(dir, version, switch, saved, save)
}
/// The `--control` server bound before the window opens.
struct LaunchControl {
listener: std::net::TcpListener,
token: String,
/// The roots the launch named, if any (otherwise the agent folders apply).
folders: Option<craft_control::agents::AgentFolders>,
}
/// Binds `127.0.0.1:port` for `--control` with its token: the one given (64 hex characters),
/// otherwise the one in `agent-control.token` in the settings folder (created when missing), which
/// `gridcraft-cli send` reads.
fn bind_control(port: u16, token: Option<&str>, args: &DesktopArgs) -> Result<LaunchControl, String> {
use craft_automation::security::server_token;
let token = match token.map(str::trim).filter(|t| !t.is_empty()) {
Some(t) => server_token(Some(t), None).map_err(|e| format!("the control token: {e}"))?,
None => {
let dir = config_dir().ok_or("no settings folder for the control token; set GRIDCRAFT_CONTROL_TOKEN (64 hex characters)")?;
server_token(None, Some(&dir.join(craft_control::agents::TOKEN_FILE))).map_err(|e| format!("the control token: {e}"))?
}
};
let folders = (args.read_root.is_some() || args.write_root.is_some()).then(|| {
let mut f = craft_control::agents::AgentFolders::default();
f.read = args.read_root.as_deref().map(std::path::PathBuf::from);
f.write = args.write_root.as_deref().map(std::path::PathBuf::from);
f
});
let listener = std::net::TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("couldn't listen on 127.0.0.1:{port}: {e}"))?;
Ok(LaunchControl { listener, token, folders })
}
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
/// them, and keep no log file.
fn prefs_enabled() -> bool {
@@ -354,6 +416,13 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
struct DesktopArgs {
control_port: Option<u16>,
control_token: Option<String>,
/// `--automation-read-root` / `--automation-write-root`: the folders `--control` requests may
/// use instead of the agent folders.
read_root: Option<String>,
write_root: Option<String>,
/// An option given without its value (`--automation-write-root` last, or followed by another
/// option): the launch is refused rather than run with other folders.
invalid: Option<String>,
sample: Option<String>,
files: Vec<String>,
}
@@ -375,6 +444,18 @@ fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Optio
i += 1;
parsed.control_token = args.get(i).cloned();
}
flag @ ("--automation-read-root" | "--automation-write-root") => {
i += 1;
match args.get(i).filter(|v| !v.is_empty() && !v.starts_with("--")) {
Some(dir) if flag == "--automation-read-root" => parsed.read_root = Some(dir.clone()),
Some(dir) => parsed.write_root = Some(dir.clone()),
None => {
parsed.invalid.get_or_insert_with(|| format!("{flag} needs a folder"));
// The option in the value position is read as an option again.
i -= 1;
}
}
}
"--sample" => {
i += 1;
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
@@ -391,7 +472,10 @@ fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Optio
/// document named `--control` is opened rather than read as a flag.
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
nightly
&& args[..options_end]
.iter()
.any(|a| matches!(a.as_str(), "--control" | "--control-token" | "--automation-read-root" | "--automation-write-root"))
}
fn main() -> eframe::Result<()> {
@@ -408,8 +492,10 @@ fn main() -> eframe::Result<()> {
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
// for a control server can never write the stable app's token file.
if let Some(root) = launch_profile::current().root() {
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
Ok(()) => {}
// The nightly channel has no control server; its profile's control folder must still be
// its own, as the profile's other folders are.
match profile_root::control_directory(root) {
Ok(_) => {}
Err(error) => {
report_launch_profile_error(&error);
std::process::exit(2);
@@ -463,7 +549,20 @@ fn main() -> eframe::Result<()> {
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
let parsed = desktop_args(&args, control_port, control_token);
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
let (control_port, control_token, sample, files) =
(parsed.control_port, parsed.control_token.clone(), parsed.sample.clone(), parsed.files.clone());
if let Some(problem) = &parsed.invalid {
eprintln!("gridcraft: {problem}");
std::process::exit(2);
}
// `--control`: bound now, so a taken port or a bad token fails before a window opens.
let control = match control_port.map(|port| bind_control(port, control_token.as_deref(), &parsed)).transpose() {
Ok(control) => std::cell::Cell::new(control),
Err(e) => {
eprintln!("gridcraft: --control: {e}");
std::process::exit(2);
}
};
// The log file lives in the settings folder, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
@@ -588,11 +687,13 @@ fn main() -> eframe::Result<()> {
};
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
if let Some(port) = control_port {
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
Ok(rx) => app.control_rx = Some(rx),
Err(e) => log::error!("control channel on port {port}: {e}"),
}
if let Some(control) = control.take() {
let host = craft_ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
let (requests, server) = craft_automation::server::serve(control.listener, control.token, host)?;
eprintln!("gridcraft: control server listening on {}", server.addr);
app.agents = Some(agents_for(&cc.egui_ctx, prefs_enabled()).launched_with_control(server, requests, control.folders));
} else if !nightly && prefs_enabled() && config_dir().is_some() {
app.agents = Some(agents_for(&cc.egui_ctx, true));
}
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
Ok(Box::new(App {
@@ -720,6 +821,17 @@ mod launch_separator_tests {
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
}
#[test]
fn an_automation_root_without_its_folder_is_refused() {
let args = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(desktop_args(&args(&["--control", "7979", "--automation-write-root"]), None, None).invalid.is_some());
let next_is_an_option = desktop_args(&args(&["--automation-read-root", "--control", "7979"]), None, None);
assert!(next_is_an_option.invalid.is_some());
assert_eq!(next_is_an_option.control_port, Some(7979), "the option in the value position still counts");
let read_only = desktop_args(&args(&["--control", "7979", "--automation-read-root", "in"]), None, None);
assert_eq!((read_only.read_root.as_deref(), read_only.write_root.as_deref(), read_only.invalid), (Some("in"), None, None));
}
#[test]
fn a_control_flag_before_the_separator_still_names_the_port() {
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
+7
View File
@@ -29,7 +29,14 @@ gridcraft-math = { workspace = true }
image = { workspace = true }
unicode-segmentation = "=1.13.3"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
cap-std = "4.0.3"
getrandom = "0.4"
[dev-dependencies]
gridcraft-xlsx = { workspace = true, features = ["test-support"] }
gridcraft-model = { workspace = true, features = ["test-support"] }
zip = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
tempfile = "3.27"
+678
View File
@@ -0,0 +1,678 @@
//! The folders automation may read and write (#445, #2172).
//!
//! Adapted from Isaac Levine's PR #480 (20bc9432a773689698190e0b32067a7863e0cf22).
//!
//! `gridcraft-cli mcp --headless --automation-read-root <dir> --automation-write-root <dir>`
//! confines the files an agent's commands reach (in the open window, the agent folders of its
//! Agents page apply instead). [`AutomationRoots`] holds the two folders. While they are in
//! force, every document open and save applies their read or write policy. The checks sit behind
//! [`crate::io::read_file`] and [`crate::io::write_file`], the
//! only functions the engine opens user-named files with (`file.open`, `file.saveAs`,
//! `file.export`, `file.exportPdf`, `insert.picture`, CSV and text import), so a new command that
//! reads or writes through them is confined without further work.
//!
//! - The path is made absolute against the working directory, as the file system reads it. Its
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
//! `/work`), using their canonical spellings rather than Unicode case folding.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
//! [`confine_process`] (`gridcraft-cli mcp`), except inside [`unconfined`] (what the person at the
//! keyboard does). Without roots nothing is checked.
//!
//! Native I/O resolves each checked path relative to an open root directory. Opens and atomic
//! saves use capability-relative operations, so replacing a checked component with an escaping
//! symlink cannot redirect them. This is a document-I/O policy, not a process sandbox.
use std::cell::RefCell;
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, OnceLock};
/// Read access or write access.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Access {
Read,
Write,
}
/// The folders automation may read and write; a root left out grants no access of its kind.
#[derive(Debug)]
pub struct AutomationRoots {
read: Option<Root>,
write: Option<Root>,
}
#[derive(Debug)]
struct Root {
/// The folder made absolute, links followed: what paths are compared with.
resolved: PathBuf,
/// The same without Windows' `\\?\` prefix, for people.
shown: PathBuf,
/// Retain the authorized directory object instead of reopening its ambient path for I/O.
#[cfg(not(target_arch = "wasm32"))]
dir: cap_std::fs::Dir,
}
impl Root {
/// The folder at `path`, which must exist.
fn open(path: &Path, access: Access) -> Result<Self, String> {
Self::open_resolving(path, access, |p| std::fs::canonicalize(p))
}
fn open_resolving(path: &Path, access: Access, resolve: impl FnOnce(&Path) -> std::io::Result<PathBuf>) -> Result<Self, String> {
let kind = match access {
Access::Read => "read",
Access::Write => "write",
};
// Capture the operator-selected directory before resolving its display/check name.
// A rename or symlink swap during resolution must not change the retained authority:
// later I/O always uses this handle, never reopens the resolved ambient pathname.
#[cfg(not(target_arch = "wasm32"))]
let dir = cap_std::fs::Dir::open_ambient_dir(path, cap_std::ambient_authority())
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?;
let resolved = resolve(path)
.and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) })
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?;
Ok(Self {
shown: plain(resolved.clone()),
resolved,
#[cfg(not(target_arch = "wasm32"))]
dir,
})
}
}
/// `path` without the `\\?\` prefix `canonicalize` gives on Windows (`\\?\C:\x` becomes `C:\x`,
/// `\\?\UNC\server\share` becomes `\\server\share`); other paths are returned as they are.
fn plain(path: PathBuf) -> PathBuf {
if !cfg!(windows) {
return path;
}
let Some(text) = path.to_str() else { return path };
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
match text.strip_prefix(r"\\?\") {
Some(rest) if rest.as_bytes().get(1) == Some(&b':') => PathBuf::from(rest),
_ => path,
}
}
impl AutomationRoots {
/// The roots `read` and `write`, which must be existing folders; `None` when neither is given
/// (nothing is confined then).
pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result<Option<Arc<Self>>, String> {
if read.is_none() && write.is_none() {
return Ok(None);
}
let read = read.map(|p| Root::open(p, Access::Read)).transpose()?;
let write = write.map(|p| Root::open(p, Access::Write)).transpose()?;
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every open and save is refused. An agent session whose folders
/// can't be used gets these rather than no roots, which would confine nothing.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_ref().map(|r| r.shown.as_path())
}
/// The write root, absolute with its links followed.
pub fn write_root(&self) -> Option<&Path> {
self.write.as_ref().map(|r| r.shown.as_path())
}
/// May the file or folder at `path` be read (or written)? `Err` says why not.
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
self.checked(path, access).map(|_| ())
}
/// Resolve a path to the selected root plus a relative name; native I/O uses that root's
/// retained handle, so the ambient pathname is never reopened after this check.
fn checked(&self, path: &str, access: Access) -> Result<(&Root, PathBuf), String> {
let root = match access {
Access::Read => self.read.as_ref(),
Access::Write => self.write.as_ref(),
};
let Some(root) = root else {
return match access {
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
};
};
let resolved = resolve(path)?;
if inside(&resolved, &root.resolved) {
return resolved
.strip_prefix(&root.resolved)
.map(|p| (root, p.to_path_buf()))
.map_err(|e| format!("automation path rejected: {path}: {e}"));
}
let shown = root.shown.display();
match access {
Access::Read => Err(format!("automation path rejected: outside the read root {shown}: {path}")),
Access::Write => Err(format!("automation path rejected: outside the write root {shown}: {path}")),
}
}
}
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
#[derive(Clone, Debug)]
enum Scope {
Confined(Arc<AutomationRoots>),
Unconfined,
}
thread_local! {
/// This thread's scope; `None`: the process's roots ([`confine_process`]).
static SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
}
/// The roots in force in every thread outside [`confine`] and [`unconfined`].
static PROCESS: OnceLock<Arc<AutomationRoots>> = OnceLock::new();
/// Put `roots` in force in the whole process, for good. `false` when roots were in force already
/// (they stay as they were).
pub fn confine_process(roots: Arc<AutomationRoots>) -> bool {
PROCESS.set(roots).is_ok()
}
/// Puts the scope it replaced back when dropped (also when `f` panics).
struct Restore(Option<Scope>);
impl Drop for Restore {
fn drop(&mut self) {
let previous = self.0.take();
SCOPE.with(|s| *s.borrow_mut() = previous);
}
}
fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
let _restore = Restore(SCOPE.with(|s| s.replace(scope)));
f()
}
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
match roots {
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
None => f(),
}
}
/// Run `f` with no roots in force on this thread: what the person at the keyboard does.
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
with_scope(Some(Scope::Unconfined), f)
}
/// The roots in force on this thread, if any.
pub fn current() -> Option<Arc<AutomationRoots>> {
match SCOPE.with(|s| s.borrow().clone()) {
Some(Scope::Confined(r)) => Some(r),
Some(Scope::Unconfined) => None,
None => PROCESS.get().cloned(),
}
}
/// May `path` be read here? Always, without roots in force.
pub fn check_read(path: &str) -> Result<(), String> {
current().map_or(Ok(()), |r| r.check(path, Access::Read))
}
/// May `path` be written here? Always, without roots in force.
pub fn check_write(path: &str) -> Result<(), String> {
current().map_or(Ok(()), |r| r.check(path, Access::Write))
}
/// Open a document relative to the retained read root, or use ordinary I/O when unconfined.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn open_read(path: &str) -> Result<std::fs::File, String> {
let result = match current() {
Some(roots) => {
let (root, relative) = roots.checked(path, Access::Read)?;
// Check through the retained authority: a FIFO must not block the GUI thread.
// As in ordinary I/O, a type swap between metadata and open still needs O_NONBLOCK.
if !root.dir.metadata(&relative).map_err(|e| format!("{path}: {e}"))?.is_file() {
return Err(format!("{path}: only regular files can be opened"));
}
root.dir.open(relative).map(cap_std::fs::File::into_std)
}
None => {
if !std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?.is_file() {
return Err(format!("{path}: only regular files can be opened"));
}
std::fs::File::open(path)
}
};
result.map_err(|e| format!("{path}: {e}"))
}
/// Pin the save's parent directory before creating its temporary file. Both creation and
/// rename are relative to this same handle, even if its ambient path is replaced meanwhile.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn write_parent(path: &str, roots: Option<&AutomationRoots>) -> Result<(cap_std::fs::Dir, OsString), String> {
// Path::file_name normalizes these final components before splitting off the parent.
if matches!(path.rsplit(std::path::is_separator).next(), Some("" | "." | "..")) {
return Err(format!("{path}: not a file path"));
}
let result = match roots {
Some(roots) => {
let (root, _) = roots.checked(path, Access::Write)?;
// Atomic rename replaces the requested leaf, not its symlink target. Resolve only
// the parent here, after also checking the leaf above, to preserve that behavior.
let absolute = std::path::absolute(path).map_err(|e| format!("{path}: {e}"))?;
let name = absolute.file_name().ok_or_else(|| format!("{path}: not a file path"))?;
let parent = absolute.parent().ok_or_else(|| format!("{path}: no parent directory"))?;
let parent = std::fs::canonicalize(parent).map_err(|e| format!("{path}: {e}"))?;
let relative = parent
.strip_prefix(&root.resolved)
.map_err(|_| format!("automation path rejected: outside the write root {}: {path}", root.shown.display()))?
.join(name);
parent_in(&root.dir, &relative)
}
None => {
let absolute = std::path::absolute(path).map_err(|e| format!("{path}: {e}"))?;
let name = absolute.file_name().ok_or_else(|| format!("{path}: not a file path"))?.to_os_string();
let parent = absolute.parent().ok_or_else(|| format!("{path}: no parent directory"))?;
cap_std::fs::Dir::open_ambient_dir(parent, cap_std::ambient_authority()).map(|dir| (dir, name))
}
};
result.map_err(|e| format!("{path}: {e}"))
}
#[cfg(not(target_arch = "wasm32"))]
fn parent_in(dir: &cap_std::fs::Dir, relative: &Path) -> std::io::Result<(cap_std::fs::Dir, OsString)> {
let name = relative.file_name().ok_or(std::io::ErrorKind::InvalidInput)?.to_os_string();
let parent = relative.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
dir.open_dir(parent).map(|dir| (dir, name))
}
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
/// existing folder's links followed and the rest appended.
fn resolve(path: &str) -> Result<PathBuf, String> {
if path.is_empty() {
return Err("automation path rejected: path is empty".into());
}
// Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows.
if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
return Err(format!("automation path rejected: reserved device names are not allowed: {path}"));
}
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
// The names below the nearest existing folder, last first.
let mut missing: Vec<OsString> = vec![];
let mut at = absolute.as_path();
loop {
match std::fs::canonicalize(at) {
Ok(mut found) => {
found.extend(missing.iter().rev());
return Ok(found);
}
Err(e) => match std::fs::symlink_metadata(at) {
Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {path}")),
// There, yet its real path can't be had (no permission): nothing to compare.
Ok(_) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")),
},
}
let parent = at.parent();
match (at.components().next_back(), parent) {
(Some(Component::Normal(name)), Some(parent)) => {
missing.push(name.to_os_string());
at = parent;
}
(Some(Component::ParentDir), _) => {
return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {path}"));
}
// Down to the root (or drive) and it doesn't exist either.
_ => {
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
return Err(format!("automation path rejected: cannot resolve {path}: {e}"));
}
}
}
}
/// Is `path` (resolved) `root` or inside it, component by component?
///
/// Compare canonical spellings exactly. Manual Unicode case folding can conflate distinct
/// directories on case-sensitive Windows volumes; a mismatch must fail closed.
fn inside(path: &Path, root: &Path) -> bool {
path.starts_with(root)
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
/// A fresh folder holding `in` (read root), `out` (write root) and `outside`.
fn folders(name: &str) -> (PathBuf, Arc<AutomationRoots>) {
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let base = std::env::temp_dir().join(format!("gc-file-access-{name}-{}-{stamp}", std::process::id()));
for d in ["in/sub", "out", "outside", "in2"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
std::fs::write(base.join("in/a.csv"), "a,b").unwrap();
std::fs::write(base.join("outside/secret.csv"), "x").unwrap();
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap();
(base, roots)
}
fn s(p: PathBuf) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn paths_inside_the_roots_pass_and_others_dont() {
let (base, roots) = folders("inside");
assert_eq!(roots.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
assert_eq!(roots.check(&s(base.join("in")), Access::Read), Ok(()), "the root itself");
assert_eq!(roots.check(&s(base.join("in/sub/new.csv")), Access::Read), Ok(()), "missing files are checked by their folder");
assert_eq!(roots.check(&s(base.join("out/new/deeper/x.xlsx")), Access::Write), Ok(()), "and by their nearest folder");
let e = roots.check(&s(base.join("outside/secret.csv")), Access::Read).unwrap_err();
assert!(e.starts_with("automation path rejected: outside the read root"), "{e}");
// Read and write access are separate.
let e = roots.check(&s(base.join("in/a.csv")), Access::Write).unwrap_err();
assert!(e.contains("outside the write root"), "{e}");
assert!(roots.check(&s(base.join("out/x.xlsx")), Access::Read).unwrap_err().contains("outside the read root"));
}
#[test]
fn both_roots_may_be_the_same_folder() {
let (base, _) = folders("same");
let both = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
assert_eq!(both.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
assert_eq!(both.check(&s(base.join("in/new.xlsx")), Access::Write), Ok(()));
assert!(both.check(&s(base.join("out/new.xlsx")), Access::Write).is_err());
}
/// A nested write root permits output without granting writes to the surrounding inputs.
#[test]
fn write_root_may_be_a_subfolder_of_the_read_root() {
let (base, _) = folders("nested");
let read = base.join("in");
let write = read.join("_artcraft");
std::fs::create_dir_all(&write).unwrap();
let roots = AutomationRoots::new(Some(&read), Some(&write)).unwrap().unwrap();
for path in [read.join("a.csv"), write.join("new.xlsx"), write.join("deeper/new.xlsx")] {
assert_eq!(roots.check(&s(path), Access::Read), Ok(()));
}
for path in [write.clone(), write.join("new.xlsx"), write.join("deeper/new.xlsx")] {
assert_eq!(roots.check(&s(path), Access::Write), Ok(()));
}
for path in [read.join("a.csv"), read.join("new.xlsx"), read.join("_artcraft2/new.xlsx"), write.join("../new.xlsx")] {
assert!(roots.check(&s(path), Access::Write).unwrap_err().contains("outside the write root"));
}
assert!(roots.check(&s(base.join("outside/secret.csv")), Access::Read).is_err());
assert_eq!(std::fs::read_to_string(read.join("a.csv")).unwrap(), "a,b");
}
/// Existing case aliases use the filesystem's canonical spelling on macOS.
#[cfg(target_os = "macos")]
#[test]
fn macos_existing_case_aliases_follow_the_filesystem() {
let (base, roots) = folders("macos-case");
let original = base.join("in/MixedCase");
std::fs::create_dir_all(&original).unwrap();
std::fs::write(original.join("Input.csv"), "synthetic,7").unwrap();
let alias = base.join("IN/mixedcase/input.CSV");
if alias.exists() {
assert_eq!(roots.check(&s(alias), Access::Read), Ok(()));
} else {
assert!(roots.check(&s(alias), Access::Read).is_err());
}
assert_eq!(std::fs::read_to_string(original.join("Input.csv")).unwrap(), "synthetic,7");
}
#[test]
fn a_sibling_with_the_same_prefix_is_outside() {
let (base, roots) = folders("prefix");
std::fs::write(base.join("in2/b.csv"), "b").unwrap();
assert!(roots.check(&s(base.join("in2/b.csv")), Access::Read).is_err(), "in2 is not inside in");
assert!(roots.check(&format!("{}2/c.csv", s(base.join("in"))), Access::Read).is_err());
}
#[test]
fn parent_traversal_is_resolved_or_refused() {
let (base, roots) = folders("dotdot");
let sep = std::path::MAIN_SEPARATOR;
let up = format!("{}{sep}..{sep}outside{sep}secret.csv", s(base.join("in")));
assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root");
let back = format!("{}{sep}..{sep}a.csv", s(base.join("in/sub")));
assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside");
let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.csv", s(base.join("out")));
let e = roots.check(&missing, Access::Write).unwrap_err();
// Windows resolves `..` by name first (so does opening the file there): then it's outside.
assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}");
}
#[test]
fn relative_and_empty_paths() {
let (_base, roots) = folders("relative");
// The tests' working directory is the crate's folder: not inside the roots.
assert!(roots.check("a.csv", Access::Read).unwrap_err().contains("outside the read root"));
assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty"));
}
#[test]
fn a_missing_root_is_an_error_and_none_is_no_confinement() {
let (base, _) = folders("missing");
let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err();
assert!(e.starts_with("cannot open the automation read root"), "{e}");
let e = AutomationRoots::new(None, Some(&base.join("in/a.csv"))).unwrap_err();
assert!(e.starts_with("cannot open the automation write root"), "{e}");
assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``"));
assert!(AutomationRoots::new(None, None).unwrap().is_none());
}
#[test]
fn a_root_left_out_grants_none_of_its_access() {
let (base, _) = folders("one-root");
let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
assert_eq!(read_only.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
let e = read_only.check(&s(base.join("in/x.xlsx")), Access::Write).unwrap_err();
assert!(e.contains("write authority is absent"), "{e}");
let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap();
assert_eq!(write_only.check(&s(base.join("out/x.xlsx")), Access::Write), Ok(()));
let e = write_only.check(&s(base.join("out/x.xlsx")), Access::Read).unwrap_err();
assert!(e.contains("read authority is absent"), "{e}");
}
#[cfg(unix)]
#[test]
fn links_are_followed_before_comparing() {
use std::os::unix::fs::symlink;
let (base, roots) = folders("links");
symlink(base.join("outside/secret.csv"), base.join("in/leak.csv")).unwrap();
assert!(roots.check(&s(base.join("in/leak.csv")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out");
symlink(base.join("outside"), base.join("out/away")).unwrap();
let e = roots.check(&s(base.join("out/away/new.xlsx")), Access::Write).unwrap_err();
assert!(e.contains("outside the write root"), "a folder link out: {e}");
symlink(base.join("outside/gone.csv"), base.join("out/dangling.xlsx")).unwrap();
let e = roots.check(&s(base.join("out/dangling.xlsx")), Access::Write).unwrap_err();
assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}");
// A link to a folder inside the root stays inside.
symlink(base.join("in/sub"), base.join("in/alias")).unwrap();
assert_eq!(roots.check(&s(base.join("in/alias/x.csv")), Access::Read), Ok(()));
// A root given through a link is the folder it leads to.
symlink(base.join("in"), base.join("in-link")).unwrap();
let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap();
assert_eq!(linked.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
}
#[cfg(windows)]
#[test]
fn windows_resolves_case_and_refuses_devices() {
let (base, roots) = folders("case");
assert_eq!(roots.check(&s(base.join("IN/A.CSV")), Access::Read), Ok(()));
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
}
#[test]
fn scopes_nest_and_restore() {
let (base, roots) = folders("scopes");
let outside = s(base.join("outside/secret.csv"));
assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default");
confine(Some(&roots), || {
assert!(check_read(&outside).is_err());
assert_eq!(unconfined(|| check_read(&outside)), Ok(()));
assert!(check_read(&outside).is_err(), "restored after unconfined");
let o = outside.clone();
assert!(std::thread::spawn(move || check_read(&o).is_ok()).join().unwrap(), "another thread is not in this thread's scope");
});
assert_eq!(check_read(&outside), Ok(()), "restored after confine");
let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom")));
assert!(r.is_err());
assert_eq!(check_read(&outside), Ok(()), "restored after a panic");
assert_eq!(confine(None, || check_read(&outside)), Ok(()));
}
#[test]
fn canonical_components_are_not_case_folded() {
assert!(inside(Path::new("scope/Case/child"), Path::new("scope/Case")));
assert!(!inside(Path::new("scope/case/child"), Path::new("scope/Case")));
assert!(!inside(Path::new("scope/Case2/child"), Path::new("scope/Case")));
}
#[test]
fn device_names() {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.csv", "NUL "] {
assert!(is_device_name(d), "{d}");
}
for f in ["console", "com10", "COM0", "lpt", "a.csv", "nul-x"] {
assert!(!is_device_name(f), "{f}");
}
}
/// A root replaced during name resolution must never replace the captured authority.
#[cfg(unix)]
#[test]
fn root_handle_is_captured_before_resolving_its_name() {
for access in [Access::Read, Access::Write] {
for swap_before_resolution in [false, true] {
let (base, _) = folders("root-setup-swap");
let requested = base.join("in");
let retained = base.join("retained-root");
std::fs::write(requested.join("secret.csv"), "authorized sentinel").unwrap();
let root = Root::open_resolving(&requested, access, |path| {
let swap = || {
std::fs::rename(&requested, &retained).unwrap();
std::os::unix::fs::symlink(base.join("outside"), &requested).unwrap();
};
if swap_before_resolution {
swap();
}
let resolved = std::fs::canonicalize(path);
if !swap_before_resolution {
swap();
}
resolved
})
.unwrap();
assert_eq!(
root.dir.read("secret.csv").unwrap(),
b"authorized sentinel",
"{access:?}, swap before resolution: {swap_before_resolution}"
);
root.dir.write("new.csv", "authorized output").unwrap();
assert_eq!(std::fs::read(retained.join("new.csv")).unwrap(), b"authorized output");
assert!(!base.join("outside/new.csv").exists());
assert_eq!(std::fs::read(base.join("outside/secret.csv")).unwrap(), b"x");
}
}
}
/// cap-std's Windows handle prevents replacing the root while its name is resolved.
#[cfg(windows)]
#[test]
fn root_handle_prevents_replacement_during_name_resolution() {
let (base, _) = folders("root-setup-lock");
let requested = base.join("in");
let root = Root::open_resolving(&requested, Access::Read, |path| {
assert!(std::fs::rename(&requested, base.join("retained-root")).is_err());
std::fs::canonicalize(path)
})
.unwrap();
assert_eq!(root.dir.read("a.csv").unwrap(), b"a,b");
assert!(requested.is_dir());
}
/// Replacing a checked path component must not redirect the later capability-relative open.
#[cfg(unix)]
#[test]
fn checked_read_and_save_parent_reject_a_subsequent_escaping_symlink() {
let (base, roots) = folders("checked-swap");
std::fs::write(base.join("in/sub/secret.csv"), "inside").unwrap();
std::fs::create_dir_all(base.join("out/sub")).unwrap();
let input = s(base.join("in/sub/secret.csv"));
let output = s(base.join("out/sub/book.xlsx"));
let (read, relative_read) = roots.checked(&input, Access::Read).unwrap();
let (write, relative_write) = roots.checked(&output, Access::Write).unwrap();
for kind in ["in", "out"] {
std::fs::rename(base.join(kind).join("sub"), base.join(kind).join("retained-sub")).unwrap();
std::os::unix::fs::symlink(base.join("outside"), base.join(kind).join("sub")).unwrap();
}
assert!(read.dir.open(relative_read).is_err());
assert!(parent_in(&write.dir, &relative_write).is_err());
assert_eq!(std::fs::read_to_string(base.join("outside/secret.csv")).unwrap(), "x");
assert!(!base.join("outside/book.xlsx").exists());
assert_eq!(std::fs::read_to_string(base.join("in/retained-sub/secret.csv")).unwrap(), "inside");
}
/// An outside symlink into the write root cannot authorize replacing that outside entry.
#[cfg(unix)]
#[test]
fn write_parent_rejects_an_outside_leaf_alias_into_the_root() {
let (base, roots) = folders("outside-alias");
let target = base.join("out/book.xlsx");
std::fs::write(&target, "inside sentinel").unwrap();
let alias = base.join("outside/alias.xlsx");
std::os::unix::fs::symlink(&target, &alias).unwrap();
let result = confine(Some(&roots), || crate::io::write_file(alias.to_str().unwrap(), b"must not be saved"));
assert!(result.is_err());
assert!(std::fs::symlink_metadata(&alias).unwrap().file_type().is_symlink());
assert_eq!(std::fs::read_to_string(target).unwrap(), "inside sentinel");
}
/// Ordinary inside-pointing links remain usable after resolving them to root-relative names.
#[cfg(unix)]
#[test]
fn native_read_accepts_an_inside_pointing_symlink() {
let (base, roots) = folders("inside-alias");
let alias = base.join("in/sub/link.csv");
std::os::unix::fs::symlink(base.join("in/a.csv"), &alias).unwrap();
let bytes = confine(Some(&roots), || crate::io::read_file(alias.to_str().unwrap())).unwrap();
assert_eq!(bytes, b"a,b");
}
/// Confined reads reject a FIFO through their retained root before an open can block.
#[cfg(unix)]
#[test]
fn confined_fifo_is_refused_before_opening() {
let (base, roots) = folders("fifo");
let fifo = base.join("in/pipe.xlsx");
let made = std::process::Command::new("mkfifo").arg(&fifo).status();
assert!(made.as_ref().is_ok_and(|s| s.success()), "mkfifo could not make the fixture: {made:?}");
let error = confine(Some(&roots), || crate::io::read_file(fifo.to_str().unwrap())).unwrap_err().to_string();
assert!(error.contains("only regular files"), "{error}");
}
}
+103 -77
View File
@@ -1055,13 +1055,7 @@ const MAX_READ_BYTES: u64 = 2 * 1024 * 1024 * 1024;
pub fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
script_sandbox_check(path)?;
// Checked before opening: opening a FIFO nobody writes to blocks the calling (GUI) thread.
// shortcut: a FIFO swapped in between this check and the open still blocks; close that with
// O_NONBLOCK when the crate takes a libc dependency.
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
return Err(EngineError::Other(format!("{path}: only regular files can be opened")));
}
let f = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let f = crate::file_access::open_read(path).map_err(EngineError::Other)?;
// A symlink to an endless device reports length 0 but streams forever, so metadata
// alone never bounds the read: require a real file and cap the bytes actually taken.
if !f.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
@@ -1084,81 +1078,113 @@ pub fn read_file(path: &str) -> Result<Vec<u8>> {
#[cfg(not(target_arch = "wasm32"))]
pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
use std::io::Write;
script_sandbox_check(path)?;
// Write to a temporary file, then rename: a crash never leaves a half-written workbook.
// The temporary file is created exclusively, so an existing file or symlink at that
// path (planted by another local user) makes the save fail instead of truncating the
// link's target; and it inherits the destination's access restrictions, so saving a
// private workbook doesn't widen who can read it.
let tmp = format!("{path}.sctmp");
let prior_meta = std::fs::metadata(path).ok();
let prior = prior_meta.as_ref().map(std::fs::Metadata::permissions);
let mut opts = std::fs::OpenOptions::new();
let roots = crate::file_access::current();
let (dir, name) = crate::file_access::write_parent(path, roots.as_deref()).map_err(EngineError::Other)?;
let metadata = dir.metadata(&name).or_else(|err| {
// A desktop save may replace a symlink to a file outside its immediate parent.
// Only follow that link with ambient authority when no automation roots are active.
if roots.is_none() && dir.symlink_metadata(&name).is_ok_and(|m| m.file_type().is_symlink()) {
std::fs::metadata(path).map(cap_std::fs::Metadata::from_just_metadata)
} else {
Err(err)
}
});
atomic_write(&dir, &name, bytes, metadata).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
/// Each save owns an exclusively created, unpredictable temporary name. A stale temporary
/// file never blocks a later save; creation, cleanup and rename stay on the pinned directory.
#[cfg(not(target_arch = "wasm32"))]
fn atomic_write(
dir: &cap_std::fs::Dir,
name: &std::ffi::OsStr,
bytes: &[u8],
metadata: std::io::Result<cap_std::fs::Metadata>,
) -> std::io::Result<()> {
use std::io::Write;
let prior_meta = match metadata {
Ok(meta) => Some(meta),
// Only an absent leaf is new. A dangling or unresolvable symlink is not permission
// to replace an existing destination with the ordinary creation mode. A regular file that
// appeared since the first look (another save published first) is an existing destination.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => match dir.symlink_metadata(name) {
Err(leaf) if leaf.kind() == std::io::ErrorKind::NotFound => None,
Ok(leaf) if leaf.is_file() => Some(leaf),
_ => return Err(e),
},
Err(e) => return Err(e),
};
#[cfg(not(unix))]
let prior = prior_meta.as_ref().map(|m| m.permissions());
let mut opts = cap_std::fs::OpenOptions::new();
opts.write(true).create_new(true);
// Over an existing file the replacement starts owner-only, whatever the umask: its group is
// still the saving user's primary one until it is changed below, and a member of that group
// must not be able to open it (and keep the descriptor) before then.
#[cfg(unix)]
if prior.is_some() {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
// A brand-new file gets the restrictive default: no group/other write, whatever the umask.
#[cfg(unix)]
if prior.is_none() {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o644);
}
let mut f = opts.open(&tmp).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
// The replacement belongs to the saving user's primary group: restore the old file's group and
// then its mode. When the group can't be restored its access is dropped rather than handed to a
// different group; failing to read that back is a failed save.
#[cfg(unix)]
if let Some(m) = &prior_meta {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let _ = std::os::unix::fs::fchown(&f, None, Some(m.gid()));
let group_kept = f.metadata().map(|now| now.gid() == m.gid()).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
// Best effort: a file system that can't change modes keeps the owner-only one. Without the
// group, the old owner and other bits are kept and the group, setuid and setgid bits dropped.
let _ = f.set_permissions(std::fs::Permissions::from_mode(restored_mode(m.mode(), group_kept)));
}
#[cfg(not(unix))]
if let Some(p) = &prior {
let _ = f.set_permissions(p.clone());
}
// `sync_all` before the rename: without it a power loss right after the rename can leave
// the new name pointing at an empty or truncated file while the old workbook is gone.
// A file system that cannot flush at all (some network mounts; on Apple targets std asks
// for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename.
let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) });
f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
drop(f);
std::fs::rename(&tmp, path).map_err(|e| {
// A write or rename that fails (full disk, the workbook locked by another app) leaves
// no temporary file beside the user's workbook.
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
// Make the rename itself durable. Best effort: the workbook is already in place, so a
// directory that can't be opened or synced (some file systems) is not a failed save.
#[cfg(unix)]
{
let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
use cap_std::fs::OpenOptionsExt;
opts.mode(if prior_meta.is_some() { 0o600 } else { 0o644 });
}
let mut created = None;
for _ in 0..32 {
let mut random = [0u8; 16];
getrandom::fill(&mut random).map_err(std::io::Error::other)?;
let suffix = u128::from_le_bytes(random);
let tmp = format!(".gridcraft-{suffix:032x}.sctmp");
match dir.open_with(&tmp, &opts) {
Ok(file) => {
created = Some((tmp, file));
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Ok(())
let (tmp, file) = created.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::AlreadyExists, "cannot create a unique save file"))?;
#[cfg(unix)]
let mut file = file.into_std();
// Restore the old group before its mode; a failed group restore must not grant access to
// the saving user's different group. The temporary file starts owner-only until this point.
#[cfg(unix)]
if let Some(m) = &prior_meta {
use cap_std::fs::MetadataExt as _;
use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
let _ = std::os::unix::fs::fchown(&file, None, Some(m.gid()));
let group_kept = file.metadata().map(|now| now.gid() == m.gid()).inspect_err(|_| {
let _ = dir.remove_file(&tmp);
})?;
if let Some(mode) = restored_mode(m.mode(), group_kept) {
let _ = file.set_permissions(std::fs::Permissions::from_mode(mode));
}
}
#[cfg(not(unix))]
let mut file = file;
#[cfg(not(unix))]
if let Some(p) = prior {
let _ = file.set_permissions(p);
}
// Flush before rename, preserving the unsupported-filesystem fallback.
let result = file
.write_all(bytes)
.and_then(|()| file.flush())
.and_then(|()| file.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) }));
// Close before rename, including on Windows; no other attempt ever owns this name.
drop(file);
let result = result.and_then(|()| dir.rename(&tmp, dir, name));
if result.is_err() {
let _ = dir.remove_file(&tmp);
}
// The held directory remains the authority for the best-effort directory flush.
#[cfg(unix)]
if result.is_ok()
&& let Ok(directory) = dir.open(".")
{
let _ = directory.sync_all();
}
result
}
/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what
@@ -1179,11 +1205,11 @@ fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool {
(unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported
}
/// The mode a saved file gets from the file it replaces (`old`): all of it when its group was
/// restored; without the group, the owner and other bits only.
/// Restore the saved mode only when the old group is kept. Otherwise leave the temporary
/// file's restrictive permissions unchanged: old group members could now match the other class.
#[cfg(unix)]
fn restored_mode(old: u32, group_kept: bool) -> u32 {
if group_kept { old & 0o7777 } else { old & 0o707 }
fn restored_mode(old: u32, group_kept: bool) -> Option<u32> {
group_kept.then_some(old & 0o7777)
}
#[cfg(target_arch = "wasm32")]
+163 -17
View File
@@ -18,23 +18,107 @@ fn copied(wb: &Workbook, range: &str) -> String {
range_html(wb, 0, r, &crate::display::range_text(wb, 0, r)).unwrap()
}
/// Isolate each native save fixture and clean it on normal return or unwinding. Set
/// `GRIDCRAFT_RETAIN_TEST_FIXTURES` to retain diagnostics on workstations that forbid cleanup.
#[cfg(not(target_arch = "wasm32"))]
fn save_fixture(label: &str) -> tempfile::TempDir {
tempfile::Builder::new()
.prefix(&format!("gridcraft-save-{label}-"))
.disable_cleanup(std::env::var_os("GRIDCRAFT_RETAIN_TEST_FIXTURES").is_some())
.tempdir()
.unwrap()
}
/// New saves inherit the process umask just like an ordinary newly created file.
#[cfg(all(not(target_arch = "wasm32"), unix))]
#[test]
fn new_workbook_save_keeps_default_creation_permissions() {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let fixture = save_fixture("new-permissions");
let reference = fixture.path().join("ordinary.txt");
// The save asks for 0644; the reference asks for the same, so both meet the same umask.
std::fs::OpenOptions::new().write(true).create_new(true).mode(0o644).open(&reference).unwrap();
let saved = fixture.path().join("synthetic.xlsx");
write_file(saved.to_str().unwrap(), b"synthetic workbook bytes").unwrap();
let expected = std::fs::metadata(&reference).unwrap().permissions().mode() & 0o777;
let actual = std::fs::metadata(&saved).unwrap().permissions().mode() & 0o777;
assert_eq!(actual, expected, "a new save must use the save creation mode (0644) after umask");
assert_eq!(std::fs::read(saved).unwrap(), b"synthetic workbook bytes");
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(unix)]
#[test]
fn save_fails_upfront_when_the_temp_name_is_taken() {
// Another local user who can write the directory must not be able to point the
// save's predictable temporary name at their own file: creation is exclusive.
let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-temp-name-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
fn stale_temporary_file_does_not_block_save_or_get_removed() {
let fixture = save_fixture("stale");
let dir = fixture.path();
let stale = dir.join("book.xlsx.sctmp");
std::fs::write(&stale, b"stale contents").unwrap();
let dest = dir.join("book.xlsx");
write_file(dest.to_str().unwrap(), b"new").unwrap();
assert_eq!(std::fs::read(dest).unwrap(), b"new");
assert_eq!(std::fs::read(stale).unwrap(), b"stale contents");
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 2);
}
#[cfg(all(not(target_arch = "wasm32"), unix))]
#[test]
fn planted_temporary_symlink_does_not_block_save_or_modify_its_target() {
let fixture = save_fixture("planted");
let dir = fixture.path();
let victim = dir.join("victim.txt");
std::fs::write(&victim, b"original").unwrap();
let dest = dir.join("book.xlsx");
std::os::unix::fs::symlink(&victim, dir.join("book.xlsx.sctmp")).unwrap();
let err = write_file(dest.to_str().unwrap(), b"new").unwrap_err();
assert_eq!(std::fs::read(&victim).unwrap(), b"original");
assert!(!dir.join("book.xlsx").exists(), "{err}");
let _ = std::fs::remove_dir_all(&dir);
let planted = dir.join("book.xlsx.sctmp");
std::os::unix::fs::symlink(&victim, &planted).unwrap();
write_file(dest.to_str().unwrap(), b"new").unwrap();
assert_eq!(std::fs::read(victim).unwrap(), b"original");
assert_eq!(std::fs::read(dest).unwrap(), b"new");
assert!(std::fs::symlink_metadata(planted).unwrap().file_type().is_symlink());
}
#[cfg(all(not(target_arch = "wasm32"), unix))]
#[test]
fn atomic_save_uses_the_pinned_parent_after_a_directory_swap() {
let fixture = save_fixture("parent-swap");
let dir = fixture.path();
for sub in ["allowed/sub", "outside"] {
std::fs::create_dir_all(dir.join(sub)).unwrap();
}
std::fs::write(dir.join("outside/book.xlsx"), b"outside sentinel").unwrap();
let roots = crate::file_access::AutomationRoots::new(None, Some(&dir.join("allowed"))).unwrap();
let dest = dir.join("allowed/sub/book.xlsx");
let (parent, name) = crate::file_access::write_parent(dest.to_str().unwrap(), roots.as_deref()).unwrap();
std::fs::rename(dir.join("allowed/sub"), dir.join("allowed/retained-sub")).unwrap();
std::os::unix::fs::symlink(dir.join("outside"), dir.join("allowed/sub")).unwrap();
atomic_write(&parent, &name, b"inside saved", parent.metadata(&name)).unwrap();
assert_eq!(std::fs::read(dir.join("outside/book.xlsx")).unwrap(), b"outside sentinel");
assert_eq!(std::fs::read(dir.join("allowed/retained-sub/book.xlsx")).unwrap(), b"inside saved");
assert_eq!(std::fs::read_dir(dir.join("outside")).unwrap().count(), 1);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn simultaneous_atomic_saves_do_not_share_temporary_names() {
let fixture = save_fixture("parallel");
let dir = fixture.path();
let destination = dir.join("book.xlsx");
let barrier = std::sync::Barrier::new(8);
std::thread::scope(|scope| {
for n in 0..8u8 {
let destination = &destination;
let barrier = &barrier;
scope.spawn(move || {
barrier.wait();
write_file(destination.to_str().unwrap(), &[n; 64]).unwrap();
});
}
});
let saved = std::fs::read(destination).unwrap();
assert_eq!(saved.len(), 64);
assert!(saved.iter().all(|v| *v == saved[0]));
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1);
}
#[cfg(not(target_arch = "wasm32"))]
@@ -67,15 +151,17 @@ fn save_keeps_the_destination_access_restrictions() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Without the old group, a saved file keeps the old owner and other bits and nothing for a group.
/// Without the old group, a saved file keeps the restrictive temporary mode.
#[cfg(not(target_arch = "wasm32"))]
#[cfg(unix)]
#[test]
fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() {
assert_eq!(super::restored_mode(0o100_664, true), 0o664);
assert_eq!(super::restored_mode(0o100_664, false), 0o604);
assert_eq!(super::restored_mode(0o102_444, false), 0o404, "an original read-only file stays read-only, setgid is dropped");
assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped");
fn restored_mode_keeps_restrictive_permissions_when_the_group_is_lost() {
assert_eq!(super::restored_mode(0o100_664, true), Some(0o664));
assert_eq!(super::restored_mode(0o100_664, false), None);
assert_eq!(super::restored_mode(0o102_444, false), None, "leave the restrictive temporary mode; do not copy setgid");
assert_eq!(super::restored_mode(0o104_755, false), None, "do not copy setuid or other-class access");
assert_eq!(super::restored_mode(0o100_604, false), None, "members of a lost group must not gain the old other-class read access");
assert_eq!(super::restored_mode(0o100_604, true), Some(0o604));
}
#[cfg(not(target_arch = "wasm32"))]
@@ -1101,6 +1187,66 @@ fn the_merge_index_holds_a_bounded_number_of_cells() {
assert!(merge_index(&sh, rect).is_none());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn desktop_save_rejects_file_names_spelled_as_directories() {
let fixture = save_fixture("trailing-separator");
let file = fixture.path().join("book.xlsx");
std::fs::write(&file, b"original").unwrap();
for suffix in ["", ".", ".."] {
let spelling = format!("{}{}{suffix}", file.display(), std::path::MAIN_SEPARATOR);
assert!(crate::file_access::unconfined(|| write_file(&spelling, b"new")).is_err());
}
assert_eq!(std::fs::read(file).unwrap(), b"original");
}
#[cfg(all(not(target_arch = "wasm32"), unix))]
#[test]
fn desktop_save_replaces_a_valid_relative_symlink_and_keeps_the_target_mode() {
use std::os::unix::fs::PermissionsExt;
let fixture = save_fixture("desktop-alias");
let parent = fixture.path().join("sub");
std::fs::create_dir(&parent).unwrap();
let target = fixture.path().join("original.xlsx");
std::fs::write(&target, b"original").unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();
let alias = parent.join("book.xlsx");
std::os::unix::fs::symlink("../original.xlsx", &alias).unwrap();
crate::file_access::unconfined(|| write_file(alias.to_str().unwrap(), b"new")).unwrap();
assert!(std::fs::symlink_metadata(&alias).unwrap().is_file());
assert_eq!(std::fs::read(&alias).unwrap(), b"new");
assert_eq!(std::fs::metadata(alias).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read(target).unwrap(), b"original");
}
/// A target inside the write root can still be outside a narrower retained parent handle.
/// Metadata refusal must not replace its symlink with a more widely readable saved copy.
#[cfg(all(not(target_arch = "wasm32"), unix))]
#[test]
fn failed_destination_metadata_does_not_widen_a_saved_copy() {
use std::os::unix::fs::PermissionsExt;
let fixture = save_fixture("metadata-refused");
let selected = fixture.path().join("selected");
std::fs::create_dir_all(selected.join("sub")).unwrap();
let private = selected.join("private.xlsx");
std::fs::write(&private, b"private sentinel").unwrap();
std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o600)).unwrap();
let alias = selected.join("sub/book.xlsx");
std::os::unix::fs::symlink("../private.xlsx", &alias).unwrap();
let roots = crate::file_access::AutomationRoots::new(None, Some(&selected)).unwrap();
let result = crate::file_access::confine(roots.as_ref(), || write_file(alias.to_str().unwrap(), b"new saved copy"));
assert!(result.is_err(), "a refused metadata lookup cannot be treated as a new file");
assert!(std::fs::symlink_metadata(&alias).unwrap().file_type().is_symlink());
assert_eq!(std::fs::read(&private).unwrap(), b"private sentinel");
assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o600);
// Also refuse a leaf whose target disappeared after an earlier path check.
let dangling = selected.join("sub/lost.xlsx");
std::os::unix::fs::symlink("missing.xlsx", &dangling).unwrap();
let dir = cap_std::fs::Dir::open_ambient_dir(selected.join("sub"), cap_std::ambient_authority()).unwrap();
assert!(atomic_write(&dir, std::ffi::OsStr::new("lost.xlsx"), b"new saved copy", dir.metadata("lost.xlsx")).is_err());
assert!(std::fs::symlink_metadata(dangling).unwrap().file_type().is_symlink());
}
#[test]
fn json_without_sheets_keeps_its_text_defaults() -> std::result::Result<(), Box<dyn std::error::Error>> {
// Saved and opened as GridCraft JSON, with the sheet list emptied in between: the reset to a
+1
View File
@@ -13,6 +13,7 @@ mod chart_svg;
mod clip_html;
pub mod cmd;
pub mod display;
pub mod file_access;
pub mod fill;
pub mod io;
pub mod links;
+10
View File
@@ -10,6 +10,16 @@ workspace = true
[dependencies]
craft-mcp-server = { workspace = true }
# The ArtCraft Launcher's switch, the connection file and the live client (`agents`), and the
# challenge handshake's proofs (`security`): plain `mcp` finds the open window with them.
craft-control = { workspace = true, features = ["agents"] }
craft-automation = { workspace = true, features = ["agents"] }
gridcraft-engine = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
[dev-dependencies]
# The framework's control server, which the desktop app's agent link runs, for the window tests.
craft-automation = { workspace = true, features = ["agents", "ui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
egui = { workspace = true }
+367
View File
@@ -0,0 +1,367 @@
//! Agents in the open window: GridCraft's side of the ArtCraft Launcher's switch.
//!
//! While the launcher's *Settings › AI agents* switch names GridCraft (behind the suite's `AI-MCP`
//! flag), the desktop app serves its control channel on loopback and publishes where in its
//! settings folder (`craft_automation::agents::AgentLink`). Plain `gridcraft-cli mcp` reads that
//! file on every tool call ([`LiveBackend`], over the shared `craft_control::agents::Live`), so an
//! MCP client's configuration holds no port and no token, and the app may start, quit or move to
//! another port while the client stays connected. Adding GridCraft to MCP clients is the
//! launcher's job (one entry for every Craft app); GridCraft writes no client configuration.
//!
//! What is GridCraft's here: its launcher id, its agent settings file ([`SETTINGS_FILE`]), its
//! window client ([`Window`], which authenticates the app before it proves it holds the token)
//! and its headless session ([`Headless`] with the agent folders as automation roots).
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use craft_automation::security::{self, ProofRole};
use craft_control::agents::{self as shared, AgentFolders, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
use gridcraft_engine::file_access::AutomationRoots;
use serde_json::{Value, json};
use crate::backend::Backend;
use crate::headless::Headless;
/// The id the ArtCraft Launcher's app list names GridCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "gridcraft";
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/GridCraft`).
pub const APP_NAME: &str = "GridCraft";
/// The desktop app's file name beside the CLI (without `.exe`).
pub const APP_EXE: &str = "gridcraft";
/// The agent settings in the settings folder: `{"controlPort", "readRoot", "writeRoot",
/// "whenAppClosed", "allowAgentControl"}` (`craft_control::agents::AgentSettings`). The app writes it
/// when they change, so `gridcraft-cli mcp` reads the current choice on every tool call.
pub const SETTINGS_FILE: &str = "agents.json";
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
pub const FOLDERS_METHOD: &str = "agent.folders";
/// The largest settings file read; the settings are a few short strings.
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
/// GridCraft's settings folder for the platform `platform` (`std::env::consts::OS`), with
/// environment variables from `env`: `%APPDATA%\GridCraft`, `~/Library/Application Support/GridCraft`,
/// else `$XDG_CONFIG_HOME/gridcraft` (`~/.config/gridcraft`). The desktop app keeps `ui.json`,
/// `prefs.json` and its agent files there; `gridcraft-cli mcp` looks for the open window there.
pub fn settings_dir_for(platform: &str, env: &impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
match platform {
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
_ => env("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft")),
}
}
/// [`settings_dir_for`] this system.
pub fn settings_dir() -> Option<PathBuf> {
settings_dir_for(std::env::consts::OS, &|key| std::env::var_os(key))
}
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be
/// read, so neither the app nor the CLI fails over them. One bad value resets only itself.
pub fn read_settings(dir: &Path) -> AgentSettings {
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
let mut text = String::new();
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
return AgentSettings::default();
}
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
let mut settings = AgentSettings::default();
for (key, value) in saved {
let mut one = serde_json::to_value(&settings).unwrap_or_default();
if let Some(o) = one.as_object_mut()
&& o.contains_key(&key)
{
o.insert(key, value);
if let Ok(next) = serde_json::from_value(one) {
settings = next;
}
}
}
settings
}
/// Saves `settings` in `dir` (created when missing), replacing the file in one step so a
/// `gridcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
std::fs::write(&partial, text)?;
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
let _ = std::fs::remove_file(&partial);
})
}
/// Whether the person lets agents use GridCraft now: with the suite's `AI-MCP` flag, the
/// launcher's switch. GridCraft had no agent consent of its own before the switch, so without the
/// flag agents get a headless session, as `mcp` always gave them.
pub fn allowed_now() -> bool {
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
}
/// The automation roots for `folders`: what a session with these folders may open and save. A
/// direction without a folder is refused, and so is everything when there is no folder at all.
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
Ok(AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref())?.unwrap_or_else(AutomationRoots::none))
}
/// The `agent_folders` answer for these roots.
pub fn folders_answer(roots: Option<&AutomationRoots>) -> Value {
match roots {
Some(roots) => {
let mut folders = AgentFolders::default();
folders.read = roots.read_root().map(Path::to_path_buf);
folders.write = roots.write_root().map(Path::to_path_buf);
shared::folders_answer(&folders)
}
// A session started with no automation roots (`--headless` without them, or with the
// agents switch off) isn't confined: say so rather than claim it has no folders.
None => json!({
"read_folder": null,
"write_folder": null,
"unrestricted": true,
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
}),
}
}
// ---- The open window ---------------------------------------------------------------------------
/// How long connecting to the window may take: it is on loopback.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(800);
/// How long a reply may take: the app's own deadline (60 s) plus a margin, so its timeout error
/// arrives first.
const CALL_TIMEOUT: Duration = Duration::from_secs(65);
/// Longest reply line read from the app.
const MAX_REPLY: u64 = 256 * 1024 * 1024;
/// One authenticated connection to the open window. The app proves it holds the token first
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
/// wire, and a program that took a stale port learns nothing derived from it.
pub struct Window {
addr: SocketAddr,
token: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
}
impl Window {
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
pub fn new(port: u16, token: String) -> Self {
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
}
/// Connects and runs the challenge handshake.
pub fn connect(&mut self) -> Result<(), String> {
self.conn = None;
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?
.map_err(|e| format!("{} refused challenge authentication ({e}); the control token was not used", self.addr))?;
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
return Err(format!("{} answered the challenge without a proof; the control token was not used", self.addr));
};
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
return Err(format!("{} could not prove it holds GridCraft's agent token; nothing was sent to it", self.addr));
}
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}))?.map_err(|e| format!("GridCraft refused the agent token: {e}"))?;
self.conn = Some(conn);
Ok(())
}
}
/// Sends one request and reads its reply: `Err` when the connection failed, `Ok(Err)` when the app
/// answered with an error.
fn round_trip(conn: &mut (BufReader<TcpStream>, TcpStream), id: u64, method: &str, params: Value) -> Result<Result<Value, String>, String> {
let (reader, writer) = conn;
let line = json!({"id": id, "method": method, "params": params}).to_string();
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
let mut reply = String::new();
let n = reader.by_ref().take(MAX_REPLY).read_line(&mut reply).map_err(|e| e.to_string())?;
if n == 0 || !reply.ends_with('\n') {
return Err("the window closed the connection".into());
}
let v: Value = serde_json::from_str(reply.trim()).map_err(|e| format!("bad reply from the window: {e}"))?;
if v.get("id").and_then(Value::as_u64) != Some(id) {
return Err("the window answered another request".into());
}
Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
})
}
impl Backend for Window {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
if self.conn.is_none() {
self.connect()?;
}
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1).max(1);
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
match round_trip(conn, id, method, params) {
Ok(answer) => answer,
// Never sent again: the request may have run (#5000). The next call reconnects.
Err(e) => {
self.conn = None;
Err(format!("lost the connection to the GridCraft window ({e}); the request may or may not have run"))
}
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
format!("the open GridCraft window ({})", self.addr)
}
}
/// The environment variable a client takes the control token from instead of the settings folder.
pub const TOKEN_ENV: &str = "GRIDCRAFT_CONTROL_TOKEN";
/// The client for a `gridcraft --control` window at `addr` (`7979`, `127.0.0.1:7979` or
/// `localhost:7979`; loopback only, as the server is), with the token from [`TOKEN_ENV`] or the
/// window's `agent-control.token` in the settings folder. The window authenticates first (the
/// challenge handshake), so nothing derived from the token goes to another program on that port.
pub fn control_window(addr: &str) -> Result<Window, String> {
let port = match addr.rsplit_once(':') {
None => addr.trim().parse::<u16>().ok(),
Some(("127.0.0.1" | "localhost", port)) => port.trim().parse::<u16>().ok(),
Some(_) => return Err(format!("{addr} is not a loopback address: GridCraft's control server listens on 127.0.0.1 only")),
}
.ok_or_else(|| format!("expected a port, 0-65535 (or 127.0.0.1:<port>), not `{addr}`"))?;
let supplied = std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty());
let file = settings_dir().map(|d| d.join(shared::TOKEN_FILE));
let names = craft_automation::args::EnvNames::for_app("GRIDCRAFT");
let token = match supplied {
Some(t) => security::client_token(Some(t.trim()), None, &craft_automation::args::FlagNames::default(), &names),
None => security::client_token(None, file.as_deref(), &craft_automation::args::FlagNames::default(), &names),
}
.map_err(|e| format!("no control token: {e} (start GridCraft with --control on this machine and user, or set {TOKEN_ENV})"))?;
let mut window = Window::new(port, token);
window.connect().map_err(|e| format!("cannot reach the GridCraft app on 127.0.0.1:{port}: {e} (start it with `gridcraft --control {port}`)"))?;
Ok(window)
}
// ---- The live backend --------------------------------------------------------------------------
type SharedWindow = Arc<Mutex<Window>>;
type SharedHeadless = Arc<Mutex<Headless>>;
/// Prepares a fresh headless session (the CLI's `--in` / `--sample`).
pub type PrepareFn = Box<dyn Fn(&mut Headless) -> Result<(), String> + Send + Sync>;
/// What plain `gridcraft-cli mcp` needs to find the window.
pub struct LiveConfig {
/// The app's settings folder: connection file, token file and agent settings.
pub config_dir: PathBuf,
/// Overrides the app's closed-app choice (`--when-closed`).
pub when_closed: Option<WhenAppClosed>,
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
pub read_root: Option<PathBuf>,
pub write_root: Option<PathBuf>,
/// Starts the app; `None` when this install can't.
pub launch: Option<shared::LaunchFn>,
pub launch_timeout: Duration,
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
pub allowed: fn() -> bool,
/// The default agent folder for an empty folder setting; tests replace it.
pub default_folder: Option<PathBuf>,
/// Prepares each new headless session.
pub prepare: Option<PrepareFn>,
}
impl LiveConfig {
/// The settings in `config_dir`, the launcher's switch, the default agent folder.
pub fn new(config_dir: PathBuf) -> Self {
Self {
config_dir,
when_closed: None,
read_root: None,
write_root: None,
launch: None,
launch_timeout: shared::LAUNCH_TIMEOUT,
allowed: allowed_now,
default_folder: shared::default_folder(APP_NAME),
prepare: None,
}
}
}
/// Plain `gridcraft-cli mcp`: every call goes to the open window while the person lets agents use
/// it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup is
/// the shared `craft_control::agents::Live`; a session that went headless stays headless.
pub struct LiveBackend {
live: shared::Live<SharedWindow, SharedHeadless>,
}
impl LiveBackend {
pub fn new(cfg: LiveConfig) -> Self {
let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder, prepare } = cfg;
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
let mut window = Window::new(w.port, w.token.clone());
window.connect()?;
Ok(Arc::new(Mutex::new(window)))
};
let headless = move |folders: &HeadlessFolders| -> Result<SharedHeadless, String> {
// Each folder grants its direction and a missing one denies it, as in every Craft
// app: with no folder at all (none given, or an agent folder that couldn't be made)
// nothing may be opened or saved.
let roots = if folders.read.is_empty() && folders.write.is_none() {
Some(AutomationRoots::none())
} else {
let mut wanted = AgentFolders::default();
wanted.read = folders.read.first().cloned();
wanted.write = folders.write.clone();
Some(roots_for(&wanted)?)
};
let mut session = Headless::new().with_automation_roots(roots);
if let Some(prepare) = &prepare {
prepare(&mut session)?;
}
Ok(Arc::new(Mutex::new(session)))
};
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
shared_cfg.when_closed = when_closed;
shared_cfg.read_roots = read_root.into_iter().collect();
shared_cfg.write_root = write_root;
shared_cfg.launch = launch;
shared_cfg.launch_timeout = launch_timeout;
shared_cfg.default_folder = default_folder;
Self { live: shared::Live::new(shared_cfg) }
}
}
impl Backend for LiveBackend {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
match self.live.resolve()? {
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
Route::Headless(h) => h.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
}
}
fn has_ui(&self) -> bool {
matches!(self.live.resolve(), Ok(Route::Window(_)))
}
fn describe(&self) -> String {
"the open GridCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window".into()
}
}
+161
View File
@@ -0,0 +1,161 @@
//! Plain `mcp` and the open window: the switch, the closed-app choice, the token handshake and the
//! agent folders, against the framework's own control server.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::Duration;
use craft_automation::agents::{Connection, TOKEN_FILE, write_connection};
use craft_automation::control::ControlRequest;
use craft_automation::server::Listening;
use craft_control::agents::WhenAppClosed;
use serde_json::{Value, json};
use crate::Backend;
use crate::agents::{LiveBackend, LiveConfig, Window, write_settings};
fn temp(label: &str) -> PathBuf {
#[allow(clippy::disallowed_methods)] // native-only fixture
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("gridcraft-agents-{label}-{}-{stamp}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn config(dir: &Path, allowed: fn() -> bool, when_closed: WhenAppClosed) -> LiveConfig {
let mut cfg = LiveConfig::new(dir.to_path_buf());
cfg.allowed = allowed;
cfg.when_closed = Some(when_closed);
cfg.default_folder = None;
cfg
}
fn yes() -> bool {
true
}
fn no() -> bool {
false
}
/// A window: the framework's control server with the token in `dir`, published in `dir` as an
/// app publishes it. The returned receiver gets the requests the "app" runs.
fn window(dir: &Path) -> (Listening, Receiver<ControlRequest>) {
let token_file = dir.join(TOKEN_FILE);
let token = craft_automation::security::server_token(None, Some(&token_file)).unwrap();
let host = craft_ui::runtime::windows::WindowHost::of(&egui::Context::default());
let (requests, server) = craft_automation::server::listen(0, token, host).unwrap();
write_connection(dir, &Connection::new(server.addr.port(), token_file, "GridCraft test")).unwrap();
(server, requests)
}
/// Answers requests on another thread: `ping` with the method name, so a reply shows it came
/// from the window.
fn serve(requests: Receiver<ControlRequest>) {
std::thread::spawn(move || {
while let Ok(req) = requests.recv() {
let _ = req.reply.send(json!({"ok": true, "result": format!("window {}", req.method)}));
}
});
}
#[test]
fn switch_off_serves_headless_without_the_apps_folders_or_a_start() {
let dir = temp("off");
// The person chose to start the app and set agent folders; with the switch off neither applies
// (the app doesn't listen then either: `agents_link_follows_the_switch` in the app).
let mut settings = craft_control::agents::AgentSettings::default();
settings.read_root = dir.display().to_string();
write_settings(&dir, &settings).unwrap();
let mut cfg = config(&dir, no, WhenAppClosed::Launch);
cfg.launch = Some(Box::new(|| panic!("the switch is off: the app must not be started")));
let mut live = LiveBackend::new(cfg);
assert_eq!(live.call("ping", json!({})).unwrap(), json!("pong"));
assert!(!live.has_ui());
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
// The command gave no folders, and the app's are only for agents let in: nothing is granted.
assert_eq!((folders["read_folder"].clone(), folders["write_folder"].clone()), (Value::Null, Value::Null), "{folders}");
assert!(folders.get("unrestricted").is_none(), "{folders}");
}
#[test]
fn switch_on_reaches_the_window() {
let dir = temp("on");
let (_server, requests) = window(&dir);
serve(requests);
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Error));
assert_eq!(live.call("ping", json!({})).unwrap(), json!("window ping"));
assert!(live.has_ui());
}
#[test]
fn a_closed_app_follows_the_closed_app_choice() {
let dir = temp("closed");
// A connection file a crashed app left behind: nothing listens on its port.
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
write_connection(&dir, &Connection::new(port, dir.join(TOKEN_FILE), "GridCraft test")).unwrap();
let err = LiveBackend::new(config(&dir, yes, WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
assert!(err.contains("isn't running"), "{err}");
// Headless with the app's agent folders: file commands stay inside them.
let folder = dir.join("agent folder");
std::fs::create_dir_all(&folder).unwrap();
let mut settings = craft_control::agents::AgentSettings::default();
settings.read_root = folder.display().to_string();
settings.write_root = folder.display().to_string();
write_settings(&dir, &settings).unwrap();
std::fs::write(dir.join("outside.csv"), "secret,1\n").unwrap();
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Headless));
assert_eq!(live.call("ping", json!({})).unwrap(), json!("pong"));
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
let shown = folders["read_folder"].as_str().unwrap();
assert!(Path::new(shown).ends_with("agent folder"), "{folders}");
let refused = live.call("engine.execute", json!({"command": "file.open", "params": {"path": dir.join("outside.csv")}})).unwrap_err();
assert!(refused.contains("outside the read root"), "{refused}");
}
#[test]
fn agents_let_in_without_any_folder_may_open_and_save_nothing() {
// Agents are let in, the app is closed, the choice is headless, and neither a folder setting nor
// a default agent folder exists: the session gets no file access, never unconfined access.
let dir = temp("nofolder");
std::fs::write(
dir.join("any.csv"),
"secret,1
",
)
.unwrap();
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Headless));
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
assert_eq!((folders["read_folder"].clone(), folders["unrestricted"].clone()), (Value::Null, Value::Null), "{folders}");
let refused = live.call("engine.execute", json!({"command": "file.open", "params": {"path": dir.join("any.csv")}})).unwrap_err();
assert!(refused.contains("not granted"), "{refused}");
}
#[test]
fn the_window_must_prove_it_holds_the_token_before_anything_is_sent() {
let dir = temp("token");
let (server, requests) = window(&dir);
let port = server.addr.port();
// A different token than the window's: as a program on a stale port would hold.
let wrong = "0".repeat(64);
let err = Window::new(port, wrong).connect().unwrap_err();
assert!(err.contains("could not prove"), "{err}");
assert!(requests.recv_timeout(Duration::from_millis(200)).is_err(), "no request may reach the window");
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_owned();
serve(requests);
let mut ok = Window::new(port, token);
assert_eq!(ok.call("ping", Value::Null).unwrap(), json!("window ping"));
}
#[test]
fn the_control_client_reaches_only_loopback() {
// Refused before any token is read, so no token can go to another machine.
for addr in ["192.0.2.1:7979", "example.com:7979", "[::ffff:192.0.2.1]:7979"] {
let err = crate::agents::control_window(addr).err().unwrap();
assert!(err.contains("not a loopback address"), "{addr}: {err}");
}
assert!(crate::agents::control_window("not a port").is_err());
}
+1 -138
View File
@@ -1,10 +1,6 @@
//! Where MCP tool calls end up: a control-channel method call.
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use serde_json::{Value, json};
use serde_json::Value;
/// Something that answers control-channel methods (`engine.execute`, `engine.commands`,
/// `document.inspect`, `sheet.read`, `ui.screenshot`, …).
@@ -16,136 +12,3 @@ pub trait Backend {
/// Short human description ("headless", "connected to 127.0.0.1:7979").
fn describe(&self) -> String;
}
/// Read/write timeout on the control connection.
const IO_TIMEOUT: Duration = Duration::from_secs(30);
/// Longest reply line accepted from the app (guards against a runaway peer).
const MAX_REPLY: u64 = 256 * 1024 * 1024;
/// A running GridCraft app, reached through its loopback control port.
pub struct Remote {
addr: String,
token: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
}
impl Remote {
/// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. The app
/// requires a token (#777): `GRIDCRAFT_CONTROL_TOKEN`, else the file the app wrote for this port.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let token = crate::control_auth::client_token(addr).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
Self::connect_with_token(addr, token)
}
/// Like [`Remote::connect`] with a token the caller already has.
pub fn connect_with_token(addr: &str, token: String) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), token, conn: None, next_id: 1 };
r.reconnect()?;
Ok(r)
}
pub fn addr(&self) -> &str {
&self.addr
}
fn reconnect(&mut self) -> std::io::Result<()> {
self.conn = None;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs()? {
// The token goes over plain TCP, so only to this machine: a network peer could read it,
// and the app's control port listens on loopback only.
if !sa.ip().is_loopback() {
last = std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!("{sa} is not a loopback address: the control token is sent only to 127.0.0.1 or ::1"),
);
continue;
}
match TcpStream::connect_timeout(&sa, Duration::from_secs(2)) {
Ok(s) => {
s.set_nodelay(true).ok();
s.set_read_timeout(Some(IO_TIMEOUT)).ok();
s.set_write_timeout(Some(IO_TIMEOUT)).ok();
let read = s.try_clone()?;
let mut conn = (BufReader::new(read), s);
Self::authenticate(&mut conn, &self.token)?;
self.conn = Some(conn);
return Ok(());
}
Err(e) => last = e,
}
}
Err(last)
}
/// The handshake every connection starts with: the app closes one that doesn't send the token first.
fn authenticate(conn: &mut (BufReader<TcpStream>, TcpStream), token: &str) -> std::io::Result<()> {
let (reader, writer) = conn;
writer.write_all(crate::control_auth::auth_line(0, token).as_bytes())?;
writer.write_all(b"\n")?;
writer.flush()?;
let mut reply = String::new();
let n = std::io::Read::take(reader, 64 * 1024).read_line(&mut reply)?;
let ok = n > 0 && serde_json::from_str::<Value>(reply.trim()).ok().and_then(|v| v.get("ok").and_then(Value::as_bool)) == Some(true);
if ok {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"the app refused the control token (is GRIDCRAFT_CONTROL_TOKEN or the app's token file for this port out of date?)",
))
}
}
fn roundtrip(&mut self, line: &str) -> std::io::Result<String> {
if self.conn.is_none() {
self.reconnect()?;
}
let Some((reader, writer)) = self.conn.as_mut() else {
return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"));
};
writer.write_all(line.as_bytes())?;
writer.write_all(b"\n")?;
writer.flush()?;
let mut reply = String::new();
let n = std::io::Read::take(reader, MAX_REPLY).read_line(&mut reply)?;
if n == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed"));
}
Ok(reply)
}
}
impl Backend for Remote {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
let line = json!({"id": id, "method": method, "params": params}).to_string();
// One retry with a fresh connection (the app may have restarted).
let reply = match self.roundtrip(&line) {
Ok(r) => r,
Err(_) => {
self.conn = None;
self.roundtrip(&line).map_err(|e| {
self.conn = None;
format!("GridCraft app at {} is not reachable: {e}", self.addr)
})?
}
};
let v: Value = serde_json::from_str(reply.trim()).map_err(|e| format!("bad reply from app: {e}"))?;
if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string())
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
format!("connected to the GridCraft app at {}", self.addr)
}
}
-158
View File
@@ -1,158 +0,0 @@
//! Authentication of the control channel (#777).
//!
//! Anything on the machine, and a web page that POSTs `text/plain` to `127.0.0.1:<port>`, can
//! reach a loopback port. So the first line of every connection must be
//! `{"id":…,"method":"auth","params":{"token":"…"}}`, with the secret the app made at start. The
//! app keeps it in memory and writes it to a file only the user can read (or the user chooses it
//! with `GRIDCRAFT_CONTROL_TOKEN`); [`Remote`](crate::Remote) reads it from the same places.
use std::path::PathBuf;
use serde_json::{Value, json};
/// Environment variable holding a token chosen by the user. The app uses it instead of making
/// one (and writes no file); clients use it instead of reading the file.
pub const TOKEN_ENV: &str = "GRIDCRAFT_CONTROL_TOKEN";
/// The method of the handshake line.
pub const AUTH_METHOD: &str = "auth";
/// Shortest token the app accepts from the user (a made one has 256 bits).
pub const MIN_TOKEN_LEN: usize = 16;
/// Longest first line the app reads from a peer that hasn't authenticated yet.
pub const MAX_AUTH_LINE: usize = 4096;
/// Compare two secrets without stopping at the first difference. Unequal lengths are unequal
/// at once (the length of a token isn't secret).
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b) {
diff |= x ^ y;
}
// Keep the optimiser from turning the loop into an early exit.
std::hint::black_box(diff) == 0
}
/// A made token as lowercase hex (two characters per byte).
pub fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(bytes.len().saturating_mul(2));
for b in bytes {
s.push(char::from(DIGITS[usize::from(b >> 4)]));
s.push(char::from(DIGITS[usize::from(b & 15)]));
}
s
}
/// The handshake line a client sends first.
pub fn auth_line(id: u64, token: &str) -> String {
json!({"id": id, "method": AUTH_METHOD, "params": {"token": token}}).to_string()
}
/// Check a connection's first line. `Ok` is the reply to send before serving further requests;
/// `Err` is the reply for a refused connection, which the caller sends and then closes. The
/// refusal is the same whatever was wrong, so it tells a stranger nothing.
pub fn check_first_line(line: &str, token: &str) -> Result<Value, Value> {
let refused = || json!({"ok": false, "error": "authentication required"});
let msg: Value = serde_json::from_str(line.trim()).map_err(|_| refused())?;
if msg.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
return Err(refused());
}
let given = msg.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or("");
// Always compare, so a missing token costs the same as a wrong one.
if constant_time_eq(given.as_bytes(), token.as_bytes()) && !token.is_empty() {
Ok(json!({"id": msg.get("id").cloned().unwrap_or(Value::Null), "ok": true, "result": {"authenticated": true}}))
} else {
Err(refused())
}
}
/// An app-selected folder for the tokens, set once before any window exists. The nightly channel
/// points it at its own private profile, so a nightly control server can never write the stable
/// app's token (and two channels can never authenticate each other).
static TOKEN_ROOT: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Choose the token folder for this process. Only a desktop app that owns its data root calls
/// this; a client (`gridcraft-cli`, the MCP bridge) keeps reading the app's own folder.
pub fn set_token_root(dir: PathBuf) -> Result<(), String> {
if !dir.is_absolute() {
return Err("the control token folder must be absolute".into());
}
TOKEN_ROOT.set(dir).map_err(|_| "the control token folder was already selected".to_string())
}
/// The folder tokens go in: [`set_token_root`]'s when an app chose one, else the user's own.
pub fn token_root() -> Option<PathBuf> {
TOKEN_ROOT.get().cloned().or_else(default_token_root)
}
fn default_token_root() -> Option<PathBuf> {
let dir = if cfg!(windows) {
PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft")
} else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) {
PathBuf::from(run).join("gridcraft")
} else {
PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft")
};
Some(dir)
}
/// Where the app writes the token it made for `port`, and where clients look for it: a folder
/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows
/// `%USERPROFILE%\.gridcraft`), file `control-<port>.token`. `None` when no such folder is known.
pub fn token_path(port: u16) -> Option<PathBuf> {
Some(token_root()?.join(format!("control-{port}.token")))
}
/// The port of a control address (`127.0.0.1:7979` → 7979).
fn port_of(addr: &str) -> Option<u16> {
addr.rsplit(':').next()?.parse().ok()
}
/// The token a client uses for `addr`: [`TOKEN_ENV`] if set, else the file the app wrote.
pub fn client_token(addr: &str) -> Result<String, String> {
if let Ok(t) = std::env::var(TOKEN_ENV)
&& !t.trim().is_empty()
{
return Ok(t.trim().to_string());
}
let path = port_of(addr).and_then(token_path).ok_or_else(|| format!("no control token: set {TOKEN_ENV}"))?;
match std::fs::read_to_string(&path) {
Ok(t) if !t.trim().is_empty() => Ok(t.trim().to_string()),
_ => Err(format!("no control token: set {TOKEN_ENV}, or start the app on this machine and user (it writes {})", path.display())),
}
}
/// Write `token` to [`token_path`] for the app: the folder is made private (mode 0700 on Unix),
/// an older file is replaced, and the new one is created readable by the user only (mode 0600).
/// Returns the path.
pub fn write_token_file(port: u16, token: &str) -> std::io::Result<PathBuf> {
use std::io::Write;
let path = token_path(port).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no user folder for the control token"))?;
let dir = path.parent().ok_or_else(|| std::io::Error::other("token path has no folder"))?;
std::fs::create_dir_all(dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
// Only our own folder: leave a shared one (`$XDG_RUNTIME_DIR` itself) as it is.
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
// Replace rather than open: a leftover file may have looser permissions, or be a link.
match std::fs::remove_file(&path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut f = opts.open(&path)?;
f.write_all(token.as_bytes())?;
f.write_all(b"\n")?;
Ok(path)
}
+161
View File
@@ -0,0 +1,161 @@
//! Synthetic end-to-end regressions for confined MCP. Fixtures are retained for inspection.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use crate::{Backend, Headless, Server};
use gridcraft_engine::{Session, file_access::AutomationRoots};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
fn fixture(label: &str) -> PathBuf {
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let base = std::env::temp_dir().join(format!("gridcraft-confined-{label}-{}-{stamp}", std::process::id()));
for sub in ["allowed", "allowed2", "outside"] {
std::fs::create_dir_all(base.join(sub)).unwrap();
}
std::fs::write(base.join("allowed/in.csv"), "inside,7\n").unwrap();
std::fs::write(base.join("outside/private.csv"), "outside,91\n").unwrap();
base
}
fn confined(base: &Path, write: bool) -> Headless {
let read = base.join("allowed");
let roots = AutomationRoots::new(Some(&read), write.then_some(read.as_path())).unwrap();
Headless::new().with_automation_roots(roots)
}
fn execute(b: &mut Headless, command: &str, params: Value) -> Result<Value, String> {
b.call("engine.execute", json!({"command":command,"params":params}))
}
#[test]
fn folder_confinement_import_and_generic_commands_reject_existing_outside_files() {
let base = fixture("reads");
let mut b = confined(&base, true);
execute(&mut b, "file.open", json!({"path":base.join("allowed/in.csv")})).unwrap();
let before = b.call("sheet.read", json!({"range":"A1:B1"})).unwrap();
for command in ["file.open", "data.fromTextCsv", "data.getData", "insert.picture"] {
let err = execute(&mut b, command, json!({"path":base.join("outside/private.csv"),"placement":"overCells"})).unwrap_err();
assert!(err.contains("outside the read root"), "{command}: {err}");
assert_eq!(b.call("sheet.read", json!({"range":"A1:B1"})).unwrap(), before);
}
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
}
#[test]
fn folder_confinement_mcp_protocol_rejects_traversal_and_prefix_siblings() {
let base = fixture("rpc");
std::fs::write(base.join("allowed2/private.csv"), "sibling,91\n").unwrap();
let mut s = Server::new(Box::new(confined(&base, true)));
for path in [base.join("outside/private.csv"), base.join("allowed/../outside/private.csv"), base.join("allowed2/private.csv")] {
let result =
s.handle(json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"open_workbook","arguments":{"path":path}}})).unwrap();
assert_eq!(result["result"]["isError"], true, "{result}");
assert!(result.to_string().contains("outside the read root"), "{result}");
}
}
#[test]
fn folder_confinement_all_exports_and_implicit_save_are_checked() {
let base = fixture("writes");
let mut b = confined(&base, true);
execute(&mut b, "cell.set", json!({"cell":"A1","input":"7"})).unwrap();
for (command, extension) in [
("file.save", "xlsx"),
("file.saveAs", "xlsx"),
("file.exportCsv", "csv"),
("file.exportHtml", "html"),
("file.exportPdf", "pdf"),
("file.print", "pdf"),
] {
let path = base.join("outside").join(format!("{command}.{extension}"));
let err = execute(&mut b, command, json!({"path":path})).unwrap_err();
assert!(err.contains("outside the write root"), "{command}: {err}");
assert!(!path.exists());
assert!(!PathBuf::from(format!("{}.sctmp", path.display())).exists());
}
let destination = base.join("allowed/new.xlsx");
execute(&mut b, "file.save", json!({"path":destination})).unwrap();
assert!(destination.is_file());
let mut session = Session::new();
session.execute_headless("file.open", json!({"path":base.join("outside/private.csv")})).unwrap();
let roots = AutomationRoots::new(Some(&base.join("allowed")), Some(&base.join("allowed"))).unwrap();
let mut outside = Headless::with_session(session).with_automation_roots(roots);
let err = execute(&mut outside, "file.save", json!({})).unwrap_err();
assert!(err.contains("outside the write root"), "{err}");
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
}
#[test]
fn folder_confinement_read_only_and_in_memory_export() {
let base = fixture("read-only");
let mut b = confined(&base, false);
execute(&mut b, "file.open", json!({"path":base.join("allowed/in.csv")})).unwrap();
let err = execute(&mut b, "file.save", json!({"path":base.join("allowed/new.xlsx")})).unwrap_err();
assert!(err.contains("write authority is absent"), "{err}");
let bytes = execute(&mut b, "file.saveBytes", json!({"format":"xlsx"})).unwrap();
assert!(bytes["base64"].as_str().is_some_and(|s| !s.is_empty()));
}
#[cfg(unix)]
#[test]
fn folder_confinement_symlinks_and_temporary_save_paths_are_checked() {
use std::os::unix::fs::symlink;
let base = fixture("links");
symlink(base.join("outside/private.csv"), base.join("allowed/link.csv")).unwrap();
symlink(base.join("outside"), base.join("allowed/away")).unwrap();
symlink(base.join("outside/missing.xlsx"), base.join("allowed/dangling.xlsx")).unwrap();
symlink(base.join("outside/private.csv"), base.join("allowed/new.xlsx.sctmp")).unwrap();
let mut b = confined(&base, true);
assert!(execute(&mut b, "file.open", json!({"path":base.join("allowed/link.csv")})).unwrap_err().contains("outside the read root"));
for name in ["away/new.xlsx", "dangling.xlsx"] {
let err = execute(&mut b, "file.save", json!({"path":base.join("allowed").join(name)})).unwrap_err();
assert!(err.contains("outside the write root") || err.contains("link that leads nowhere"), "{err}");
}
execute(&mut b, "file.save", json!({"path":base.join("allowed/new.xlsx")})).unwrap();
assert!(std::fs::symlink_metadata(base.join("allowed/new.xlsx.sctmp")).unwrap().file_type().is_symlink());
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
}
#[test]
fn folder_confinement_existing_temporary_file_survives_successful_save() {
let base = fixture("existing-temporary");
let destination = base.join("allowed/new.xlsx");
let temporary = base.join("allowed/new.xlsx.sctmp");
std::fs::write(&temporary, b"existing temporary content").unwrap();
let mut b = confined(&base, true);
execute(&mut b, "file.save", json!({"path":destination})).unwrap();
assert_eq!(std::fs::read(&temporary).unwrap(), b"existing temporary content");
assert!(destination.is_file());
execute(&mut b, "file.open", json!({"path":destination})).unwrap();
}
/// The operator may keep inputs readable while allowing writes only to a nested output folder.
#[test]
fn folder_confinement_nested_write_root_preserves_inputs() {
let base = fixture("nested");
let read = base.join("allowed");
let write = read.join("_artcraft");
std::fs::create_dir_all(&write).unwrap();
let roots = AutomationRoots::new(Some(&read), Some(&write)).unwrap();
let mut b = Headless::new().with_automation_roots(roots);
let input = read.join("in.csv");
execute(&mut b, "file.open", json!({"path":input})).unwrap();
execute(&mut b, "cell.set", json!({"cell":"B1","input":"42"})).unwrap();
// Implicit Save still points at the input, outside the narrower write root.
assert!(execute(&mut b, "file.save", json!({})).unwrap_err().contains("outside the write root"));
for path in [read.join("new.xlsx"), read.join("_artcraft2/new.xlsx"), write.join("../new.xlsx"), base.join("outside/new.xlsx")] {
assert!(execute(&mut b, "file.saveAs", json!({"path":path})).unwrap_err().contains("outside the write root"));
assert!(!path.exists());
}
let destination = write.join("result.xlsx");
execute(&mut b, "file.saveAs", json!({"path":destination})).unwrap();
execute(&mut b, "file.open", json!({"path":destination})).unwrap();
let sheet = b.call("sheet.read", json!({"range":"A1:B1"})).unwrap();
assert!(sheet.to_string().contains("42"), "{sheet}");
execute(&mut b, "file.exportCsv", json!({"path":write.join("result.csv")})).unwrap();
assert!(std::fs::read_to_string(write.join("result.csv")).unwrap().contains("42"));
assert!(execute(&mut b, "file.open", json!({"path":base.join("outside/private.csv")})).unwrap_err().contains("outside the read root"));
assert_eq!(std::fs::read_to_string(input).unwrap(), "inside,7\n");
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
}
+26 -7
View File
@@ -1,17 +1,22 @@
//! An in-process engine session that answers the engine-level control-channel methods itself.
use gridcraft_engine::{Session, Target};
use std::sync::Arc;
use gridcraft_engine::{
Session, Target,
file_access::{self, AutomationRoots},
};
use serde_json::{Value, json};
use crate::backend::Backend;
/// Error for methods that need a window.
pub(crate) const NO_UI: &str = "no UI in headless mode: start the app with `gridcraft --control 7979` and run the MCP server \
with `gridcraft-cli mcp --connect 7979`";
pub(crate) const NO_UI: &str = "no window in this session: open GridCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `gridcraft-cli mcp` without --headless";
/// Headless backend: a [`Session`] with one blank workbook to start with.
pub struct Headless {
pub session: Session,
roots: Option<Arc<AutomationRoots>>,
}
impl Default for Headless {
@@ -25,17 +30,23 @@ impl Headless {
pub fn new() -> Self {
let mut session = Session::new();
session.new_workbook();
Self { session }
Self { session, roots: None }
}
/// A session wrapping an existing one (e.g. with a file already open).
pub fn with_session(session: Session) -> Self {
Self { session }
Self { session, roots: None }
}
/// Apply read/write roots to every command, including generic and nested dispatch.
pub fn with_automation_roots(mut self, roots: Option<Arc<AutomationRoots>>) -> Self {
self.roots = roots;
self
}
fn execute(&mut self, target: Target, id: &str, params: Value) -> Result<Value, String> {
// Programmatic calls never open dialogs; anything a command queued for a UI is dropped.
self.session.execute_headless_in(target, id, params).map_err(|e| e.to_string())
file_access::confine(self.roots.as_ref(), || self.session.execute_headless_in(target, id, params)).map_err(|e| e.to_string())
}
fn commands(&self, params: &Value) -> Value {
@@ -62,6 +73,7 @@ impl Backend for Headless {
let params = if params.is_null() { json!({}) } else { params };
match method {
"ping" => Ok(json!("pong")),
crate::agents::FOLDERS_METHOD => Ok(crate::agents::folders_answer(self.roots.as_deref())),
"engine.execute" => {
let id = params.get("command").and_then(Value::as_str).ok_or("engine.execute: missing `command`")?.to_string();
let p = params.get("params").cloned().unwrap_or_else(|| json!({}));
@@ -99,6 +111,13 @@ impl Backend for Headless {
}
fn describe(&self) -> String {
"headless (in-process engine, no window)".to_string()
match &self.roots {
None => "headless (in-process engine, no window; unrestricted filesystem)".to_string(),
Some(roots) => format!(
"headless (read root: {}; write root: {})",
roots.read_root().map(|p| p.display().to_string()).unwrap_or_else(|| "none".into()),
roots.write_root().map(|p| p.display().to_string()).unwrap_or_else(|| "none".into())
),
}
}
}
+13 -13
View File
@@ -4,9 +4,11 @@
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes GridCraft as MCP tools and
//! resources and forwards everything to a [`Backend`]:
//!
//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel
//! (`gridcraft --control 7979`): one `{"id","method","params"}` line in, one
//! `{"id","ok","result"|"error"}` line out (see `docs/control-protocol.md`).
//! - [`agents::Window`] talks to the open desktop app through its loopback JSON-lines control
//! channel (the framework's server, found through the agent connection file, or a
//! `gridcraft --control 7979` app): one `{"id","method","params"}` line in, one
//! `{"id","ok","result"|"error"}` line out, after the challenge handshake (see
//! `docs/control-protocol.md`).
//! - [`Headless`] hosts an in-process [`gridcraft_engine::Session`] and implements the
//! engine-level control-channel methods itself, so agents can build workbooks without a window.
//!
@@ -14,24 +16,22 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod agents;
mod backend;
pub mod control_auth;
mod headless;
mod server;
mod tools;
pub use backend::{Backend, Remote};
pub use backend::Backend;
pub use headless::Headless;
pub use server::{COMMANDS_URI, FUNCTIONS_URI, PROTOCOL_VERSION, SUPPORTED_VERSIONS, Server, WORKBOOK_URI};
pub use tools::{ToolResult, call_tool, tool_definitions};
/// Default control-channel port of the desktop app.
pub const DEFAULT_PORT: u16 = 7979;
/// `"7979"` → `"127.0.0.1:7979"`; `"host:port"` is kept as is.
pub fn control_addr(s: &str) -> String {
if s.parse::<u16>().is_ok() { format!("127.0.0.1:{s}") } else { s.to_string() }
}
#[cfg(test)]
mod tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod folder_confinement_tests;
#[cfg(test)]
mod agents_tests;
+2 -106
View File
@@ -1,10 +1,8 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::{BufRead, BufReader, Write};
use serde_json::{Value, json};
use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, control_addr, tool_definitions};
use crate::{Headless, PROTOCOL_VERSION, Server, tool_definitions};
fn server() -> Server {
Server::new(Box::new(Headless::new()))
@@ -159,7 +157,7 @@ fn malformed_input_never_panics() {
fails(&mut s, "sort_range", json!({"keys": []}));
fails(&mut s, "open_workbook", json!({"path": "/definitely/not/here.xlsx"}));
fails(&mut s, "save_workbook", json!({}));
assert!(fails(&mut s, "screenshot", json!({"path": "/tmp/x.png"})).contains("no UI in headless mode"));
assert!(fails(&mut s, "screenshot", json!({"path": "/tmp/x.png"})).contains("no window in this session"));
}
#[test]
@@ -436,108 +434,6 @@ fn cell_set_without_input_is_error() {
assert_eq!(ok(&mut s, "get_cell", json!({"cell": "B2"}))["text"], "");
}
#[test]
fn remote_backend_over_tcp() {
// A fake app: answers engine.execute by running a headless session; closes after the first
// request to exercise the reconnect path.
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let handle = std::thread::spawn(move || {
let mut h = Headless::new();
for (i, stream) in listener.incoming().take(2).enumerate() {
let stream = stream.unwrap();
let mut w = stream.try_clone().unwrap();
let mut r = BufReader::new(stream);
// Every connection starts with the token, as the app requires.
let mut first = String::new();
r.read_line(&mut first).unwrap();
let hello = crate::control_auth::check_first_line(&first, "secret-token-0123456789").unwrap();
w.write_all(format!("{hello}\n").as_bytes()).unwrap();
loop {
let mut line = String::new();
if r.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
let req: Value = serde_json::from_str(&line).unwrap();
let reply = match h.call(req["method"].as_str().unwrap(), req["params"].clone()) {
Ok(v) => json!({"id": req["id"], "ok": true, "result": v}),
Err(e) => json!({"id": req["id"], "ok": false, "error": e}),
};
w.write_all(format!("{reply}\n").as_bytes()).unwrap();
if i == 0 {
break; // drop the first connection
}
}
}
});
let addr = control_addr(&port.to_string());
assert_eq!(addr, format!("127.0.0.1:{port}"));
let mut s = Server::new(Box::new(Remote::connect_with_token(&addr, "secret-token-0123456789".into()).unwrap()));
assert_eq!(ok(&mut s, "evaluate_formula", json!({"formula": "=1+1"}))["result"], json!(2.0));
// Second call reconnects transparently.
ok(&mut s, "set_cell", json!({"cell": "A1", "input": "7"}));
assert_eq!(ok(&mut s, "get_cell", json!({"cell": "A1"}))["value"], json!(7.0));
let msg = fails(&mut s, "execute_command", json!({"command": "nope"}));
assert!(msg.contains("unknown command"), "{msg}");
drop(s);
handle.join().unwrap();
assert!(Remote::connect_with_token("127.0.0.1:1", "x".into()).is_err());
// A network address is refused before anything, the token included, is sent.
let err = Remote::connect_with_token("192.0.2.1:7979", "x".into()).err().unwrap();
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
}
#[test]
fn control_auth_handshake_and_compare() {
use crate::control_auth::{auth_line, check_first_line, constant_time_eq, hex};
let token = "0123456789abcdef0123456789abcdef";
let ok = check_first_line(&auth_line(7, token), token).unwrap();
assert_eq!((ok["id"].clone(), ok["ok"].clone()), (json!(7), json!(true)));
// Wrong or missing token, another method, and non-JSON are all refused the same way.
let wrong = check_first_line(&auth_line(1, "0123456789abcdef0123456789abcdee"), token).unwrap_err();
for bad in [
auth_line(1, ""),
r#"{"id":1,"method":"auth","params":{}}"#.into(),
r#"{"id":1,"method":"app.save","params":{"path":"/tmp/x","token":"0123456789abcdef0123456789abcdef"}}"#.into(),
"POST / HTTP/1.1".into(),
String::new(),
] {
assert_eq!(check_first_line(&bad, token).unwrap_err(), wrong, "{bad}");
}
// An empty configured token never matches an empty given one.
assert!(check_first_line(&auth_line(1, ""), "").is_err());
assert!(constant_time_eq(b"abc", b"abc"));
assert!(!constant_time_eq(b"abc", b"abd"));
assert!(!constant_time_eq(b"abc", b"abcd"));
assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff");
}
#[test]
fn a_relative_token_root_is_refused_before_it_is_selected() {
// The app may point the tokens at its own private profile, but only at an absolute folder: a
// relative one would resolve against whatever directory the process was started in. (A
// successful selection is process-wide, so this test only exercises the refusal.)
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("relative/tokens")).is_err());
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("")).is_err());
}
#[cfg(unix)]
#[test]
fn control_token_file_is_private() {
use std::os::unix::fs::PermissionsExt;
// Unique port per run so parallel tests don't share a file; the folder is the real one.
let port = 40_000 + (std::process::id() % 20_000) as u16;
let path = crate::control_auth::write_token_file(port, "tok-0123456789abcdef").unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::metadata(path.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);
// A looser leftover is replaced, not reused.
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
crate::control_auth::write_token_file(port, "tok-1123456789abcdef").unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "tok-1123456789abcdef");
std::fs::remove_file(&path).unwrap();
}
#[test]
fn file_commands_without_a_file_fail() {
let mut s = server();
+5 -2
View File
@@ -107,7 +107,8 @@ const BORDER_PRESETS: &[&str] = &[
];
/// Tools that don't act on one workbook, so they take no `window`/`doc` target.
const UNTARGETED: &[&str] = &["list_commands", "list_functions", "list_windows", "new_workbook", "open_workbook", "screenshot"];
const UNTARGETED: &[&str] =
&["list_commands", "list_functions", "list_windows", "new_workbook", "open_workbook", "screenshot", craft_control::agents::FOLDERS_TOOL];
/// All tools, in `tools/list` order. Tools that act on a workbook take an optional `window` or
/// `doc` id (from list_windows) and default to the active window.
@@ -388,7 +389,7 @@ fn base_tool_definitions() -> Vec<Value> {
tool(
"screenshot",
"Screenshot",
"Save a PNG screenshot of the GridCraft window to `path`. Desktop app only (`gridcraft-cli mcp --connect 7979`).",
"Save a PNG screenshot of the GridCraft window to `path` (inside the agent folders: see agent_folders). Needs the open window: AI agents on in ArtCraft Launcher › Settings › AI agents.",
obj(json!({"path": string("Output PNG path")}), &["path"]),
true,
),
@@ -402,6 +403,7 @@ fn base_tool_definitions() -> Vec<Value> {
),
true,
),
tool(craft_control::agents::FOLDERS_TOOL, "Agent folders", craft_control::agents::FOLDERS_TOOL_DESCRIPTION, obj(json!({}), &[]), true),
]
}
@@ -663,6 +665,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<Value, String>
"redo" => exec(b, "edit.redo", pick(a, &["steps"])),
"screenshot" => screenshot(b, a),
"list_functions" => exec(b, "formulas.functions", pick(a, &["search", "category"])),
craft_control::agents::FOLDERS_TOOL => b.call(crate::agents::FOLDERS_METHOD, json!({})),
other => Err(format!("unknown tool `{other}`")),
}
}
+4
View File
@@ -46,6 +46,10 @@ gridcraft-xlsx = { workspace = true, features = ["test-support"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# Agents in the open window (`agents`): the ArtCraft Launcher's switch, the link host with its
# control server, and the Agents page of File › Options.
craft-automation = { workspace = true, features = ["agents", "ui"] }
craft-control = { workspace = true, features = ["agents"] }
# The desktop's preferred language for the first-run interface language.
sys-locale = { workspace = true }
+168
View File
@@ -0,0 +1,168 @@
//! Agents in the open window: the ArtCraft Launcher's switch lets agents into this window.
//!
//! The switch, the control server, its token and the connection file `gridcraft-cli mcp` finds
//! the window by are the framework's (`craft_automation::agents::AgentSwitch` and `AgentLink`).
//! GridCraft supplies its agent settings (saved by the app, `options.agents`), runs the requests
//! that arrive with its own control methods (`control::poll`), and confines their file commands to
//! the agent folders: the folders set on the Agents page of File › Options, or
//! `Documents/ArtCraft/Agents/GridCraft` for an empty one.
use std::path::PathBuf;
use std::sync::Arc;
use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
use craft_automation::control::{ControlChannel, ControlRequest};
use craft_ui::runtime::windows::WindowHost;
use gridcraft_engine::file_access::AutomationRoots;
/// The control method `gridcraft-cli mcp`'s `agent_folders` tool calls.
pub const FOLDERS_METHOD: &str = "agent.folders";
/// The `agent_folders` answer for the folders agent requests may use now: `null` for a direction
/// they may not use (the folder couldn't be opened, or the link doesn't run).
pub fn folders_answer(roots: &AutomationRoots) -> serde_json::Value {
let mut folders = craft_control::agents::AgentFolders::default();
folders.read = roots.read_root().map(std::path::Path::to_path_buf);
folders.write = roots.write_root().map(std::path::Path::to_path_buf);
craft_control::agents::folders_answer(&folders)
}
/// Saves the agent settings where `gridcraft-cli mcp` reads them; `Err` says why it couldn't.
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
/// The agents link of the open window.
pub struct Agents {
link: AgentLink,
switch: AgentSwitch,
settings: AgentSettings,
save: SaveFn,
channel: Option<ControlChannel>,
/// What agent requests may open and save: nothing until the link runs.
roots: Arc<AutomationRoots>,
default_folder: Option<PathBuf>,
}
impl Agents {
/// The link for the window, keeping its token and connection file in `settings_dir`, naming
/// `app` (the version string) in the connection file, following `switch` with the saved
/// `settings`; `save` stores the settings when the Agents page changes them.
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self {
Self {
link: AgentLink::new(settings_dir, app),
switch,
settings,
save,
channel: None,
roots: AutomationRoots::none(),
default_folder: craft_control::agents::default_folder("GridCraft"),
}
}
/// The window was started with `--control`: `server` (the framework's control server, bound to
/// that port) serves the whole run, the switch and the settings change nothing, and the Agents
/// page says the launch options manage it. Its requests are confined like an agent's: to
/// `folders` when the launch named them (`--automation-read-root`, `--automation-write-root`),
/// otherwise to the agent folders.
pub fn launched_with_control(
mut self,
server: craft_automation::server::Listening,
requests: std::sync::mpsc::Receiver<ControlRequest>,
folders: Option<craft_control::agents::AgentFolders>,
) -> Self {
self.link = AgentLink::from_launch(server);
self.channel = Some(ControlChannel::new(requests));
let folders = folders.unwrap_or_else(|| self.settings.folders_with(self.default_folder.as_deref()));
self.open_roots(&folders);
self
}
/// Opens `folders` as the roots agent requests may use; a folder that can't be opened leaves
/// no file access and is named on the Agents page.
fn open_roots(&mut self, folders: &craft_control::agents::AgentFolders) {
self.roots = match AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref()) {
Ok(roots) => roots.unwrap_or_else(AutomationRoots::none),
Err(e) => {
self.link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
AutomationRoots::none()
}
};
}
/// `default` replaces the default agent folder (tests).
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
self.default_folder = default;
self
}
/// The saved agent settings.
pub fn settings(&self) -> &AgentSettings {
&self.settings
}
/// Where the link stands, for the Agents page and `ui.inspect`.
pub fn status(&self) -> &AgentLinkStatus {
self.link.status()
}
/// The suite's `AI-MCP` flag: the launcher's switch decides, and the Agents page shows.
pub fn mcp_flag(&self) -> bool {
self.switch.mcp_flag()
}
/// Whether the launcher's switch lets agents use GridCraft now.
pub fn allowed(&self) -> bool {
// GridCraft had no agent consent of its own before the switch.
self.switch.allows(false)
}
/// Saves `settings` and applies them on the next [`Self::sync`].
pub fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
(self.save)(&settings)?;
self.settings = settings;
Ok(())
}
/// Brings the link in line with the switch and the settings: the control server starts, moves
/// or stops, and the agent folders are opened again when they changed.
pub fn sync(&mut self, host: &WindowHost) {
let allowed = self.allowed();
let update = self.link.sync(allowed.then_some(&self.settings), host);
if update.stopped {
self.channel = None;
}
if let Some(requests) = update.requests {
self.channel = Some(ControlChannel::new(requests));
}
if !update.changed {
return;
}
if self.link.status().port.is_none() {
self.roots = AutomationRoots::none();
return;
}
let folders = self.settings.folders_with(self.default_folder.as_deref());
self.open_roots(&folders);
}
/// The next agent request to run this frame, with the folders it may use. Requests whose
/// client stopped waiting are answered and skipped.
pub fn next_request(&mut self) -> Option<(ControlRequest, Arc<AutomationRoots>)> {
let request = self.channel.as_mut()?.next_request()?;
Some((request, self.roots.clone()))
}
/// The folders agent requests may open from and save to now.
pub fn roots(&self) -> &Arc<AutomationRoots> {
&self.roots
}
}
impl crate::SheetApp {
/// Runs one of the app's passes (`logic`, a window's `ui`): while input an agent queued is
/// still being applied (`SheetApp::agent_input`), confined to that agent's folders, so a key
/// or click it sent can't save outside them or change the agent settings.
pub fn with_agent_input<T>(&mut self, pass: impl FnOnce(&mut Self) -> T) -> T {
let roots = self.agent_input.clone();
gridcraft_engine::file_access::confine(roots.as_ref(), || pass(self))
}
}
+14
View File
@@ -48,6 +48,18 @@ impl SheetApp {
synthetic_pending: false,
synthetic_injected_at_pass: None,
control_rx: None,
#[cfg(not(target_arch = "wasm32"))]
agents: None,
#[cfg(not(target_arch = "wasm32"))]
agent_input: None,
#[cfg(not(target_arch = "wasm32"))]
agent_changed: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
agent_seen: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
agent_draft: None,
#[cfg(not(target_arch = "wasm32"))]
agent_seen_draft: None,
grid: grid::GridState {
last_border: "bottom".into(),
last_fill: "#FFFF00".into(),
@@ -141,6 +153,8 @@ impl SheetApp {
// issues the capture command (after every widget, so a command cannot be missed).
control::drain_screenshots(self, ctx);
control::poll(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
control::poll_agents(self, ctx);
// Printing feedback is polled once per frame, here, so hidden windows and logic-only
// frames still see worker completion. `ui` and the desktop app no longer poll it.
self.poll_printing(ctx);
+37
View File
@@ -273,6 +273,7 @@ impl SheetApp {
self.ui.autocomplete = p.get("on").and_then(Json::as_bool).unwrap_or(!self.ui.autocomplete);
Ok(json!({"on": self.ui.autocomplete}))
}
"options.agents" => self.agents_option(p),
"options.highlightActiveRow" => {
self.ui.highlight_active_row = p.get("on").and_then(Json::as_bool).unwrap_or(!self.ui.highlight_active_row);
Ok(json!({"on": self.ui.highlight_active_row}))
@@ -527,3 +528,39 @@ impl SheetApp {
}
}
}
impl SheetApp {
/// `options.agents`: the agent settings of File › Options, the agents link's status and the
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves
/// those settings first. Agents can't change them: their requests run confined to the agent
/// folders, and widening those is the person's choice.
fn agents_option(&mut self, p: &Json) -> Result<Json, String> {
#[cfg(target_arch = "wasm32")]
{
let _ = p;
Err("agents in the open window need the desktop app".into())
}
#[cfg(not(target_arch = "wasm32"))]
{
const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"];
let Some(agents) = self.agents.as_mut() else {
return Err("agents can't use this window: it has no settings folder, or it is a nightly".into());
};
if let Some(unknown) = p.as_object().and_then(|o| o.keys().find(|k| !KEYS.contains(&k.as_str()))) {
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
}
if p.as_object().is_some_and(|o| !o.is_empty()) {
if gridcraft_engine::file_access::current().is_some() {
return Err("agents can't change the agent settings: the person sets them in File › Options".into());
}
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
if let (Some(next), Some(given)) = (next.as_object_mut(), p.as_object()) {
next.extend(given.clone());
}
let next = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?;
agents.set(next)?;
}
Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}))
}
}
}
+15
View File
@@ -113,6 +113,12 @@ impl SheetApp {
/// forced hidden UI pass from saving the same change twice.
pub(super) fn autosave(&mut self, ctx: &egui::Context) {
let dirty_xlsx = self.session.active().is_some_and(|d| d.is_dirty() && d.path.as_deref().is_some_and(|p| p.ends_with(".xlsx")));
// A workbook saved since an agent changed it is the person's again.
#[cfg(not(target_arch = "wasm32"))]
{
let session = &self.session;
self.agent_changed.retain(|uid, _| session.documents().iter().any(|d| d.uid == *uid && d.is_dirty()));
}
if !(self.ui.autosave && dirty_xlsx) {
self.end_autosave_hold();
}
@@ -134,6 +140,15 @@ impl SheetApp {
}
self.end_autosave_hold();
self.store_view_state();
// Changes an agent made are saved only inside its folders (an agent's edit to a workbook
// the person opened elsewhere waits for the person's own Save).
#[cfg(not(target_arch = "wasm32"))]
{
let roots = self.session.active().and_then(|d| self.agent_changed.get(&d.uid).cloned());
let session = &mut self.session;
let _ = gridcraft_engine::file_access::confine(roots.as_ref(), || session.run("file.save", json!({})));
}
#[cfg(target_arch = "wasm32")]
let _ = self.session.run("file.save", json!({}));
} else if self.ui.autosave && dirty_xlsx {
// Keep checking even when no input arrives while the window is hidden.
+30
View File
@@ -31,6 +31,8 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
if ui.checkbox(&mut autosave, lang.tr("Save .xlsx workbooks automatically after every change")).changed() {
app.toggle_autosave();
}
#[cfg(not(target_arch = "wasm32"))]
agents_options(app, ui, lang);
let Some((calc, view)) = app.session.active().map(|d| (d.wb.calc.clone(), d.wb.view)) else { return };
ui.add_space(18.0);
// Excel's Advanced › Display options for this workbook: saved with the workbook (#3101).
@@ -59,6 +61,34 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
dim(ui, lang.tr("Calculation settings are saved with the workbook."));
}
/// The Agents section: the shared Agents page over the saved agent settings, with the suite's
/// `AI-MCP` flag (the ArtCraft Launcher's switch decides; the page has no switch of its own).
/// A change runs `options.agents`, which saves it where `gridcraft-cli mcp` reads it.
#[cfg(not(target_arch = "wasm32"))]
fn agents_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
use craft_automation::agents::AgentSettings;
use craft_automation::ui::agents::AgentsPage;
use craft_ui::patterns::preferences::SettingsDraft;
const PAGE: &str = "integrations";
let Some(agents) = app.agents.as_ref().filter(|a| a.mcp_flag()) else { return };
let (settings, status) = (agents.settings().clone(), agents.status().clone());
ui.add_space(18.0);
section(ui, lang, "Agents");
let mut draft = SettingsDraft::default();
if draft.replace(&json!({ PAGE: &settings })).is_err() {
return;
}
let out = AgentsPage::new(PAGE, &mut draft, &status).mcp_flag(true).show(ui);
if !out.changed {
return;
}
let Some(next) = draft.get::<AgentSettings>(PAGE).filter(|next| *next != settings) else { return };
app.run_or_alert(
"options.agents",
json!({"controlPort": next.control_port, "readRoot": next.read_root, "writeRoot": next.write_root, "whenAppClosed": next.when_app_closed}),
);
}
/// The display theme and interface language controls of the General section.
fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
egui::Grid::new("backstage_options_general").num_columns(2).spacing(vec2(18.0, 10.0)).show(ui, |ui| {
+121 -2
View File
@@ -279,6 +279,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
("view.animations", "Animations", "{on?: bool} (toggles without it) → {on}"),
("options.autoComplete", "Enable AutoComplete for cell values", "{on?: bool} (toggles without it) → {on}"),
("options.highlightActiveRow", "Highlight the active cell's row", "{on?: bool} (toggles without it) → {on}"),
(
"options.agents",
"Agents",
"{controlPort?: int, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} saves those settings → {settings, status, allowed, mcpFlag}",
),
("view.interfaceScale", "Interface Size", "{percent: 75–200 | \"auto\"} (100 = auto; clamped)"),
("ui.window.minimize", "Minimize Window", ""),
("ui.window.maximize", "Maximize Window", "{on: bool}"),
@@ -534,7 +539,7 @@ pub fn poll(app: &mut SheetApp, ctx: &egui::Context) {
Outcome::Done(v) => {
let _ = req.reply.send(v);
}
Outcome::Screenshot { path } => admit(app, ctx, path, req.reply),
Outcome::Screenshot { path } => admit(app, ctx, path, req.reply, None),
}
}
app.control_rx = Some(rx);
@@ -543,6 +548,111 @@ pub fn poll(app: &mut SheetApp, ctx: &egui::Context) {
}
}
/// Runs the requests agents sent through the ArtCraft Launcher's switch (`crate::agents`): the same
/// methods as the `--control` channel, with file commands confined to the agent folders. A
/// screenshot is written only inside the write folder.
#[cfg(not(target_arch = "wasm32"))]
pub fn poll_agents(app: &mut SheetApp, ctx: &egui::Context) {
use gridcraft_engine::file_access;
let Some(agents) = app.agents.as_mut() else { return };
agents.sync(&craft_ui::runtime::windows::WindowHost::of(ctx));
// What the agent's queued input changed in the frames since the last look is the agent's too,
// and so is a cell draft it left open: committed later by anyone, it is still the agent's edit.
if let Some(roots) = app.agent_input.clone() {
let seen = std::mem::take(&mut app.agent_seen);
mark_agent_changes(app, &seen, &roots);
// Only a draft the input opened or changed is the agent's; a pointer move over the person's
// open draft leaves it theirs.
let draft = app.editor.as_ref().map(|e| e.text.clone());
if draft.is_some() && draft != app.agent_seen_draft && app.agent_draft.is_none() {
app.agent_draft = Some((roots, workbooks(app)));
}
app.agent_seen_draft = draft;
}
if let Some((roots, before)) = app.agent_draft.take() {
if app.editor.is_some() {
app.agent_draft = Some((roots, before));
} else {
mark_agent_changes(app, &before, &roots);
}
}
// The agent's queued input has been applied: the frames that follow are the person's again,
// and the workbook snapshots kept to compare against are let go.
if app.synthetic.is_empty() && !app.synthetic_pending {
app.agent_input = None;
app.agent_seen.clear();
app.agent_seen_draft = None;
}
while let Some((req, roots)) = app.agents.as_mut().and_then(crate::agents::Agents::next_request) {
if req.method == crate::agents::FOLDERS_METHOD {
let _ = req.reply.send(json!({"ok": true, "result": crate::agents::folders_answer(&roots)}));
continue;
}
let queued = app.synthetic.len();
let before = workbooks(app);
let draft_before = app.editor.as_ref().map(|e| e.text.clone());
let outcome = file_access::confine(Some(&roots), || handle(app, ctx, &req.method, &req.params));
mark_agent_changes(app, &before, &roots);
// A cell draft this request opened or changed (`ui.edit.begin`, `ui.edit.text`) is the
// agent's, whoever commits it later. A draft the person opened stays theirs until an agent
// request really changes it; a refused one leaves it as it was.
let draft_after = app.editor.as_ref().map(|e| e.text.clone());
if app.agent_draft.is_none() && draft_after.is_some() && draft_after != draft_before {
app.agent_draft = Some((roots.clone(), before));
}
// Input an agent queued is applied in later passes, outside this call: those passes run
// with the agent folders too (`SheetApp::agent_input`), so a key or click the agent sends
// can't save outside them or change the agent settings.
if app.synthetic.len() > queued {
if app.agent_input.is_none() {
app.agent_seen_draft = app.editor.as_ref().map(|e| e.text.clone());
}
app.agent_input = Some(roots.clone());
app.agent_seen = workbooks(app);
}
match outcome {
Outcome::Done(v) => {
let _ = req.reply.send(v);
}
Outcome::Screenshot { path } => match path.as_deref().map(|p| roots.check(p, file_access::Access::Write)) {
Some(Err(e)) => {
let _ = req.reply.send(json!({"ok": false, "error": e}));
}
_ => admit(app, ctx, path, req.reply, Some(roots.clone())),
},
}
}
if !app.synthetic.is_empty() {
ctx.request_repaint();
}
}
/// Each open workbook by document uid, to see later which ones changed.
#[cfg(not(target_arch = "wasm32"))]
fn workbooks(app: &SheetApp) -> Vec<(u64, std::sync::Arc<gridcraft_engine::model::Workbook>)> {
app.session.documents().iter().map(|d| (d.uid, d.wb.clone())).collect()
}
/// Workbooks that changed since `before` are an agent's changes: AutoSave writes them only inside
/// `roots` until they are saved (`SheetApp::agent_changed`). While queued agent input remains, the
/// current state is kept for the next look.
#[cfg(not(target_arch = "wasm32"))]
fn mark_agent_changes(
app: &mut SheetApp,
before: &[(u64, std::sync::Arc<gridcraft_engine::model::Workbook>)],
roots: &std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>,
) {
for d in app.session.documents() {
let unchanged = before.iter().any(|(uid, wb)| *uid == d.uid && std::sync::Arc::ptr_eq(wb, &d.wb));
if !unchanged && d.is_dirty() {
app.agent_changed.insert(d.uid, roots.clone());
}
}
if app.agent_input.is_some() {
app.agent_seen = workbooks(app);
}
}
/// Put the request token on every screenshot reply (success, rejection, timeout), so a client can
/// correlate an asynchronous capture even when the reply order differs from the request order.
fn with_token(mut reply: Json, token: u64) -> Json {
@@ -564,7 +674,15 @@ fn next_token(app: &mut SheetApp) -> u64 {
/// Admit one screenshot request against the count and byte budgets **before** any capture is
/// issued. A rejected request gets one error reply and never evicts an earlier request.
fn admit(app: &mut SheetApp, ctx: &egui::Context, path: Option<String>, reply: Sender<ControlResponse>) {
/// Queues a screenshot. `roots` are an agent's folders: its PNG is written through them when the
/// capture completes, not by reopening the path (`save_image`).
fn admit(
app: &mut SheetApp,
ctx: &egui::Context,
path: Option<String>,
reply: Sender<ControlResponse>,
roots: Option<std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
) {
let token = next_token(app);
let geometry = current_capture_geometry(app, ctx);
let expected = geometry.expected_size();
@@ -628,6 +746,7 @@ fn admit(app: &mut SheetApp, ctx: &egui::Context, path: Option<String>, reply: S
app.shots.requests.push(Shot {
token,
path,
roots,
reply,
deadline: now + 8000.0,
ready_at: now + 100.0,
+24 -2
View File
@@ -255,6 +255,8 @@ pub(super) fn check_peak_budget(reserved: usize, expected: [usize; 2], base64: b
pub(super) struct Shot {
pub(super) token: u64,
pub(super) path: Option<String>,
/// An agent's folders: the PNG is written through them (`save_image`).
pub(super) roots: Option<std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
pub(super) reply: Sender<ControlResponse>,
/// Monotonic deadline for the whole request, including retries.
pub(super) deadline: f64,
@@ -624,7 +626,7 @@ fn drain_image(r: &mut Shot, image: std::sync::Arc<egui::ColorImage>, now: f64,
drop(image);
DrainAction::Restart
}
Ok(()) => DrainAction::Remove(save_image(image, r.path.as_deref())),
Ok(()) => DrainAction::Remove(save_image(image, r.path.as_deref(), r.roots.as_ref())),
}
}
@@ -688,7 +690,15 @@ fn retry_capture(app: &mut SheetApp, i: usize, geometry: CaptureGeometry, epoch:
/// straight to the file. A base64 reply is length-checked against
/// [`SCREENSHOT_MAX_BASE64_BYTES`] *before* the string is allocated, so one admitted capture cannot
/// retain an unbounded reply alongside its image.
pub fn save_image(image: std::sync::Arc<egui::ColorImage>, path: Option<&str>) -> Json {
///
/// With an agent's `roots`, the PNG is encoded first and written through the engine's confined
/// writer, relative to the write folder it opened: the path is checked again as it is written, so
/// an entry replaced after admission (a link to somewhere else) can't redirect it.
pub fn save_image(
image: std::sync::Arc<egui::ColorImage>,
path: Option<&str>,
roots: Option<&std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
) -> Json {
use image::ImageEncoder as _;
let [w, h] = image.size;
let Some(capacity) = w.checked_mul(h).and_then(|p| p.checked_mul(4)) else { return json!({"ok": false, "error": "bad image"}) };
@@ -703,6 +713,18 @@ pub fn save_image(image: std::sync::Arc<egui::ColorImage>, path: Option<&str>) -
rgba.extend_from_slice(&p.to_array());
}
drop(image);
if let (Some(p), Some(roots)) = (path, roots) {
let mut png = Vec::new();
let encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Err(e) = encoder.write_image(&rgba, width, height, image::ExtendedColorType::Rgba8) {
return json!({"ok": false, "error": e.to_string()});
}
drop(rgba);
return match gridcraft_engine::file_access::confine(Some(roots), || gridcraft_engine::io::write_file(p, &png)) {
Ok(()) => json!({"ok": true, "result": {"path": p, "width": w, "height": h}}),
Err(e) => json!({"ok": false, "error": e.to_string()}),
};
}
match path {
Some(p) => match std::fs::File::create(p) {
Ok(file) => {
+489 -29
View File
@@ -178,13 +178,13 @@ fn screenshot_admission_stops_on_the_count_budget_without_evicting() {
let mut replies = Vec::new();
for _ in 0..SCREENSHOT_MAX_REQUESTS {
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
replies.push(rx);
}
assert_eq!(app.shots.requests.len(), SCREENSHOT_MAX_REQUESTS);
assert!(replies.iter_mut().all(|r| r.try_recv().is_err()), "admitted requests do not reply early");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
let reply = rx.try_recv().expect("the over-count request is rejected");
assert_eq!(reply["ok"], false);
assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit 4")), "{reply}");
@@ -202,7 +202,7 @@ fn screenshot_admission_stops_on_aggregate_bytes_before_the_count() {
for _ in 0..3 {
let (tx, rx) = std::sync::mpsc::channel();
// A path capture (not base64) isolates the retained-image aggregate budget.
admit(&mut app, &ctx, Some(path.clone()), tx);
admit(&mut app, &ctx, Some(path.clone()), tx, None);
if let Ok(reply) = rx.try_recv() {
rejected = Some(reply);
}
@@ -218,7 +218,7 @@ fn requests_without_a_size_stay_queued_and_time_out() {
let ctx = sized_context(egui::Vec2::ZERO);
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
assert!(rx.try_recv().is_err(), "an unknown size is queued, not refused with an overflow error");
assert_eq!(app.shots.requests[0].bytes, UNKNOWN_CAPTURE_BYTES, "the largest possible image is reserved meanwhile");
// Settling passes without a size neither issue nor fail the request.
@@ -244,7 +244,7 @@ fn a_queued_capture_requests_hidden_paint_until_it_is_issued() {
let ctx = sized_context(egui::vec2(64.0, 48.0));
let mut app = test_app();
let (tx, _rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
let queued = ctx.run_logic(&raw_of(egui::vec2(64.0, 48.0)), |ctx| app.logic(ctx));
assert_eq!(hidden_paints(&queued), 1, "a queued capture needs a real `ui` pass");
@@ -267,7 +267,7 @@ fn a_minimized_capture_does_not_force_hidden_frames_while_it_waits() {
}
app.raw_input_hook(&ctx, &mut raw);
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
assert!(rx.try_recv().is_err());
let waited = ctx.run_logic(&raw, |ctx| app.logic(ctx));
assert_eq!(hidden_paints(&waited), 0, "a minimized request cannot issue until it is restored");
@@ -304,7 +304,7 @@ fn one_admitted_capture_issues_one_callback_and_replies_once() {
let ctx = h.ctx.clone();
let (tx, rx) = std::sync::mpsc::channel();
admit(h.state_mut(), &ctx, None, tx);
admit(h.state_mut(), &ctx, None, tx, None);
let token = h.state().shots.requests[0].token;
h.state_mut().shots.requests[0].ready_at = 0.0;
let mut callbacks = Vec::new();
@@ -334,10 +334,10 @@ fn out_of_order_completions_reply_on_their_own_request() {
let p1 = temp_png("order-1");
let p2 = temp_png("order-2");
let (tx1, rx1) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1);
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1, None);
let token1 = app.shots.requests[0].token;
let (tx2, rx2) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2);
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2, None);
let token2 = app.shots.requests[1].token;
for request in &mut app.shots.requests {
request.ready_at = 0.0;
@@ -370,7 +370,7 @@ fn a_timed_out_capture_replies_once_and_never_writes() {
let mut app = test_app();
let path = temp_png("timeout");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].deadline = 0.0;
let _ = ui_pass(&ctx, egui::RawInput::default(), |ui| drain_screenshots(&mut app, ui.ctx()));
let reply = rx.try_recv().expect("the timeout replies");
@@ -389,7 +389,7 @@ fn a_capture_completed_after_its_deadline_writes_nothing() {
let mut app = test_app();
let path = temp_png("late");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
let token = app.shots.requests[0].token;
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
@@ -414,7 +414,7 @@ fn a_callback_after_the_request_is_removed_is_inert() {
let mut app = test_app();
let path = temp_png("removed");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
assert_eq!(callbacks.len(), 1);
@@ -433,7 +433,7 @@ fn a_resize_between_admission_and_issuance_does_not_cost_a_retry() {
let ctx = sized_context(egui::vec2(64.0, 48.0));
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
app.shots.requests[0].ready_at = 0.0;
let admitted_epoch = app.shots.requests[0].epoch;
let resized = raw_of(egui::vec2(32.0, 24.0));
@@ -458,7 +458,7 @@ fn the_retained_reservation_is_the_slot_bound() {
let ctx = sized_context(egui::vec2(10.0, 8.0));
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
// validate_image accepts one pixel of rounding per axis: an 11x9 image is the largest.
assert_eq!(app.shots.requests[0].bytes, 11 * 9 * 4);
app.shots.requests[0].ready_at = 0.0;
@@ -480,9 +480,9 @@ fn an_image_beyond_the_reservation_is_released_without_writing() {
let p1 = temp_png("over-1");
let p2 = temp_png("over-2");
let (tx1, rx1) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1);
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1, None);
let (tx2, rx2) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2);
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2, None);
for request in &mut app.shots.requests {
request.ready_at = 0.0;
}
@@ -521,7 +521,7 @@ fn settling_counts_one_real_pass_and_skips_a_discarded_one() {
let ctx = sized_context(egui::vec2(64.0, 48.0));
let mut app = test_app();
let (tx, _rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
// Two `ui` calls in one pass are one settling frame.
let _ = ui_pass(&ctx, egui::RawInput::default(), |ui| {
issue_screenshots(&mut app, ui.ctx());
@@ -547,7 +547,7 @@ fn a_discard_requested_after_issuance_still_issues_and_writes_once() {
let mut app = test_app();
let path = temp_png("discard-after-issue");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].ready_at = 0.0;
let mut asked = false;
let mut callbacks = Vec::new();
@@ -580,7 +580,7 @@ fn an_image_larger_than_the_reservation_retries_like_a_smaller_one() {
let ctx = sized_context(egui::vec2(10.0, 8.0));
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
assert_eq!(callbacks.len(), 1);
@@ -618,7 +618,7 @@ fn a_minimize_retry_without_a_size_still_checks_the_aggregate_budget() {
let path = temp_png(&format!("minimize-retry-{n}"));
let (tx, rx) = std::sync::mpsc::channel();
// A path capture isolates the retained-image aggregate budget.
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
paths.push(path);
receivers.push(rx);
}
@@ -695,7 +695,7 @@ fn a_hidden_resize_rejects_an_image_issued_before_it_and_reissues() {
let ctx = sized_context(egui::vec2(64.0, 48.0));
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
assert_eq!(callbacks.len(), 1);
@@ -737,7 +737,7 @@ fn a_drained_capture_frees_its_slot_for_the_next_admission() {
let mut receivers = Vec::new();
for _ in 0..SCREENSHOT_MAX_REQUESTS {
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
receivers.push(rx);
}
for request in &mut app.shots.requests {
@@ -753,7 +753,7 @@ fn a_drained_capture_frees_its_slot_for_the_next_admission() {
assert_eq!(app.shots.requests.len(), 0);
assert!(receivers.iter_mut().all(|rx| rx.try_recv().is_ok()));
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
assert!(rx.try_recv().is_err(), "a new request is admitted once the drained slots are free");
assert_eq!(app.shots.requests.len(), 1);
}
@@ -809,7 +809,7 @@ fn minimized_geometry_has_no_size_and_restore_bumps_the_epoch() {
// Admission while minimized reserves the unknown-size maximum and waits.
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
assert_eq!(app.shots.requests[0].bytes, UNKNOWN_CAPTURE_BYTES);
assert!(rx.try_recv().is_err());
let epoch = app.capture_epoch;
@@ -834,7 +834,7 @@ fn a_document_switch_before_issuance_cancels_without_writing() {
let mut app = test_app();
let path = temp_png("doc-queued");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].ready_at = 0.0;
let admitted = app.shots.requests[0].document;
assert!(app.run("file.new", json!({})).is_ok());
@@ -855,7 +855,7 @@ fn a_document_switch_after_issuance_rejects_the_completed_image() {
let mut app = test_app();
let path = temp_png("doc-issued");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
assert_eq!(callbacks.len(), 1);
@@ -875,7 +875,7 @@ fn a_completion_for_another_viewport_is_rejected() {
let mut app = test_app();
let path = temp_png("viewport");
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
app.shots.requests[0].ready_at = 0.0;
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
assert_eq!(callbacks.len(), 1);
@@ -922,7 +922,7 @@ fn base64_capture_over_the_encoding_budget_is_rejected_before_admission() {
let ctx = sized_context(egui::vec2(5000.0, 4000.0));
let mut app = test_app();
let (tx, rx) = std::sync::mpsc::channel();
admit(&mut app, &ctx, None, tx);
admit(&mut app, &ctx, None, tx, None);
let reply = rx.try_recv().expect("an oversized base64 capture is refused at admission");
assert_eq!(reply["ok"], false, "{reply}");
assert!(reply["error"].as_str().is_some_and(|e| e.contains("encoding") || e.contains("base64")), "the error names the encoding budget: {reply}");
@@ -931,7 +931,7 @@ fn base64_capture_over_the_encoding_budget_is_rejected_before_admission() {
// The same capture as a file is admitted within the per-image and encoding budgets.
let path = temp_png("encoding-path");
let (tx2, rx2) = std::sync::mpsc::channel();
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx2);
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx2, None);
assert!(rx2.try_recv().is_err(), "the path form is admitted");
assert_eq!(app.shots.requests.len(), 1);
app.shots.cancel_all();
@@ -1255,3 +1255,463 @@ fn python_mode_does_not_start_on_a_draft_typed_inside_a_spill() {
let a2 = app.session.active().and_then(|d| d.wb.sheet(0)).and_then(|sh| sh.cell(gridcraft_engine::core::CellRef::new(1, 0)).cloned());
assert_eq!(a2.map(|c| (c.input_text(), c.py.is_some())), Some(("5".to_string(), false)));
}
#[cfg(not(target_arch = "wasm32"))]
mod agents_support {
use super::*;
use craft_control::agents::{AgentSettings, AgentSwitch, read_connection};
pub(super) fn temp(label: &str) -> std::path::PathBuf {
#[allow(clippy::disallowed_methods)] // native-only fixture
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("gridcraft-ui-agents-{label}-{}-{stamp}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
pub(super) fn agents(dir: &std::path::Path, launcher: bool, folder: &std::path::Path) -> crate::agents::Agents {
let mut settings = AgentSettings::default();
settings.read_root = folder.display().to_string();
settings.write_root = folder.display().to_string();
crate::agents::Agents::new(
Some(dir.to_path_buf()),
"GridCraft test".into(),
AgentSwitch::fixed(true, launcher),
settings,
Box::new(|_| Ok(())),
)
.with_default_folder(None)
}
/// Runs `calls` from another thread over the window's agent connection while this thread runs
/// the app's frames, as the app's loop would.
pub(super) fn agent_calls(
app: &mut SheetApp,
ctx: &egui::Context,
dir: &std::path::Path,
calls: Vec<(&'static str, Json)>,
) -> Vec<Result<Json, String>> {
let connection = read_connection(dir).unwrap().expect("the window publishes its connection while agents may use it");
let token = std::fs::read_to_string(&connection.token_file).unwrap().trim().to_owned();
let addr: std::net::SocketAddr = connection.addr().parse().unwrap();
let client = std::thread::spawn(move || {
let mut c = craft_automation::client::ControlClient::connect(addr, &token).unwrap();
calls.into_iter().map(|(m, p)| c.call(m, p)).collect::<Vec<_>>()
});
while !client.is_finished() {
poll_agents(app, ctx);
std::thread::sleep(std::time::Duration::from_millis(5));
}
client.join().unwrap()
}
}
#[cfg(not(target_arch = "wasm32"))]
mod agents {
use super::agents_support::*;
use super::*;
use craft_control::agents::read_connection;
#[test]
fn agents_link_follows_the_switch() {
let dir = temp("switch");
let mut app = test_app();
app.agents = Some(agents(&dir, false, &dir));
let ctx = egui::Context::default();
poll_agents(&mut app, &ctx);
assert!(read_connection(&dir).unwrap().is_none(), "the switch is off: nothing may be published");
assert!(app.agents.as_ref().unwrap().status().port.is_none());
app.agents = Some(agents(&dir, true, &dir));
poll_agents(&mut app, &ctx);
let port = app.agents.as_ref().unwrap().status().port.expect("the switch is on: agents can connect");
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(port));
app.agents = None;
assert!(read_connection(&dir).unwrap().is_none(), "closing the link removes its connection file");
}
#[test]
fn agent_requests_stay_in_the_agent_folders() {
let dir = temp("folders");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("in.csv"), "inside,7\n").unwrap();
std::fs::write(dir.join("private.csv"), "outside,91\n").unwrap();
let mut app = test_app();
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
poll_agents(&mut app, &ctx);
let outside = dir.join("private.csv").display().to_string();
let replies = agent_calls(
&mut app,
&ctx,
&dir,
vec![
("app.open", json!({"path": outside})),
("app.open", json!({"path": folder.join("in.csv")})),
("ui.screenshot", json!({"path": dir.join("shot.png")})),
("engine.execute", json!({"command": "options.agents", "params": {"readRoot": dir}})),
("agent.folders", json!({})),
("ui.text", json!({"text": "x"})),
],
);
let refused = replies[0].as_ref().unwrap_err();
assert!(refused.contains("outside the read root"), "{refused}");
assert!(replies[1].is_ok(), "{:?}", replies[1]);
assert!(replies[2].as_ref().unwrap_err().contains("outside the write root"), "{:?}", replies[2]);
assert!(replies[3].as_ref().unwrap_err().contains("can't change"), "{:?}", replies[3]);
assert_eq!(app.agents.as_ref().unwrap().settings().read_root, folder.display().to_string());
let answered = replies[4].as_ref().unwrap();
assert!(answered["write_folder"].as_str().is_some_and(|f| std::path::Path::new(f).ends_with("agents")), "{answered}");
// The text it typed is applied in later passes: those run with the agent folders too.
assert!(app.agent_input.is_some(), "queued agent input must keep the agent folders");
// Once that input is gone, the frames are the person's again and nothing is kept for it.
app.synthetic.clear();
app.synthetic_pending = false;
poll_agents(&mut app, &ctx);
assert!(app.agent_input.is_none() && app.agent_seen.is_empty());
// The person at the keyboard isn't confined: the same open runs from the window.
assert!(app.run("file.open", json!({"path": outside})).is_ok());
}
}
#[cfg(not(target_arch = "wasm32"))]
mod agent_autosave {
use super::agents_support::*;
use super::*;
#[test]
fn autosave_keeps_an_agents_change_inside_the_agent_folders() {
let dir = temp("autosave");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
// The person saved this workbook outside the agent folder and turned AutoSave on.
let outside = dir.join("person.xlsx");
app.run("cell.set", json!({"cell": "A1", "input": "mine"})).unwrap();
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
poll_agents(&mut app, &ctx);
let replies =
agent_calls(&mut app, &ctx, &dir, vec![("engine.execute", json!({"command": "cell.set", "params": {"cell": "A1", "input": "agent"}}))]);
assert!(replies[0].is_ok(), "{:?}", replies[0]);
// AutoSave's two seconds have passed.
app.grid.last_autosave = f64::MIN;
app.logic(&ctx);
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote an agent's change outside the agent folders");
assert!(app.session.active().unwrap().is_dirty());
// The person's own Save still writes it, and the workbook is theirs again.
app.run("file.save", json!({})).unwrap();
assert_ne!(std::fs::read(&outside).unwrap(), saved);
app.grid.last_autosave = f64::MIN;
app.logic(&ctx);
assert!(app.agent_changed.is_empty());
}
}
#[cfg(not(target_arch = "wasm32"))]
mod agent_writes {
use super::agents_support::*;
use super::*;
use gridcraft_engine::file_access::AutomationRoots;
#[test]
fn an_agents_screenshot_is_written_through_its_folder_not_by_path() {
let dir = temp("shot-write");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let roots = AutomationRoots::new(Some(&folder), Some(&folder)).unwrap().unwrap();
let image = || std::sync::Arc::new(egui::ColorImage::filled([4, 3], egui::Color32::RED));
// Checked again as it is written: a path outside the folder writes nothing, even though
// nothing checked it before.
let outside = dir.join("outside.png");
let refused = save_image(image(), outside.to_str(), Some(&roots));
assert_eq!(refused["ok"], json!(false), "{refused}");
assert!(!outside.exists());
let inside = folder.join("shot.png");
let written = save_image(image(), inside.to_str(), Some(&roots));
assert_eq!(written["ok"], json!(true), "{written}");
assert!(std::fs::read(&inside).unwrap().starts_with(b"\x89PNG"));
}
/// An agent's typed input is applied by later passes; what it changes is the agent's for
/// AutoSave, while the input is still queued and after the queue has emptied.
#[test]
fn autosave_keeps_changes_made_by_an_agents_queued_input_inside_its_folders() {
for pending in [true, false] {
let dir = temp(if pending { "input-pending" } else { "input-done" });
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
poll_agents(&mut app, &ctx);
agent_calls(&mut app, &ctx, &dir, vec![("ui.text", json!({"text": "x"}))]);
assert!(app.agent_input.is_some());
// A later pass applies the agent's input: here, the edit it makes.
app.run("cell.set", json!({"cell": "B2", "input": "typed by the agent"})).unwrap();
if !pending {
app.synthetic.clear();
app.synthetic_pending = false;
}
app.grid.last_autosave = f64::MIN;
app.logic(&ctx);
assert_eq!(std::fs::read(&outside).unwrap(), saved, "pending={pending}: AutoSave wrote the agent's input outside its folders");
assert!(app.session.active().unwrap().is_dirty(), "pending={pending}");
}
}
}
#[cfg(not(target_arch = "wasm32"))]
mod launch_control {
use super::agents_support::*;
use super::*;
use craft_control::agents::{AgentFolders, AgentSwitch};
/// `--control` runs the framework's server for the whole run, and its requests stay in the
/// folders the launch named, as an agent's do.
#[test]
fn control_requests_are_confined_like_an_agents() {
let dir = temp("launch");
let folder = dir.join("roots");
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("in.csv"), "inside,7\n").unwrap();
std::fs::write(dir.join("private.csv"), "outside,91\n").unwrap();
let token = "ab".repeat(32);
let host = craft_ui::runtime::windows::WindowHost::of(&egui::Context::default());
let (requests, server) = craft_automation::server::listen(0, token.clone(), host).unwrap();
let addr = server.addr;
let mut folders = AgentFolders::default();
folders.read = Some(folder.clone());
folders.write = Some(folder.clone());
let mut app = test_app();
// The switch is off: `--control` doesn't depend on it.
let agents =
crate::agents::Agents::new(None, "GridCraft test".into(), AgentSwitch::fixed(true, false), Default::default(), Box::new(|_| Ok(())))
.with_default_folder(None)
.launched_with_control(server, requests, Some(folders));
assert!(agents.status().launch_flags);
app.agents = Some(agents);
let ctx = egui::Context::default();
let outside = dir.join("private.csv");
let inside = folder.join("in.csv");
let client = std::thread::spawn(move || {
let mut c = craft_automation::client::ControlClient::connect(addr, &token).unwrap();
vec![c.call("app.open", json!({"path": outside})), c.call("app.open", json!({"path": inside}))]
});
while !client.is_finished() {
poll_agents(&mut app, &ctx);
std::thread::sleep(std::time::Duration::from_millis(5));
}
let replies = client.join().unwrap();
assert!(replies[0].as_ref().unwrap_err().contains("outside the read root"), "{:?}", replies[0]);
assert!(replies[1].is_ok(), "{:?}", replies[1]);
}
}
#[cfg(not(target_arch = "wasm32"))]
mod agent_input_frames {
use super::agents_support::*;
use super::*;
/// One desktop frame: the agent's queued input goes into the raw input, then `logic` and `ui`
/// run as the desktop app runs them (`SheetApp::with_agent_input`).
fn frame(app: &mut SheetApp, ctx: &egui::Context) {
let mut raw = raw_of(egui::vec2(1200.0, 800.0));
app.raw_input_hook(ctx, &mut raw);
app.with_agent_input(|app| app.logic(ctx));
let _ = ui_pass(ctx, raw, |ui| app.with_agent_input(|app| app.ui(ui)));
}
/// Text an agent types into the grid is applied by later UI passes. AutoSave doesn't write
/// that change outside the agent folders: not while the input is still being applied, and not
/// after the queue has emptied.
#[test]
fn autosave_keeps_an_agents_typed_input_inside_its_folders() {
let dir = temp("typed");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx);
}
let replies = agent_calls(
&mut app,
&ctx,
&dir,
vec![
("engine.execute", json!({"command": "selection.set", "params": {"range": "C3"}})),
("ui.text", json!({"text": "typed by the agent"})),
("ui.key", json!({"key": "Enter"})),
],
);
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
let mut applied = false;
for _ in 0..40 {
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's typed input outside its folders");
applied |= app.run("cell.get", json!({"cell": "C3"})).is_ok_and(|c| c["input"] == json!("typed by the agent"));
if applied && app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
break;
}
}
assert!(applied, "the typed input must reach the cell through the UI passes");
assert!(app.agent_input.is_none(), "the queue emptied and the frames are the person's again");
// After the queue emptied, AutoSave still keeps the agent's change inside its folders.
for _ in 0..3 {
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
}
assert_eq!(std::fs::read(&outside).unwrap(), saved);
assert!(app.session.active().unwrap().is_dirty());
}
/// The agent types into a cell and stops before Enter; the person commits the draft later.
/// The committed change is still the agent's: AutoSave keeps it inside the agent folders.
#[test]
fn a_draft_the_agent_left_open_stays_the_agents_when_the_person_commits_it() {
let dir = temp("draft");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx);
}
let replies = agent_calls(
&mut app,
&ctx,
&dir,
vec![("engine.execute", json!({"command": "selection.set", "params": {"range": "D4"}})), ("ui.text", json!({"text": "left open"}))],
);
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
for _ in 0..40 {
frame(&mut app, &ctx);
if app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
break;
}
}
assert!(app.editor.is_some(), "the agent's draft is still open");
assert!(app.agent_input.is_none(), "its input is all applied");
// The person commits the draft (Enter in their own frame).
assert!(app.commit_edit(1, 0, false, false));
for _ in 0..3 {
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
}
assert!(app.run("cell.get", json!({"cell": "D4"})).is_ok_and(|c| c["input"] == json!("left open")));
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's draft outside its folders");
}
/// A draft an agent opens directly (`ui.edit.begin` with text, no queued keys) and the person
/// commits later is still the agent's edit for AutoSave.
#[test]
fn a_draft_the_agent_opened_directly_stays_the_agents_when_the_person_commits_it() {
let dir = temp("direct-draft");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx);
}
let replies = agent_calls(
&mut app,
&ctx,
&dir,
vec![
("engine.execute", json!({"command": "selection.set", "params": {"range": "D5"}})),
("ui.edit.begin", json!({"text": "opened directly"})),
],
);
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
assert!(app.editor.is_some() && app.agent_input.is_none(), "a direct draft, no queued input");
assert!(app.commit_edit(1, 0, false, false));
for _ in 0..3 {
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
}
assert!(app.run("cell.get", json!({"cell": "D5"})).is_ok_and(|c| c["input"] == json!("opened directly")));
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's direct draft outside its folders");
}
/// The person's own draft is saved by AutoSave as before, also when an agent request that
/// didn't change it ran meanwhile.
#[test]
fn the_persons_own_draft_is_still_autosaved() {
let dir = temp("own-draft");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
frame(&mut app, &ctx);
app.begin_edit(Some("mine".into()), false);
// An agent request that is refused, or only reads, leaves the person's draft theirs.
let replies = agent_calls(&mut app, &ctx, &dir, vec![("ui.edit.unknown", json!({})), ("engine.commands", json!({}))]);
assert!(replies[0].is_err(), "{replies:?}");
assert!(app.commit_edit(1, 0, false, false));
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
assert_ne!(std::fs::read(&outside).unwrap(), saved, "the person's own edit must still be autosaved");
}
/// A pointer move an agent queues over the person's open draft leaves the draft theirs: AutoSave
/// still saves their commit.
#[test]
fn queued_input_that_leaves_the_persons_draft_alone_keeps_it_theirs() {
let dir = temp("move-draft");
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = test_app();
let outside = dir.join("person.xlsx");
app.run("file.saveAs", json!({"path": outside})).unwrap();
let saved = std::fs::read(&outside).unwrap();
app.ui.autosave = true;
app.agents = Some(agents(&dir, true, &folder));
let ctx = egui::Context::default();
frame(&mut app, &ctx);
app.begin_edit(Some("mine".into()), false);
let replies = agent_calls(&mut app, &ctx, &dir, vec![("ui.move", json!({"x": 900.0, "y": 700.0}))]);
assert!(replies[0].is_ok(), "{replies:?}");
for _ in 0..40 {
frame(&mut app, &ctx);
if app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
break;
}
}
assert!(app.editor.is_some(), "the person's draft is still open");
assert!(app.commit_edit(1, 0, false, false));
app.grid.last_autosave = f64::MIN;
frame(&mut app, &ctx);
assert_ne!(std::fs::read(&outside).unwrap(), saved, "the person's own commit must still be autosaved");
}
}
+34
View File
@@ -15,6 +15,8 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
..craft_update::suite::GRIDCRAFT
};
#[cfg(not(target_arch = "wasm32"))]
pub mod agents;
pub mod backstage;
mod border_preview;
mod capture;
@@ -242,6 +244,13 @@ pub struct Perf {
last: f64,
}
/// The folders an agent's requests may use (`gridcraft_engine::file_access`).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) type AgentRoots = std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>;
/// Each open workbook by document uid, to tell later which ones changed.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) type WorkbookSnapshot = Vec<(u64, std::sync::Arc<gridcraft_engine::model::Workbook>)>;
pub struct SheetApp {
pub session: Session,
pub ui: UiState,
@@ -275,6 +284,31 @@ pub struct SheetApp {
/// without reaching input handling, so the hook must offer the same step again.
pub(crate) synthetic_injected_at_pass: Option<u64>,
pub control_rx: Option<std::sync::mpsc::Receiver<ControlRequest>>,
/// Agents in this window through the ArtCraft Launcher's switch; `None` without a settings
/// folder, in a nightly and in tests.
#[cfg(not(target_arch = "wasm32"))]
pub agents: Option<agents::Agents>,
/// The agent folders while input an agent queued (`ui.key`, `ui.click`, …) is still being
/// applied: the app's passes run confined to them until that input is gone
/// (`control::poll_agents`).
#[cfg(not(target_arch = "wasm32"))]
pub agent_input: Option<std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
/// Workbooks an agent changed since they were last saved, with that agent's folders: AutoSave
/// writes them only inside those folders (`autosave`).
#[cfg(not(target_arch = "wasm32"))]
pub agent_changed: std::collections::HashMap<u64, std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
/// Each workbook as it was when the agent's queued input last started a frame, to see what
/// that input changed.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) agent_seen: WorkbookSnapshot,
/// A cell draft an agent's input opened or typed into, with that agent's folders and the
/// workbooks as they were then: whoever commits it later, the change is the agent's for AutoSave.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) agent_draft: Option<(AgentRoots, WorkbookSnapshot)>,
/// The cell draft's text when the agent's queued input last started a frame (`None`: no draft),
/// so only a draft that input opens or changes becomes the agent's.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) agent_seen_draft: Option<String>,
pub grid: grid::GridState,
pub perf: Perf,
pub fonts_ready: bool,
+1 -1
View File
@@ -30,7 +30,7 @@ cargo install --path apps/gridcraft-cli # or: cargo run -p gridcraft-cli --
| `run …` | see below |
| `commands [--json] [--search X]` | `gridcraft-cli commands --search border` — every command with its parameter docs. |
| `functions [--json] [--search X] [--category C]` | `gridcraft-cli functions --search lookup` |
| `mcp [--connect PORT] [--in FILE \| --sample NAME]` | MCP server on stdio ([mcp.md](mcp.md)). |
| `mcp [--headless] [--when-closed launch\|headless\|error] [--in FILE \| --sample NAME] [root options]` | MCP server on stdio: the open GridCraft window while AI agents may use it ([agents in the open window](mcp.md#agents-in-the-open-window)), otherwise a session without a window; `--headless`, `--in` and `--sample` always use one. Root options: `--automation-read-root DIR` and `--automation-write-root DIR`; each grants its direction of file access and an omitted one denies it, so without them nothing may be opened or saved ([folder access](mcp.md#restrict-file-access-to-a-folder)). `--connect PORT` (a `gridcraft --control` app) still works and is deprecated. |
| `send <port> <method> [json]` | `gridcraft-cli send 7979 engine.execute '{"command":"home.bold","params":{"range":"A1:C1"}}'` — one control-channel request to a running app (`gridcraft --control 7979`). |
| `version` | Prints `gridcraft-cli <version>`. |
+33 -20
View File
@@ -6,32 +6,45 @@ Start the desktop app with a control port:
gridcraft --control 7979 # or GRIDCRAFT_CONTROL_PORT=7979
```
## One server for scripts and agents
GridCraft serves its control channel with the framework's control server
(`craft_automation::server`), the same one every Craft app uses. It runs in two ways:
- `--control PORT` (or `GRIDCRAFT_CONTROL_PORT`) starts it for the whole run, on `127.0.0.1:PORT`.
- While the ArtCraft Launcher's AI agents switch names GridCraft, the window starts and stops it
by itself and publishes the port in `agent-connection.json` in the settings folder
([`mcp.md`](mcp.md#agents-in-the-open-window)). `--control` takes precedence for the run.
Both take the same requests and methods (below), and both confine file commands: to the agent
folders (File › Options › Agents, or `Documents/ArtCraft/Agents/GridCraft`), or for `--control` to
`--automation-read-root DIR` / `--automation-write-root DIR` when the launch names them. A
screenshot's `path` must lie in the write folder, and requests can't change the agent settings
(`options.agents`). A request line is at most 1 MiB and a reply at most 8 MiB.
## Authentication
The control port is reachable by every program on the machine, and by a web page that POSTs
`text/plain` to `127.0.0.1:7979`, so every connection must prove it knows the app's token
(#777). **There is no way to turn this off.**
The port is reachable by every program on the machine, so every connection must prove it knows
the app's token. **There is no way to turn this off.**
- The app makes a token at start (256 random bits from the operating system, kept in memory) and
writes it to a file only you can read: `$XDG_RUNTIME_DIR/gridcraft/control-<port>.token` (else
`~/.cache/gridcraft/…`; Windows: `%USERPROFILE%\.gridcraft\…`; the folder is mode 0700 and the
file 0600 on Unix). The path is printed on stderr. The token itself is never printed or logged.
- Or choose the token yourself: `GRIDCRAFT_CONTROL_TOKEN=…` (preferred) or `--control-token …`
(visible in the process list), at least 16 characters. The app then writes no file.
- The first line of a connection must be
`{"id":0,"method":"auth","params":{"token":"…"}}`; the reply is
`{"id":0,"ok":true,"result":{"authenticated":true}}`. Any other first line (a wrong or missing
token, another method, text that isn't JSON such as an HTTP request, no line within 10 s, or
one longer than 4 KiB) gets `{"ok":false,"error":"authentication required"}` and the
connection is closed. At most 16 connections may be waiting to send their token at once; past that a new
connection is closed before anything is read. After that, a line that isn't JSON also closes the connection.
- `gridcraft-cli send`/`mcp --connect` and `gridcraft_mcp::Remote` do this themselves: they use
`GRIDCRAFT_CONTROL_TOKEN` if set, else the token file of that port (so they work for the same
user on the same machine without setup). Your own client reads the file or the variable.
- The token (64 hex characters) is in `agent-control.token` in the settings folder (`%APPDATA%\GridCraft`,
`~/Library/Application Support/GridCraft`, `~/.config/gridcraft`), created on first use and readable
by its owner only. Or choose it: `GRIDCRAFT_CONTROL_TOKEN=…` (preferred) or `--control-token …`
(visible in the process list), 64 hex characters.
- The challenge handshake: `{"id":1,"method":"auth.challenge","params":{"clientNonce":"<64 hex>"}}`
is answered with `{"serverNonce","serverProof"}`. The client checks the proof (HMAC-SHA256 keyed
by the token), then sends `{"id":2,"method":"auth","params":{"proof":"…"}}`. The token never
crosses the wire, and a client learns that the server holds it before revealing anything derived
from it. The one-line `{"method":"auth","params":{"token":"…"}}` is accepted too.
- No method is answered before authentication; a refused connection gets
`{"ok":false,"error":"authentication required"}` and is closed.
- `gridcraft-cli send` and `gridcraft-cli mcp` always use the challenge, with
`GRIDCRAFT_CONTROL_TOKEN` if set, else the token file. A connection lost during a request is never
sent again: the request may already have run.
## Requests
Then send newline-delimited JSON to `127.0.0.1:7979` (after the `auth` line). Every request line gets one reply line:
Then send newline-delimited JSON (after authenticating). Every request line gets one reply line:
```json
{"id": 1, "method": "engine.execute", "params": {"command": "cell.set", "params": {"cell": "B2", "input": "=SUM(A1:A9)"}}}
+32
View File
@@ -252,3 +252,35 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-11 | minor | XLSX: Allow Edit Ranges (`protectedRanges`) read and written with their password hashes (#307) |
| 2026-10-10 | minor | Encrypted and `.xls` files are now recognised and refused with a message (#17) |
| 2026-10-10 | major | Created: every Excel format with our read/write support; XLSB and ODS values-only imports recorded; `.xls`, encryption and large files flagged as beta gates | 
## Contribution #2739 — scoped notes
> **Last updated:** 2026-11-15 · These notes describe this contribution. The mainline assessment and progress tables above are retained verbatim from `1d0b311b4a94`. The contribution does not revise the mainline readiness estimates.
The behavior described in these scoped notes applies to this branch and supersedes corresponding older baseline statements above. Dated rows below record the contribution history, rather than adding a new claim of general parity.
Topic change: MCP file confinement retained with upstream Arabic PDF progress.
> **Automation confinement update:** 2026-10-30 · Headless MCP accepts operator-selected read/write roots, applied before `--in` and at file I/O. Native reads and atomic saves bind their operations to open authorized directory handles; exclusive random temporary names prevent stale `.sctmp` files from blocking saves. Desktop `--connect` confinement and process-wide OS sandboxing remain outside this change. Readiness estimates unchanged. See [MCP file access](mcp.md#restrict-file-access-to-a-folder).
#### Filesystem integration — 2026-11-15
Capability-relative reads retain the upstream regular-file precheck, including for confined
FIFO paths. Atomic saves keep unpredictable exclusive temporary names and restore an existing
file's group before its permission bits; a lost group retains the restrictive temporary mode.
New files request mode 0644, which then passes through the process umask. Both command-line
sandbox and folder-confinement regressions remain, with an additional confined-FIFO control.
Only an absent destination leaf permits ordinary new-file permissions. A failed metadata lookup
for an existing or dangling symlink refuses the save; losing the old group never copies its
other-class rights to a replacement with a different group. Synthetic controls retain both links
and the private target bytes and permissions when these saves are refused.
### Contribution revision history
| Date | Change | Summary |
|---|---|---|
| 2026-11-05 | trivial | new native saves request mode 0644 before the umask; when an existing file's group can't be kept, the replacement keeps its owner-only temporary mode instead of restoring the old owner and other bits; synthetic regression, no readiness change |
| 2026-10-29 | minor | Align root flags with DeckCraft, cover nested write roots and macOS case aliases; desktop scope and readiness estimates unchanged |
| 2026-10-27 | minor | Headless MCP filesystem roots, initial `--in` confinement and regression tests; desktop control scope and readiness estimates unchanged |
+18
View File
@@ -249,3 +249,21 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 2026-10-10 | minor | Updated for the 10-10 merges (#17, #31, #38, #62, #82, #104, #116) and the new chart resize bug (#190) |
| 2026-10-10 | minor | Noted that no gap blocks the alpha gate |
| 2026-10-10 | major | Created: 24 ranked gaps with evidence, from the full re-measure and the 60 open issues |
## Contribution #2739 — scoped notes
> **Last updated:** 2026-11-15 · These notes describe this contribution. The mainline assessment and progress tables above are retained verbatim from `1d0b311b4a94`. The contribution does not revise the mainline readiness estimates.
The behavior described in these scoped notes applies to this branch and supersedes corresponding older baseline statements above. Dated rows below record the contribution history, rather than adding a new claim of general parity.
Topic change: MCP file confinement retained with upstream Arabic PDF progress.
> **Automation confinement update:** 2026-10-30 · Headless MCP accepts operator-selected read/write roots, applied before `--in` and at file I/O. Native reads and atomic saves bind their operations to open authorized directory handles; exclusive random temporary names prevent stale `.sctmp` files from blocking saves. Desktop `--connect` confinement and process-wide OS sandboxing remain outside this change. Readiness estimates unchanged. See [MCP file access](mcp.md#restrict-file-access-to-a-folder).
### Contribution revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | minor | Align root flags with DeckCraft, cover nested write roots and macOS case aliases; desktop scope and readiness estimates unchanged |
| 2026-10-27 | minor | Headless MCP filesystem roots, initial `--in` confinement and regression tests; desktop control scope and readiness estimates unchanged |
+130 -15
View File
@@ -4,22 +4,58 @@
newline-delimited JSON-RPC 2.0 on stdin/stdout (protocol `2025-06-18`; `2025-03-26` and `2024-11-05` clients are
answered in their own version). Logs go to stderr.
Two backends:
Where tool calls go:
| Mode | Command | What it drives |
|---|---|---|
| Headless (default) | `gridcraft-cli mcp [--in book.xlsx \| --sample budget]` | An in-process engine session — no window. |
| Remote | `gridcraft-cli mcp --connect 7979` | A running app started with `gridcraft --control 7979` (TCP JSON lines on `127.0.0.1`, authenticated with the app's token: it is read from the app's token file or `GRIDCRAFT_CONTROL_TOKEN`, see [`control-protocol.md`](control-protocol.md)). |
| Live (default) | `gridcraft-cli mcp` | The open GridCraft window while AI agents may use it (below), otherwise a session without a window. |
| Headless | `gridcraft-cli mcp --headless [--in book.xlsx \| --sample budget]` | An in-process engine session, no window. `--in` and `--sample` always run headless. |
| Remote (deprecated) | `gridcraft-cli mcp --connect 7979` | A running app started with `gridcraft --control 7979`, reached with the same challenge handshake (see [`control-protocol.md`](control-protocol.md)). Prints a deprecation line on stderr; it will be removed in a later release. |
## Claude Code
## Agents in the open window
```sh
claude mcp add gridcraft -- gridcraft-cli mcp
# or drive the desktop app you are looking at:
claude mcp add gridcraft-app -- gridcraft-cli mcp --connect 7979
```
One switch serves every Craft app: **ArtCraft Launcher › Settings › AI agents › Let AI agents use
Craft apps** (with the suite's `AI-MCP` flag on). The launcher adds one `ArtCraft` entry to the MCP
clients it knows; GridCraft itself writes no client configuration.
JSON config (`.mcp.json`, Claude Desktop, other clients):
While the switch names GridCraft, the open window serves its control channel on loopback and
publishes `agent-connection.json` in its settings folder (`%APPDATA%\GridCraft`,
`~/Library/Application Support/GridCraft`, `~/.config/gridcraft`): the port, the process id and the
token file (`agent-control.token`, readable by its owner only). Plain `gridcraft-cli mcp` reads that file
before every tool call, so the client's configuration holds no port and no token, and the app may
start, quit or move to another port while the client stays connected. The client authenticates the
window first (`auth.challenge`): the window proves it holds the token before the client sends its
own proof, and the token never crosses the wire. When the switch turns off, the window stops
listening and removes the file at once, without a restart; a file a crashed run left is removed
at the next start.
**File › Options › Agents** shows where the link stands, the control port (0 picks a free one),
the folders agents may open from and save to, and what `gridcraft-cli mcp` does while GridCraft is
closed: start it and wait (the default), use a session without a window with the agent folders, or
report that GridCraft isn't running. `--when-closed launch|headless|error` overrides that choice for
one MCP session. A session that went headless stays headless, so workbooks don't move under the
agent. The settings are kept in `agents.json` in the settings folder; agents can't change them
(`options.agents` refuses an agent request).
Agent requests are confined to the agent folders, in the window as in a headless session: the
folders set on the Agents page, or `Documents/ArtCraft/Agents/GridCraft` (created when used) for an
empty one. Opening or saving outside them, and a screenshot outside the write folder, is refused
with the reason. Input an agent sends (`ui.key`, `ui.click`, `ui.text`, …) is applied in later
frames; until it has all been applied, those frames run with the agent folders too, so a Ctrl+S or
an edit on the Agents page sent by an agent can't save outside them or widen them. What the person
does in the window is otherwise not confined. With agents let in but no usable folder (the default
agent folder can't be made), nothing may be opened or saved. The `agent_folders` tool tells the
agent which folders those are, as the window really opened them. With the switch off, `gridcraft-cli mcp` serves a session
without a window with only the folders given to the command (see below), as it always did.
`--control PORT` runs the same server for the whole run (scripts, tests), confined the same way (to
the agent folders, or to `--automation-read-root` / `--automation-write-root` on the desktop app);
the Agents page then says the launch options manage the connection.
## MCP clients
With the ArtCraft Launcher, turn on its AI agents switch: it registers the suite once. Without it,
add `gridcraft-cli mcp` as a stdio server in the client's MCP settings:
```json
{
@@ -32,8 +68,8 @@ JSON config (`.mcp.json`, Claude Desktop, other clients):
}
```
Use `"args": ["mcp", "--connect", "7979"]` for the desktop app, or `["mcp", "--in", "/path/book.xlsx"]` to start
with a file open.
Use `["mcp", "--headless", "--in", "/path/book.xlsx"]` to start a session without a window with a
file open.
## Tools
@@ -55,11 +91,12 @@ with a file open.
| `filter` | `column`, `range?`, `values?`, `custom?`, `top?`, `blanks?`, `clear?` | `data.filterBy` (turns AutoFilter on when needed). |
| `open_workbook` / `save_workbook` / `new_workbook` | `path` / `path?` / `sample?` | Files (`.xlsx`, `.csv`, `.tsv`, `.json`, `.html`). |
| `undo` / `redo` | `steps?` | History. |
| `screenshot` | `path` | PNG of the window (Remote only). |
| `screenshot` | `path` | PNG of the window (the open window only; inside the write folder for agents). |
| `list_functions` | `search?`, `category?` | Worksheet functions with signatures. |
| `agent_folders` | | `read_folder` and `write_folder`: where this session's file commands may open and save (`null`: none). |
Every tool that acts on a workbook (all but `list_commands`, `list_functions`, `list_windows`, `open_workbook`,
`new_workbook` and `screenshot`) also takes `window` or `doc`, an id from `list_windows`, and acts in that window
`new_workbook`, `screenshot` and `agent_folders`) also takes `window` or `doc`, an id from `list_windows`, and acts in that window
(for `doc`, the workbook's most recent window) without bringing it forward. Without them it acts in the active window.
Results are one text block holding pretty JSON; failures set `isError: true` with a readable message. Unknown tools,
@@ -87,6 +124,84 @@ methods `-32601`.
## Embedding
`gridcraft-mcp` is a library: `Server::new(Box::new(Headless::new()))` or
`Server::new(Box::new(Remote::connect(&control_addr("7979"))?))`, then `Server::serve(stdin, stdout)` or
`Server::new(Box::new(gridcraft_mcp::agents::control_window("7979")?))`, then `Server::serve(stdin, stdout)` or
`Server::handle_line(line) -> Option<String>`. Implement the `Backend` trait (`call(method, params)`) to drive another
host.
## Restrict file access to a folder
Use the in-process server with read and write folders chosen by the operator. For
example, keep inputs readable and allow outputs only in a nested directory:
```sh
gridcraft-cli mcp --headless --automation-read-root /path/to/project --automation-write-root /path/to/project/_artcraft
```
These folders apply to sessions without a window. Without `--headless`, while agents may use an
open GridCraft window, calls go to that window, which uses the folders of its Agents page instead.
Both folders must already exist. Give the same folder to both options if read and
write access should have the same boundary; sibling folders also work. The CLI
uses the separate root flags from DeckCraft and VectorCraft, without a `--root`
alias. Relative paths keep their working-directory-based meaning.
Each access root grants its direction of file access and an omitted one denies it, as in
every Craft app: with no root options, a session without a window opens and saves nothing (the
`--in FILE` the command names is still opened, before that applies). The startup message and MCP
initialization say which policy is active.
Relative paths are relative to the server's working directory, and still have to
resolve inside the corresponding root. Roots must exist and be directories.
Duplicate root flags and empty roots are errors. Both `--automation-read-root DIR`
and `--automation-read-root=DIR` are accepted (likewise for the write root).
The checks apply before `--in FILE` is opened and at the engine's file I/O
boundary: workbook open/save, CSV and text import, picture import, CSV/HTML/PDF
export, `file.print` with a path, implicit Save to the workbook's current path,
and the temporary path used for atomic saving. `execute_command` and nested
commands use the same checks. Returning workbook/PDF bytes without writing a path
still works in read-only mode. Resolving symlinks and comparing whole path
components rejects traversal outside the root and similarly named sibling
folders. Canonical components are compared exactly; Unicode case folding never
widens a root. Dangling links are refused.
Root flags cannot be combined with `--connect`: a `--control` app applies its own folders
(given to the desktop app), so the CLI refuses that configuration rather than advertising a
restriction it cannot apply. This is a file policy for the
headless MCP server, not an OS sandbox. Native roots capture open directory handles
from the operator-selected paths before resolving their canonical names. A root
name swapped during initialization cannot replace the captured directory authority.
After resolving and checking a path, reads open it relative to the retained read
root. Saves pin the authorized parent directory, then create a fresh temporary
file exclusively and rename it through that same handle. Replacing a checked
path component with a symlink cannot redirect these operations outside the root.
A pre-existing `.sctmp` file or symlink is left untouched and does not block a save.
The parent directory is an authorized object: a later rename of that directory
does not revoke its open handle. Hard links, other local programs' own access,
and a process-wide OS sandbox remain outside this document-I/O policy.
The canonical path policy follows the implementation accepted in
[DeckCraft #247](https://github.com/storytold/deckcraft/pull/247); the additional
native handle-based I/O uses `cap-std`, with native-only `getrandom` temporary names.
On macOS and Linux the component-containment rule is equivalent. On Windows GridCraft
compares canonical components exactly rather than applying Unicode lowercasing,
so distinct directories on case-sensitive volumes cannot be conflated. A casing
mismatch can conservatively refuse access. Windows path display also preserves
non-Unicode paths and strips only recognised verbatim disk/UNC prefixes. Native
Windows validation is still needed.
Example MCP client configuration:
```json
{
"mcpServers": {
"gridcraft": {
"command": "/path/to/gridcraft-cli",
"args": ["mcp", "--headless", "--automation-read-root", "/path/to/project", "--automation-write-root", "/path/to/project/_artcraft"]
}
}
}
```
This implementation adapts Isaac Levine's [PR #480](https://github.com/storytold/gridcraft/pull/480) and additionally checks the
initial `--in` file and the atomic-save temporary path, and covers the current
command layout. Related issues: #445 and #2172.
+5 -1
View File
@@ -116,6 +116,9 @@ echo "==> assembling $APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
cp "$WORK/bin/gridcraft" "$APP/Contents/MacOS/GridCraft"
# The CLI too, beside the app: the ArtCraft Launcher finds `gridcraft-cli` next to the app's
# executable and registers `gridcraft-cli mcp` for agents.
cp "$WORK/bin/gridcraft-cli" "$APP/Contents/MacOS/gridcraft-cli"
cp "$ROOT/assets/app-icon/gridcraft.icns" "$APP/Contents/Resources/GridCraft.icns"
# Bundled dependency font notices are installed before the app is signed.
cp "$ROOT/NOTICE" "$ROOT/ATTRIBUTION.md" "$APP/Contents/Resources/"
@@ -128,7 +131,8 @@ plutil -lint "$APP/Contents/Info.plist"
printf 'APPL????' >"$APP/Contents/PkgInfo"
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
# The bundled CLI is nested executable code; sign it before sealing the app bundle.
sign --options runtime --identifier ai.storyteller.gridcraft-cli "$APP/Contents/MacOS/gridcraft-cli"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/GridCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"