mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-05 12:07:17 -06:00
Compare commits
30
Commits
@@ -8,7 +8,7 @@ workflows:
|
||||
'.github/workflows/house-rules.yml': []
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
@@ -16,7 +16,7 @@ workflows:
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/release.yml': []
|
||||
'.github/workflows/sonarcloud.yml': []
|
||||
'.github/workflows/windows-arm64.yml': []
|
||||
@@ -26,8 +26,8 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'step-security/harden-runner@v2.23.0':
|
||||
ref: 'v2.23.0'
|
||||
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
|
||||
'step-security/harden-runner@v2.22.4':
|
||||
ref: 'v2.22.4'
|
||||
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
|
||||
owner_id: 88700172
|
||||
repo_id: 422287306
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
Generated
+197
-6
@@ -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,10 +3164,13 @@ dependencies = [
|
||||
name = "gridcraft-ui-egui"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-print",
|
||||
"craft-quit",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -3244,6 +3365,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 +3801,7 @@ dependencies = [
|
||||
"byteorder-lite",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -3711,6 +3841,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 +4213,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 +4319,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 +5272,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 +5959,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 +6966,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
@@ -8082,6 +8263,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"
|
||||
|
||||
@@ -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
|
||||
@@ -105,6 +110,7 @@ craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -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
|
||||
@@ -304,6 +304,8 @@ emerge --ask app-office/gridcraft-bin
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Current prebuilt FreeBSD downloads require FreeBSD 15.1 or later; they are not compatible with FreeBSD 14.x.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `gridcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
+21
@@ -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 |
|
||||
|
||||
@@ -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
@@ -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");
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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()];
|
||||
|
||||
@@ -810,6 +810,7 @@ fn arrays_do_not_spill_in_tables() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
t.set("C4", "=SEQUENCE(2)");
|
||||
t.set("E1", "=SEQUENCE(4)");
|
||||
@@ -839,6 +840,7 @@ fn one_value_array_in_a_table_is_not_a_spill() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
};
|
||||
let mut t = T::new();
|
||||
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
|
||||
@@ -1569,6 +1571,7 @@ fn subtotal_skips_filtered_rows() {
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
}],
|
||||
style: String::new(),
|
||||
@@ -1580,6 +1583,7 @@ fn subtotal_skips_filtered_rows() {
|
||||
filter: crit(),
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
|
||||
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -72,9 +72,19 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Query field identity follows the surviving physical column, even if its header was renamed.
|
||||
let query_field_id = c.checked_sub(old.start.col).and_then(|i| old_cols.get(i as usize)).and_then(|x| x.query_field_id);
|
||||
cols.push(match existing {
|
||||
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
|
||||
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
Some(x) => TableColumn { name: name.clone(), query_field_id, ..x.clone() },
|
||||
None => TableColumn {
|
||||
name: name.clone(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id,
|
||||
xml: None,
|
||||
},
|
||||
});
|
||||
}
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
|
||||
@@ -413,7 +413,15 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
totals_row: false,
|
||||
columns: headers
|
||||
.iter()
|
||||
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|h| TableColumn {
|
||||
name: h.clone(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
@@ -424,6 +432,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let q = gridcraft_formula::quote_sheet(&sheet_name);
|
||||
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
|
||||
|
||||
@@ -112,7 +112,15 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
totals_row: false,
|
||||
columns: names
|
||||
.into_iter()
|
||||
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|n| TableColumn {
|
||||
name: n,
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style,
|
||||
banded_rows: true,
|
||||
@@ -123,6 +131,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
cx.structural = true;
|
||||
Ok(json!({"table": name, "range": r.a1()}))
|
||||
|
||||
@@ -958,6 +958,7 @@ fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, inse
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
t.columns.insert((idx + k).min(t.columns.len()), col);
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -904,6 +904,7 @@ mod tests {
|
||||
filter: Vec::new(),
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)];
|
||||
let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None };
|
||||
|
||||
@@ -695,6 +695,7 @@ fn grow_right(
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
});
|
||||
cx.rebuild_deps = true;
|
||||
|
||||
@@ -600,8 +600,15 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let col =
|
||||
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
let col = |name: &str| TableColumn {
|
||||
name: name.into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
sh.tables.push(Table {
|
||||
id: 1,
|
||||
name: "LeftTable".into(),
|
||||
@@ -618,6 +625,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.tables.push(Table {
|
||||
id: 2,
|
||||
@@ -635,6 +643,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(2).or_default().hidden = true;
|
||||
|
||||
@@ -55,6 +55,31 @@ fn resize_next_to_another_table_still_works() {
|
||||
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_keeps_a_renamed_column_query_field() {
|
||||
let mut s = table();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let si = d.wb.active_sheet();
|
||||
std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns[1].query_field_id = Some(7);
|
||||
s.execute("range.setValues", json!({"range":"B1", "values":[["Amount"]]})).unwrap();
|
||||
s.execute("table.resize", json!({"table":"T", "range":"A1:B3"})).unwrap();
|
||||
let col = &s.doc().unwrap().wb.active().unwrap().tables[0].columns[1];
|
||||
assert_eq!((col.name.as_str(), col.query_field_id), ("Amount", Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_preserves_query_fields_only_for_surviving_addresses() {
|
||||
let mut s = table();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let si = d.wb.active_sheet();
|
||||
let columns = &mut std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns;
|
||||
columns[0].query_field_id = Some(3);
|
||||
columns[1].query_field_id = Some(7);
|
||||
s.execute("table.resize", json!({"table":"T", "range":"B1:C3"})).unwrap();
|
||||
let cols = &s.doc().unwrap().wb.active().unwrap().tables[0].columns;
|
||||
assert_eq!(cols.iter().map(|c| c.query_field_id).collect::<Vec<_>>(), [Some(7), None]);
|
||||
}
|
||||
|
||||
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
|
||||
s.doc().unwrap().wb.active().unwrap()
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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();
|
||||
|
||||
@@ -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}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,10 @@ pub struct TableColumn {
|
||||
/// `uniqueName`: the name XML maps know the column by.
|
||||
#[serde(default)]
|
||||
pub unique_name: Option<String>,
|
||||
/// `queryTableFieldId`: the field of the table's query table this column shows. It moves with
|
||||
/// the column; inserted columns have none.
|
||||
#[serde(default)]
|
||||
pub query_field_id: Option<u32>,
|
||||
/// Binding to an element of an XML map. It moves with the column and goes when the column is
|
||||
/// deleted; inserted columns are unmapped.
|
||||
#[serde(default)]
|
||||
@@ -102,6 +106,10 @@ pub struct Table {
|
||||
/// The connection (`xl/connections.xml`) an XML table is bound through.
|
||||
#[serde(default)]
|
||||
pub connection_id: Option<u32>,
|
||||
/// The XML of the table's query table part (`xl/queryTables/…`), kept as read so the table
|
||||
/// stays attached to its data connection. Never refreshed.
|
||||
#[serde(default)]
|
||||
pub query_table: Option<String>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
|
||||
@@ -16,6 +16,7 @@ craft-behavior = { workspace = true }
|
||||
craft-host = { workspace = true }
|
||||
craft-keymap = { workspace = true }
|
||||
craft-print = { workspace = true }
|
||||
craft-quit = { workspace = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
gridcraft-engine = { workspace = true }
|
||||
@@ -46,6 +47,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 }
|
||||
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
@@ -93,6 +105,7 @@ impl SheetApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: Default::default(),
|
||||
framework_dialogs: Default::default(),
|
||||
unsaved_prompt: None,
|
||||
framework_host: crate::framework::host(),
|
||||
}
|
||||
}
|
||||
@@ -114,6 +127,9 @@ impl SheetApp {
|
||||
|
||||
/// Per-frame logic (control channel, screenshots). Call before `ui`.
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
// A completed answer wins over a concurrent forced close; otherwise retire an orphan.
|
||||
self.take_unsaved_changes_dialog(ctx);
|
||||
self.retire_closed_unsaved_prompt(ctx);
|
||||
self.ensure_text_width(ctx);
|
||||
// A keytip control request lives one frame: the ribbon consumes it during `ui`, and
|
||||
// anything that never reached a control (collapsed ribbon, tab switch) is dropped. One
|
||||
@@ -141,6 +157,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);
|
||||
@@ -205,6 +223,9 @@ impl SheetApp {
|
||||
let t0 = now_ms();
|
||||
// A script may have switched windows since the last frame.
|
||||
self.follow_active_window();
|
||||
// The window this pass draws: a command run in it may switch to another window, which draws
|
||||
// in its own pass.
|
||||
let drawn = self.ui_window();
|
||||
// This window's key tip request that waited for this frame (its tab or ribbon was just
|
||||
// shown); any other window's request was dropped before it.
|
||||
self.ui.keytip_invoke = self.ui.keytip_invoke_next.take();
|
||||
@@ -267,10 +288,13 @@ impl SheetApp {
|
||||
widgets::toast(self, &ctx);
|
||||
// Last, so its resize cursors win over the widgets under the window edges.
|
||||
ribbon::window_frame(self, &ctx);
|
||||
// The update flow and the framework dialogs run once per frame, in the root window.
|
||||
// The update flow runs once per frame, in the root window; the framework dialogs too, unless
|
||||
// the unsaved-changes question asks about a workbook in another window: they show there.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::show(self, &ctx);
|
||||
}
|
||||
if self.framework_dialogs_here(&ctx, drawn) {
|
||||
self.run_framework_dialogs(ui);
|
||||
}
|
||||
self.flush_viewport_commands(&ctx);
|
||||
@@ -302,6 +326,18 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a modal question is up and owns the keyboard: a GridCraft dialog or the shared
|
||||
/// unsaved-changes question.
|
||||
pub fn modal_open(&self) -> bool {
|
||||
self.dialog.is_some() || self.unsaved_prompt.is_some()
|
||||
}
|
||||
|
||||
/// The name of the open dialog, for automation: a GridCraft dialog's, or `saveChanges` while
|
||||
/// the shared unsaved-changes question is up.
|
||||
pub fn open_dialog_name(&self) -> Option<&str> {
|
||||
self.dialog.as_ref().map(|d| d.name()).or_else(|| self.unsaved_prompt.as_ref().map(|_| "saveChanges"))
|
||||
}
|
||||
|
||||
/// Current selection's top-left cell text as A1 (for the Name Box).
|
||||
pub fn name_box_text(&self) -> String {
|
||||
let Some(d) = self.session.active() else { return String::new() };
|
||||
|
||||
@@ -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}))
|
||||
@@ -335,7 +336,7 @@ impl SheetApp {
|
||||
"ui.dialog" => {
|
||||
let name = p.get("name").and_then(Json::as_str).unwrap_or("");
|
||||
self.open_dialog(name, p.clone());
|
||||
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
|
||||
Ok(json!({"dialog": self.open_dialog_name()}))
|
||||
}
|
||||
"ui.selectionMode" => {
|
||||
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
|
||||
@@ -481,6 +482,7 @@ impl SheetApp {
|
||||
}
|
||||
// The notice AutoSave holds back with: Save asks what the notice says.
|
||||
"saveLoss" => self.run_or_alert("file.save", json!({})),
|
||||
"saveChanges" => self.open_unsaved_changes(¶ms),
|
||||
// File › Options (`file.options`) and the File tab itself open the Backstage view.
|
||||
"options" => self.open_backstage(backstage::Page::Options),
|
||||
"backstage" => {
|
||||
@@ -527,3 +529,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()}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -4,7 +4,7 @@ impl SheetApp {
|
||||
pub(super) fn ribbon_keys(&mut self, ctx: &egui::Context) {
|
||||
let before = self.keytips.prefix().map(str::to_string);
|
||||
let enabled = self.editor.is_none()
|
||||
&& self.dialog.is_none()
|
||||
&& !self.modal_open()
|
||||
&& self.message.is_none()
|
||||
&& self.name_box.is_none()
|
||||
&& !ctx.text_edit_focused()
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use craft_quit::{CloseAnswer, CloseScope};
|
||||
use craft_ui::dialog::{DialogResult, UnsavedAnswer, UnsavedChangesDialog};
|
||||
use craft_ui::shell::embed::CloseDecision;
|
||||
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
|
||||
|
||||
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
|
||||
use crate::state::UnsavedPrompt;
|
||||
|
||||
impl SheetApp {
|
||||
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
|
||||
@@ -31,12 +34,11 @@ impl SheetApp {
|
||||
if !self.session.documents().iter().any(|d| d.is_dirty()) {
|
||||
return CloseDecision::Close;
|
||||
}
|
||||
match self.dialog.as_mut() {
|
||||
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
|
||||
// Already asking about a workbook (File › Close): answering it now goes on to quit.
|
||||
Some(d) if d.name() == "saveChanges" => {
|
||||
d.values.insert("quit".into(), json!(true));
|
||||
}
|
||||
_ => self.continue_quit(ctx),
|
||||
self.promote_unsaved_to_quit();
|
||||
} else {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
CloseDecision::Hold
|
||||
}
|
||||
@@ -233,13 +235,107 @@ impl SheetApp {
|
||||
crate::macro_editor::request_close(self, true);
|
||||
return;
|
||||
}
|
||||
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
|
||||
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
|
||||
// Already asking about a workbook (File › Close): answering it goes on to quit.
|
||||
d.values.insert("quit".into(), json!(true));
|
||||
self.promote_unsaved_to_quit();
|
||||
return;
|
||||
}
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
|
||||
/// Opens the shared unsaved-changes dialog on `framework_dialogs` for the active workbook.
|
||||
pub(crate) fn open_unsaved_changes(&mut self, params: &Json) {
|
||||
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
|
||||
self.message = Some((
|
||||
"Macro".into(),
|
||||
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
if let Some(mut old) = self.dialog.take() {
|
||||
let _ = old.end_pick(self);
|
||||
}
|
||||
let Some(doc) = self.session.active().map(|d| d.uid) else { return };
|
||||
let title = params
|
||||
.get("title")
|
||||
.and_then(Json::as_str)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| self.session.active().map(|d| d.display_title()))
|
||||
.unwrap_or_else(|| "this workbook".into());
|
||||
let quitting = params.get("quit").and_then(Json::as_bool) == Some(true);
|
||||
let scope = if quitting { CloseScope::Quit } else { CloseScope::Close };
|
||||
self.unsaved_prompt = Some(UnsavedPrompt { doc, window: self.ui_window(), quitting });
|
||||
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
|
||||
// A replaced question leaves a Cancel result; it is not the new question's answer.
|
||||
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
|
||||
}
|
||||
|
||||
fn promote_unsaved_to_quit(&mut self) {
|
||||
if let Some(prompt) = self.unsaved_prompt.as_mut()
|
||||
&& !prompt.quitting
|
||||
{
|
||||
prompt.quitting = true;
|
||||
let title =
|
||||
self.session.documents().iter().find(|d| d.uid == prompt.doc).map(|d| d.display_title()).unwrap_or_else(|| "this workbook".into());
|
||||
self.framework_dialogs.open(UnsavedChangesDialog::new(CloseScope::Quit, title).document_wording(true));
|
||||
// The question it replaced left a Cancel as its result; it was not answered, and the
|
||||
// quit's question asks on.
|
||||
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
|
||||
}
|
||||
}
|
||||
|
||||
/// A forced close can remove the workbook and its window while the question is open. Retire
|
||||
/// that question and continue a pending quit without applying its answer to another workbook.
|
||||
pub(crate) fn retire_closed_unsaved_prompt(&mut self, ctx: &egui::Context) {
|
||||
let Some(prompt) = self.unsaved_prompt.as_ref() else { return };
|
||||
if self.session.documents().iter().any(|doc| doc.uid == prompt.doc) {
|
||||
return;
|
||||
}
|
||||
let quitting = prompt.quitting;
|
||||
self.unsaved_prompt = None;
|
||||
self.framework_dialogs.cancel::<UnsavedChangesDialog>(ctx);
|
||||
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
|
||||
if quitting {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the answer from an open [`UnsavedChangesDialog`] and continues closing or quitting.
|
||||
pub(crate) fn take_unsaved_changes_dialog(&mut self, ctx: &egui::Context) {
|
||||
let Some(result) = self.framework_dialogs.take::<UnsavedChangesDialog>() else {
|
||||
return;
|
||||
};
|
||||
let Some(prompt) = self.unsaved_prompt.take() else {
|
||||
return;
|
||||
};
|
||||
let answer = match result {
|
||||
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::DontSave, .. }) => SaveAnswer::DontSave,
|
||||
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Save, .. }) => SaveAnswer::Save,
|
||||
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Cancel, .. }) | DialogResult::Cancel | _ => SaveAnswer::Cancel,
|
||||
};
|
||||
if answer == SaveAnswer::Cancel {
|
||||
return;
|
||||
}
|
||||
if let Some(w) = prompt.window.filter(|w| self.session.window(*w).is_some())
|
||||
&& self.ui_window() != Some(w)
|
||||
{
|
||||
self.enter_window(w);
|
||||
}
|
||||
if self.session.active().map(|d| d.uid) != Some(prompt.doc) {
|
||||
// A completed answer for a workbook closed in the same frame cannot apply to the
|
||||
// replacement workbook; a pending quit still needs to ask about what remains.
|
||||
if prompt.quitting && !self.session.documents().iter().any(|doc| doc.uid == prompt.doc) {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !self.answer_save_changes(answer, prompt.quitting, ctx) {
|
||||
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
|
||||
let scope = if prompt.quitting { CloseScope::Quit } else { CloseScope::Close };
|
||||
self.unsaved_prompt = Some(prompt);
|
||||
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -258,7 +258,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
});
|
||||
bs.text_edit_focused = ctx.text_edit_focused();
|
||||
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
|
||||
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
|
||||
out.close = true;
|
||||
}
|
||||
if let Some(page) = out.page {
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -147,7 +147,8 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
|
||||
"grid": app.grid.cells_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
|
||||
"scroll": [v.scroll.x, v.scroll.y],
|
||||
"editor": app.editor.as_ref().map(|e| editor_json(app, e)),
|
||||
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab})),
|
||||
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab}))
|
||||
.or_else(|| app.unsaved_prompt.as_ref().map(|p| json!({"name": "saveChanges", "values": {"quit": p.quitting}}))),
|
||||
"backstage": app.backstage.as_ref().map(|b| b.page.id()),
|
||||
"message": app.message.as_ref().map(|(t, m)| json!({"title": t, "text": m})),
|
||||
"selectedObject": app.selected_object,
|
||||
@@ -279,6 +280,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}"),
|
||||
@@ -339,7 +345,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
}
|
||||
"ui.dialog" => {
|
||||
app.open_dialog(s("name").unwrap_or(""), p.clone());
|
||||
ok(json!({"dialog": app.dialog.as_ref().map(|d| d.name.clone())}))
|
||||
ok(json!({"dialog": app.open_dialog_name()}))
|
||||
}
|
||||
"ui.dialog.set" => match app.dialog.as_mut() {
|
||||
Some(d) => {
|
||||
@@ -534,7 +540,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 +549,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 +675,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 +747,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,
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1166,7 +1166,6 @@ impl Dialog {
|
||||
"formatControl" => return crate::control_ui::open_format(app, ¶ms),
|
||||
"controlQuestion" => return crate::control_ui::open_question(¶ms),
|
||||
"saveCopy" => Dialog::custom("saveCopy", "Save a Copy", json!({"format": p("format")})),
|
||||
"saveChanges" => Dialog::custom("saveChanges", "Save Changes?", json!({"title": p("title"), "quit": p("quit")})),
|
||||
"start" => Dialog::custom("start", "GridCraft", json!({})),
|
||||
"comments" => {
|
||||
app.grid.pane = None;
|
||||
|
||||
@@ -374,19 +374,6 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
"saveChanges" => {
|
||||
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
|
||||
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
|
||||
ui.horizontal(|ui| {
|
||||
for (label, answer) in
|
||||
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
|
||||
{
|
||||
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
"saveLoss" => {
|
||||
let lang = app.ui.language;
|
||||
let pending = d.pending_save();
|
||||
|
||||
@@ -529,7 +529,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
|
||||
let chars_before = ed.text.chars().count();
|
||||
// A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the
|
||||
// editor takes it back afterwards.
|
||||
let dialog_open = app.dialog.is_some();
|
||||
let dialog_open = app.modal_open();
|
||||
if dialog_open && mine {
|
||||
ed.request_focus = true;
|
||||
ed.keep_selection = true;
|
||||
@@ -671,7 +671,7 @@ fn editor_shortcuts(
|
||||
) -> EditorKeyOutcome {
|
||||
let mut outcome = EditorKeyOutcome { action: None, arrow: false, cancel: false, to_python: false };
|
||||
// A message or dialog owns Enter and Escape until it closes.
|
||||
if !has_focus || !mine || app.message.is_some() || app.dialog.is_some() {
|
||||
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
|
||||
return outcome;
|
||||
}
|
||||
// Ctrl+Alt+Shift+P turns the edit into Python code.
|
||||
@@ -864,7 +864,7 @@ fn python_editor(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, width: f32
|
||||
let Some(mut ed) = app.editor.take() else { return EditorInfo::default() };
|
||||
// A message box (the code was refused) or a dialog over the edit has the keyboard; the
|
||||
// editor takes it back when it closes.
|
||||
let blocked = app.message.is_some() || app.dialog.is_some();
|
||||
let blocked = app.message.is_some() || app.modal_open();
|
||||
let mut caret = None;
|
||||
if blocked {
|
||||
ed.request_focus = true;
|
||||
|
||||
@@ -112,9 +112,22 @@ impl SheetApp {
|
||||
embed::logic(ctx, || self.close_decision(ctx));
|
||||
}
|
||||
|
||||
/// Whether this pass draws [`SheetApp::framework_dialogs`]: the pass of the window the unsaved-changes
|
||||
/// question asks about (the window that keeps it, as a GridCraft dialog stays in its window), else the root's.
|
||||
/// `drawn` is the window the pass began drawing: a question a command in it opened for another window (a quit
|
||||
/// moving on to the next unsaved workbook) shows in that window's own pass, not for a frame in this one.
|
||||
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context, drawn: Option<u64>) -> bool {
|
||||
let shown = |w: &u64| self.session.window(*w).is_some_and(|w| !w.hidden);
|
||||
match self.unsaved_prompt.as_ref().and_then(|p| p.window).filter(shown) {
|
||||
Some(w) => drawn == Some(w),
|
||||
None => ctx.viewport_id() == egui::ViewportId::ROOT,
|
||||
}
|
||||
}
|
||||
|
||||
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
|
||||
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
|
||||
self.framework_dialogs.run(ui);
|
||||
self.take_unsaved_changes_dialog(ui.ctx());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response
|
||||
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
|
||||
// arrow key would move the selection the menu fills from), and a macro's question.
|
||||
editing
|
||||
|| app.dialog.is_some()
|
||||
|| app.modal_open()
|
||||
|| other_focus
|
||||
|| app.message.is_some()
|
||||
|| app.grid.filter_menu.is_some()
|
||||
|
||||
@@ -328,7 +328,7 @@ pub(super) fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo,
|
||||
app.grid.fill_tag = None;
|
||||
return;
|
||||
}
|
||||
if app.editor.is_some() || app.dialog.is_some() || app.grid.drag != Drag::None {
|
||||
if app.editor.is_some() || app.modal_open() || app.grid.drag != Drag::None {
|
||||
return;
|
||||
}
|
||||
let size = vec2(18.0, 18.0);
|
||||
@@ -471,7 +471,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
/// The warning button beside an active cell holding a number stored as text, as in Excel: its
|
||||
/// menu names the problem and offers Convert to Number for the selection (#1994).
|
||||
pub(super) fn error_check_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
|
||||
if app.editor.is_some() || app.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
|
||||
if app.editor.is_some() || app.modal_open() || sh.show_formulas || app.grid.drag != Drag::None {
|
||||
return;
|
||||
}
|
||||
let Some(active) = app.session.active().map(|d| d.selection.active) else { return };
|
||||
|
||||
@@ -171,6 +171,7 @@ fn filter_menu_uses_the_table_whose_header_was_clicked() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
};
|
||||
let mut sh = Sheet::new("S");
|
||||
sh.tables.push(table(1, 0, 2));
|
||||
|
||||
@@ -574,7 +574,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Zoom Out" => "Σμίκρυνση",
|
||||
"Dismiss" => "Κλείσιμο",
|
||||
"OK" => "Εντάξει",
|
||||
"Don't Save" => "Χωρίς αποθήκευση",
|
||||
"Open…" => "Άνοιγμα…",
|
||||
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
|
||||
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
|
||||
@@ -583,7 +582,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Βαθμολόγιο",
|
||||
"this workbook" => "αυτό το βιβλίο εργασίας",
|
||||
"This workbook" => "Αυτό το βιβλίο εργασίας",
|
||||
"Do you want to save the changes you made to {title}?" => "Θέλετε να αποθηκεύσετε τις αλλαγές που κάνατε στο {title};",
|
||||
"Save a copy as .{format}" => "Αποθήκευση αντιγράφου ως .{format}",
|
||||
"Select a chart first." => "Επιλέξτε πρώτα ένα γράφημα.",
|
||||
"Row Height" => "Ύψος γραμμής",
|
||||
@@ -624,7 +622,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Τοποθέτηση εικόνας πάνω από κελιά",
|
||||
"Pick From List" => "Επιλογή από λίστα",
|
||||
"Save a Copy" => "Αποθήκευση αντιγράφου",
|
||||
"Save Changes?" => "Αποθήκευση αλλαγών;",
|
||||
"Shift cells right" => "Μετατόπιση κελιών προς τα δεξιά",
|
||||
"Shift cells down" => "Μετατόπιση κελιών προς τα κάτω",
|
||||
"Shift cells left" => "Μετατόπιση κελιών προς τα αριστερά",
|
||||
|
||||
@@ -445,7 +445,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Calculation settings are saved with the workbook." => "Le impostazioni di calcolo vengono salvate con la cartella di lavoro.",
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Annulla",
|
||||
"Don't Save" => "Non salvare",
|
||||
"Open…" => "Apri…",
|
||||
"Show password" => "Mostra password",
|
||||
"Start a new workbook" => "Crea una nuova cartella di lavoro",
|
||||
@@ -454,7 +453,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Registro dei voti",
|
||||
"this workbook" => "questa cartella di lavoro",
|
||||
"This workbook" => "Questa cartella di lavoro",
|
||||
"Do you want to save the changes you made to {title}?" => "Vuoi salvare le modifiche apportate a {title}?",
|
||||
"Save a copy as .{format}" => "Salva una copia come .{format}",
|
||||
"Select a chart first." => "Seleziona prima un grafico.",
|
||||
"Text Box" => "Casella di testo",
|
||||
@@ -505,7 +503,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Inserisci immagine sopra le celle",
|
||||
"Pick From List" => "Scegli dall'elenco",
|
||||
"Save a Copy" => "Salva una copia",
|
||||
"Save Changes?" => "Salvare le modifiche?",
|
||||
"Shift cells right" => "Sposta celle a destra",
|
||||
"Shift cells down" => "Sposta celle in basso",
|
||||
"Shift cells left" => "Sposta celle a sinistra",
|
||||
|
||||
@@ -462,7 +462,6 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("OK", "OK"),
|
||||
("Cancel", "キャンセル"),
|
||||
("Don't Save", "保存しない"),
|
||||
("Open…", "開く…"),
|
||||
("Show password", "パスワードの表示"),
|
||||
("Start a new workbook", "新しいブックの作成"),
|
||||
@@ -471,7 +470,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Gradebook", "成績表"),
|
||||
("this workbook", "このブック"),
|
||||
("This workbook", "このブック"),
|
||||
("Do you want to save the changes you made to {title}?", "{title} への変更を保存しますか?"),
|
||||
("Save a copy as .{format}", ".{format} としてコピーを保存"),
|
||||
("Select a chart first.", "先にグラフを選択してください。"),
|
||||
("Text Box", "テキスト ボックス"),
|
||||
@@ -522,7 +520,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Place Picture over Cells", "セルの上に画像を配置"),
|
||||
("Pick From List", "リストから選択"),
|
||||
("Save a Copy", "コピーを保存"),
|
||||
("Save Changes?", "変更を保存しますか?"),
|
||||
("Shift cells right", "セルを右に移動"),
|
||||
("Shift cells down", "セルを下に移動"),
|
||||
("Shift cells left", "セルを左に移動"),
|
||||
|
||||
@@ -436,7 +436,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Calculation settings are saved with the workbook." => "Ustawienia obliczeń są zapisywane razem ze skoroszytem.",
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Anuluj",
|
||||
"Don't Save" => "Nie zapisuj",
|
||||
"Open…" => "Otwórz…",
|
||||
"Show password" => "Pokaż hasło",
|
||||
"Start a new workbook" => "Utwórz nowy skoroszyt",
|
||||
@@ -445,7 +444,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Dziennik ocen",
|
||||
"this workbook" => "ten skoroszyt",
|
||||
"This workbook" => "Ten skoroszyt",
|
||||
"Do you want to save the changes you made to {title}?" => "Czy chcesz zapisać zmiany wprowadzone w pliku {title}?",
|
||||
"Save a copy as .{format}" => "Zapisz kopię jako .{format}",
|
||||
"Select a chart first." => "Najpierw zaznacz wykres.",
|
||||
"Text Box" => "Pole tekstowe",
|
||||
@@ -496,7 +494,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Umieść obraz na komórkach",
|
||||
"Pick From List" => "Wybierz z listy",
|
||||
"Save a Copy" => "Zapisz kopię",
|
||||
"Save Changes?" => "Zapisać zmiany?",
|
||||
"Shift cells right" => "Przesuń komórki w prawo",
|
||||
"Shift cells down" => "Przesuń komórki w dół",
|
||||
"Shift cells left" => "Przesuń komórki w lewo",
|
||||
|
||||
@@ -464,7 +464,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.",
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Cancelar",
|
||||
"Don't Save" => "Não Salvar",
|
||||
"Open…" => "Abrir…",
|
||||
"Show password" => "Mostrar senha",
|
||||
"Start a new workbook" => "Criar uma pasta de trabalho",
|
||||
@@ -473,7 +472,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Boletim de Notas",
|
||||
"this workbook" => "esta pasta de trabalho",
|
||||
"This workbook" => "Esta pasta de trabalho",
|
||||
"Do you want to save the changes you made to {title}?" => "Deseja salvar as alterações feitas em {title}?",
|
||||
"Save a copy as .{format}" => "Salvar uma cópia como .{format}",
|
||||
"Select a chart first." => "Selecione um gráfico primeiro.",
|
||||
"Text Box" => "Caixa de Texto",
|
||||
@@ -530,7 +528,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Colocar Imagem sobre as Células",
|
||||
"Pick From List" => "Escolher na Lista",
|
||||
"Save a Copy" => "Salvar uma Cópia",
|
||||
"Save Changes?" => "Salvar Alterações?",
|
||||
"Shift cells right" => "Deslocar células para a direita",
|
||||
"Shift cells down" => "Deslocar células para baixo",
|
||||
"Shift cells left" => "Deslocar células para a esquerda",
|
||||
|
||||
@@ -442,7 +442,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Calculation settings are saved with the workbook." => "Setările de calcul se salvează împreună cu registrul.",
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Anulare",
|
||||
"Don't Save" => "Nu salva",
|
||||
"Open…" => "Deschidere…",
|
||||
"Show password" => "Afișare parolă",
|
||||
"Start a new workbook" => "Începeți un registru nou",
|
||||
@@ -451,7 +450,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Catalog de note",
|
||||
"this workbook" => "acest registru",
|
||||
"This workbook" => "Acest registru",
|
||||
"Do you want to save the changes you made to {title}?" => "Doriți să salvați modificările făcute în {title}?",
|
||||
"Save a copy as .{format}" => "Salvare copie ca .{format}",
|
||||
"Select a chart first." => "Selectați mai întâi o diagramă.",
|
||||
"Text Box" => "Casetă de text",
|
||||
@@ -502,7 +500,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Plasare imagine peste celule",
|
||||
"Pick From List" => "Alegere din listă",
|
||||
"Save a Copy" => "Salvare copie",
|
||||
"Save Changes?" => "Salvați modificările?",
|
||||
"Shift cells right" => "Deplasare celule la dreapta",
|
||||
"Shift cells down" => "Deplasare celule în jos",
|
||||
"Shift cells left" => "Deplasare celule la stânga",
|
||||
|
||||
@@ -599,8 +599,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Display:" => "Отображать:",
|
||||
"Distributed" => "Распределённый",
|
||||
"Divide" => "Разделить",
|
||||
"Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?",
|
||||
"Don't Save" => "Не сохранять",
|
||||
"Double" => "Двойное",
|
||||
"Double Accounting" => "Двойное бухгалтерское",
|
||||
"Doughnut" => "Кольцевая",
|
||||
@@ -846,7 +844,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Rows" => "Строки",
|
||||
"Sample" => "Выборка",
|
||||
"Save (⌘S)" => "Сохранить (⌘S)",
|
||||
"Save Changes?" => "Сохранить изменения?",
|
||||
"Save a Copy" => "Сохранить копию",
|
||||
"Save a copy as .{format}" => "Сохранить копию как .{format}",
|
||||
"Scatter" => "Точечная",
|
||||
|
||||
@@ -440,7 +440,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Calculation settings are saved with the workbook." => "Параметри обчислень зберігаються разом із книгою.",
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Cancel",
|
||||
"Don't Save" => "Don't Save",
|
||||
"Open…" => "Open…",
|
||||
"Show password" => "Show password",
|
||||
"Start a new workbook" => "Start a new workbook",
|
||||
@@ -449,7 +448,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Gradebook",
|
||||
"this workbook" => "this workbook",
|
||||
"This workbook" => "This workbook",
|
||||
"Do you want to save the changes you made to {title}?" => "Do you want to save the changes you made to {title}?",
|
||||
"Save a copy as .{format}" => "Save a copy as .{format}",
|
||||
"Select a chart first." => "Спочатку виділіть діаграму.",
|
||||
"Text Box" => "Напис",
|
||||
@@ -500,7 +498,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Place Picture over Cells",
|
||||
"Pick From List" => "Pick From List",
|
||||
"Save a Copy" => "Save a Copy",
|
||||
"Save Changes?" => "Save Changes?",
|
||||
"Shift cells right" => "Shift cells right",
|
||||
"Shift cells down" => "Shift cells down",
|
||||
"Shift cells left" => "Shift cells left",
|
||||
|
||||
@@ -450,7 +450,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
// Dialogs, menus, context menus and tooltips.
|
||||
"OK" => "OK",
|
||||
"Cancel" => "Hủy",
|
||||
"Don't Save" => "Không lưu",
|
||||
"Open…" => "Mở…",
|
||||
"Show password" => "Hiện mật khẩu",
|
||||
"Start a new workbook" => "Bắt đầu sổ làm việc mới",
|
||||
@@ -459,7 +458,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Gradebook" => "Sổ điểm",
|
||||
"this workbook" => "sổ làm việc này",
|
||||
"This workbook" => "Sổ làm việc này",
|
||||
"Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?",
|
||||
"Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}",
|
||||
"Select a chart first." => "Hãy chọn một biểu đồ trước.",
|
||||
"Text Box" => "Hộp văn bản",
|
||||
@@ -510,7 +508,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Place Picture over Cells" => "Đặt ảnh đè lên các ô",
|
||||
"Pick From List" => "Chọn từ danh sách",
|
||||
"Save a Copy" => "Lưu bản sao",
|
||||
"Save Changes?" => "Lưu thay đổi?",
|
||||
"Shift cells right" => "Dịch các ô sang phải",
|
||||
"Shift cells down" => "Dịch các ô xuống dưới",
|
||||
"Shift cells left" => "Dịch các ô sang trái",
|
||||
|
||||
@@ -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,
|
||||
@@ -362,9 +396,11 @@ pub struct SheetApp {
|
||||
/// The update check, the startup prompt and a running self-update (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: updates_ui::Runtime,
|
||||
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
|
||||
/// after GridCraft's own UI in the root window's pass.
|
||||
/// The framework dialogs GridCraft keeps as values (the update dialogs and the unsaved-changes
|
||||
/// prompt), run once per frame after GridCraft's own UI in the root window's pass.
|
||||
pub framework_dialogs: craft_ui::dialog::DialogHost,
|
||||
/// Which workbook and window the open `UnsavedChangesDialog` is asking about.
|
||||
pub unsaved_prompt: Option<state::UnsavedPrompt>,
|
||||
/// Who GridCraft is to the framework's dialogs.
|
||||
framework_host: std::sync::Arc<craft_host::Host>,
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_quit::{CloseAnswer, CloseScope};
|
||||
use craft_ui::dialog::UnsavedChangesDialog;
|
||||
use egui::{Color32, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use gridcraft_engine::core::RangeRef;
|
||||
use gridcraft_engine::macros::policy::{Policy, macro_policy};
|
||||
@@ -1100,7 +1102,7 @@ fn ref_edit(app: &SheetApp, ui: &mut Ui, d: &mut Dialog, refs: &mut RefPick, key
|
||||
d.values.insert(key.into(), json!(s));
|
||||
}
|
||||
|
||||
/// Keep changes? (stopping a debugged run) and Save changes? (closing with unsaved edits).
|
||||
/// Keep changes? (stopping a debugged run) and the unsaved-changes question (closing with unsaved edits).
|
||||
fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut bool) {
|
||||
if ed.ask_stop {
|
||||
let mut answer: Option<Option<bool>> = None;
|
||||
@@ -1141,25 +1143,20 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
|
||||
return;
|
||||
}
|
||||
if ed.ask_close {
|
||||
let mut answer: Option<Option<bool>> = None;
|
||||
egui::Modal::new(Id::unique("gridcraft.macro_editor.close")).show(ctx, |ui| {
|
||||
ui.set_width(360.0);
|
||||
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
answer = Some(None);
|
||||
}
|
||||
if ui.button("Don't Save").clicked() {
|
||||
answer = Some(Some(false));
|
||||
}
|
||||
if ui.button("Save").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
answer = Some(Some(true));
|
||||
}
|
||||
});
|
||||
});
|
||||
// The shared unsaved-changes question, named for the macro. Each asking gets its own area,
|
||||
// so the question's own open state starts open every time it is asked.
|
||||
let scope = if ed.quit { CloseScope::Quit } else { CloseScope::Close };
|
||||
let asked = Id::unique("gridcraft.macro_editor.close");
|
||||
let opening = ctx.data(|d| d.get_temp::<u64>(asked)).unwrap_or_default();
|
||||
let shown = egui::Area::new(asked.with(opening))
|
||||
.order(egui::Order::Foreground)
|
||||
.show(ctx, |ui| UnsavedChangesDialog::new(scope, ed.draft.name.clone()).document_wording(true).show(ui));
|
||||
let answer = shown.inner.answer.map(|a| a.answer);
|
||||
if answer.is_some() {
|
||||
ctx.data_mut(|d| d.insert_temp(asked, opening + 1));
|
||||
}
|
||||
match answer {
|
||||
Some(Some(true)) => {
|
||||
Some(CloseAnswer::Save) => {
|
||||
ed.ask_close = false;
|
||||
if save(app, ed) {
|
||||
*open = false;
|
||||
@@ -1170,11 +1167,11 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
|
||||
ed.quit = false;
|
||||
}
|
||||
}
|
||||
Some(Some(false)) => {
|
||||
Some(CloseAnswer::DontSave) => {
|
||||
ed.ask_close = false;
|
||||
*open = false;
|
||||
}
|
||||
Some(None) => {
|
||||
Some(CloseAnswer::Cancel) => {
|
||||
ed.ask_close = false;
|
||||
ed.quit = false;
|
||||
ed.then_close = None;
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool {
|
||||
d.selection.ranges.len() > 1
|
||||
|| d.selection.current().is_single()
|
||||
|| app.editor.is_some()
|
||||
|| app.dialog.is_some()
|
||||
|| app.modal_open()
|
||||
|| app.text_box_editor.is_some()
|
||||
|| app.grid.context_menu.is_some()
|
||||
|| geo.paper.is_some()
|
||||
|
||||
@@ -19,6 +19,15 @@ pub enum SaveAnswer {
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// Which workbook and window an open [`craft_ui::dialog::UnsavedChangesDialog`] is asking about,
|
||||
/// and whether answering it goes on to quit.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UnsavedPrompt {
|
||||
pub doc: u64,
|
||||
pub window: Option<u64>,
|
||||
pub quitting: bool,
|
||||
}
|
||||
|
||||
/// How a save held back for an answer goes on.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum SaveRequest {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use craft_ui::dialog::UnsavedChangesDialog;
|
||||
use egui::{Context, RawInput, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
|
||||
use gridcraft_engine::{Session, core::CellRef, core::Value};
|
||||
use gridcraft_ui_egui::doc_windows::DocWindows;
|
||||
@@ -18,8 +19,8 @@ thread_local! {
|
||||
static INFOS: RefCell<egui::ViewportIdMap<ViewportInfo>> = RefCell::new(egui::ViewportIdMap::default());
|
||||
/// The viewport commands the app sent this frame.
|
||||
static SENT: RefCell<Vec<(ViewportId, ViewportCommand)>> = const { RefCell::new(Vec::new()) };
|
||||
/// Input events for the root window's next frame (a key pressed in it).
|
||||
static EVENTS: RefCell<Vec<egui::Event>> = const { RefCell::new(Vec::new()) };
|
||||
/// Each viewport's input events for its next pass (a key pressed in that window).
|
||||
static EVENTS: RefCell<egui::ViewportIdMap<Vec<egui::Event>>> = RefCell::new(egui::ViewportIdMap::default());
|
||||
}
|
||||
|
||||
fn record(mut out: egui::FullOutput) {
|
||||
@@ -32,6 +33,17 @@ fn record(mut out: egui::FullOutput) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The events waiting for viewport `id`'s next pass.
|
||||
fn take_events(id: ViewportId) -> Vec<egui::Event> {
|
||||
EVENTS.with(|e| e.borrow_mut().remove(&id).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Presses `key` with `modifiers` in viewport `id`'s next pass.
|
||||
fn press(id: ViewportId, key: egui::Key, modifiers: egui::Modifiers) {
|
||||
let event = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
EVENTS.with(|e| e.borrow_mut().entry(id).or_default().push(event));
|
||||
}
|
||||
|
||||
struct Desk {
|
||||
ctx: Context,
|
||||
app: SheetApp,
|
||||
@@ -49,6 +61,7 @@ impl Desk {
|
||||
let mut input = RawInput { viewport_id: id, ..RawInput::default() };
|
||||
input.viewports = INFOS.with(|i| i.borrow().clone());
|
||||
input.viewports.entry(id).or_default().parent = Some(viewport.ids.parent);
|
||||
input.events = take_events(id);
|
||||
let mut cb = viewport.viewport_ui_cb;
|
||||
record(ctx.run_ui(input, |ui| cb(ui)));
|
||||
});
|
||||
@@ -68,7 +81,7 @@ impl Desk {
|
||||
let mut input = RawInput { viewport_id: ViewportId::ROOT, ..RawInput::default() };
|
||||
input.viewports = INFOS.with(|i| i.borrow().clone());
|
||||
input.viewports.entry(ViewportId::ROOT).or_default();
|
||||
input.events = EVENTS.with(|e| std::mem::take(&mut *e.borrow_mut()));
|
||||
input.events = take_events(ViewportId::ROOT);
|
||||
let Desk { ctx, app, windows } = self;
|
||||
let mut act = Some(act);
|
||||
let out = ctx.clone().run_ui(input, |ui| {
|
||||
@@ -81,6 +94,15 @@ impl Desk {
|
||||
app.close_path(&ctx);
|
||||
windows.show(app, ui);
|
||||
});
|
||||
// As eframe's, every pass's input lists each open window: the UI runtime keeps a window's state (the layers
|
||||
// its dialogs showed, its focus) only while the root's input lists that window.
|
||||
INFOS.with(|i| {
|
||||
let mut i = i.borrow_mut();
|
||||
i.retain(|id, _| out.viewport_output.contains_key(id));
|
||||
for id in out.viewport_output.keys() {
|
||||
i.entry(*id).or_default();
|
||||
}
|
||||
});
|
||||
record(out);
|
||||
// Close buttons are one-shot events.
|
||||
INFOS.with(|i| i.borrow_mut().values_mut().for_each(|v| v.events.clear()));
|
||||
@@ -104,15 +126,24 @@ impl Desk {
|
||||
sent
|
||||
}
|
||||
|
||||
/// Answers the Save Changes question showing in the active window, as its button does.
|
||||
/// Answers the Save Changes question with its key (Enter Save, Escape Cancel, Cmd+D Don't
|
||||
/// Save), pressed in the window of the workbook it asks about: the question shows there.
|
||||
/// The person reads the question first: the shared dialog takes its Cmd+D from the pass after
|
||||
/// one in which it already showed on top, so a press in the frame right after it opened is
|
||||
/// not an answer.
|
||||
fn answer(&mut self, answer: SaveAnswer) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
let mut sent = self.frame_with(|app, ctx| {
|
||||
let d = app.dialog.take().unwrap_or_else(|| panic!("no question is showing"));
|
||||
assert_eq!(d.name(), "saveChanges");
|
||||
let quitting = d.values.get("quit").and_then(serde_json::Value::as_bool) == Some(true);
|
||||
app.answer_save_changes(answer, quitting, ctx);
|
||||
});
|
||||
sent.extend(self.frames(2));
|
||||
assert!(self.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "no question is showing");
|
||||
let w = self.app.unsaved_prompt.as_ref().and_then(|p| p.window).expect("the question names its window");
|
||||
let mut sent = self.frames(2);
|
||||
assert!(self.app.unsaved_prompt.as_ref().is_some_and(|p| p.window == Some(w)), "the question in window {w} waits for its answer");
|
||||
let (key, modifiers) = match answer {
|
||||
SaveAnswer::Save => (egui::Key::Enter, egui::Modifiers::NONE),
|
||||
SaveAnswer::Cancel => (egui::Key::Escape, egui::Modifiers::NONE),
|
||||
SaveAnswer::DontSave => (egui::Key::D, egui::Modifiers::COMMAND),
|
||||
};
|
||||
press(self.viewport(w), key, modifiers);
|
||||
sent.extend(self.frames(3));
|
||||
assert!(self.app.unsaved_prompt.as_ref().is_none_or(|p| p.window != Some(w)), "the question in window {w} was answered");
|
||||
sent
|
||||
}
|
||||
|
||||
@@ -123,9 +154,7 @@ impl Desk {
|
||||
|
||||
/// The user presses `key` in the root window.
|
||||
fn key(&mut self, key: egui::Key) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
EVENTS.with(|e| {
|
||||
e.borrow_mut().push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE })
|
||||
});
|
||||
press(ViewportId::ROOT, key, egui::Modifiers::NONE);
|
||||
let mut sent = self.frame_with(|_, _| {});
|
||||
sent.extend(self.frames(2));
|
||||
sent
|
||||
@@ -202,7 +231,7 @@ fn closing_the_last_window_of_an_unsaved_workbook_asks_and_the_app_quits_after()
|
||||
let w = desk.window_of(0);
|
||||
let sent = desk.close(w);
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::CancelClose), "the window stays open to ask: {sent:?}");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
|
||||
assert_eq!(desk.app.session.documents().len(), 1);
|
||||
|
||||
let sent = desk.answer(SaveAnswer::Cancel);
|
||||
@@ -244,21 +273,41 @@ fn quit_asks_about_each_unsaved_workbook_in_its_window_and_cancel_stops() {
|
||||
let sent = desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
assert_eq!(desk.app.session.active_window(), Some(w1), "Book1's window comes forward to ask");
|
||||
assert!(sent_to(&sent, desk.viewport(w1), &ViewportCommand::Focus), "{sent:?}");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
|
||||
let sent = desk.answer(SaveAnswer::Cancel);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel stops the quit: {sent:?}");
|
||||
assert_eq!(desk.app.session.documents().len(), 2);
|
||||
assert!(desk.app.dialog.is_none());
|
||||
assert!(!desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
|
||||
|
||||
desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
let sent = desk.answer(SaveAnswer::DontSave);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Book2 is still unsaved: {sent:?}");
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2), "then Book2's window asks");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
|
||||
let sent = desk.answer(SaveAnswer::DontSave);
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "both answered: the app quits: {sent:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_continues_when_automation_closes_the_prompted_workbook() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
let first = desk.app.session.active().unwrap().uid;
|
||||
desk.app.run("file.new", json!({})).unwrap();
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
|
||||
let second = desk.app.session.active().unwrap().uid;
|
||||
desk.frames(3);
|
||||
desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.doc == first && p.quitting));
|
||||
desk.app.run("file.close", json!({"force": true, "document": true})).unwrap();
|
||||
desk.frames(3);
|
||||
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.doc == second && p.quitting), "quit asks the remaining workbook");
|
||||
assert!(desk.app.session.active().is_some_and(|doc| doc.uid == second && doc.is_dirty()));
|
||||
let sent = desk.answer(SaveAnswer::Cancel);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel still stops quit");
|
||||
assert!(desk.app.session.active().is_some_and(|doc| doc.uid == second && doc.is_dirty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_question_brings_its_window_to_the_front_from_the_background() {
|
||||
// A Dock quit reaches the app while it is behind other apps, hidden or minimized.
|
||||
@@ -268,7 +317,7 @@ fn a_quit_question_brings_its_window_to_the_front_from_the_background() {
|
||||
let w = desk.window_of(0);
|
||||
|
||||
let sent = desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
|
||||
for cmd in [ViewportCommand::Visible(true), ViewportCommand::Minimized(false), ViewportCommand::Focus] {
|
||||
assert!(sent_to(&sent, desk.viewport(w), &cmd), "{cmd:?} missing: {sent:?}");
|
||||
}
|
||||
@@ -406,6 +455,20 @@ fn two_windows_on_one_workbook_show_their_own_sheet_and_each_others_edits() {
|
||||
assert_eq!(d.wb.active().unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_an_unsaved_question_keeps_the_new_answer() {
|
||||
let mut desk = Desk::new(false);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
|
||||
desk.frames(2);
|
||||
desk.app.open_dialog("saveChanges", json!({}));
|
||||
desk.frames(2);
|
||||
desk.app.open_dialog("saveChanges", json!({}));
|
||||
desk.frames(2);
|
||||
assert!(desk.app.unsaved_prompt.is_some(), "the replaced question's cancel is not the new answer");
|
||||
desk.answer(SaveAnswer::DontSave);
|
||||
assert!(desk.app.session.documents().is_empty(), "the new answer closes the workbook");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_stays_with_its_window_across_a_switch() {
|
||||
let mut desk = Desk::new(true);
|
||||
@@ -517,9 +580,8 @@ fn quit_takes_over_a_workbook_close_waiting_on_the_macro_editor() {
|
||||
assert!(desk.app.macros.editor.is_none());
|
||||
// The quit asks about Book2 in its window, as the quit's question, not as a File › Close.
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2));
|
||||
let d = desk.app.dialog.as_ref().expect("Book2 is asked about");
|
||||
assert_eq!(d.name(), "saveChanges");
|
||||
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
|
||||
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
|
||||
assert_eq!(desk.app.session.documents().len(), 2, "nothing closed before the answer");
|
||||
}
|
||||
|
||||
@@ -551,10 +613,8 @@ fn quit_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_order_an
|
||||
assert!(desk.app.macros.editor.is_none());
|
||||
// Book2 is asked about next, in its window, as the quit's question.
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2), "the unsaved workbook's window comes forward");
|
||||
let d = desk.app.dialog.as_ref().expect("Book2 is asked about");
|
||||
assert_eq!(d.name(), "saveChanges");
|
||||
assert_eq!(d.values.get("title").and_then(serde_json::Value::as_str), Some("Book2"));
|
||||
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
|
||||
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
|
||||
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
|
||||
assert_eq!(desk.app.session.documents().len(), 2, "nothing closed before the answer");
|
||||
// Cancel: the quit stops with both windows and workbooks open; the discarded draft stays
|
||||
// discarded.
|
||||
|
||||
@@ -164,7 +164,7 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() {
|
||||
choose(&mut h, "Close");
|
||||
assert!(h.state().backstage.is_none());
|
||||
assert_eq!(h.state().session.documents().len(), 1);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
|
||||
}
|
||||
|
||||
@@ -376,23 +376,80 @@ fn closing_the_window_asks_about_every_unsaved_workbook() {
|
||||
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "unsaved changes hold the window open: {sent:?}");
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
let sent = click_commands(&mut h, "Cancel");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel keeps the app open");
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
assert_eq!(h.state().session.documents().len(), 2, "Cancel keeps both workbooks");
|
||||
|
||||
request_window_close(&mut h);
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "the other workbook is still unsaved");
|
||||
assert_eq!(h.state().session.documents().len(), 1);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"), "then it asks about the next one");
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>(), "then it asks about the next one");
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "once every workbook is answered the window closes: {sent:?}");
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(!sent.contains(&egui::ViewportCommand::CancelClose), "the close that follows is let through");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_window_while_close_asks_turns_the_question_into_the_quits() {
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label_contains("before closing?").is_some());
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
|
||||
assert!(h.query_by_label_contains("before quitting?").is_some(), "the question now asks before quitting");
|
||||
assert!(h.state().unsaved_prompt.as_ref().is_some_and(|p| p.quitting), "and still waits for its answer");
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "its answer goes on to quit: {sent:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_question_names_the_actions_in_the_platform_order() {
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
let dont_save = h.get_by_role_and_label(egui::accesskit::Role::Button, "Don't Save").rect();
|
||||
let cancel = h.get_by_role_and_label(egui::accesskit::Role::Button, "Cancel").rect();
|
||||
let save = h.get_by_role_and_label(egui::accesskit::Role::Button, "Save").rect();
|
||||
// The order every Craft dialog uses on the platform: Save first on Windows; Don't Save, Cancel, Save elsewhere.
|
||||
// The footer orders by the OS the craft shell runs on, which need not be the machine running the test.
|
||||
let platform_order = if craft_ui::runtime::windows::os_of(&h.ctx) == craft_host::target::Os::Windows {
|
||||
save.min.x < dont_save.min.x && dont_save.min.x < cancel.min.x
|
||||
} else {
|
||||
dont_save.min.x < cancel.min.x && cancel.min.x < save.min.x
|
||||
};
|
||||
assert!(platform_order, "Don't Save {dont_save:?}, Cancel {cancel:?}, Save {save:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_question_starts_on_save_and_enter_saves() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-close-enter-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
// The answer that keeps the edits has the focus first; Don't Save never does.
|
||||
assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, "Save").is_focused(), "the question starts on Save");
|
||||
assert!(!h.get_by_role_and_label(egui::accesskit::Role::Button, "Don't Save").is_focused());
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(42.0), "Enter saved the change before closing");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_window_can_save_first_and_a_saved_workbook_closes_at_once() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-close-window-{}", std::process::id()));
|
||||
@@ -427,7 +484,7 @@ fn quitting_with_one_of_two_workbooks_unsaved_asks_once() {
|
||||
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
assert_eq!(h.state().session.active_index(), 0, "the unsaved workbook comes forward");
|
||||
let sent = click_commands(&mut h, "Cancel");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel stops the quit");
|
||||
@@ -436,7 +493,7 @@ fn quitting_with_one_of_two_workbooks_unsaved_asks_once() {
|
||||
request_window_close(&mut h);
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "the saved workbook isn't asked about: {sent:?}");
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
}
|
||||
|
||||
/// Book1 has a cell being typed when File › New runs (the macOS menu runs the command directly).
|
||||
|
||||
@@ -493,7 +493,7 @@ fn quitting_asks_about_the_editors_unsaved_steps_first() {
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
|
||||
assert!(h.query_by_label_contains("Save changes to macro “Unsaved”").is_some());
|
||||
assert!(asks_about(&h, "Unsaved"));
|
||||
// Cancel keeps the app and the draft.
|
||||
// The formula bar's Cancel button has the same name; the question's is the button drawn last.
|
||||
h.get_all_by_role_and_label(egui::Role::Button, "Cancel").last().unwrap().click();
|
||||
@@ -522,7 +522,7 @@ fn quitting_with_the_editor_open_still_asks_about_unsaved_workbooks() {
|
||||
assert!(h.state().macros.editor.is_none());
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
|
||||
request_window_close(&mut h);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -634,8 +634,14 @@ fn is_open(h: &Harness, uid: u64) -> bool {
|
||||
h.state().session.documents().iter().any(|d| d.uid == uid)
|
||||
}
|
||||
|
||||
/// Whether the shared unsaved-changes question is asking about the macro `name`.
|
||||
fn asks_about(h: &Harness, name: &str) -> bool {
|
||||
h.query_by_label_contains(&format!("Save changes to macro “{name}”")).is_some()
|
||||
h.query_by_label_contains(&question_about(name)).is_some()
|
||||
}
|
||||
|
||||
/// The words of the unsaved-changes question that name the macro, closing or quitting.
|
||||
fn question_about(name: &str) -> String {
|
||||
format!("the changes you made to “{name}”")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -687,7 +693,7 @@ fn save_in_the_question_saves_the_macro_then_the_workbook_asks_about_itself() {
|
||||
// The macro is in the workbook now, which makes it unsaved: closing it goes on and asks.
|
||||
assert!(h.state().macros.editor.is_none());
|
||||
assert_eq!(h.state().session.active().unwrap().wb.macros.len(), 1);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
h.get_all_by_role_and_label(egui::Role::Button, "Save").last().unwrap().click();
|
||||
h.run_steps(4);
|
||||
assert!(!is_open(&h, book));
|
||||
@@ -699,6 +705,38 @@ fn save_in_the_question_saves_the_macro_then_the_workbook_asks_about_itself() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_editors_question_is_the_shared_one_and_enter_saves_the_draft() {
|
||||
let mut h = harness();
|
||||
edited_new_macro(&mut h);
|
||||
let name = h.state().macros.editor.as_ref().unwrap().draft.name.clone();
|
||||
let book = h.state().session.active().unwrap().uid;
|
||||
h.state_mut().run("file.close", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(asks_about(&h, &name));
|
||||
// The question's buttons are drawn last (the formula bar has a Cancel and the editor a Save).
|
||||
let button = |label: &'static str| h.get_all_by_role_and_label(egui::Role::Button, label).last().unwrap();
|
||||
let (dont_save, cancel, save) = (button("Don't Save").rect(), button("Cancel").rect(), button("Save").rect());
|
||||
// The order the workbook's question and every Craft dialog use on the platform: Save first on
|
||||
// Windows; Don't Save, Cancel, Save elsewhere. The footer orders by the OS the craft shell runs
|
||||
// on, which need not be the machine running the test.
|
||||
let platform_order = if craft_ui::runtime::windows::os_of(&h.ctx) == craft_host::target::Os::Windows {
|
||||
save.min.x < dont_save.min.x && dont_save.min.x < cancel.min.x
|
||||
} else {
|
||||
dont_save.min.x < cancel.min.x && cancel.min.x < save.min.x
|
||||
};
|
||||
assert!(platform_order, "Don't Save {dont_save:?}, Cancel {cancel:?}, Save {save:?}");
|
||||
// Save has the focus first and Enter answers it: neither discards the draft.
|
||||
assert!(button("Save").is_focused(), "the question starts on Save");
|
||||
assert!(!button("Don't Save").is_focused());
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(4);
|
||||
assert!(h.state().macros.editor.is_none());
|
||||
let wb = &h.state().session.documents().iter().find(|d| d.uid == book).expect("the workbook asks about itself next").wb;
|
||||
assert_eq!(wb.macros.iter().map(|m| m.steps.len()).collect::<Vec<_>>(), [1], "Enter saved the draft into the workbook");
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_that_cannot_be_saved_keeps_its_workbook_open() {
|
||||
let mut h = harness();
|
||||
@@ -920,7 +958,7 @@ fn a_close_request_during_the_editors_save_dialog_waits_for_it() {
|
||||
let r = h.state_mut().run("window.close", json!({"window": home})).unwrap();
|
||||
assert_eq!(r["closed"], false);
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.get_all_by_label_contains("Save changes to macro").count(), 1, "one question");
|
||||
assert_eq!(h.get_all_by_label_contains(&question_about(&name)).count(), 1, "one question");
|
||||
assert!(is_open(&h, book1) && is_open(&h, book2));
|
||||
assert!(h.state().message.is_none(), "{:?}", h.state().message);
|
||||
let pending = h.state().macros.editor.as_ref().and_then(|e| e.then_close.as_ref()).expect("the close waits");
|
||||
@@ -954,7 +992,7 @@ fn a_different_close_during_the_editors_question_is_refused_until_it_is_answered
|
||||
let e = h.state_mut().run("file.close", json!({"document": true})).unwrap_err();
|
||||
assert!(e.contains("asking whether to save") && e.contains("its window closes"), "{e}");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.get_all_by_label_contains("Save changes to macro").count(), 1, "one question");
|
||||
assert_eq!(h.get_all_by_label_contains(&question_about(&name)).count(), 1, "one question");
|
||||
assert!(is_open(&h, book));
|
||||
assert_eq!(h.state().session.windows().len(), 2);
|
||||
// Don't Save closes the editor's window alone, as the question was asked for.
|
||||
@@ -996,7 +1034,6 @@ fn quitting_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_orde
|
||||
h.state_mut().run("cell.set", json!({"cell": "Z9", "input": "unsaved"})).unwrap();
|
||||
h.run_steps(2);
|
||||
let book2 = h.state().session.active().unwrap().uid;
|
||||
let title2 = h.state().session.active().unwrap().display_title();
|
||||
let b = h.state().session.active_window().unwrap();
|
||||
assert_ne!(a, b);
|
||||
let both_open =
|
||||
@@ -1016,17 +1053,15 @@ fn quitting_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_orde
|
||||
request_window_close(&mut h);
|
||||
// Book2 is asked about next, in its window, as the quit's question.
|
||||
assert_eq!(h.state().session.active_window(), Some(b), "the unsaved workbook's window comes forward");
|
||||
let d = h.state().dialog.as_ref().expect("Book2 is asked about");
|
||||
assert_eq!(d.name(), "saveChanges");
|
||||
assert_eq!(d.values.get("title").and_then(serde_json::Value::as_str), Some(title2.as_str()));
|
||||
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
|
||||
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>(), "Book2 is asked about");
|
||||
assert!(h.state().unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
|
||||
assert!(both_open(&h));
|
||||
// Cancel: the quit stops with both windows and workbooks open and Book2's changes kept; the
|
||||
// draft the person discarded stays discarded.
|
||||
h.get_all_by_role_and_label(egui::Role::Button, "Cancel").last().unwrap().click();
|
||||
let sent = step_commands(&mut h);
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close) && !h.state().allow_close, "{sent:?}");
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
|
||||
assert!(both_open(&h));
|
||||
assert!(h.state().session.documents().iter().find(|d| d.uid == book2).unwrap().is_dirty());
|
||||
assert!(h.state().macros.editor.is_none());
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
//! original chart part with the style, colour and shape parts behind it, together with the chart
|
||||
//! as it was read.
|
||||
//!
|
||||
//! Table-linked query parts are held by the table model because the table part is rewritten.
|
||||
//!
|
||||
//! Table-linked query parts are held by the table model because the table part is rewritten.
|
||||
//!
|
||||
//! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in
|
||||
//! kept XML are rewritten to match. Kept content is conservative:
|
||||
//! - Anything whose relationship graph reaches a part GridCraft reads and rewrites (worksheets,
|
||||
|
||||
@@ -44,7 +44,7 @@ impl KeptOut {
|
||||
|
||||
/// A part name for a kept part: its original name when that can't collide with anything
|
||||
/// written, otherwise a fresh one in the same folder.
|
||||
pub(super) fn claim(&mut self, original: &str) -> String {
|
||||
pub(crate) fn claim(&mut self, original: &str) -> String {
|
||||
let lower = original.to_ascii_lowercase();
|
||||
let own = OWN_DIRS.iter().any(|d| lower.starts_with(d));
|
||||
if own && self.used.insert(lower) {
|
||||
|
||||
@@ -415,8 +415,9 @@ fn apply_craft_sheet_part(
|
||||
|
||||
fn read_sheet_notes_and_tables(cx: &mut Ctx<'_>, sp: &CraftSheetPart, rels: &[Rel], sheet: &mut Sheet) -> Result<(), IoError> {
|
||||
let tables = cx.pkg.craft_mut().tables(sp).map_err(craft_error)?;
|
||||
for (_, t) in tables {
|
||||
for (part, t) in tables {
|
||||
let mut model = parts::from_craft_table(cx, &t);
|
||||
parts::read_query_table(cx, &part, &t, &mut model);
|
||||
model.id = cx.next_object_id();
|
||||
sheet.tables.push(model);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use quick_xml::Reader;
|
||||
use quick_xml::events::Event;
|
||||
|
||||
use super::{
|
||||
AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, MAX_COLS, MAX_ROWS, NoteBox, NoteCorner, RangeRef, Sheet, Table, TableColumn,
|
||||
TotalsFn, XmlColumnPr, from_file, xml,
|
||||
};
|
||||
use crate::write::NS_MAIN;
|
||||
|
||||
/// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the
|
||||
/// cells and bytes this sheet's hyperlinks have copied so far, across `<hyperlinks>` blocks.
|
||||
@@ -38,6 +42,7 @@ pub(super) fn from_craft_table(cx: &mut Ctx<'_>, t: &craft_xlsx::Table) -> Table
|
||||
totals_label,
|
||||
formula: c.calculated_formula.as_ref().map(|(f, _)| from_file(f.trim())),
|
||||
unique_name: c.unique_name.clone(),
|
||||
query_field_id: c.query_table_field_id,
|
||||
xml,
|
||||
}
|
||||
})
|
||||
@@ -61,6 +66,7 @@ pub(super) fn from_craft_table(cx: &mut Ctx<'_>, t: &craft_xlsx::Table) -> Table
|
||||
filter,
|
||||
table_type: xml_table.then(|| "xml".to_string()),
|
||||
connection_id: t.connection_id.filter(|_| xml_table),
|
||||
query_table: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,6 +182,62 @@ pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option<AutoFilter> {
|
||||
Some(AutoFilter { range, criteria })
|
||||
}
|
||||
|
||||
/// Most bytes kept for one table's query table part.
|
||||
const MAX_QUERY_TABLE: u64 = 1024 * 1024;
|
||||
|
||||
/// Keeps the query table part a table of type `queryTable` points to. Without the part the table
|
||||
/// is written as a plain table, so a file that names none stays valid.
|
||||
pub(super) fn read_query_table(cx: &mut Ctx<'_>, part: &str, source: &craft_xlsx::Table, t: &mut Table) {
|
||||
if source.table_type.as_deref() != Some("queryTable") {
|
||||
return;
|
||||
}
|
||||
let target = match cx.pkg.rels(part) {
|
||||
Ok(rels) => rels.into_iter().find(|r| r.kind == "queryTable" && !r.external).map(|r| r.target),
|
||||
Err(_) => None,
|
||||
};
|
||||
let kept = target.and_then(|n| {
|
||||
let bytes = cx.pkg.read_limited(&n, MAX_QUERY_TABLE).ok().flatten()?;
|
||||
// Its own relationships (none in practice) would need to be kept with it.
|
||||
let own_rels = cx.pkg.rels(&n).ok().is_none_or(|r| !r.is_empty());
|
||||
let text = String::from_utf8(bytes).ok()?;
|
||||
(!own_rels && xml::parse(text.as_bytes()).is_ok() && is_query_table_root(&text)).then_some(text)
|
||||
});
|
||||
match kept {
|
||||
Some(text) => {
|
||||
t.query_table = Some(text);
|
||||
t.table_type = Some("queryTable".to_string());
|
||||
t.connection_id = source.connection_id;
|
||||
}
|
||||
None => cx.warn(format!("table \"{}\": its query table could not be kept; the table was kept as a plain table", t.name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a part's root is `queryTable` in the SpreadsheetML namespace. `El` drops namespaces, so
|
||||
/// this reads the root start tag itself, for a default or a prefixed namespace binding.
|
||||
fn is_query_table_root(text: &str) -> bool {
|
||||
let mut reader = Reader::from_reader(text.as_bytes());
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(Event::Start(e) | Event::Empty(e)) => {
|
||||
let raw = e.name();
|
||||
let raw = raw.as_ref();
|
||||
let (prefix, local) = raw.split_once(':').unwrap_or(("", raw));
|
||||
return local == "queryTable"
|
||||
&& e.attributes().flatten().any(|a| {
|
||||
let key = a.key.as_ref();
|
||||
let bound = if prefix.is_empty() { key == "xmlns" } else { key.strip_prefix("xmlns:") == Some(prefix) };
|
||||
bound && a.value.as_ref() == NS_MAIN
|
||||
});
|
||||
}
|
||||
Ok(Event::Decl(_) | Event::Comment(_) | Event::PI(_) | Event::DocType(_)) => {}
|
||||
Ok(Event::Text(t)) if t.as_bytes().iter().all(u8::is_ascii_whitespace) => {}
|
||||
_ => return false,
|
||||
}
|
||||
buf.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn read_threaded(cx: &Ctx<'_>, x: &El, sheet: &mut Sheet) {
|
||||
let mut by_id: HashMap<String, CellRef> = HashMap::new();
|
||||
let mut replies: Vec<(String, String, String, String)> = vec![];
|
||||
|
||||
@@ -21,8 +21,8 @@ use crate::fmla::text_to_file;
|
||||
use crate::styles::{color_attrs, dxf_id, dxf_xml};
|
||||
use crate::tables::{paper_id, px_to_col_width, px_to_pt};
|
||||
use crate::write::{
|
||||
CT_CHART, CT_COMMENTS, CT_DRAWING, CT_TABLE, CT_THREADED_COMMENTS, NS_MAIN, NS_REL, NS_THREADED, Out, REL_THREADED_COMMENT, Rels, XML_DECL,
|
||||
x14_cf_rule_guid,
|
||||
CT_CHART, CT_COMMENTS, CT_DRAWING, CT_QUERY_TABLE, CT_TABLE, CT_THREADED_COMMENTS, NS_MAIN, NS_REL, NS_THREADED, Out, REL_THREADED_COMMENT, Rels,
|
||||
XML_DECL, x14_cf_rule_guid,
|
||||
};
|
||||
use crate::xml::{encode_xstring, esc, esc_attr, num};
|
||||
|
||||
@@ -34,7 +34,8 @@ mod rules;
|
||||
|
||||
pub(crate) use parts::password_attrs;
|
||||
use parts::{
|
||||
autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_filter, table_name, table_xml, thread_ids, threaded_xml, vml_xml,
|
||||
autofilter_xml, comments_xml, protected_ranges_xml, remap_query_fields, table_columns, table_filter, table_name, table_xml, thread_ids,
|
||||
threaded_xml, vml_xml,
|
||||
};
|
||||
use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml};
|
||||
|
||||
@@ -208,6 +209,13 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
let filter = table_filter(sheet, t);
|
||||
let xml = table_xml(t, cols, &name, out.table_id, &filter, out);
|
||||
out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes());
|
||||
if let Some(query) = &t.query_table {
|
||||
let path = out.kept.claim(&format!("xl/queryTables/queryTable{n}.xml"));
|
||||
out.part(&path, Some(CT_QUERY_TABLE), remap_query_fields(query, t).into_bytes());
|
||||
let mut table_rels = Rels::default();
|
||||
table_rels.add("queryTable", &format!("/{path}"));
|
||||
out.part(&format!("xl/tables/_rels/table{n}.xml.rels"), None, table_rels.xml().into_bytes());
|
||||
}
|
||||
part.features.table_parts.push(rels.add("table", &format!("../tables/table{n}.xml")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@ use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::name::ResolveResult;
|
||||
use quick_xml::{NsReader, Writer};
|
||||
|
||||
/// Valid table name: letters, digits, `_` and `.`, starting with a letter, `_` or `\`
|
||||
/// (Microsoft "Names in formulas" rules).
|
||||
pub(super) fn table_name(name: &str, used: &mut HashSet<String>, n: u32) -> String {
|
||||
@@ -131,6 +135,126 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)
|
||||
s
|
||||
}
|
||||
|
||||
/// Rewrites a retained query table part for the columns as saved. Each `queryTableField` takes its
|
||||
/// column's new `tableColumn` id, linked through the field id a column keeps
|
||||
/// (`TableColumn::query_field_id`). A field whose column is gone is dropped, and the count follows.
|
||||
pub(super) fn remap_query_fields(query: &str, t: &Table) -> String {
|
||||
let new_id: HashMap<u32, u32> = t.columns.iter().enumerate().filter_map(|(i, c)| Some((c.query_field_id?, u32::try_from(i + 1).ok()?))).collect();
|
||||
let Some((_, counts)) = walk_query_fields(query, &new_id, None) else { return query.to_string() };
|
||||
walk_query_fields(query, &new_id, Some(&counts)).map(|(xml, _)| xml).unwrap_or_else(|| query.to_string())
|
||||
}
|
||||
|
||||
/// The only elements we edit are direct SpreadsheetML children of the query-table hierarchy.
|
||||
/// Extensions can contain unrelated elements with exactly the same local names.
|
||||
fn query_level(parent: Option<u8>, local: &str, spreadsheet: bool) -> u8 {
|
||||
if !spreadsheet {
|
||||
return 0;
|
||||
}
|
||||
match (parent, local) {
|
||||
(None, "queryTable") => 1,
|
||||
(Some(1), "queryTableRefresh") => 2,
|
||||
(Some(2), "queryTableFields") => 3,
|
||||
(Some(3), "queryTableField") => 4,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// First pass counts retained fields in each container; the second writes those counts and fields.
|
||||
fn walk_query_fields(query: &str, new_id: &HashMap<u32, u32>, counts: Option<&[usize]>) -> Option<(String, Vec<usize>)> {
|
||||
let mut reader = NsReader::from_reader(query.as_bytes());
|
||||
let mut writer = Writer::new(Vec::new());
|
||||
let mut buf = Vec::new();
|
||||
let mut ancestors = Vec::new();
|
||||
let mut found = Vec::new();
|
||||
let mut container = 0usize;
|
||||
let mut dropped = 0usize;
|
||||
loop {
|
||||
buf.clear();
|
||||
let (namespace, event) = reader.read_resolved_event_into(&mut buf).ok()?;
|
||||
let spreadsheet = matches!(namespace, ResolveResult::Bound(ns) if ns.as_ref() == NS_MAIN);
|
||||
if matches!(event, Event::Eof) {
|
||||
break;
|
||||
}
|
||||
if dropped > 0 {
|
||||
match event {
|
||||
Event::Start(_) => dropped += 1,
|
||||
Event::End(_) => dropped -= 1,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let empty = matches!(&event, Event::Empty(_));
|
||||
let out = match event {
|
||||
Event::Start(e) | Event::Empty(e) => {
|
||||
let level = query_level(ancestors.last().copied(), e.local_name().as_ref(), spreadsheet);
|
||||
let mut element = e.to_owned();
|
||||
if level == 3 {
|
||||
found.push(0usize);
|
||||
if let Some(counts) = counts {
|
||||
element = set_attr(&e, "count", &counts.get(container)?.to_string());
|
||||
}
|
||||
container += 1;
|
||||
} else if level == 4 {
|
||||
match query_field_el(&e, new_id) {
|
||||
Some(field) => {
|
||||
*found.last_mut()? += 1;
|
||||
element = field;
|
||||
}
|
||||
None => {
|
||||
if !empty {
|
||||
dropped = 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if empty {
|
||||
Event::Empty(element)
|
||||
} else {
|
||||
ancestors.push(level);
|
||||
Event::Start(element)
|
||||
}
|
||||
}
|
||||
Event::End(e) => {
|
||||
ancestors.pop()?;
|
||||
Event::End(e)
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
writer.write_event(out).ok()?;
|
||||
}
|
||||
if !ancestors.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((String::from_utf8(writer.into_inner()).ok()?, found))
|
||||
}
|
||||
|
||||
/// A `queryTableField` with its `tableColumnId` set to its column's new id; None when the column is gone.
|
||||
fn query_field_el(e: &BytesStart, new_id: &HashMap<u32, u32>) -> Option<BytesStart<'static>> {
|
||||
let id = e.attributes().flatten().find(|a| a.key.as_ref() == "id")?;
|
||||
let new = new_id.get(&id.value.trim().parse::<u32>().ok()?)?;
|
||||
Some(set_attr(e, "tableColumnId", &new.to_string()))
|
||||
}
|
||||
|
||||
/// The element with attribute `key` set to `value`, every other attribute kept in order.
|
||||
fn set_attr(e: &BytesStart, key: &str, value: &str) -> BytesStart<'static> {
|
||||
let mut out = e.to_owned();
|
||||
out.clear_attributes();
|
||||
let mut set = false;
|
||||
for a in e.attributes().flatten() {
|
||||
if a.key.as_ref() == key {
|
||||
out.push_attribute((key, value));
|
||||
set = true;
|
||||
} else {
|
||||
out.push_attribute(a);
|
||||
}
|
||||
}
|
||||
if !set {
|
||||
out.push_attribute((key, value));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The criteria saved in a table's `<autoFilter>`: its own, plus those of a sheet AutoFilter
|
||||
/// that starts on the table's header row. GridCraft filters a table through the sheet
|
||||
/// AutoFilter, but a file can't hold a sheet AutoFilter that overlaps a table (the sheet element
|
||||
@@ -169,10 +293,11 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter:
|
||||
} else {
|
||||
s.push_str(" totalsRowShown=\"0\"");
|
||||
}
|
||||
if let Some(ty) = &t.table_type {
|
||||
// `queryTable` needs its part: without it the table is plain.
|
||||
if let Some(ty) = t.table_type.as_ref().filter(|ty| *ty != "queryTable" || t.query_table.is_some()) {
|
||||
let _ = write!(s, " tableType=\"{}\"", esc_attr(ty));
|
||||
}
|
||||
if let Some(c) = t.connection_id {
|
||||
if let Some(c) = t.connection_id.filter(|_| t.table_type.as_deref() != Some("queryTable") || t.query_table.is_some()) {
|
||||
let _ = write!(s, " connectionId=\"{c}\"");
|
||||
}
|
||||
s.push('>');
|
||||
@@ -189,6 +314,11 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter:
|
||||
let _ = write!(s, " uniqueName=\"{}\"", esc_attr(u));
|
||||
}
|
||||
let _ = write!(s, " name=\"{}\"", esc_attr(&encode_xstring(name)));
|
||||
if t.query_table.is_some()
|
||||
&& let Some(f) = col.and_then(|c| c.query_field_id)
|
||||
{
|
||||
let _ = write!(s, " queryTableFieldId=\"{f}\"");
|
||||
}
|
||||
let totals = col.map(|c| c.totals).unwrap_or_default();
|
||||
// A hidden Total Row keeps each column's calculation, as Excel's files do: turning the row
|
||||
// back on restores it (#4296). The reader takes them whether the row is shown or not.
|
||||
@@ -444,7 +574,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn repeated_headers_are_renamed_without_retrying_suffixes() {
|
||||
let col = |n: &str| TableColumn { name: n.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
let col = |n: &str| TableColumn {
|
||||
name: n.into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
query_field_id: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
};
|
||||
let mut columns: Vec<TableColumn> = (0..10_000).map(|_| col("Total")).collect();
|
||||
columns[1] = col("total3");
|
||||
let t = Table {
|
||||
@@ -463,6 +601,7 @@ mod tests {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
};
|
||||
let names = table_columns(&t);
|
||||
assert_eq!(names.len(), 10_000);
|
||||
|
||||
@@ -215,13 +215,22 @@ fn calculated_table_column_keeps_formula_and_cell_value() {
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![
|
||||
TableColumn { name: "Input".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn {
|
||||
name: "Input".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "Output".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: Some("A2*2".into()),
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
],
|
||||
@@ -234,6 +243,7 @@ fn calculated_table_column_keeps_formula_and_cell_value() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut pkg = Package::open(&bytes).unwrap();
|
||||
@@ -263,13 +273,22 @@ fn this_row_references_are_written_in_long_form() {
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![
|
||||
TableColumn { name: "Input".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn {
|
||||
name: "Input".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "Output".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: Some("[@Input]*2".into()),
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
],
|
||||
@@ -282,6 +301,7 @@ fn this_row_references_are_written_in_long_form() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut pkg = Package::open(&bytes).unwrap();
|
||||
@@ -434,13 +454,22 @@ fn implicit_intersection_metadata_distinguishes_table_rows_and_columns() {
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![
|
||||
TableColumn { name: "Input".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn {
|
||||
name: "Input".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "Output".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: Some("[@Input]*2".into()),
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
],
|
||||
@@ -453,6 +482,7 @@ fn implicit_intersection_metadata_distinguishes_table_rows_and_columns() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.cells.set(at("A2"), Cell::value(Value::Number(3.0)));
|
||||
sh.cells.set(at("B2"), formula("[@Input]*2", 6.0));
|
||||
|
||||
@@ -570,6 +570,202 @@ fn xml_maps_and_their_bindings_survive_a_round_trip() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A workbook with a table that is the result range of a query on a data connection.
|
||||
fn query_table_package() -> Vec<u8> {
|
||||
let types = r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/tables/table1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/><Override PartName="/xl/connections.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml"/><Override PartName="/xl/queryTables/queryTable1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml"/></Types>"#;
|
||||
let workbook = format!(
|
||||
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="Data" sheetId="1" r:id="rId1"/></sheets></workbook>"#
|
||||
);
|
||||
let sheet = format!(
|
||||
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Id</t></is></c><c r="B1" t="inlineStr"><is><t>Name</t></is></c></row><row r="2"><c r="A2"><v>1</v></c><c r="B2" t="inlineStr"><is><t>x</t></is></c></row></sheetData><tableParts count="1"><tablePart r:id="rId1"/></tableParts></worksheet>"#
|
||||
);
|
||||
let table = format!(
|
||||
r#"<?xml version="1.0"?><table xmlns="{NS_MAIN}" id="1" name="Table_Query" displayName="Table_Query" ref="A1:B2" tableType="queryTable" connectionId="1" totalsRowShown="0"><tableColumns count="2"><tableColumn id="1" uniqueName="Id" name="Id" queryTableFieldId="1"/><tableColumn id="2" uniqueName="Name" name="Name" queryTableFieldId="2"/></tableColumns><tableStyleInfo name="TableStyleMedium2" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/></table>"#
|
||||
);
|
||||
let query = format!(
|
||||
r#"<?xml version="1.0"?><queryTable xmlns="{NS_MAIN}" name="ExternalData_1" connectionId="1" autoFormatId="16" applyNumberFormats="0"><queryTableRefresh nextId="3"><queryTableFields count="2"><queryTableField id="1" name="Id" tableColumnId="1"/><queryTableField id="2" name="Name" tableColumnId="2"/></queryTableFields></queryTableRefresh></queryTable>"#
|
||||
);
|
||||
let root_rels = rels(&[("rId1", "officeDocument", "xl/workbook.xml")]);
|
||||
let wb_rels = rels(&[("rId1", "worksheet", "worksheets/sheet1.xml"), ("rId2", "connections", "connections.xml")]);
|
||||
let sheet_rels = rels(&[("rId1", "table", "../tables/table1.xml")]);
|
||||
let table_rels = rels(&[("rId1", "queryTable", "../queryTables/queryTable1.xml")]);
|
||||
make_zip(&[
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", root_rels.as_bytes()),
|
||||
("xl/workbook.xml", workbook.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", sheet.as_bytes()),
|
||||
("xl/worksheets/_rels/sheet1.xml.rels", sheet_rels.as_bytes()),
|
||||
("xl/tables/table1.xml", table.as_bytes()),
|
||||
("xl/tables/_rels/table1.xml.rels", table_rels.as_bytes()),
|
||||
("xl/queryTables/queryTable1.xml", query.as_bytes()),
|
||||
("xl/connections.xml", CONNECTIONS.as_bytes()),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_keeps_its_query_table_on_save() {
|
||||
let (wb, rep) = read_xlsx(&query_table_package()).unwrap();
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("query table")), "{:?}", rep.warnings);
|
||||
let out = write_xlsx(&wb).unwrap();
|
||||
let u = Unpacked::new(&out);
|
||||
u.assert_valid();
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let t = xml::parse(u.text(&table).as_bytes()).unwrap();
|
||||
assert_eq!((t.attr("tableType"), t.attr("connectionId")), (Some("queryTable"), Some("1")));
|
||||
let fields: Vec<_> = t.child("tableColumns").unwrap().kids("tableColumn").map(|c| c.attr("queryTableFieldId")).collect();
|
||||
assert_eq!(fields, [Some("1"), Some("2")]);
|
||||
// The table points at its query table, byte for byte, with the content type it needs.
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
assert!(u.text(&query).contains("<queryTableField id=\"2\" name=\"Name\" tableColumnId=\"2\"/>"));
|
||||
let types = u.text("[Content_Types].xml");
|
||||
assert!(
|
||||
types.contains(&format!("PartName=\"/{query}\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml\"")),
|
||||
"{types}"
|
||||
);
|
||||
// The connection it queries is kept too.
|
||||
assert!(u.parts.contains_key("xl/connections.xml"));
|
||||
// And it reads back the same.
|
||||
let (again, _) = read_xlsx(&out).unwrap();
|
||||
assert_eq!(again.sheets[0].tables[0].query_table, wb.sheets[0].tables[0].query_table);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_table_that_cannot_be_kept_leaves_a_plain_table() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), b"<queryTable".to_vec());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (wb, rep) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("query table")), "{:?}", rep.warnings);
|
||||
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
|
||||
u.assert_valid();
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let t = xml::parse(u.text(&table).as_bytes()).unwrap();
|
||||
assert_eq!(t.attr("tableType"), None);
|
||||
assert!(t.child("tableColumns").unwrap().kids("tableColumn").all(|c| c.attr("queryTableFieldId").is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_table_with_a_prefixed_root_and_a_formatted_prolog_is_kept() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
let query = format!("<?xml version=\"1.0\"?>\n<q:queryTable xmlns:q=\"{NS_MAIN}\" name=\"ExternalData_1\" connectionId=\"1\"/>");
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), query.into_bytes());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (wb, rep) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
assert!(!rep.warnings.iter().any(|w| w.contains("query table")), "{:?}", rep.warnings);
|
||||
assert!(wb.sheets[0].tables[0].query_table.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_table_root_outside_the_spreadsheet_namespace_leaves_a_plain_table() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), br#"<?xml version="1.0"?><queryTable name="ExternalData_1"/>"#.to_vec());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (wb, rep) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("query table")), "{:?}", rep.warnings);
|
||||
assert_eq!(wb.sheets[0].tables[0].table_type, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_table_keeps_its_field_links_when_columns_move() {
|
||||
let (mut wb, _) = read_xlsx(&query_table_package()).unwrap();
|
||||
Arc::make_mut(&mut wb.sheets[0]).tables[0].columns.swap(0, 1);
|
||||
let out = write_xlsx(&wb).unwrap();
|
||||
let u = Unpacked::new(&out);
|
||||
u.assert_valid();
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
// Id is now the second column, Name the first: each field follows its column to the new id.
|
||||
let text = u.text(&query);
|
||||
assert!(text.contains("<queryTableField id=\"1\" name=\"Id\" tableColumnId=\"2\"/>"), "{text}");
|
||||
assert!(text.contains("<queryTableField id=\"2\" name=\"Name\" tableColumnId=\"1\"/>"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefixed_query_table_keeps_its_field_links_when_columns_move() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
let query = format!(
|
||||
"<?xml version=\"1.0\"?>\n<q:queryTable xmlns:q=\"{NS_MAIN}\" name=\"ExternalData_1\" connectionId=\"1\"><q:queryTableRefresh nextId=\"3\"><q:queryTableFields count=\"2\"><q:queryTableField id=\"1\" name=\"Id\" tableColumnId=\"1\"/><q:queryTableField id=\"2\" name=\"Name\" tableColumnId=\"2\"/></q:queryTableFields></q:queryTableRefresh></q:queryTable>"
|
||||
);
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), query.into_bytes());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (mut wb, _) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
Arc::make_mut(&mut wb.sheets[0]).tables[0].columns.swap(0, 1);
|
||||
let out = write_xlsx(&wb).unwrap();
|
||||
let u = Unpacked::new(&out);
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
let text = u.text(&query);
|
||||
assert!(text.contains("<q:queryTableField id=\"1\" name=\"Id\" tableColumnId=\"2\"/>"), "{text}");
|
||||
assert!(text.contains("<q:queryTableField id=\"2\" name=\"Name\" tableColumnId=\"1\"/>"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_table_field_remapping_leaves_extensions_untouched() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
let query = format!(
|
||||
r#"<q:queryTable xmlns:q="{NS_MAIN}" xmlns:x="urn:example"><q:queryTableRefresh><q:queryTableFields count="2"><q:queryTableField id="1" tableColumnId="1"/><q:queryTableField id="2" tableColumnId="2"/><x:queryTableField id="77" tableColumnId="99"/><q:extLst><q:queryTableField id="88" tableColumnId="98"/></q:extLst></q:queryTableFields></q:queryTableRefresh><q:extLst><x:queryTableFields count="42"><x:queryTableField id="99" tableColumnId="97"/></x:queryTableFields><q:queryTableRefresh><q:queryTableFields count="41"><q:queryTableField id="98" tableColumnId="96"/></q:queryTableFields></q:queryTableRefresh></q:extLst></q:queryTable>"#
|
||||
);
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), query.into_bytes());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (mut wb, _) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
Arc::make_mut(&mut wb.sheets[0]).tables[0].columns.pop();
|
||||
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
let text = u.text(&query);
|
||||
assert!(text.contains(r#"<q:queryTableFields count="1">"#), "{text}");
|
||||
assert!(!text.contains(r#"id="2" tableColumnId="2""#), "{text}");
|
||||
for retained in [
|
||||
r#"<x:queryTableField id="77" tableColumnId="99"/>"#,
|
||||
r#"<q:queryTableField id="88" tableColumnId="98"/>"#,
|
||||
r#"<x:queryTableFields count="42"><x:queryTableField id="99" tableColumnId="97"/></x:queryTableFields>"#,
|
||||
r#"<q:queryTableFields count="41"><q:queryTableField id="98" tableColumnId="96"/></q:queryTableFields>"#,
|
||||
] {
|
||||
assert!(text.contains(retained), "missing {retained}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_field_whose_column_is_gone_is_dropped_on_save() {
|
||||
let (mut wb, _) = read_xlsx(&query_table_package()).unwrap();
|
||||
Arc::make_mut(&mut wb.sheets[0]).tables[0].columns.pop();
|
||||
let out = write_xlsx(&wb).unwrap();
|
||||
let u = Unpacked::new(&out);
|
||||
u.assert_valid();
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
let text = u.text(&query);
|
||||
assert!(text.contains("<queryTableField id=\"1\" name=\"Id\" tableColumnId=\"1\"/>"), "{text}");
|
||||
assert!(!text.contains("name=\"Name\""), "{text}");
|
||||
assert!(text.contains("<queryTableFields count=\"1\">"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_field_with_single_quoted_attributes_follows_its_column() {
|
||||
let mut zip = Unpacked::new(&query_table_package()).parts;
|
||||
let query = String::from_utf8(zip["xl/queryTables/queryTable1.xml"].clone()).unwrap().replace('"', "'");
|
||||
zip.insert("xl/queryTables/queryTable1.xml".to_string(), query.into_bytes());
|
||||
let items: Vec<(&str, &[u8])> = zip.iter().map(|(k, v)| (k.as_str(), v.as_slice())).collect();
|
||||
let (mut wb, _) = read_xlsx(&make_zip(&items)).unwrap();
|
||||
Arc::make_mut(&mut wb.sheets[0]).tables[0].columns.swap(0, 1);
|
||||
let out = write_xlsx(&wb).unwrap();
|
||||
let u = Unpacked::new(&out);
|
||||
u.assert_valid();
|
||||
let sheet = sheet_part(&u, "Data");
|
||||
let (_, table) = u.rels(&sheet).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/table")).unwrap();
|
||||
let (_, query) = u.rels(&table).into_iter().map(|r| (r.1, r.2)).find(|(ty, _)| ty.ends_with("/queryTable")).unwrap();
|
||||
let text = u.text(&query);
|
||||
assert!(text.contains("<queryTableField id=\"1\" name=\"Id\" tableColumnId=\"2\"/>"), "{text}");
|
||||
assert!(text.contains("<queryTableField id=\"2\" name=\"Name\" tableColumnId=\"1\"/>"), "{text}");
|
||||
}
|
||||
|
||||
/// Where a link with `target`, in a workbook read from `from`, points once saved into `to`.
|
||||
#[cfg(unix)]
|
||||
fn rebased(target: &str, from: &str, to: &str) -> String {
|
||||
|
||||
@@ -65,7 +65,15 @@ fn workbook() -> Workbook {
|
||||
totals_row: false,
|
||||
columns: headers
|
||||
.iter()
|
||||
.map(|h| TableColumn { name: (*h).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|h| TableColumn {
|
||||
name: (*h).into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
@@ -76,6 +84,7 @@ fn workbook() -> Workbook {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
wb.names.push(DefinedName { name: "SalesData".into(), scope: None, formula: "Data!$A$1:$F$9".into(), comment: String::new(), hidden: false });
|
||||
|
||||
|
||||
@@ -334,15 +334,25 @@ fn sample() -> Workbook {
|
||||
totals_label: Some("Total".into()),
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "Amount".into(),
|
||||
totals: TotalsFn::Sum,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn { name: "Amount".into(), totals: TotalsFn::Sum, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn {
|
||||
name: "Tax".into(),
|
||||
totals: TotalsFn::Custom,
|
||||
totals_label: Some("SUM(R2:R4)".into()),
|
||||
formula: Some("Q2*0.1".into()),
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
],
|
||||
@@ -358,6 +368,7 @@ fn sample() -> Workbook {
|
||||
],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let png = b"\x89PNG\r\n\x1a\n0000IHDRfake".to_vec();
|
||||
s.images.push(Image {
|
||||
@@ -907,8 +918,24 @@ fn writing_repairs_invalid_models() {
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![
|
||||
TableColumn { name: "X".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn { name: "x".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
TableColumn {
|
||||
name: "X".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "x".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
],
|
||||
style: String::new(),
|
||||
banded_rows: true,
|
||||
@@ -919,6 +946,7 @@ fn writing_repairs_invalid_models() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
s.cells.set(at("B2"), Cell { value: Value::Number(1.0), formula: None, style: StyleId(9999), py: None });
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
@@ -1559,7 +1587,15 @@ fn table_newline_column_and_backslash_name_survive() {
|
||||
s.set_value(at("A1"), Value::text("Handle\nBars"));
|
||||
s.set_value(at("B1"), Value::text("Name"));
|
||||
s.set_value(at("B2"), Value::text("x"));
|
||||
let col = |n: &str| TableColumn { name: n.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
let col = |n: &str| TableColumn {
|
||||
name: n.into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
s.tables.push(Table {
|
||||
id: 1,
|
||||
name: "\\_Prime.1".into(),
|
||||
@@ -1576,6 +1612,7 @@ fn table_newline_column_and_backslash_name_survive() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
s.cells.set(at("D1"), Cell::formula(Formula::new("COUNTA(\\_Prime.1[Name])")));
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
@@ -1597,6 +1634,7 @@ fn hidden_total_row_keeps_its_calculations() {
|
||||
totals_label: label.map(str::to_string),
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
let mut wb = Workbook::new();
|
||||
@@ -1621,6 +1659,7 @@ fn hidden_total_row_keeps_its_calculations() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut xml = String::new();
|
||||
@@ -1676,9 +1715,18 @@ fn header_and_totals_table_without_data_row_survives() {
|
||||
totals_label: Some("Total".into()),
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn {
|
||||
name: "Amount".into(),
|
||||
totals: TotalsFn::Sum,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
},
|
||||
TableColumn { name: "Amount".into(), totals: TotalsFn::Sum, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
],
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
@@ -1689,6 +1737,7 @@ fn header_and_totals_table_without_data_row_survives() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let (back, report) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
|
||||
@@ -1974,7 +2023,15 @@ fn a_table_filter_criteria_survive_a_round_trip() {
|
||||
range: rr("A1:A4"),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![TableColumn { name: "Region".into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }],
|
||||
columns: vec![TableColumn {
|
||||
name: "Region".into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
}],
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
@@ -1984,6 +2041,7 @@ fn a_table_filter_criteria_survive_a_round_trip() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
// The dropdown of a table's header cell installs the sheet AutoFilter over the table's
|
||||
// range, and `data.filterBy` stores its criteria there.
|
||||
@@ -2013,8 +2071,15 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
|
||||
for (a, v) in [("A1", "Id"), ("B1", "Region"), ("A2", "1"), ("B2", "East"), ("A3", "2"), ("B3", "West")] {
|
||||
s.set_value(at(a), Value::text(v));
|
||||
}
|
||||
let column =
|
||||
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
let column = |name: &str| TableColumn {
|
||||
name: name.into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
s.tables.push(Table {
|
||||
id: 1,
|
||||
name: "Sales".into(),
|
||||
@@ -2031,6 +2096,7 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
s.autofilter = Some(AutoFilter {
|
||||
range: rr("B1:B3"),
|
||||
|
||||
@@ -19,7 +19,15 @@ fn table(range: &str, cols: &[&str]) -> Table {
|
||||
totals_row: false,
|
||||
columns: cols
|
||||
.iter()
|
||||
.map(|n| TableColumn { name: (*n).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|n| TableColumn {
|
||||
name: (*n).into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style: String::new(),
|
||||
banded_rows: true,
|
||||
@@ -30,6 +38,7 @@ fn table(range: &str, cols: &[&str]) -> Table {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ pub const CT_WORKSHEET: &str = "application/vnd.openxmlformats-officedocument.sp
|
||||
pub const CT_DRAWING: &str = "application/vnd.openxmlformats-officedocument.drawing+xml";
|
||||
pub const CT_CHART: &str = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
|
||||
pub const CT_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml";
|
||||
pub const CT_QUERY_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml";
|
||||
pub const CT_COMMENTS: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml";
|
||||
pub const CT_VBA: &str = "application/vnd.ms-office.vbaProject";
|
||||
pub const CT_THREADED_COMMENTS: &str = "application/vnd.ms-excel.threadedcomments+xml";
|
||||
|
||||
+1
-1
@@ -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
@@ -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)"}}}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+21
-3
@@ -38,11 +38,10 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
- **Estimate:** 25–40 h. [target-app-parity.md](target-app-parity.md#performance), [hardware-parity.md](hardware-parity.md)
|
||||
|
||||
### 3. Some unmodelled XLSX content is dropped on save (FF)
|
||||
- **Missing:** slicers and their caches, timelines, the data model, query tables attached to
|
||||
tables, unmodelled `extLst` entries (among them x14 data bar settings beyond a solid fill,
|
||||
- **Missing:** slicers and their caches, timelines, unmodelled `extLst` entries (among them x14 data bar settings beyond a solid fill,
|
||||
icon sets, colour scales and the text rules containsText, notContainsText, beginsWith and
|
||||
endsWith), chart details. Pass-through (#330) keeps custom XML, external links, connections,
|
||||
sheet query tables, printer settings, form and ActiveX controls, OLE objects and sheet
|
||||
sheet query tables and supported table-linked query parts, printer settings, form and ActiveX controls, OLE objects and sheet
|
||||
backgrounds; x14-only colour-scale, data-bar and icon-set rules with cross-sheet `cfvo` are
|
||||
still dropped on read with a warning, while the other Excel 2010 conditional format rules
|
||||
(including cross-sheet cell-value and expression rules) are read and written. In tested
|
||||
@@ -236,6 +235,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
| 2026-10-11 | minor | §7: password-encrypted workbooks open with their password; saving with one remains (#11) |
|
||||
| 2026-10-11 | minor | §16: comment navigation, Show Comments, Show All Notes and Convert to Comments landed (#281) |
|
||||
| 2026-10-11 | minor | §7: `.xls` (BIFF8) import of values, formulas and number formats (#121) |
|
||||
| 2026-10-24 | minor | §3: query tables attached to tables are kept on save |
|
||||
| 2026-10-11 | minor | §3: XLSX pass-through keeps custom XML, external links, connections, query tables, printer settings, controls and OLE objects (#330, #324) |
|
||||
| 2026-10-11 | minor | §13: Forecast Sheet landed (#322) |
|
||||
| 2026-10-11 | minor | §15: ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD added (18 functions missing) |
|
||||
@@ -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
@@ -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.
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ and upload their artifacts, the environment refuses macOS and Windows, and no re
|
||||
| Linux aarch64 | `gridcraft-<v>-linux-aarch64.{AppImage,AppImage.zsync,deb,rpm,tar.gz}` | `ubuntu-22.04-arm` |
|
||||
| Linux riscv64 | `gridcraft-<v>-linux-riscv64.tar.gz` (cross-compiled, glibc >= 2.39; CLI smoke-tested under QEMU) | `ubuntu-24.04` |
|
||||
| Flatpak x86_64, aarch64 | `gridcraft-<v>-linux-<arch>.flatpak` (repackages the Linux tarball) | `ubuntu-24.04`, `ubuntu-24.04-arm` |
|
||||
| FreeBSD 14 x86_64 | `gridcraft-<v>-freebsd-x86_64.tar.gz` | FreeBSD 14.3 VM (`freebsd.yml`, called by `release.yml`) |
|
||||
| FreeBSD 15.1+ x86_64 | `gridcraft-<v>-freebsd-x86_64.tar.gz` | FreeBSD 15.1-STABLE VM (`freebsd.yml`, called by `release.yml`) |
|
||||
| Web | `gridcraft-web-<v>.zip` (static site; see [`packaging/web/README.md`](../packaging/web/README.md)) | `ubuntu-latest` |
|
||||
|
||||
### macOS
|
||||
@@ -185,7 +185,7 @@ Locally (on Linux): install [nfpm](https://nfpm.goreleaser.com/install/), then
|
||||
|
||||
### FreeBSD
|
||||
|
||||
GitHub has no FreeBSD runners. `.github/workflows/freebsd.yml` boots a FreeBSD 14.3 VM
|
||||
GitHub has no FreeBSD runners. `.github/workflows/freebsd.yml` boots a FreeBSD 15.1-STABLE VM
|
||||
(`vmactions/freebsd-vm`). Run by hand from `release`, it builds and tests the workspace; called
|
||||
from `release.yml` with `package: true` it runs `packaging/freebsd/package.sh`, which builds the
|
||||
release binaries and writes `gridcraft-<v>-freebsd-x86_64.tar.gz` (`bin/` + `share/`, extract
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user