mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 17:10:43 -10:00
Compare commits
127
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95da89e081 | ||
|
|
2895ba3249 | ||
|
|
5573356405 | ||
|
|
a44df06755 | ||
|
|
4d3dbd69f6 | ||
|
|
533e75933e | ||
|
|
d87d0d959e | ||
|
|
f0ce91a097 | ||
|
|
ea43bb3014 | ||
|
|
66c923f4a8 | ||
|
|
e2163d96e6 | ||
|
|
a3d2f761ce | ||
|
|
dbad5a9b3a | ||
|
|
f54af950c9 | ||
|
|
1b4e253791 | ||
|
|
7588b5ebee | ||
|
|
164d78aa27 | ||
|
|
4c31478ae5 | ||
|
|
7804257a1f | ||
|
|
263bec799e | ||
|
|
22632b359f | ||
|
|
da57c88a62 | ||
|
|
cad3c58f8a | ||
|
|
793bb263a3 | ||
|
|
5a292a1392 | ||
|
|
35713ed46e | ||
|
|
b326c1e0f5 | ||
|
|
57bf125488 | ||
|
|
ac1a737eef | ||
|
|
e67fe2ce96 | ||
|
|
a9b5a74306 | ||
|
|
e64f7f50cd | ||
|
|
0c3539814d | ||
|
|
05acef3f03 | ||
|
|
cd21b99e82 | ||
|
|
21c7ff3691 | ||
|
|
8ad50df92b | ||
|
|
85cf456da1 | ||
|
|
9b50a7cf6b | ||
|
|
ff4066b56d | ||
|
|
958f8c7e97 | ||
|
|
c7be40d404 | ||
|
|
1e77d19966 | ||
|
|
5e44450ac4 | ||
|
|
cd74ec3a60 | ||
|
|
8bf2ca8bb1 | ||
|
|
e84a047949 | ||
|
|
f1f5031f79 | ||
|
|
7f4e86d3c0 | ||
|
|
c968232e5e | ||
|
|
14cd0438f9 | ||
|
|
4b4292a4a4 | ||
|
|
e072a874d8 | ||
|
|
561f1c2726 | ||
|
|
ed1dfebb9e | ||
|
|
ba48dfe0b9 | ||
|
|
ff37e78d7d | ||
|
|
22f65521a8 | ||
|
|
f95955c781 | ||
|
|
abff4c7768 | ||
|
|
10d3a411ed | ||
|
|
c6e5891e26 | ||
|
|
2f24a1b693 | ||
|
|
59fc0b6520 | ||
|
|
17fa87d048 | ||
|
|
9bb02269b2 | ||
|
|
3670d56d9e | ||
|
|
6b723daf0d | ||
|
|
28650f0615 | ||
|
|
4e59ccc796 | ||
|
|
9a9fa80242 | ||
|
|
42c6808c94 | ||
|
|
f040da0929 | ||
|
|
0abdc91b9e | ||
|
|
fab0f72a2f | ||
|
|
8c95b2cb64 | ||
|
|
7db2857171 | ||
|
|
f8ec0a7795 | ||
|
|
0459e81d9c | ||
|
|
eadc7b1883 | ||
|
|
5b2e61d153 | ||
|
|
116162df9c | ||
|
|
835738dfec | ||
|
|
2ea83e3c0e | ||
|
|
aafdf0bc0d | ||
|
|
9fb6dbd5ae | ||
|
|
23be188e9e | ||
|
|
1786c1e3cc | ||
|
|
6906e31e47 | ||
|
|
58ec7d40f3 | ||
|
|
5ff43981d4 | ||
|
|
941c74a8a4 | ||
|
|
724fdfd87e | ||
|
|
92bfe8fc4e | ||
|
|
c8c8d8e341 | ||
|
|
d2f919736b | ||
|
|
82b9616285 | ||
|
|
9111f39d97 | ||
|
|
aa90f02c8a | ||
|
|
1599703966 | ||
|
|
7533a016b2 | ||
|
|
32c09fc148 | ||
|
|
50161c6b31 | ||
|
|
9e5c144b40 | ||
|
|
51eab7c487 | ||
|
|
62d64b2eb7 | ||
|
|
38d5748406 | ||
|
|
4fb505dedf | ||
|
|
8dec43e259 | ||
|
|
db0685a360 | ||
|
|
e32eaee455 | ||
|
|
f52a7fa8c7 | ||
|
|
e35b0f7f59 | ||
|
|
09f040098e | ||
|
|
e05b98e35a | ||
|
|
49e2a036e6 | ||
|
|
221061b759 | ||
|
|
5bd0afb74d | ||
|
|
d821569545 | ||
|
|
4d7bd5e7a7 | ||
|
|
749b7a6ede | ||
|
|
89f422ad27 | ||
|
|
2c23584ee4 | ||
|
|
6745de2eda | ||
|
|
6ee9cd0069 | ||
|
|
46284a98f4 | ||
|
|
8777a70d87 |
No files matched your search
@@ -147,6 +147,7 @@ jobs:
|
||||
node perf/git-panel.mjs
|
||||
node perf/session-move-to.mjs
|
||||
node perf/shell-refused.mjs
|
||||
node perf/external-origin.mjs
|
||||
node perf/rail-search-hold.mjs
|
||||
node perf/rail-toggle-panes.mjs
|
||||
node perf/session-move.mjs
|
||||
|
||||
+14
-5
@@ -413,8 +413,13 @@ moving a number here must not move the promise.
|
||||
- Symlinks are recorded by `Lstat`, so a write through one lands outside what
|
||||
the walk compares. Confining the resolved target is the sandbox's job.
|
||||
- `internal/safety/sandbox` confines writes to the workspace, configured extras, temp
|
||||
and toolchain caches — on macOS and Linux. Windows has no OS-level bash
|
||||
sandbox, so there nothing the host enforces bounds `Writable`.
|
||||
and toolchain caches on macOS and Linux.
|
||||
- On Windows a user-enabled write-restricted token bounds the *creation* of files
|
||||
(create, append, overwrite, `mkdir`, HKCU writes, global git config, writes through links).
|
||||
- There, deleting or renaming away an existing file is not bounded, and with the
|
||||
setting off nothing the host enforces bounds `Writable`.
|
||||
- The caches a command may write can be poisoned for the user's later unsandboxed
|
||||
builds, on every platform.
|
||||
- The governed host authorities are a *named* set — ssh-agent, docker, podman.
|
||||
DBus, Wayland, X11, gpg-agent, keyrings and arbitrary sockets stay reachable,
|
||||
so the claim is "these endpoints are governed", never "host IPC is isolated".
|
||||
@@ -460,9 +465,13 @@ stop a connect. Possession is not authority: the key can be unreadable while an
|
||||
agent still signs with it.
|
||||
|
||||
A protection claim exists only where a backend has a demonstrated enforcement
|
||||
primitive for that dimension. Unsupported dimensions stay explicitly unsupported
|
||||
— Windows currently enforces none of the three — because a claim that outruns
|
||||
its enforcement is worse than an absent one: it is believed.
|
||||
primitive for that dimension. Unsupported dimensions stay explicitly unsupported,
|
||||
because a claim that outruns its enforcement is worse than an absent one: it is
|
||||
believed.
|
||||
|
||||
Windows enforces Integrity on file creation only, when the user turns it on.
|
||||
Deletion and rename, Confidentiality and Authority (the named pipes of ssh-agent
|
||||
and docker, COM and RPC services) are not enforced there.
|
||||
|
||||
**Known unmeasured surface — macOS host-mediated delegation:** Apple Events and
|
||||
Mach-service lookup are not denied by the current allow-default profile. Prior
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Build output and local tooling state.
|
||||
build/
|
||||
.gradle/
|
||||
.kotlin/
|
||||
local.properties
|
||||
*.iml
|
||||
.idea/
|
||||
|
||||
# The signing key and the file that names it.
|
||||
#
|
||||
# A key is not part of the project: it is the identity one person ships under,
|
||||
# and publishing it would let anyone else sign an APK that installs over
|
||||
# everyone's. Neither the keystore nor its password belongs in version control.
|
||||
# `app/build.gradle` reads both from here when present and falls back to the
|
||||
# debug key when they are not, so a fresh clone builds without them.
|
||||
keystore/
|
||||
|
||||
# Build inputs, produced by scripts/ before Gradle runs.
|
||||
# jniLibs/ holds the cross-compiled kernel, assets/page/ the built
|
||||
# frontend. assets/LICENSE is hand-placed and stays tracked.
|
||||
app/src/main/jniLibs/
|
||||
app/src/main/assets/page/
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
owner: @esengine
|
||||
backup: @SivanCola
|
||||
status: active
|
||||
reviewed: 2026-10-20
|
||||
---
|
||||
|
||||
# Reasonix Mobile — the Android shell
|
||||
|
||||
Runs Reasonix as an Android app: the kernel ships inside the APK and starts on the
|
||||
device, the interface is the same `desktop/frontend-next` build the desktop Studio
|
||||
serves, and the agent reaches servers over SSH.
|
||||
|
||||
This file is for people building it. What a person installing it needs — what it
|
||||
does, how to pair with a computer, what it cannot do — belongs in the release
|
||||
notes.
|
||||
|
||||
## One command
|
||||
|
||||
```bash
|
||||
./scripts/build.sh release # or debug
|
||||
```
|
||||
|
||||
Three steps, in this order:
|
||||
|
||||
1. `build-kernel.sh` → `app/src/main/jniLibs/arm64-v8a/libreasonix.so`
|
||||
2. `sync-page.sh` → `app/src/main/assets/page/`
|
||||
3. `./gradlew assembleRelease`
|
||||
|
||||
Output: `app/build/outputs/apk/release/app-release.apk`
|
||||
|
||||
The kernel and the page are **inputs to packaging, not Gradle build steps**.
|
||||
Running `gradle assembleRelease` on its own fails on purpose and names the script
|
||||
that produces whichever input is missing (`requireBuildInputs` in
|
||||
`app/build.gradle`): an APK with no kernel in it should not be buildable by
|
||||
accident.
|
||||
|
||||
## Requirements
|
||||
|
||||
| Component | Version |
|
||||
| --- | --- |
|
||||
| JDK | 21 (17 also works) |
|
||||
| Android SDK | `platforms;android-35`, `build-tools;35.0.0`, `platform-tools` |
|
||||
| Gradle | the committed wrapper, 8.14.3 (for AGP 8.11.1) |
|
||||
| Go | 1.26+ |
|
||||
| Node / pnpm | Node 24+ / pnpm 10 |
|
||||
|
||||
```bash
|
||||
export ANDROID_HOME="$HOME/Android/Sdk"
|
||||
export ANDROID_SDK_ROOT="$ANDROID_HOME"
|
||||
export JAVA_HOME="/path/to/jdk-21"
|
||||
export PATH="$PATH:$(go env GOPATH)/bin"
|
||||
```
|
||||
|
||||
`ANDROID_HOME` is the one thing nothing sets for you.
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | What it does |
|
||||
| --- | --- |
|
||||
| `build.sh [debug\|release]` | The whole chain |
|
||||
| `build-kernel.sh` | Cross-compiles the kernel only (`GOOS=android GOARCH=arm64 CGO_ENABLED=0`) |
|
||||
| `sync-page.sh` | Builds the frontend, copies `dist/` into assets, copies `LICENSE` |
|
||||
| `verify-page.sh` | **No phone needed**: starts the real kernel against the packaged page |
|
||||
| `run.sh [debug\|release]` | `adb install`, launch, follow the log |
|
||||
|
||||
`verify-page.sh` is the one to run after a change: it starts the kernel with the
|
||||
same arguments `Kernel.kt` uses (`--auth token`, `--token-file`, `--port-file`,
|
||||
`-page`) and checks that it binds a port and answers 200. Without a device, that
|
||||
is as deep as the chain can be verified.
|
||||
|
||||
## Where the code is
|
||||
|
||||
| File | Owns |
|
||||
| --- | --- |
|
||||
| `MainActivity.kt` | The WebView, the back gesture, downloads, external links, renderer restart |
|
||||
| `Kernel.kt` | Unpacking the page, starting and stopping the kernel, waiting for the port, health probes, logs, the workspace directory |
|
||||
| `KernelService.kt` | The foreground service that keeps a long turn alive |
|
||||
| `NativeBridge.kt` | `@JavascriptInterface`: what the page may ask the phone for |
|
||||
| `BrowserShellServer.kt` | Loopback HTTP server the kernel's browser tools drive the overlay WebView through |
|
||||
| `Downloader.kt` | Writing a kernel-produced file through the system document picker |
|
||||
|
||||
The page reaches the shell through `window.reasonixHost` and `ReasonixNative`,
|
||||
defined in `desktop/frontend-next/src/port/host.ts` (`AndroidHost`).
|
||||
|
||||
**Phone and desktop share one page build.** What differs only on a phone is
|
||||
decided at runtime, not by a second set of components. `phoneShell()` in
|
||||
`src/port/host.ts` and the `[data-shell="android"]` selector in `mobile.css` both
|
||||
read `<html data-shell="android">`, which `index.html` sets before the bundle
|
||||
loads.
|
||||
|
||||
One attribute feeding both is what keeps style and components from disagreeing
|
||||
about what a phone is.
|
||||
|
||||
## What the page may ask the phone for
|
||||
|
||||
`NativeBridge` is reachable from whatever document the WebView holds, so every
|
||||
method that touches the device asks `trusted()` first.
|
||||
|
||||
The activity answers by comparing the **main frame's** origin against the
|
||||
kernel's and against the one paired computer the person scanned a code for. A
|
||||
page that navigated elsewhere is not trusted, even though it may still hold the
|
||||
object.
|
||||
|
||||
Five methods answer without the check — `version`, `systemTheme`, `safeArea`,
|
||||
`setLayerOpen`, `setRunning` — because they report back what the page already
|
||||
knows about its own window and grant nothing.
|
||||
|
||||
`openInApp(url)` is the pairing decision, not a navigation one: it loads a URL in
|
||||
this window only for the origin the scanner just returned, and only once.
|
||||
Without that, any page holding the kernel origin could hand itself the bridge.
|
||||
|
||||
External links leave through the browser. A non-web scheme is routed to the
|
||||
system only for `mailto:` and `tel:`; everything else is dropped, because an
|
||||
`intent://` URL can start an arbitrary exported activity with caller-supplied
|
||||
extras.
|
||||
|
||||
## Permissions, and what they cost
|
||||
|
||||
`MANAGE_EXTERNAL_STORAGE` — opening a folder on the phone as a workspace. The
|
||||
kernel is a Go binary: it opens real paths with `open(2)`, and SAF hands back a
|
||||
`content://` URI it cannot open.
|
||||
|
||||
Requested from the folder-picker action, never at launch. Android shows no dialog
|
||||
for it and opens system settings instead.
|
||||
|
||||
**There is no OS-level sandbox around this kernel.** The PR sets the sandbox to
|
||||
off on Android, so confining the agent to the chosen folder is Reasonix's own
|
||||
write-root check and nothing else. A shell tool with all-files access can reach
|
||||
all shared storage.
|
||||
|
||||
`REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` — Doze freezes the app group, which stops
|
||||
a turn that is still running. Asked once when a turn actually runs, never at
|
||||
launch, and the person can refuse. Refusing costs battery life during long turns
|
||||
and nothing else.
|
||||
|
||||
**Google Play restricts this permission**: fine for a sideloaded build, a
|
||||
store-policy risk if this is ever listed.
|
||||
|
||||
`FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_DATA_SYNC` — keeping the kernel alive
|
||||
while the screen is off. `dataSync` is capped per 24 hours from Android 15. It is
|
||||
the closest honest description of "an agent is working".
|
||||
|
||||
`CAMERA` — reading the pairing code a computer shows. Requested when the person
|
||||
asks to scan, never at launch. `ScanActivity` is not exported.
|
||||
|
||||
`READ_EXTERNAL_STORAGE` / `WRITE_EXTERNAL_STORAGE` — the same folder walk below
|
||||
API 33. `maxSdkVersion`-gated; above 33 they are superseded by the permission
|
||||
above.
|
||||
|
||||
`allowBackup=false` with explicit extraction rules, so a `keystore` or a token in
|
||||
app storage never leaves the device in a cloud backup.
|
||||
|
||||
## Cleartext HTTP
|
||||
|
||||
The kernel serves its page on `127.0.0.1:<port>`, and a paired computer serves
|
||||
the same page over its LAN address. Both are plain HTTP.
|
||||
|
||||
Neither address can be written into a `network-security-config`: the port is
|
||||
chosen at start, the LAN address at scan time, and the format matches literals
|
||||
and domains, not subnets.
|
||||
|
||||
So the config permits cleartext and the boundary is in the code instead.
|
||||
`shouldOverrideUrlLoading` sends every other http(s) origin to the browser, and
|
||||
the bridge answers only the kernel and the just-paired computer. A plaintext page
|
||||
on the LAN cannot become the document holding the bridge.
|
||||
|
||||
## What goes into the APK
|
||||
|
||||
| Content | Size | Why it is shaped this way |
|
||||
| --- | --- | --- |
|
||||
| `lib/arm64-v8a/libreasonix.so` | 45 MB | Go static binary, stripped. It is a `.so` rather than a file in `assets/` because only `nativeLibraryDir` is guaranteed executable — a binary copied to app storage fails on a device whose data partition is mounted `noexec`. |
|
||||
| `assets/page/` | 14 MB | The frontend build, including the Inter and Noto Sans SC fonts, `noCompress` |
|
||||
| `assets/LICENSE` | 1 KB | The repository's MIT licence, verbatim. MIT requires the notice and the licence text to accompany a binary distribution. |
|
||||
|
||||
`assets/LICENSE` is generated by `sync-page.sh` from the repository's root
|
||||
`LICENSE`, not committed a second time: a checked-in copy drifts when the root
|
||||
file is updated.
|
||||
|
||||
It sits in `assets/` rather than `assets/page/` because that directory is removed
|
||||
and rebuilt on every build.
|
||||
|
||||
A release APK is about 31 MB.
|
||||
|
||||
## Building
|
||||
|
||||
**The Gradle wrapper is committed**, jar and all. `build.sh` refuses to run
|
||||
without `gradlew` rather than generating one from whatever `gradle` is on `PATH`:
|
||||
the dependency versions are part of the build.
|
||||
|
||||
`gradle-wrapper.properties` pins `distributionSha256Sum`, so a mirror that serves
|
||||
a different distribution zip fails verification instead of being unpacked and
|
||||
run. Dependency repositories are the official ones only — a mirror belongs in a
|
||||
user-level init script.
|
||||
|
||||
**Signing.** A release with no key configured comes out **unsigned**
|
||||
(`app-release-unsigned.apk`) with a warning. It used to fall back to the debug
|
||||
key, which produced an artifact that looked shippable and was signed by a
|
||||
per-machine key nobody chose: it could not install over the previous build.
|
||||
|
||||
Point the build at a real key by writing `keystore/keystore.properties`
|
||||
(`storeFile`, `storePassword`, `keyAlias`, and optionally `keyPassword`) or by
|
||||
setting the matching `REASONIX_KEYSTORE*` environment variables. Key material
|
||||
stays out of the repository and out of build logs.
|
||||
|
||||
Debug builds always use the debug key. Signing a debug build with the release key
|
||||
would let anyone who can read the keystore produce a build that installs over the
|
||||
shipped one under the same signature.
|
||||
|
||||
**Non-ASCII checkout paths.** AGP refuses to build under a path with non-ASCII
|
||||
characters on Windows unless `android.overridePathCheck=true` is set. That is a
|
||||
property of one machine's disk layout, not of this project, so it is not in the
|
||||
repository's `gradle.properties`.
|
||||
|
||||
Set it in a user-level `~/.gradle/gradle.properties` or pass
|
||||
`-Pandroid.overridePathCheck=true`.
|
||||
@@ -0,0 +1,242 @@
|
||||
// The app module.
|
||||
//
|
||||
// Two things ship inside the APK and neither is fetched at runtime: the kernel
|
||||
// binary, and the built page it serves. Bundling the page is what makes the app
|
||||
// work offline and start instantly; bundling the kernel is what lets it run
|
||||
// `reasonix serve` on the phone itself, which is the whole point — the agent
|
||||
// starts locally and reaches the server over SSH, so the interface, the model
|
||||
// catalogue and the credentials all live on the phone.
|
||||
//
|
||||
// The kernel is placed as `jniLibs/arm64-v8a/libreasonix.so`, not under
|
||||
// `assets/`. That is not a trick for its own sake: Android permits executing a
|
||||
// file under `nativeLibraryDir` and nothing under `filesDir` has that
|
||||
// guarantee, so a binary shipped the ordinary way would have to be copied out
|
||||
// and made executable at runtime — which fails outright on a device mounted
|
||||
// noexec, and fails confusingly on the ones that are merely unusual. `scripts/
|
||||
// build-kernel.sh` writes it there; the name is fixed by the packaging rules.
|
||||
plugins {
|
||||
id "com.android.application"
|
||||
id "org.jetbrains.kotlin.android"
|
||||
}
|
||||
|
||||
// One version, read by the About screen and the update check.
|
||||
def versionMajor = 2
|
||||
def versionMinor = 0
|
||||
def versionPatch = 0
|
||||
def versionBuild = 1
|
||||
|
||||
// Where the two build inputs are expected. Both are produced from the checkout
|
||||
// beside this module, by the scripts named in each message.
|
||||
def upstream = rootProject.file("..")
|
||||
def pageDir = new File(projectDir, "src/main/assets/page")
|
||||
def kernelSo = new File(projectDir, "src/main/jniLibs/arm64-v8a/libreasonix.so")
|
||||
|
||||
android {
|
||||
namespace "io.reasonix.mobile.app"
|
||||
compileSdk 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId "io.reasonix.mobile.app"
|
||||
minSdk 26
|
||||
// 35: the API level this app is actually built and tested against.
|
||||
//
|
||||
// It was briefly lowered to 26 while chasing an install failure that
|
||||
// turned out to be a package-name collision with an unrelated app on the
|
||||
// user's phone — the signature error named the wrong cause. Nothing about
|
||||
// the target level ever caused it, so it goes back to the level the code
|
||||
// is really written for.
|
||||
//
|
||||
// One consequence to keep in mind: from 35, Android 15 forces the window
|
||||
// edge-to-edge and ignores a request to lay out inside the safe area. The
|
||||
// window therefore *is* drawn under the status bar and the home indicator,
|
||||
// and the only correct answer is for the page to pad itself — which is
|
||||
// what `MainActivity` feeds real inset values for, since a WebView does
|
||||
// not implement `env(safe-area-inset-*)`.
|
||||
targetSdk 35
|
||||
versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch * 10 + versionBuild
|
||||
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
|
||||
|
||||
// The kernel is built for arm64 only, so every other ABI would ship an
|
||||
// APK that installs and then cannot start. Naming the one real ABI keeps
|
||||
// the store listing and the installer honest.
|
||||
ndk {
|
||||
abiFilters "arm64-v8a"
|
||||
}
|
||||
|
||||
resourceConfigurations += ["zh", "en"]
|
||||
}
|
||||
|
||||
// Android identifies an app by package name *and* signing key: an APK signed
|
||||
// with a different key is not an update, it is an impostor, and the
|
||||
// installer refuses it with "the signature does not match the installed
|
||||
// app". Gradle's default release key is the debug key in the user's home
|
||||
// directory, which is per-machine, so a build made on a second computer
|
||||
// could never be installed over one made on the first.
|
||||
//
|
||||
// Whoever ships a build therefore pins a key — and that key is theirs, not
|
||||
// the project's. It lives beside the checkout, in `keystore/`, which is
|
||||
// ignored; so does the file naming it. A checkout without either signs with
|
||||
// the debug key instead, which is what a contributor building locally wants
|
||||
// and is what the README tells them to expect. Point the build at a real key
|
||||
// by writing `keystore/keystore.properties` (storeFile, storePassword,
|
||||
// keyAlias) or by setting REASONIX_KEYSTORE / REASONIX_KEYSTORE_PASSWORD /
|
||||
// REASONIX_KEY_ALIAS.
|
||||
def keyProperties = new Properties()
|
||||
def keyPropertiesFile = rootProject.file("keystore/keystore.properties")
|
||||
if (keyPropertiesFile.exists()) {
|
||||
keyPropertiesFile.withInputStream { keyProperties.load(it) }
|
||||
}
|
||||
def keyStorePath = keyProperties.getProperty("storeFile") ?: System.getenv("REASONIX_KEYSTORE")
|
||||
def keyStorePassword = keyProperties.getProperty("storePassword") ?: System.getenv("REASONIX_KEYSTORE_PASSWORD")
|
||||
// The key's own password is a separate fact from the store's. PKCS#12 keystores
|
||||
// almost always use one password for both, so falling back to the store's
|
||||
// password keeps those working — but assuming they are equal is how a keystore
|
||||
// that separates them gets a build failure at signing time, after the work is
|
||||
// done, with an error that does not say which of the two was wrong.
|
||||
def keyPasswordValue = keyProperties.getProperty("keyPassword") ?: System.getenv("REASONIX_KEY_PASSWORD") ?: keyStorePassword
|
||||
def keyAliasName = keyProperties.getProperty("keyAlias") ?: System.getenv("REASONIX_KEY_ALIAS")
|
||||
def haveReleaseKey = keyStorePath && keyStorePassword && keyAliasName &&
|
||||
rootProject.file(keyStorePath).exists()
|
||||
|
||||
signingConfigs {
|
||||
if (haveReleaseKey) {
|
||||
releaseKey {
|
||||
storeFile rootProject.file(keyStorePath)
|
||||
storePassword keyStorePassword
|
||||
keyAlias keyAliasName
|
||||
keyPassword keyPasswordValue
|
||||
// v1 is not optional here. Android 7+ reads v2 and ignores v1, so
|
||||
// a v2-only APK installs on a modern phone — and then fails on the
|
||||
// compatibility layers older devices and HarmonyOS' 卓易通 run,
|
||||
// which know only the JAR signature and report its absence as a
|
||||
// signature *mismatch*. Signing both is what makes one APK install
|
||||
// everywhere.
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing native is compiled here — the one .so is a prebuilt the kernel
|
||||
// script writes — so the external native build is left alone entirely.
|
||||
buildTypes {
|
||||
debug {
|
||||
applicationIdSuffix ".debug"
|
||||
versionNameSuffix "-debug"
|
||||
// The debug key, always. Signing a debug build with the release key
|
||||
// would mean anyone who can read the release keystore can produce a
|
||||
// build that installs over the shipped one under the same signature,
|
||||
// and it buys nothing: the debug package is suffixed `.debug`, so the
|
||||
// two already install side by side.
|
||||
}
|
||||
release {
|
||||
// The kernel is a stripped Go binary and the page is minified, but
|
||||
// the Kotlin shell still benefits and shipping the shrunk build is
|
||||
// how a size regression gets noticed.
|
||||
minifyEnabled true
|
||||
shrinkResources true
|
||||
proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
|
||||
// A release with no key of its own comes out *unsigned*
|
||||
// (`app-release-unsigned.apk`). It used to fall back to the debug key
|
||||
// so the artifact would install, which produced a release that looked
|
||||
// shippable and was signed by a per-machine key nobody chose: it could
|
||||
// not be installed over the previous build, and every machine made a
|
||||
// different one. An unsigned artifact says what it is.
|
||||
if (haveReleaseKey) {
|
||||
signingConfig signingConfigs.releaseKey
|
||||
} else {
|
||||
logger.warn(
|
||||
"release build has no signing key: producing an unsigned APK. " +
|
||||
"Write keystore/keystore.properties (storeFile, storePassword, keyAlias) " +
|
||||
"or set REASONIX_KEYSTORE / REASONIX_KEYSTORE_PASSWORD / REASONIX_KEY_ALIAS."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
// AGP 8 stops generating BuildConfig unless asked. `Kernel` reads the
|
||||
// version name and code out of it to decide whether the bundled page
|
||||
// needs unpacking, so it is asked for.
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// `extractNativeLibs=true`: the kernel must exist as a real file on
|
||||
// disk to be executed, and an uncompressed-and-mmap'd .so is not
|
||||
// one. This is the only reason the flag is on.
|
||||
useLegacyPackaging true
|
||||
}
|
||||
resources {
|
||||
excludes += ["META-INF/*.version", "META-INF/*.kotlin_module", "kotlin/**", "DebugProbesKt.bin"]
|
||||
}
|
||||
}
|
||||
|
||||
// The page is read out of assets by `Kernel.publish`, not by the resource
|
||||
// system, so it is not compressed — a page is already-compressed text and
|
||||
// shrinking it again only costs startup time.
|
||||
androidResources {
|
||||
noCompress += ["json", "woff2", "ttf", "woff", "txt", "svg"]
|
||||
}
|
||||
|
||||
lint {
|
||||
abortOnError true
|
||||
warningsAsErrors false
|
||||
checkReleaseBuilds true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "androidx.core:core-ktx:1.15.0"
|
||||
implementation "androidx.appcompat:appcompat:1.7.0"
|
||||
implementation "androidx.activity:activity-ktx:1.9.3"
|
||||
implementation "androidx.webkit:webkit:1.12.1"
|
||||
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7"
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
|
||||
|
||||
// Scanning the pairing code a computer shows.
|
||||
//
|
||||
// CameraX for the preview and the frame stream, ZXing for the decode, and
|
||||
// deliberately not ML Kit: this app installs on phones whose HarmonyOS
|
||||
// compatibility layer has no Google Play Services, so a decoder that needs
|
||||
// GMS would work on the developer's phone and fail on the user's. ZXing
|
||||
// core is pure Java with no runtime dependency at all, which is what makes
|
||||
// the scanner work on both.
|
||||
implementation "androidx.camera:camera-core:1.4.1"
|
||||
implementation "androidx.camera:camera-camera2:1.4.1"
|
||||
implementation "androidx.camera:camera-lifecycle:1.4.1"
|
||||
implementation "androidx.camera:camera-view:1.4.1"
|
||||
implementation "com.google.zxing:core:3.5.3"
|
||||
}
|
||||
|
||||
// Fail before the packaging step with something a person can act on, rather
|
||||
// than shipping an APK whose kernel is missing or whose page is a directory the
|
||||
// build never filled. The two messages name the script that produces each.
|
||||
tasks.register("requireBuildInputs") {
|
||||
doFirst {
|
||||
if (!kernelSo.exists()) {
|
||||
throw new GradleException(
|
||||
"内核二进制缺失:${kernelSo}\n先运行 ./scripts/build-kernel.sh(在 android/ 目录下)交叉编译内核。")
|
||||
}
|
||||
if (!pageDir.exists() || !new File(pageDir, "index.html").exists()) {
|
||||
throw new GradleException(
|
||||
"前端页面缺失:${pageDir}/index.html\n先运行 ./scripts/sync-page.sh(在 android/ 目录下)构建并同步页面。")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.configureEach { task ->
|
||||
if (task.name.startsWith("merge") && (task.name.contains("Assets") || task.name.contains("JniLibFolders"))) {
|
||||
task.dependsOn("requireBuildInputs")
|
||||
}
|
||||
}
|
||||
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# R8 rules for the shell.
|
||||
#
|
||||
# There is very little to keep here, and that is the point: the app's own code
|
||||
# is reached from the manifest and from Android's own callbacks, both of which
|
||||
# R8 already traces, and nothing in it is loaded reflectively. What follows is
|
||||
# the two places where a name is looked up rather than called.
|
||||
|
||||
# The WebView's JavaScript bridge, if one is ever added, is resolved by name on
|
||||
# the Java side and by the string the page uses. Keeping annotated members makes
|
||||
# that survive shrinking rather than failing at runtime with a method-not-found
|
||||
# that only shows up on a release build.
|
||||
-keepclassmembers class * {
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
|
||||
# The Kernel's child process is started by absolute path, and its own log is
|
||||
# read as text; neither is reflective, so nothing else needs keeping.
|
||||
|
||||
# Line numbers make a stack trace from a release build readable, which is the
|
||||
# only way a crash report from a phone can be acted on.
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
# Kotlin's `@Metadata` annotation is present on every class the compiler touched
|
||||
# and nothing in this app reflects over it. It is tempting to `-assumenosideeffects`
|
||||
# it away, and that was tried: any pattern broad enough to name its members also
|
||||
# matches the methods every class inherits from `Object` — `equals`, `hashCode`,
|
||||
# `toString` — and R8 then treats those as removable, which is a silent
|
||||
# behaviour change for a few kilobytes. Left as a warning suppression instead:
|
||||
# the annotation is dropped from the shrunk output anyway, because nothing reads
|
||||
# it.
|
||||
-dontwarn kotlin.Metadata
|
||||
@@ -0,0 +1,112 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
The shell's manifest.
|
||||
|
||||
There is no INTERNET-adjacent permission beyond INTERNET itself: the page and
|
||||
the kernel talk over loopback, and reaching a server is the kernel's job over
|
||||
a socket it owns. Reading and writing files goes through the system's document
|
||||
picker (SAF), which hands back a grant for one file at a time — so no
|
||||
storage permission is declared and none is needed.
|
||||
|
||||
`usesCleartextTraffic` is off here, and cleartext is re-enabled in the network
|
||||
security config only because the kernel serves its page on `127.0.0.1` and a
|
||||
paired computer serves the same page over its LAN address — both plain HTTP.
|
||||
The config says what that costs and what bounds it.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<!-- Only to tell the person the kernel is still running while the screen is
|
||||
off; it is a foreground service with a dismissible notification, not a
|
||||
background wake-up. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<!-- From API 34 every foreground-service *type* needs its own permission as
|
||||
well as the general one: naming dataSync in the manifest without asking
|
||||
for it is a SecurityException at startForeground, on the one code path
|
||||
that keeps a long task alive. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Only to read the pairing code a computer shows. Requested at the
|
||||
moment the person asks to scan, never at launch. -->
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<!-- The kernel is a child process, and a task left running is one the person
|
||||
expects to finish with the screen off. Android's own doze can freeze the
|
||||
whole app group instead, which is what the shell asks to be exempt from
|
||||
— once, when a turn is actually running, never at launch. It is a
|
||||
request the person can refuse, and refusing it only costs battery life
|
||||
during a long turn. -->
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<!-- Every-file access, for opening a folder on this phone as a workspace.
|
||||
The kernel is a plain Go binary: it opens paths with `open(2)`, and a
|
||||
document URI is not a path it can open. SAF would hand back exactly
|
||||
that unusable URI, so the one honest permission is the broad one —
|
||||
granted by the person in system settings, which is the only place
|
||||
Android offers it. Nothing here reads storage for any other purpose. -->
|
||||
<uses-permission
|
||||
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<!-- Below API 33 the same folder walk needs the older pair; from 33 they are
|
||||
superseded by the permission above and asking for them would be a lie. -->
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
|
||||
|
||||
<!-- A phone without a touchscreen cannot drive this interface; saying so
|
||||
keeps the listing honest rather than letting it install on a TV. -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="true" />
|
||||
<!-- The camera is optional: a phone without one is still a fine client for
|
||||
a kernel it already knows, and it can still pair by opening the link the
|
||||
computer shows. Requiring it would take the app off those devices. -->
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Reasonix"
|
||||
android:usesCleartextTraffic="false"
|
||||
tools:targetApi="35">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode|density|fontScale|smallestScreenSize"
|
||||
android:launchMode="singleTask"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:theme="@style/Theme.Reasonix">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- The kernel outlives the screen: a turn that takes minutes would
|
||||
otherwise be killed when the phone is pocketed. The service is
|
||||
`stopWithTask="false"` so swiping the app away ends it deliberately
|
||||
rather than silently, and `foregroundServiceType="dataSync"` is the
|
||||
closest honest description of "an agent is working". -->
|
||||
<service
|
||||
android:name=".KernelService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync"
|
||||
android:stopWithTask="false" />
|
||||
|
||||
<!-- Reading the pairing code a computer shows. Its own activity rather
|
||||
than a dialog, because the camera preview needs the whole screen to
|
||||
be worth pointing at anything. Not exported: only this app starts
|
||||
it, and a scanner another app could open is one that could be made
|
||||
to read a code on someone else's behalf. -->
|
||||
<activity
|
||||
android:name=".ScanActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/Theme.Reasonix.Scan" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,59 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* The process-wide facts this app needs.
|
||||
*
|
||||
* The kernel is one child process, so there is exactly one of it no matter how
|
||||
* many activities exist: it is held here, lazily, and the activity and the
|
||||
* service both reach the same instance. Nothing else is stored — the theme, the
|
||||
* language and every preference belong to the page and live in its localStorage.
|
||||
*/
|
||||
class App : Application() {
|
||||
|
||||
/**
|
||||
* The kernel, created on first use.
|
||||
*
|
||||
* Lazy rather than eager so that merely launching the process to answer a
|
||||
* notification does not unpack a 15MB page.
|
||||
*/
|
||||
val kernel: Kernel by lazy { Kernel(this) }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createChannel()
|
||||
}
|
||||
|
||||
/**
|
||||
* A channel the person can mute without muting the app, and one they can
|
||||
* find: an agent that runs for minutes on a phone has to say so somewhere
|
||||
* the system will not kill, and a notification is the only place Android
|
||||
* offers. `IMPORTANCE_MIN` because the notification is a receipt, not an
|
||||
* interruption — the work it reports is on another machine.
|
||||
*/
|
||||
private fun createChannel() {
|
||||
// No SDK_INT guard: minSdk is 26, which is the release NotificationChannel
|
||||
// arrived in, so every device this app installs on has it.
|
||||
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
if (manager.getNotificationChannel(CHANNEL_KERNEL) != null) return
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_KERNEL,
|
||||
getString(R.string.channel_kernel),
|
||||
NotificationManager.IMPORTANCE_MIN,
|
||||
).apply {
|
||||
description = getString(R.string.channel_kernel_desc)
|
||||
setShowBadge(false)
|
||||
enableVibration(false)
|
||||
setSound(null, null)
|
||||
}
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_KERNEL = "reasonix-kernel"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.net.SocketException
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* The kernel's browser, as a loopback HTTP server.
|
||||
*
|
||||
* The Go kernel (`internal/platform/browser/shell.go`) drives a WebView by
|
||||
* POSTing JSON to a handful of paths on 127.0.0.1. This class is the other end
|
||||
* of that conversation: it accepts connections on a random port, parses the
|
||||
* minimal HTTP the kernel sends, and translates each path into an operation on
|
||||
* the overlay WebView.
|
||||
*
|
||||
* The server is deliberately tiny — no connection pooling, no keep-alive, no
|
||||
* chunked encoding — because the kernel is its only client and sends one
|
||||
* request per connection. A `ServerSocket` accept loop on a daemon thread is
|
||||
* the whole transport; each request is handled synchronously on its own thread.
|
||||
*
|
||||
* WebView operations must run on the UI thread. Each handler posts to the main
|
||||
* looper and waits on a latch, with a timeout that bounds the worst case (a
|
||||
* page that hangs the JS thread) to something the kernel's own 30-second client
|
||||
* timeout will not outlast.
|
||||
*
|
||||
* Memory note on `/screenshot`: a full-page `WebView.draw` into an ARGB_8888
|
||||
* bitmap at device resolution can reach tens of MB for a long page. The bitmap
|
||||
* is downsampled by a factor of 2 in each dimension before PNG encoding, which
|
||||
* keeps the peak allocation under ~10 MB for a typical 1080p viewport. The
|
||||
* original is recycled immediately after the downsample.
|
||||
*/
|
||||
/** One thing a page asked the network for, as the WebView's request
|
||||
* interceptor reports it. The interceptor is handed the method and the URL
|
||||
* and nothing about the response, so a caller may show exactly this much and
|
||||
* must not read it as a completed exchange. */
|
||||
data class BrowserRequest(val method: String, val url: String, val kind: String)
|
||||
|
||||
class BrowserShellServer(
|
||||
/** The overlay WebView, when one already exists. The routes that act on an
|
||||
* open page — back, forward, reload, close — use this: with no page there
|
||||
* is nothing to act on, and creating one to do nothing to it would start a
|
||||
* renderer nobody asked for. */
|
||||
private val existingView: () -> WebView?,
|
||||
/** The overlay WebView, created on first use. The routes that drive a page
|
||||
* use this, because the kernel can open one before the panel has ever been
|
||||
* shown: the page's own panel asks for the view when it is displayed, and
|
||||
* an agent's `browser_open` can arrive first. Requiring the view to exist
|
||||
* already answered every such call with "browser view not ready", which
|
||||
* reads as a broken engine rather than as a view that was not created yet.
|
||||
* Called on the UI thread. */
|
||||
private val ensureView: () -> WebView,
|
||||
/** Why the page in the view is the browser's own error page rather than a
|
||||
* site, as `(url, chromium error)`; null when the last load succeeded.
|
||||
* `/read` asks this, because extracting `innerText` from the error page
|
||||
* returns the browser's own "this page could not be loaded" notice, which
|
||||
* the kernel would hand to the model as though the site had said it. */
|
||||
private val loadFailure: () -> Pair<String, String>? = { null },
|
||||
/** Begin a navigation: forget the load failure recorded for the page being
|
||||
* left, drop its request list, and start the wait a following `/read`
|
||||
* joins. Called on the UI thread, before the new address is loaded, so the
|
||||
* wait is in place before any callback for the new page can fire. */
|
||||
private val startNavigation: () -> Unit = {},
|
||||
/** What the page currently in the view has asked the network for, oldest
|
||||
* first. The WebView reports a request's method and URL to its interceptor
|
||||
* but nothing about the response, so that is all a caller may show. */
|
||||
private val requests: () -> List<BrowserRequest> = { emptyList() },
|
||||
/** Wait for the navigation last asked for to settle — the page arrived, or
|
||||
* its load failed — up to the given milliseconds. Called on the request's
|
||||
* own thread, never the UI thread: the settle is signalled from the UI
|
||||
* thread, so waiting on it there would deadlock. `/load` starts a
|
||||
* navigation and returns before the page has been visited; without this a
|
||||
* `/read` right behind it still sees the URL of the page before, and a
|
||||
* failure recorded for that page was handed back as the new one's answer. */
|
||||
private val awaitNavigation: (Long) -> Unit = {},
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "BrowserShellServer"
|
||||
|
||||
/** How long a UI-thread operation may take before the handler gives up.
|
||||
* The kernel's client timeout is 30 s; staying under it means the kernel
|
||||
* sees a clean error rather than a dropped connection. */
|
||||
private const val UI_TIMEOUT_MS = 25_000L
|
||||
|
||||
/** The maximum text `/read` returns. Matches the kernel's `maxReadText`
|
||||
* (400 << 10). The shell truncates here and says so, rather than letting
|
||||
* the kernel truncate silently. */
|
||||
private const val MAX_READ_TEXT = 400 * 1024
|
||||
|
||||
/** Screenshot downsample factor. 2 means half width and half height. */
|
||||
private const val SCREENSHOT_SCALE = 2
|
||||
|
||||
/** The address the kernel dials. Both ends must agree on the family:
|
||||
* see [start] for what goes wrong when they do not. */
|
||||
private const val LOOPBACK_V4 = "127.0.0.1"
|
||||
|
||||
/** How long `/read` waits for a navigation it follows to settle before
|
||||
* reading whatever the view is on. A page that never finishes loading
|
||||
* must not hold the tool call open to the kernel's own timeout. */
|
||||
private const val NAV_SETTLE_MS = 10_000L
|
||||
|
||||
/** How long `/read` then waits for the page's own script to answer.
|
||||
* `NAV_SETTLE_MS + READ_SCRIPT_MS` has to stay under [UI_TIMEOUT_MS],
|
||||
* and that under the kernel's 30-second client timeout: a read that
|
||||
* waited out both budgets would outlast the caller, which would see a
|
||||
* dropped connection instead of this shell's answer. 10 + 15 = 25 s. */
|
||||
private const val READ_SCRIPT_MS = 15_000L
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var serverSocket: ServerSocket? = null
|
||||
|
||||
/** The port the server is listening on. Valid after [start] returns. */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
private set
|
||||
|
||||
/**
|
||||
* The bearer credential every request must carry. Minted by the activity
|
||||
* and handed to the kernel through the child's environment, so the server
|
||||
* answers only the process this shell started.
|
||||
*
|
||||
* A phone's loopback is not a boundary: any other app may connect to
|
||||
* 127.0.0.1, and the routes here run script in and read text out of
|
||||
* whatever page is loaded. Binding to `getLoopbackAddress()` keeps other
|
||||
* machines out but not other apps, so the credential is what makes "only
|
||||
* the kernel this shell started" true.
|
||||
*/
|
||||
@Volatile
|
||||
var token: String = ""
|
||||
private set
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* Start listening on 127.0.0.1 with an ephemeral port. The port is available
|
||||
* via [port] immediately after this returns, and the credential the kernel
|
||||
* must present via [token].
|
||||
*/
|
||||
fun start() {
|
||||
token = newToken()
|
||||
// The loopback address is spelled out as IPv4, not taken from
|
||||
// `InetAddress.getLoopbackAddress()`. That call is allowed to answer
|
||||
// either family and Android's libcore answers IPv6 (`::1`), while the
|
||||
// kernel's client is hardcoded to `http://127.0.0.1:<port>`
|
||||
// (`internal/assembly/boot/browser.go`). A socket bound to `::1` does
|
||||
// not answer a dial to `127.0.0.1`, so every browser call failed with
|
||||
// "connection refused" while the port was bound and reported — the
|
||||
// failure looked like a server that never started. Both ends have to
|
||||
// name the same family, and IPv4 is the one the kernel names.
|
||||
val ss = ServerSocket(0, 16, java.net.InetAddress.getByName(LOOPBACK_V4))
|
||||
serverSocket = ss
|
||||
port = ss.localPort
|
||||
Log.i(TAG, "browser shell server listening on $LOOPBACK_V4:$port")
|
||||
|
||||
Thread({
|
||||
while (!ss.isClosed) {
|
||||
try {
|
||||
val client = ss.accept()
|
||||
Thread({ handleClient(client, token) }, "browser-shell-conn").apply { isDaemon = true }.start()
|
||||
} catch (_: SocketException) {
|
||||
// Server was closed; exit the loop.
|
||||
}
|
||||
}
|
||||
}, "browser-shell-accept").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
runCatching { serverSocket?.close() }
|
||||
serverSocket = null
|
||||
}
|
||||
|
||||
/** A fresh 256-bit credential, hex-encoded, for one launch of the server. */
|
||||
private fun newToken(): String {
|
||||
val bytes = ByteArray(32)
|
||||
java.security.SecureRandom().nextBytes(bytes)
|
||||
return bytes.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
// ---- HTTP plumbing --------------------------------------------------------
|
||||
|
||||
private fun handleClient(client: Socket, expected: String) {
|
||||
try {
|
||||
client.soTimeout = 30_000
|
||||
val input = BufferedInputStream(client.getInputStream())
|
||||
val output = client.getOutputStream()
|
||||
|
||||
// Parse the request line.
|
||||
val requestLine = readLine(input) ?: return
|
||||
val parts = requestLine.split(" ", limit = 3)
|
||||
if (parts.size < 2) return
|
||||
val method = parts[0]
|
||||
val path = parts[1].substringBefore('?')
|
||||
|
||||
// Read headers.
|
||||
var contentLength = 0
|
||||
var bearer: String? = null
|
||||
while (true) {
|
||||
val header = readLine(input) ?: break
|
||||
if (header.isEmpty()) break
|
||||
val lower = header.lowercase()
|
||||
if (lower.startsWith("content-length:")) {
|
||||
contentLength = header.substringAfter(':').trim().toIntOrNull() ?: 0
|
||||
} else if (lower.startsWith("authorization:")) {
|
||||
bearer = header.substringAfter(':').trim().removePrefix("Bearer ").trim()
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing behind this server is safe to hand out on the strength of
|
||||
// an address: the port is on loopback, which any other app on the
|
||||
// phone can dial, and the routes run script in and read text out of
|
||||
// the loaded page. The credential the kernel was started with is the
|
||||
// only thing that says a caller is that kernel. Every route is
|
||||
// refused without it, /health included — a probe needs no exemption.
|
||||
if (expected.isEmpty() || bearer != expected) {
|
||||
writeResponse(output, 401, """{"error":"unauthorized"}""")
|
||||
return
|
||||
}
|
||||
|
||||
// Read body.
|
||||
val body = if (contentLength > 0) {
|
||||
val buf = ByteArray(contentLength)
|
||||
var read = 0
|
||||
while (read < contentLength) {
|
||||
val n = input.read(buf, read, contentLength - read)
|
||||
if (n == -1) break
|
||||
read += n
|
||||
}
|
||||
String(buf, 0, read, Charsets.UTF_8)
|
||||
} else ""
|
||||
|
||||
// Route.
|
||||
val (status, responseBody) = route(method, path, body)
|
||||
writeResponse(output, status, responseBody)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "connection error: ${e.message}")
|
||||
} finally {
|
||||
runCatching { client.close() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun route(method: String, path: String, body: String): Pair<Int, String> {
|
||||
return when {
|
||||
method == "GET" && path == "/health" -> 200 to """{"ok":true}"""
|
||||
method == "POST" && path == "/load" -> handleLoad(body)
|
||||
method == "POST" && path == "/close" -> handleClose()
|
||||
method == "POST" && path == "/read" -> handleRead()
|
||||
method == "POST" && path == "/screenshot" -> handleScreenshot()
|
||||
method == "POST" && path == "/click" -> handleClick(body)
|
||||
method == "POST" && path == "/eval" -> handleEval(body)
|
||||
method == "POST" && path == "/back" -> handleBack()
|
||||
method == "POST" && path == "/forward" -> handleForward()
|
||||
method == "POST" && path == "/reload" -> handleReload()
|
||||
method == "POST" && path == "/requests" -> handleRequests()
|
||||
else -> 404 to """{"error":"not found"}"""
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeResponse(out: OutputStream, status: Int, body: String) {
|
||||
val reason = when (status) {
|
||||
200 -> "OK"
|
||||
404 -> "Not Found"
|
||||
500 -> "Internal Server Error"
|
||||
else -> "Error"
|
||||
}
|
||||
val bytes = body.toByteArray(Charsets.UTF_8)
|
||||
val header = "HTTP/1.1 $status $reason\r\n" +
|
||||
"Content-Type: application/json\r\n" +
|
||||
"Content-Length: ${bytes.size}\r\n" +
|
||||
"Connection: close\r\n" +
|
||||
"\r\n"
|
||||
out.write(header.toByteArray(Charsets.UTF_8))
|
||||
out.write(bytes)
|
||||
out.flush()
|
||||
}
|
||||
|
||||
private fun readLine(input: BufferedInputStream): String? {
|
||||
val sb = StringBuilder()
|
||||
while (true) {
|
||||
val b = input.read()
|
||||
if (b == -1) return if (sb.isEmpty()) null else sb.toString()
|
||||
if (b == '\r'.code) {
|
||||
val next = input.read()
|
||||
if (next == '\n'.code) return sb.toString()
|
||||
sb.append(b.toChar())
|
||||
if (next != -1) sb.append(next.toChar())
|
||||
continue
|
||||
}
|
||||
if (b == '\n'.code) return sb.toString()
|
||||
sb.append(b.toChar())
|
||||
}
|
||||
}
|
||||
|
||||
// ---- endpoint handlers ----------------------------------------------------
|
||||
|
||||
/** POST /load {"url":"..."} → {"url":"...","title":"..."} */
|
||||
private fun handleLoad(body: String): Pair<Int, String> {
|
||||
val json = runCatching { JSONObject(body) }.getOrNull()
|
||||
?: return 500 to """{"error":"invalid request body"}"""
|
||||
val url = json.optString("url", "")
|
||||
if (url.isEmpty()) return 500 to """{"error":"missing url"}"""
|
||||
|
||||
val result = AtomicReference("")
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = ensureView()
|
||||
// The failure recorded for the page being left stops being this
|
||||
// tab's, and the wait a following `/read` joins is armed before the
|
||||
// new address is loaded, so no callback for the new page can fire
|
||||
// ahead of it. `/load` answers before the page arrives, which is
|
||||
// what left the old failure to be read back as the new page's.
|
||||
startNavigation()
|
||||
wv.loadUrl(url)
|
||||
// The title and final URL are not available synchronously after
|
||||
// loadUrl; answer with what was requested. The kernel stores this
|
||||
// as the tab's URL and reads the real one on the next /read.
|
||||
result.set(JSONObject().apply {
|
||||
put("url", url)
|
||||
put("title", "")
|
||||
}.toString())
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout waiting for UI thread"}"""
|
||||
}
|
||||
return 200 to result.get()
|
||||
}
|
||||
|
||||
/** POST /close {} → 200 */
|
||||
private fun handleClose(): Pair<Int, String> {
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = existingView()
|
||||
if (wv != null) {
|
||||
wv.loadUrl("about:blank")
|
||||
wv.clearHistory()
|
||||
}
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
return 200 to "{}"
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /read {} → {"title":"...","url":"...","text":"..."}
|
||||
*
|
||||
* Injects a script that extracts readable text from the page, preferring
|
||||
* `<article>` or `<main>` and falling back to `body.innerText`. The result
|
||||
* is truncated to 400 KB (matching the kernel's `maxReadText`); when
|
||||
* truncated, a note is appended so the model knows the text was cut.
|
||||
*/
|
||||
private fun handleRead(): Pair<Int, String> {
|
||||
// The page the caller just asked for has not necessarily been visited
|
||||
// yet: `/load` returns as soon as it has started the navigation. Waiting
|
||||
// here, off the UI thread, is what makes this read answer about that
|
||||
// page instead of the one before it.
|
||||
awaitNavigation(NAV_SETTLE_MS)
|
||||
val result = AtomicReference("")
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = ensureView()
|
||||
// A page that did not load is not content. Whether the view is on
|
||||
// the browser's own error page is read from the view itself rather
|
||||
// than from a remembered failure: a failure recorded for the page
|
||||
// before a new navigation would otherwise be handed back as this
|
||||
// page's answer, long after the page the caller asked for had
|
||||
// loaded. The remembered failure is still what names the address
|
||||
// that failed and why, since the error page's own URL does not.
|
||||
if ((wv.url ?: "").startsWith("chrome-error:")) {
|
||||
val (url, reason) = loadFailure() ?: ((wv.url ?: "") to "ERR_FAILED")
|
||||
result.set(JSONObject().apply {
|
||||
put("url", url)
|
||||
put("title", "")
|
||||
put("reason", reason)
|
||||
put("text", "")
|
||||
}.toString())
|
||||
latch.countDown()
|
||||
return@post
|
||||
}
|
||||
// The extraction script: prefer article/main for content pages,
|
||||
// fall back to body. innerText preserves visual line breaks. It
|
||||
// also stamps a ref on every element a person could act on, so the
|
||||
// kernel can name one in an act step the way the desktop backend
|
||||
// names an accessibility node. A ref already on an element is kept,
|
||||
// so it stays the same across snapshots of one document; a fresh
|
||||
// document starts the numbering over, and the kernel only accepts a
|
||||
// ref from the snapshot it last read.
|
||||
val script = """
|
||||
(function(){
|
||||
var seq = window.__rxRefSeq || 0;
|
||||
var used = {};
|
||||
var marked = document.querySelectorAll('[data-rx-ref]');
|
||||
for (var i = 0; i < marked.length; i++) { used[marked[i].getAttribute('data-rx-ref')] = true; }
|
||||
function roleOf(el) {
|
||||
var tag = el.tagName.toLowerCase();
|
||||
var role = (el.getAttribute('role') || '').toLowerCase();
|
||||
if (role) return role;
|
||||
if (tag === 'a') return 'link';
|
||||
if (tag === 'button') return 'button';
|
||||
if (tag === 'select') return 'combobox';
|
||||
if (tag === 'textarea') return 'textbox';
|
||||
if (tag === 'input') {
|
||||
var t = (el.getAttribute('type') || 'text').toLowerCase();
|
||||
if (t === 'checkbox' || t === 'radio' || t === 'submit' || t === 'button' || t === 'reset') return t;
|
||||
return 'textbox';
|
||||
}
|
||||
return 'generic';
|
||||
}
|
||||
function nameOf(el) {
|
||||
var n = el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('name') || '';
|
||||
if (!n) { n = (el.innerText || el.textContent || '').trim(); }
|
||||
return n.replace(/\s+/g, ' ').slice(0, 160);
|
||||
}
|
||||
var sel = 'a[href],button,input,select,textarea,[role=button],[role=link],[role=checkbox],[role=radio],[role=tab],[role=menuitem],[contenteditable=true]';
|
||||
var els = document.querySelectorAll(sel);
|
||||
var elements = [];
|
||||
for (var j = 0; j < els.length; j++) {
|
||||
var el = els[j];
|
||||
var ref = el.getAttribute('data-rx-ref');
|
||||
if (!ref) {
|
||||
do { seq++; ref = 'e' + seq; } while (used[ref]);
|
||||
el.setAttribute('data-rx-ref', ref);
|
||||
used[ref] = true;
|
||||
}
|
||||
var raw = (el.value != null && String(el.value) !== '') ? String(el.value).slice(0, 160) : '';
|
||||
elements.push({ref: ref, role: roleOf(el), name: nameOf(el), value: raw});
|
||||
}
|
||||
window.__rxRefSeq = seq;
|
||||
var el2 = document.querySelector('article') || document.querySelector('main') || document.body;
|
||||
var text = el2 ? (el2.innerText || '') : '';
|
||||
var title = document.title || '';
|
||||
var url = location.href;
|
||||
return JSON.stringify({title: title, url: url, text: text, elements: elements});
|
||||
})()
|
||||
""".trimIndent()
|
||||
wv.evaluateJavascript(script) { value ->
|
||||
// evaluateJavascript returns a JSON-encoded string (the result
|
||||
// is double-encoded). Strip the outer quotes.
|
||||
val parsed = parseJsResult(value)
|
||||
if (parsed != null) {
|
||||
try {
|
||||
val obj = JSONObject(parsed)
|
||||
var text = obj.optString("text", "")
|
||||
if (text.length > MAX_READ_TEXT) {
|
||||
text = text.substring(0, MAX_READ_TEXT) +
|
||||
"\n\n[text truncated at 400 KB]"
|
||||
}
|
||||
result.set(JSONObject().apply {
|
||||
put("title", obj.optString("title", ""))
|
||||
put("url", obj.optString("url", ""))
|
||||
put("text", text)
|
||||
put("elements", obj.optJSONArray("elements") ?: JSONArray())
|
||||
}.toString())
|
||||
} catch (e: Exception) {
|
||||
result.set(JSONObject().apply {
|
||||
put("title", "")
|
||||
put("url", wv.url ?: "")
|
||||
put("text", parsed.take(MAX_READ_TEXT))
|
||||
}.toString())
|
||||
}
|
||||
} else {
|
||||
result.set(JSONObject().apply {
|
||||
put("title", "")
|
||||
put("url", wv.url ?: "")
|
||||
put("text", "")
|
||||
}.toString())
|
||||
}
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
if (!latch.await(READ_SCRIPT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout waiting for page script"}"""
|
||||
}
|
||||
return 200 to result.get()
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /screenshot {} → {"data":"<base64>","mime":"image/png"}
|
||||
*
|
||||
* Draws the WebView into a bitmap, downsamples by SCREENSHOT_SCALE to keep
|
||||
* memory bounded, and encodes as PNG → base64. For a 1080×2400 viewport the
|
||||
* full bitmap is ~10 MB; the downsampled one is ~2.5 MB. The full bitmap is
|
||||
* recycled immediately after scaling.
|
||||
*/
|
||||
private fun handleScreenshot(): Pair<Int, String> {
|
||||
val result = AtomicReference("")
|
||||
val failed = AtomicBoolean(false)
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = ensureView()
|
||||
try {
|
||||
val width = wv.width.takeIf { it > 0 } ?: 1080
|
||||
val height = wv.height.takeIf { it > 0 } ?: 1920
|
||||
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bmp)
|
||||
wv.draw(canvas)
|
||||
|
||||
// Downsample to bound the PNG size and the base64 string.
|
||||
val scaled = Bitmap.createScaledBitmap(
|
||||
bmp,
|
||||
width / SCREENSHOT_SCALE,
|
||||
height / SCREENSHOT_SCALE,
|
||||
true,
|
||||
)
|
||||
if (scaled !== bmp) bmp.recycle()
|
||||
|
||||
val baos = ByteArrayOutputStream()
|
||||
scaled.compress(Bitmap.CompressFormat.PNG, 85, baos)
|
||||
scaled.recycle()
|
||||
val b64 = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)
|
||||
result.set(JSONObject().apply {
|
||||
put("data", b64)
|
||||
put("mime", "image/png")
|
||||
}.toString())
|
||||
} catch (e: Exception) {
|
||||
// A 200 with an error body would be read by the kernel as a
|
||||
// screenshot whose data is empty, and it would build a `data:`
|
||||
// URI out of nothing. The status is what tells it this failed.
|
||||
result.set("""{"error":"screenshot failed: ${e.message}"}""")
|
||||
failed.set(true)
|
||||
}
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
if (failed.get()) return 500 to result.get()
|
||||
return 200 to result.get()
|
||||
}
|
||||
|
||||
/** POST /click {"selector":"..."} → {"ok":true|false} */
|
||||
private fun handleClick(body: String): Pair<Int, String> {
|
||||
val json = runCatching { JSONObject(body) }.getOrNull()
|
||||
?: return 500 to """{"error":"invalid request body"}"""
|
||||
val selector = json.optString("selector", "")
|
||||
if (selector.isEmpty()) return 500 to """{"error":"missing selector"}"""
|
||||
|
||||
val result = AtomicReference("")
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = ensureView()
|
||||
// Escape the selector for embedding in a JS string.
|
||||
val escaped = selector.replace("\\", "\\\\").replace("'", "\\'")
|
||||
val script = """
|
||||
(function(){
|
||||
try {
|
||||
var el = document.querySelector('$escaped');
|
||||
if (!el) return JSON.stringify({ok: false});
|
||||
el.click();
|
||||
return JSON.stringify({ok: true});
|
||||
} catch(e) {
|
||||
return JSON.stringify({ok: false});
|
||||
}
|
||||
})()
|
||||
""".trimIndent()
|
||||
wv.evaluateJavascript(script) { value ->
|
||||
val parsed = parseJsResult(value)
|
||||
result.set(parsed ?: """{"ok":false}""")
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
return 200 to result.get()
|
||||
}
|
||||
|
||||
/** POST /eval {"script":"..."} → {"result":"..."} */
|
||||
private fun handleEval(body: String): Pair<Int, String> {
|
||||
val json = runCatching { JSONObject(body) }.getOrNull()
|
||||
?: return 500 to """{"error":"invalid request body"}"""
|
||||
val script = json.optString("script", "")
|
||||
if (script.isEmpty()) return 500 to """{"error":"missing script"}"""
|
||||
|
||||
val result = AtomicReference("")
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = ensureView()
|
||||
wv.evaluateJavascript(script) { value ->
|
||||
// The kernel expects a plain string in "result". The value from
|
||||
// evaluateJavascript is JSON-encoded; unwrap it.
|
||||
val unwrapped = parseJsResult(value) ?: ""
|
||||
result.set(JSONObject().apply {
|
||||
put("result", unwrapped)
|
||||
}.toString())
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout waiting for eval"}"""
|
||||
}
|
||||
return 200 to result.get()
|
||||
}
|
||||
|
||||
/** POST /back → 200 */
|
||||
private fun handleBack(): Pair<Int, String> {
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
existingView()?.let { if (it.canGoBack()) it.goBack() }
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
return 200 to "{}"
|
||||
}
|
||||
|
||||
/** POST /forward → 200 */
|
||||
private fun handleForward(): Pair<Int, String> {
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
existingView()?.let { if (it.canGoForward()) it.goForward() }
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
return 200 to "{}"
|
||||
}
|
||||
|
||||
/** POST /reload → 200 */
|
||||
private fun handleReload(): Pair<Int, String> {
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
val wv = existingView()
|
||||
// A view sitting on the browser's own error page is not on the site,
|
||||
// and reloading it would retry the error page itself. The address
|
||||
// that failed is loaded again instead — which is the page a caller
|
||||
// means by "reload" — read before `startNavigation` clears it.
|
||||
val failed = if (wv != null && (wv.url ?: "").startsWith("chrome-error:"))
|
||||
loadFailure()?.first else null
|
||||
startNavigation()
|
||||
if (wv != null) {
|
||||
if (failed != null) wv.loadUrl(failed) else wv.reload()
|
||||
}
|
||||
latch.countDown()
|
||||
}
|
||||
if (!latch.await(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
|
||||
return 500 to """{"error":"timeout"}"""
|
||||
}
|
||||
return 200 to "{}"
|
||||
}
|
||||
|
||||
/** POST /requests {} → {"requests":[{"method","url","kind"},…]} */
|
||||
private fun handleRequests(): Pair<Int, String> {
|
||||
val arr = JSONArray()
|
||||
for (r in requests()) {
|
||||
arr.put(JSONObject().apply {
|
||||
put("method", r.method)
|
||||
put("url", r.url)
|
||||
put("kind", r.kind)
|
||||
})
|
||||
}
|
||||
return 200 to JSONObject().apply { put("requests", arr) }.toString()
|
||||
}
|
||||
|
||||
// ---- helpers ----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Unwrap the result of `evaluateJavascript`. The callback receives a
|
||||
* JSON-encoded string: a JS string "hello" arrives as `"\"hello\""`, a
|
||||
* number 42 as `"42"`, null as `"null"`. Strip the outer JSON encoding to
|
||||
* get the raw value.
|
||||
*/
|
||||
private fun parseJsResult(value: String?): String? {
|
||||
if (value == null || value == "null") return null
|
||||
// The value is a JSON literal. If it is a JSON string, decode it.
|
||||
return try {
|
||||
if (value.startsWith("\"") && value.endsWith("\"")) {
|
||||
JSONObject().apply { }.let {
|
||||
// Use JSONObject's string decoding: wrap in an object.
|
||||
JSONObject("""{"v":$value}""").optString("v", "")
|
||||
}
|
||||
} else {
|
||||
value
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.os.Build
|
||||
|
||||
/**
|
||||
* The phone's DNS servers, as the kernel needs them.
|
||||
*
|
||||
* The kernel is a CGO-free Go binary, and Go's own source explains why that
|
||||
* matters:
|
||||
*
|
||||
* ```
|
||||
* // DNS requests don't work on Android, so prefer the cgo resolver.
|
||||
* // Issue #10714.
|
||||
* case "android":
|
||||
* ```
|
||||
*
|
||||
* A normal Android program resolves names through `getaddrinfo`, which reaches
|
||||
* the `netd` daemon and gets the servers of the network that is actually up.
|
||||
* A static binary has no cgo resolver, so Go reads `/etc/resolv.conf` instead —
|
||||
* and Android has no such file. Go then falls back to `127.0.0.1:53`, where
|
||||
* nothing listens, and every lookup fails: the setup screen reports
|
||||
* "连接失败" for every provider, including the official ones, on a phone whose
|
||||
* browser reaches them fine.
|
||||
*
|
||||
* So they are read here and handed to the kernel through `REASONIX_DNS`. This is
|
||||
* the same source the system itself uses, so a VPN, a private DNS hostname, or a
|
||||
* network that changed since boot is all reflected without this code knowing
|
||||
* anything about them.
|
||||
*/
|
||||
object Dns {
|
||||
|
||||
/**
|
||||
* The active network's servers, comma separated, or "" when there is none.
|
||||
*
|
||||
* Read from the *active* network rather than from every link, because a phone
|
||||
* commonly has several at once — Wi-Fi, mobile data, a VPN — and the servers
|
||||
* of a network that is not carrying traffic are the wrong ones to ask.
|
||||
*/
|
||||
fun servers(context: Context): String {
|
||||
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
?: return ""
|
||||
val properties: LinkProperties = runCatching { manager.activeNetwork }.getOrNull()
|
||||
?.let { network -> runCatching { manager.getLinkProperties(network) }.getOrNull() }
|
||||
?: return ""
|
||||
return properties.dnsServers
|
||||
.mapNotNull { address -> address.hostAddress }
|
||||
.filter { it.isNotBlank() }
|
||||
.filter { routable(it) }
|
||||
.sortedBy { preference(it) }
|
||||
.joinToString(",")
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an address can actually carry a query.
|
||||
*
|
||||
* A link-local address (fe80::/10) without its zone cannot: the packet has
|
||||
* no interface to leave by, so it is dropped, nothing answers, and the
|
||||
* lookup hangs until the kernel's own timeout expires — which is reported as
|
||||
* a timeout rather than as a failure to resolve, and so reads like the
|
||||
* network is slow instead of like the address is unusable.
|
||||
*
|
||||
* Android reports the zone as a `%wlan0` suffix on `hostAddress`, and the
|
||||
* address is only usable with it kept. Nothing here trims it: an earlier
|
||||
* version called `substringBefore('%')`, which turned a usable link-local
|
||||
* server into an unroutable one.
|
||||
*/
|
||||
private fun routable(host: String): Boolean =
|
||||
!(host.startsWith("fe80:", ignoreCase = true) && !host.contains('%'))
|
||||
|
||||
/**
|
||||
* IPv4 first, then IPv6.
|
||||
*
|
||||
* A phone commonly reports both, and its IPv6 entry is often a router's
|
||||
* link-local address — reachable on one network and not the next. The
|
||||
* kernel tries the servers in the order it is given them, and stops at the
|
||||
* first that answers; putting the address family that shares the network's
|
||||
* own numbering first means its timeout is spent on a server that works.
|
||||
*/
|
||||
private fun preference(host: String): Int = if (host.contains(':')) 1 else 0
|
||||
|
||||
/**
|
||||
* The private-DNS setting, for the one case the address list cannot answer.
|
||||
*
|
||||
* Since Android 9 a phone may use DNS-over-TLS, and then `dnsServers` holds a
|
||||
* name rather than an address — a name this kernel cannot resolve *because*
|
||||
* resolving it is the thing that is broken. There is no way for the shell to
|
||||
* do that lookup for it, so this reports the situation instead of handing
|
||||
* over an unusable value: the caller says so in the log, and the person can
|
||||
* turn private DNS off or set it to automatic.
|
||||
*/
|
||||
fun looksLikeDot(servers: String): Boolean =
|
||||
servers.isNotBlank() && servers.split(',').any { part ->
|
||||
val host = part.trim()
|
||||
host.isNotEmpty() && host.none { it == ':' } && !host.all { it.isDigit() || it == '.' }
|
||||
}
|
||||
|
||||
/** Whether the system requires a VPN or private DNS, which changes nothing
|
||||
* here but is worth saying in a bug report. */
|
||||
fun describe(context: Context): String {
|
||||
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
?: return "no connectivity service"
|
||||
val network = runCatching { manager.activeNetwork }.getOrNull() ?: return "no active network"
|
||||
val properties = runCatching { manager.getLinkProperties(network) }.getOrNull()
|
||||
?: return "no link properties"
|
||||
// The DHCP server arrived in API 30, not 23: asked for below that it is a
|
||||
// NoSuchMethodError on a device this app supports (minSdk 26), and the
|
||||
// answer is only ever read out of this string by a person debugging.
|
||||
val dhcp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
properties.dhcpServerAddress?.hostAddress
|
||||
} else {
|
||||
null
|
||||
}
|
||||
return "iface=${properties.interfaceName} dns=${properties.dnsServers.joinToString(",") { it.hostAddress ?: "?" }}" +
|
||||
(dhcp?.let { " dhcp=$it" } ?: "")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.webkit.CookieManager
|
||||
import android.widget.Toast
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.FileNotFoundException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* Putting a file the page produced onto the phone's disk.
|
||||
*
|
||||
* A WebView has no downloads shelf and cannot write to the system's document
|
||||
* picker itself, so the two halves are joined here: the page asks, the picker
|
||||
* answers with a `content://` the app has been granted, and this copies the
|
||||
* bytes across.
|
||||
*
|
||||
* The request carries the WebView's own cookie, read out of the jar the page
|
||||
* authenticated in. That is the only reason this is not a plain `openStream`:
|
||||
* the kernel's download route is behind the session the page established, and a
|
||||
* shell that fetched without it would get a 403 and no explanation.
|
||||
*/
|
||||
object Downloader {
|
||||
|
||||
suspend fun run(
|
||||
context: Context,
|
||||
url: String,
|
||||
userAgent: String,
|
||||
mime: String,
|
||||
name: String,
|
||||
target: Uri,
|
||||
): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 60_000
|
||||
requestMethod = "GET"
|
||||
if (userAgent.isNotBlank()) setRequestProperty("User-Agent", userAgent)
|
||||
// The download route answers with the same session cookie the
|
||||
// page is using; without it the kernel refuses the request.
|
||||
cookieFor(url)?.let { setRequestProperty("Cookie", it) }
|
||||
}
|
||||
try {
|
||||
val code = connection.responseCode
|
||||
if (code !in 200..299) {
|
||||
throw IllegalStateException(
|
||||
context.getString(R.string.download_failed_status, code),
|
||||
)
|
||||
}
|
||||
val resolver = context.contentResolver
|
||||
val output = resolver.openOutputStream(target, "w")
|
||||
?: throw FileNotFoundException(target.toString())
|
||||
output.use { out ->
|
||||
connection.inputStream.use { input -> input.copyTo(out) }
|
||||
}
|
||||
// `copyTo` answers with a byte count; what the caller wants to
|
||||
// know is that there were no bytes missing, not how many.
|
||||
Unit
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie the page authenticated with, if any.
|
||||
*
|
||||
* `CookieManager` is the WebView's own store, so this asks the exact jar the
|
||||
* request will be checked against rather than a copy this shell kept.
|
||||
*/
|
||||
private fun cookieFor(url: String): String? =
|
||||
runCatching { CookieManager.getInstance().getCookie(url) }.getOrNull()?.takeIf { it.isNotBlank() }
|
||||
|
||||
/** A short receipt for a tap that otherwise does nothing visible. */
|
||||
fun report(context: Context, name: String, result: Result<Unit>) {
|
||||
val message = result.fold(
|
||||
onSuccess = { context.getString(R.string.download_saved, name) },
|
||||
onFailure = { failure ->
|
||||
context.getString(R.string.download_failed, failure.message ?: "")
|
||||
},
|
||||
)
|
||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.AssetManager
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.SecureRandom
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The Reasonix kernel, as this app runs it: one child process serving loopback,
|
||||
* plus the two things it needs on disk to start — the page it serves and a
|
||||
* credential for this launch.
|
||||
*
|
||||
* The shape is the desktop host's (`cmd/reasonix-studio-host`), narrowed to what
|
||||
* a phone does not have. That host binds a socket, mints a credential, speaks a
|
||||
* handshake down a pipe and holds a lease; here the credential goes through
|
||||
* `--token-file` and the bound address through `--port-file`, because a phone's
|
||||
* app process has no pipe to hand a child and no reason to care which port was
|
||||
* free. Everything after that — the kernel's own gate, its auth middleware, its
|
||||
* CSRF check — is untouched, so the security of the surface is the one upstream
|
||||
* tested, not one this shell invented.
|
||||
*
|
||||
* One instance lives in the app process. The activity asks it for a URL; the
|
||||
* foreground service asks it to stay alive. Both see the same process, so there
|
||||
* is nothing to synchronise beyond a lock on start/stop.
|
||||
*/
|
||||
class Kernel(private val context: Context) {
|
||||
|
||||
/** Where everything the kernel owns lives. Nothing here is backed up. */
|
||||
private val home = File(context.filesDir, "home")
|
||||
|
||||
/**
|
||||
* The folder the agent works in, which is not the folder the kernel lives in.
|
||||
*
|
||||
* These used to be the same directory, and that is what made the workbench
|
||||
* unreadable: the kernel's home holds `config.toml`, `projects/`, `cache/`,
|
||||
* `stats/` and the rest of its own bookkeeping, and a workspace pointed at
|
||||
* it shows all of that as if the person had put it there. Reported as "why
|
||||
* does the default workspace have so many files, the desktop version does
|
||||
* not generate these" — the desktop does generate them, in a different
|
||||
* directory, because its workspace is whatever folder it was opened on.
|
||||
*
|
||||
* Split apart, the workbench shows what the agent produced and nothing else.
|
||||
* `write_roots` follows the workspace, so the file tools stay confined to
|
||||
* the folder the person actually works in rather than to the kernel's own
|
||||
* home — which is the stricter answer, and the one the desktop already has.
|
||||
*/
|
||||
private val workspaceDir = File(context.filesDir, "workspace")
|
||||
|
||||
/**
|
||||
* The directory the kernel calls `REASONIX_HOME`, for the one caller that
|
||||
* has to put a file where the kernel can read it — a private key the person
|
||||
* picked from their Documents folder.
|
||||
*/
|
||||
fun homeDir(): File = home
|
||||
|
||||
/** The folder the agent works in. */
|
||||
fun workspaceDir(): File = workspaceDir
|
||||
|
||||
/** The built page, unpacked once per version. */
|
||||
private val pageDir = File(context.filesDir, "page")
|
||||
|
||||
private val tokenFile = File(home, "remote/launch.token")
|
||||
private val portFile = File(home, "remote/serve.port")
|
||||
private val pidFile = File(home, "remote/serve.pid")
|
||||
|
||||
private val lock = Any()
|
||||
|
||||
@Volatile
|
||||
private var process: Process? = null
|
||||
|
||||
/** The port the shell's browser HTTP server listens on, set by the
|
||||
* activity before `start()` is called. Zero means no server is up, and
|
||||
* the kernel leaves its browser tools suspended (the correct degradation
|
||||
* on a phone with no Chromium). */
|
||||
@Volatile
|
||||
var browserShellPort: Int = 0
|
||||
|
||||
/** The bearer credential for that server, set beside the port. Sent on
|
||||
* every browser call so the server can refuse anything that did not come
|
||||
* from the kernel this shell started — loopback on a phone is reachable
|
||||
* by every other app. Empty when there is no server. */
|
||||
@Volatile
|
||||
var browserShellToken: String = ""
|
||||
|
||||
/** What the WebView should load, once the kernel has bound a port. */
|
||||
@Volatile
|
||||
var origin: String? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* The launch credential, as the URL fragment the page trades for a cookie.
|
||||
* Kept in memory only: the file on disk belongs to the kernel's own
|
||||
* bookkeeping, and a phone's app data is not a place to leave a second copy.
|
||||
*/
|
||||
@Volatile
|
||||
private var token: String? = null
|
||||
|
||||
/**
|
||||
* The URL the WebView loads first. It carries the credential in the
|
||||
* fragment, which the page exchanges for an HttpOnly cookie before it makes
|
||||
* any request — the same path a shared `reasonix web` link takes, so the
|
||||
* token never enters a request line, a history entry or a log.
|
||||
*/
|
||||
fun entryUrl(): String? {
|
||||
val origin = origin ?: return null
|
||||
val token = token ?: return null
|
||||
return "$origin/#token=$token"
|
||||
}
|
||||
|
||||
/** The plain origin, for reloads once the cookie is set. */
|
||||
fun plainUrl(): String? = origin
|
||||
|
||||
fun isRunning(): Boolean = process?.isAlive == true
|
||||
|
||||
/**
|
||||
* Bring the kernel up, or answer the URL of the one already up.
|
||||
*
|
||||
* Starting is idempotent by intent: the activity and the service both call
|
||||
* this, and whichever arrives second joins the running kernel instead of
|
||||
* racing it for the port.
|
||||
*/
|
||||
suspend fun start(): Result<String> = withContext(Dispatchers.IO) {
|
||||
synchronized(lock) {
|
||||
origin?.let { return@withContext Result.success(it) }
|
||||
|
||||
runCatching {
|
||||
val binary = kernelBinary()
|
||||
publishPage()
|
||||
prepareHome()
|
||||
val launchToken = mintToken()
|
||||
token = launchToken
|
||||
|
||||
val child = launch(binary, launchToken)
|
||||
|
||||
// The port is the kernel's answer, not this shell's guess. It
|
||||
// writes the file after binding, so waiting on the file is
|
||||
// waiting on the bind.
|
||||
val bound = awaitPort(child)
|
||||
val url = "http://$bound"
|
||||
|
||||
// A kernel that bound a port and then died would look healthy
|
||||
// here and broken in the WebView; the two facts are checked
|
||||
// together, and only a kernel that is answering is adopted.
|
||||
awaitServing(child, url)
|
||||
origin = url
|
||||
process = child
|
||||
url
|
||||
}.onFailure { origin = null; process = null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the kernel.
|
||||
*
|
||||
* The graceful signal first: the kernel drains its listeners and closes the
|
||||
* runtimes it opened, which is what lets a later launch adopt the sessions
|
||||
* rather than find them locked. `destroyForcibly` is the second attempt, and
|
||||
* only after a wait — a phone that is being shut down should not keep a
|
||||
* half-killed agent.
|
||||
*/
|
||||
fun stop() {
|
||||
synchronized(lock) {
|
||||
val p = process ?: return
|
||||
process = null
|
||||
origin = null
|
||||
token = null
|
||||
runCatching {
|
||||
p.destroy()
|
||||
if (!p.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) {
|
||||
p.destroyForcibly()
|
||||
}
|
||||
}
|
||||
portFile.delete()
|
||||
pidFile.delete()
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the two inputs that ship inside the APK -------------------------
|
||||
|
||||
/**
|
||||
* The kernel binary.
|
||||
*
|
||||
* It is packaged as a native library, so Android has already extracted it to
|
||||
* a directory it allows execution from and given it the executable bit —
|
||||
* which is the one thing a file under app storage does not get for free.
|
||||
*/
|
||||
private fun kernelBinary(): File {
|
||||
val dir = File(context.applicationInfo.nativeLibraryDir)
|
||||
val binary = File(dir, "libreasonix.so")
|
||||
if (!binary.exists()) {
|
||||
throw IllegalStateException(
|
||||
"内核未随 APK 安装:${binary.path}\n这是一次构建问题,请重新安装完整 APK。",
|
||||
)
|
||||
}
|
||||
return binary
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the bundled page where the kernel can serve it.
|
||||
*
|
||||
* It goes to app storage rather than being served out of the APK because the
|
||||
* kernel's `--page` is a directory on a real filesystem; there is no
|
||||
* archive-aware variant, and adding one would be a change to the kernel for
|
||||
* this shell's convenience alone.
|
||||
*
|
||||
* Unpacking is versioned: the marker holds the app's version name, so an
|
||||
* update replaces the page and a relaunch does not. A partially written
|
||||
* directory — the app killed mid-copy — is caught by the same marker never
|
||||
* having been written, so the next launch rewrites it.
|
||||
*/
|
||||
private fun publishPage() {
|
||||
val marker = File(pageDir, ".unpacked")
|
||||
val stamp = "${BuildConfig.VERSION_NAME}:${BuildConfig.VERSION_CODE}"
|
||||
if (marker.isFile && marker.readText().trim() == stamp) return
|
||||
|
||||
pageDir.deleteRecursively()
|
||||
pageDir.mkdirs()
|
||||
copyAssetTree(context.assets, "page", pageDir)
|
||||
|
||||
if (!File(pageDir, "index.html").isFile) {
|
||||
throw IllegalStateException("随 APK 分发的页面不完整:缺少 index.html")
|
||||
}
|
||||
marker.writeText(stamp)
|
||||
}
|
||||
|
||||
/**
|
||||
* A directory tree out of assets.
|
||||
*
|
||||
* `AssetManager.list` on a file answers with an empty array, so a "file" is
|
||||
* told from a directory by trying to open it — which is the only signal the
|
||||
* API offers and the reason this is not a one-liner.
|
||||
*/
|
||||
private fun copyAssetTree(assets: AssetManager, from: String, to: File) {
|
||||
val children = assets.list(from).orEmpty()
|
||||
if (children.isEmpty()) {
|
||||
// A leaf: open it as a stream. A directory that happens to be empty
|
||||
// is indistinguishable and harmless to skip.
|
||||
runCatching {
|
||||
assets.open(from).use { input ->
|
||||
FileOutputStream(to).use { output -> input.copyTo(output) }
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
to.mkdirs()
|
||||
for (child in children) {
|
||||
copyAssetTree(assets, "$from/$child", File(to, child))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the kernel's home.
|
||||
*
|
||||
* `REASONIX_HOME` is what every path in the kernel hangs off — config,
|
||||
* sessions, the remote state directory its token file lands in — so pointing
|
||||
* it at app storage is what keeps a phone's Reasonix separate from anything
|
||||
* else and away from global storage entirely.
|
||||
*/
|
||||
private fun prepareHome() {
|
||||
File(home, "remote").mkdirs()
|
||||
// The workspace directory not existing yet is what marks the first run
|
||||
// after this build split it from the kernel's home. That is the one
|
||||
// moment a migration is due, and doing it here means it happens before
|
||||
// the kernel is asked for anything.
|
||||
val firstSplit = !workspaceDir.exists()
|
||||
workspaceDir.mkdirs()
|
||||
if (firstSplit) {
|
||||
adoptSessionsFromHome()
|
||||
}
|
||||
// Every launch, not only the first. The rewrite is cheap and
|
||||
// idempotent, and an entry that survived the first pass would otherwise
|
||||
// survive forever: `firstSplit` is spent the moment the directory
|
||||
// exists, so a build that cleaned the list once and missed leaves the
|
||||
// home on the sidebar for good. Running it unconditionally costs one
|
||||
// small read and makes the whole thing self-correcting.
|
||||
forgetHomeFromWorkspaceList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the kernel's own home from the sidebar's remembered projects.
|
||||
*
|
||||
* The list is written whenever a pane opens, and until this build the pane
|
||||
* opened on the home itself — so an upgraded install carries a "project"
|
||||
* that is really the kernel's own directory. Leaving it there would put the
|
||||
* person back where they started: one tap on it and the workbench is full
|
||||
* of `config.toml`, `cache/` and `projects/` again, which is the complaint
|
||||
* this whole change answers. Only that one path is removed; every folder
|
||||
* someone added on purpose stays.
|
||||
*
|
||||
* Parsed rather than pattern-matched, because the file's two shapes — a bare
|
||||
* array of paths and an object with `paths` and `launch` — both have to keep
|
||||
* whatever else they hold.
|
||||
*/
|
||||
private fun forgetHomeFromWorkspaceList() {
|
||||
val file = File(home, "serve-workspaces.json")
|
||||
if (!file.isFile) return
|
||||
val text = runCatching { file.readText() }.getOrNull() ?: return
|
||||
val wrong = runCatching { homeNames() }.getOrNull() ?: return
|
||||
val rewritten = runCatching { withoutHome(text, wrong) }.getOrNull() ?: return
|
||||
if (!rewritten.dropped) return
|
||||
runCatching { file.writeText(rewritten.text) }
|
||||
.onSuccess { Log.i(TAG, "dropped the kernel home from the project list") }
|
||||
.onFailure { Log.w(TAG, "could not rewrite the project list: ${it.message}") }
|
||||
}
|
||||
|
||||
/**
|
||||
* Every name of the kernel's home on this device — not just the one this
|
||||
* process happens to write.
|
||||
*
|
||||
* Android shows one directory under two names: `/data/data/<pkg>` and
|
||||
* `/data/user/0/<pkg>` are two mounts of the same tree, the same inode
|
||||
* either way, and which name a path carries depends on how it was written
|
||||
* rather than on where it points. The list is written by the kernel, whose
|
||||
* working directory this shell set from a path it built itself; a lookup
|
||||
* that compared against only one spelling would silently keep the entry
|
||||
* this exists to remove. Both names are compared, so either spelling is
|
||||
* recognised.
|
||||
*/
|
||||
private fun homeNames(): Set<String> {
|
||||
val path = home.absolutePath
|
||||
val names = mutableSetOf(path)
|
||||
val user = "/data/user/0/"
|
||||
val data = "/data/data/"
|
||||
when {
|
||||
path.startsWith(user) -> names.add(data + path.removePrefix(user))
|
||||
path.startsWith(data) -> names.add(user + path.removePrefix(data))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/** What a rewrite produced, and whether it actually removed anything. */
|
||||
private class Rewrite(val text: String, val dropped: Boolean)
|
||||
|
||||
/**
|
||||
* The list without the home, in whichever shape it arrived, and whether
|
||||
* anything was actually dropped from it.
|
||||
*
|
||||
* The flag matters because `JSONObject` re-serialises: it escapes every
|
||||
* `/` and does not preserve key order, so a round trip never reproduces
|
||||
* the original bytes. Deciding to write on "the text differs" alone would
|
||||
* therefore rewrite the kernel's file on every single launch, log a drop
|
||||
* that never happened, and race the kernel for a file it also writes.
|
||||
*/
|
||||
private fun withoutHome(text: String, wrong: Set<String>): Rewrite {
|
||||
if (text.trimStart().startsWith("[")) {
|
||||
val paths = JSONArray(text)
|
||||
val kept = JSONArray()
|
||||
var dropped = false
|
||||
for (i in 0 until paths.length()) {
|
||||
val path = paths.optString(i)
|
||||
if (path in wrong) {
|
||||
dropped = true
|
||||
continue
|
||||
}
|
||||
kept.put(path)
|
||||
}
|
||||
return if (dropped) Rewrite(kept.toString(), true) else Rewrite(text, false)
|
||||
}
|
||||
val list = JSONObject(text)
|
||||
val kept = JSONArray()
|
||||
var dropped = false
|
||||
val paths = list.optJSONArray("paths")
|
||||
if (paths != null) {
|
||||
for (i in 0 until paths.length()) {
|
||||
val path = paths.optString(i)
|
||||
if (path in wrong) {
|
||||
dropped = true
|
||||
continue
|
||||
}
|
||||
kept.put(path)
|
||||
}
|
||||
if (dropped) list.put("paths", kept)
|
||||
}
|
||||
if (list.optString("launch") in wrong) {
|
||||
list.remove("launch")
|
||||
dropped = true
|
||||
}
|
||||
return if (dropped) Rewrite(list.toString(), true) else Rewrite(text, false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the conversations that were filed under the kernel's own home.
|
||||
*
|
||||
* The transcript store is keyed by the workspace root — one directory per
|
||||
* project, under `<state>/projects/<slug>/sessions` — and until this build
|
||||
* the root was the home itself. Splitting the two therefore moves every
|
||||
* existing conversation to a slug nothing looks under, which reads as "my
|
||||
* history is gone" rather than as a reorganisation. So the old directory is
|
||||
* renamed onto the new slug once.
|
||||
*
|
||||
* Renaming the project directory rather than just `sessions/` carries the
|
||||
* rest of it too: `memory/` is filed the same way, and a project's memory
|
||||
* lost while its transcripts were kept would be a stranger failure than
|
||||
* either alone.
|
||||
*
|
||||
* The slug is the absolute path with its separators flattened, which is
|
||||
* what `config.WorkspaceSlug` does on the kernel's side. Only the home's own
|
||||
* slug is touched: a slug for some other folder is left exactly where it is,
|
||||
* because those are projects someone added on purpose.
|
||||
*/
|
||||
private fun adoptSessionsFromHome() {
|
||||
val projects = File(home, "projects")
|
||||
if (!projects.isDirectory) return
|
||||
val from = projects.resolve(slugOf(home.absolutePath))
|
||||
if (!from.isDirectory) return
|
||||
val to = projects.resolve(slugOf(workspaceDir.absolutePath))
|
||||
// A target already there means a previous run half-finished, or the
|
||||
// person opened this folder before. Either way its contents win:
|
||||
// merging two transcript directories is not a thing this can do safely,
|
||||
// and the old one is still on disk to be looked at.
|
||||
if (to.exists()) {
|
||||
Log.i(TAG, "${to.name} already exists; leaving ${from.name} in place")
|
||||
return
|
||||
}
|
||||
if (!from.renameTo(to)) {
|
||||
Log.w(TAG, "could not move ${from.name} to ${to.name}; history stays under the old slug")
|
||||
} else {
|
||||
Log.i(TAG, "moved conversations from ${from.name} to ${to.name}")
|
||||
}
|
||||
}
|
||||
|
||||
/** The kernel's `config.WorkspaceSlug`, for the two paths that matter here. */
|
||||
private fun slugOf(path: String): String = path.replace('/', '-').replace('\\', '-').replace(':', '-')
|
||||
|
||||
/**
|
||||
* The launch credential.
|
||||
*
|
||||
* Minted here rather than read from configuration: a credential a person can
|
||||
* set is one anything that can read their files can present. 32 bytes, hex,
|
||||
* the same shape the desktop host mints.
|
||||
*/
|
||||
private fun mintToken(): String {
|
||||
val bytes = ByteArray(32)
|
||||
SecureRandom().nextBytes(bytes)
|
||||
val token = bytes.joinToString("") { "%02x".format(it) }
|
||||
tokenFile.parentFile?.mkdirs()
|
||||
tokenFile.writeText("$token\n")
|
||||
// 0600 by intent, and the app's own private directory means it is
|
||||
// already unreachable to every other app on the device.
|
||||
runCatching {
|
||||
tokenFile.setReadable(false, false)
|
||||
tokenFile.setReadable(true, true)
|
||||
tokenFile.setWritable(false, false)
|
||||
tokenFile.setWritable(true, true)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the child.
|
||||
*
|
||||
* `--addr 127.0.0.1:0` lets the kernel pick a free port; `--port-file`
|
||||
* makes it announce which. `--auth token` is the mode a phone needs: the
|
||||
* page authenticates, and a state-changing request without the credential
|
||||
* is refused. `--no-open` is belt and braces — a serve never opens a
|
||||
* browser, and a phone has no browser to open.
|
||||
*/
|
||||
private fun launch(binary: File, token: String): Process {
|
||||
portFile.delete()
|
||||
pidFile.delete()
|
||||
// The folder the agent works in, resolved before the command line is
|
||||
// built so it can be named on it. See the note under the environment
|
||||
// block for why naming it is not the same as setting the directory.
|
||||
val workspace = launchWorkspaceDir()
|
||||
val command = listOf(
|
||||
binary.absolutePath,
|
||||
"serve",
|
||||
"--addr", "127.0.0.1:0",
|
||||
"--auth", "token",
|
||||
"--token-file", tokenFile.absolutePath,
|
||||
"--port-file", portFile.absolutePath,
|
||||
"--pid-file", pidFile.absolutePath,
|
||||
"--no-open",
|
||||
"-page", pageDir.absolutePath,
|
||||
// The project root, said outright. Without this the kernel derives
|
||||
// it from its working directory, and on this phone the two did not
|
||||
// agree: the sidebar named the shared folder, `write_roots` confined
|
||||
// the file tools to the app's own directory, and every write into the
|
||||
// folder the person was looking at came back
|
||||
// `workspace.write_outside_scope`. A flag is a fact the kernel was
|
||||
// told rather than one it inferred from a mount it sees differently.
|
||||
"--dir", workspace.absolutePath,
|
||||
)
|
||||
val builder = ProcessBuilder(command)
|
||||
builder.environment().apply {
|
||||
put("REASONIX_HOME", home.absolutePath)
|
||||
put("HOME", home.absolutePath)
|
||||
// The kernel's own language, for its tool failures, approval
|
||||
// prompts and error sentences. Without this it detects from the
|
||||
// POSIX locale variables, and Android sets none of them for an
|
||||
// app: the kernel then answers in English while the page in front
|
||||
// of the person is Chinese, and every sentence added for a Chinese
|
||||
// reader was dead text. The tag, not the bare language, so a
|
||||
// Traditional Chinese device resolves to zh-TW rather than zh.
|
||||
// An explicit `language` in the kernel's config.toml still wins:
|
||||
// DetectLanguage applies the configured value over this.
|
||||
val languageTag = Locale.getDefault().toLanguageTag()
|
||||
if (languageTag.isNotBlank() && languageTag != "und") {
|
||||
put("REASONIX_LANG", languageTag)
|
||||
}
|
||||
// Android has no /tmp. Everything that wants a scratch directory —
|
||||
// the shell tool, tool output spooling, sqlite journals — reads this.
|
||||
put("TMPDIR", context.cacheDir.absolutePath)
|
||||
// The phone's own DNS servers. A CGO-free Go binary cannot read them
|
||||
// for itself — Android keeps them in `netd`, and Go looks for a
|
||||
// `/etc/resolv.conf` that does not exist — so without this the kernel
|
||||
// resolves nothing and every provider probe reports "连接失败" on a
|
||||
// device whose browser reaches the same address fine.
|
||||
val dns = Dns.servers(context)
|
||||
if (dns.isNotBlank()) {
|
||||
put("REASONIX_DNS", dns)
|
||||
Log.i(TAG, "kernel DNS: $dns (${Dns.describe(context)})")
|
||||
if (Dns.looksLikeDot(dns)) {
|
||||
// Private DNS (DNS-over-TLS) is on, and it hands back a
|
||||
// hostname this kernel cannot resolve by definition. Saying
|
||||
// so here is what turns "连不上" into something actionable.
|
||||
Log.w(TAG, "kernel DNS looks like a private-DNS hostname; turn private DNS off or set it to automatic")
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "kernel DNS: none reported by the system")
|
||||
}
|
||||
// The shell's browser server, when one is listening. The kernel
|
||||
// reads this to bind its browser tools to the shell's WebView
|
||||
// instead of looking for a Chromium binary that does not exist on
|
||||
// a phone. When absent (zero), the variable is not set and the
|
||||
// kernel keeps the browser tools suspended — the correct
|
||||
// degradation for a phone with no engine to drive.
|
||||
val shellPort = browserShellPort
|
||||
if (shellPort > 0) {
|
||||
put("REASONIX_SHELL_BROWSER_PORT", shellPort.toString())
|
||||
// The credential the server checks. Set only alongside the
|
||||
// port: a token with nothing listening would be a variable the
|
||||
// kernel carries for no reason.
|
||||
val shellToken = browserShellToken
|
||||
if (shellToken.isNotBlank()) {
|
||||
put("REASONIX_SHELL_BROWSER_TOKEN", shellToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The agent's folder, not the kernel's. `REASONIX_HOME` above is still
|
||||
// where the config, the sessions and the transcripts live; this is what
|
||||
// the workspace root resolves to, because the kernel reads the working
|
||||
// directory for it.
|
||||
//
|
||||
// The folder the person last opened, when it is still usable — the same
|
||||
// answer the desktop host gives (`launchWorkspace`), and the reason a
|
||||
// phone session used to work in the app's own `files/workspace` while
|
||||
// the sidebar said it was in the shared folder: the launch entry in
|
||||
// `serve-workspaces.json` was written and then ignored, and `write_roots`
|
||||
// is derived from the working directory, so the file tools were confined
|
||||
// to the app's private folder and every write into the shared one was
|
||||
// refused. `workspaceDir` is still the answer for a first run and for a
|
||||
// folder since deleted, but the choice is never silent — see
|
||||
// [launchWorkspaceDir]. `workspace` was resolved above so it could also
|
||||
// be named on the command line.
|
||||
builder.directory(workspace)
|
||||
// `PWD` is what the kernel's own `os.Getwd` prefers: Go uses it whenever
|
||||
// it names the same directory as `.`, which is exactly this case, and it
|
||||
// is the only way to make the kernel resolve its root to the string this
|
||||
// shell chose. Without it `os.Getwd` falls back to the kernel's view of
|
||||
// the mount, and on Android `/storage/emulated/0/...` and the path the
|
||||
// FUSE layer reports for it need not be spelled the same way. The kernel
|
||||
// derives `write_roots` from that root, so the two spellings have to be
|
||||
// the same one.
|
||||
builder.environment().put("PWD", workspace.absolutePath)
|
||||
builder.redirectErrorStream(true)
|
||||
val process = builder.start()
|
||||
|
||||
// The kernel's own log is the only place a startup failure says why, and
|
||||
// a phone has no terminal to read. It is drained on a thread and kept
|
||||
// ring-buffered so the About screen can show the last of it.
|
||||
Thread({ drain(process) }, "kernel-log").apply { isDaemon = true }.start()
|
||||
return process
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder the person last opened, or null when there is not one.
|
||||
*
|
||||
* `serve-workspaces.json` is the kernel's own record of the projects the
|
||||
* sidebar lists, and its `launch` entry is which of them a session starts
|
||||
* in. Both shapes the file has are read — a bare array of paths, and an
|
||||
* object with `paths` and `launch` — because both are written in the wild
|
||||
* and a reader that only knew one would silently fall back.
|
||||
*
|
||||
* The entry has to be one of the listed paths, which is the same rule the
|
||||
* kernel applies when it reads this file (`workspacelist.Read` blanks a
|
||||
* `launch` that is not in `paths`). It matters more here than there: the
|
||||
* working directory decides `write_roots`, so whatever this answers is
|
||||
* where the agent's file tools may write — and on a phone that permission
|
||||
* reaches all of shared storage. A file with a `launch` outside its own
|
||||
* list is one this shell did not write, and it gets the listed answer.
|
||||
*
|
||||
* Null for anything unusable: no file, unreadable JSON, a launch that is
|
||||
* not among the listed folders, an entry that has since been deleted, or a
|
||||
* path that is now a file. Every one of those means the same thing to the
|
||||
* caller — start where this shell always started.
|
||||
*/
|
||||
private fun rememberedLaunchDir(): File? {
|
||||
val file = File(home, "serve-workspaces.json")
|
||||
if (!file.isFile) return null
|
||||
val text = runCatching { file.readText() }.getOrNull() ?: return null
|
||||
val launch = runCatching {
|
||||
// A bare array is the file's other shape — the one older kernels
|
||||
// wrote, and therefore the one a person upgrading is most likely to
|
||||
// have. Without this branch `JSONObject(text)` throws on it and the
|
||||
// whole function falls back, which is the same mismatch (the
|
||||
// sidebar naming one folder, the session working in another) this
|
||||
// exists to fix. `withoutHome` below reads both shapes the same way.
|
||||
if (text.trimStart().startsWith("[")) {
|
||||
val arr = JSONArray(text)
|
||||
if (arr.length() == 0) return@runCatching null
|
||||
arr.optString(0)
|
||||
} else {
|
||||
val json = JSONObject(text)
|
||||
val paths = json.optJSONArray("paths")
|
||||
?.let { arr -> (0 until arr.length()).mapNotNull { arr.optString(it).takeIf(String::isNotBlank) } }
|
||||
.orEmpty()
|
||||
if (paths.isEmpty()) return@runCatching null
|
||||
json.optString("launch").takeIf { it.isNotBlank() && it in paths } ?: paths.first()
|
||||
}
|
||||
}.getOrNull()?.takeIf { it.isNotBlank() } ?: return null
|
||||
val dir = runCatching { File(launch) }.getOrNull() ?: return null
|
||||
if (!dir.isDirectory) {
|
||||
// A launch entry this process cannot stat is exactly the failure the
|
||||
// caller exists to avoid, and falling back silently is what made it
|
||||
// take three releases to notice: the session opened in the app's own
|
||||
// folder while the sidebar named the shared one. A phone has no
|
||||
// terminal, so the log is the only place the reason can be said —
|
||||
// and `exists`/`readable` tell apart "deleted" from "not permitted",
|
||||
// which need different answers from the person.
|
||||
Log.w(
|
||||
TAG,
|
||||
"launch entry $launch is not a usable directory " +
|
||||
"(exists=${dir.exists()}, readable=${dir.canRead()})",
|
||||
)
|
||||
return null
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder the kernel should start in.
|
||||
*
|
||||
* Either the launch entry — the folder the person last opened, which is
|
||||
* also the one the sidebar shows — or the app's own folder when there is
|
||||
* none. Whichever it is, it is logged, because the two disagreeing is the
|
||||
* bug this exists to fix and a silent choice is what let it survive.
|
||||
*/
|
||||
private fun launchWorkspaceDir(): File {
|
||||
val remembered = rememberedLaunchDir()
|
||||
if (remembered != null) {
|
||||
Log.i(TAG, "kernel workspace: ${remembered.absolutePath} (the remembered launch project)")
|
||||
return remembered
|
||||
}
|
||||
Log.i(TAG, "kernel workspace: ${workspaceDir.absolutePath} (no remembered launch project)")
|
||||
return workspaceDir
|
||||
}
|
||||
|
||||
private val logLines = ArrayDeque<String>()
|
||||
|
||||
private fun drain(process: Process) {
|
||||
runCatching {
|
||||
process.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
synchronized(logLines) {
|
||||
logLines.addLast(line)
|
||||
while (logLines.size > LOG_KEEP) logLines.removeFirst()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The kernel's tail, newest last, for a bug report or the About screen. */
|
||||
fun recentLog(): String = synchronized(logLines) { logLines.joinToString("\n") }
|
||||
|
||||
private fun awaitPort(process: Process): String {
|
||||
val deadline = System.currentTimeMillis() + START_TIMEOUT_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (!process.isAlive) {
|
||||
throw IllegalStateException("内核启动即退出。\n${recentLog().takeLast(2000)}")
|
||||
}
|
||||
val text = if (portFile.isFile) runCatching { portFile.readText().trim() }.getOrNull() else null
|
||||
// The file is written by the kernel on the way to serving, and the
|
||||
// kernel rewrites it with the real port when it was given :0.
|
||||
if (!text.isNullOrBlank() && text.contains(":")) return text
|
||||
Thread.sleep(POLL_MS)
|
||||
}
|
||||
throw IllegalStateException("内核在 ${START_TIMEOUT_MS / 1000}s 内没有报告监听地址。\n${recentLog().takeLast(2000)}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until the bound port answers.
|
||||
*
|
||||
* A port that is open but not yet serving is the normal first second of a
|
||||
* kernel's life; a WebView pointed at it would show a connection error and
|
||||
* cache the failure, so the wait belongs here rather than in the page.
|
||||
*/
|
||||
private fun awaitServing(process: Process, origin: String) {
|
||||
val deadline = System.currentTimeMillis() + START_TIMEOUT_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (!process.isAlive) {
|
||||
throw IllegalStateException("内核在开始服务前退出。\n${recentLog().takeLast(2000)}")
|
||||
}
|
||||
if (probe("$origin/")) return
|
||||
Thread.sleep(POLL_MS)
|
||||
}
|
||||
throw IllegalStateException("内核已监听 $origin,但页面没有响应。\n${recentLog().takeLast(2000)}")
|
||||
}
|
||||
|
||||
private fun probe(url: String): Boolean = runCatching {
|
||||
(URL(url).openConnection() as HttpURLConnection).run {
|
||||
connectTimeout = 1000
|
||||
readTimeout = 1000
|
||||
requestMethod = "GET"
|
||||
try {
|
||||
responseCode in 200..399
|
||||
} finally {
|
||||
disconnect()
|
||||
}
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReasonixKernel"
|
||||
const val LOG_KEEP = 400
|
||||
const val POLL_MS = 120L
|
||||
const val START_TIMEOUT_MS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Keeps the kernel alive while the app is not on screen.
|
||||
*
|
||||
* The reason this exists at all: an agent turn that takes minutes is a normal
|
||||
* turn, and Android reclaims a backgrounded app's child process within seconds
|
||||
* of the screen going off. Without the service, pocketing the phone would kill
|
||||
* a running task — the one failure mode that makes a phone a bad client for
|
||||
* something that works on its own.
|
||||
*
|
||||
* A foreground service needs a notification the person can see, which is also
|
||||
* the honest thing to show: the kernel is running and what it is doing lives on
|
||||
* another machine.
|
||||
*/
|
||||
class KernelService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// Promoted before `start()`: a service that starts work first and
|
||||
// notifies after has a window in which the system may kill it, and the
|
||||
// work it would have been protecting is exactly what is being started.
|
||||
startForegroundNotification()
|
||||
|
||||
val kernel = (application as App).kernel
|
||||
scope.launch {
|
||||
kernel.start().onFailure { failure ->
|
||||
// A kernel that will not start is a fact the person needs, and a
|
||||
// notification that only ever said "running" would be a lie.
|
||||
notify(SERVICE_NOTICE, getString(R.string.notify_failed_title), failure.message.orEmpty())
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
// Sticky, so a kernel killed under memory pressure comes back when there
|
||||
// is room — which is what a person who left a task running expects.
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun startForegroundNotification() {
|
||||
val notification = buildNotification(
|
||||
getString(R.string.notify_running_title),
|
||||
getString(R.string.notify_running_body),
|
||||
)
|
||||
// `dataSync` matches the manifest's declaration. On 34+ the type is
|
||||
// mandatory and a mismatch throws, so it is named in both places.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
SERVICE_NOTICE,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
|
||||
)
|
||||
} else {
|
||||
startForeground(SERVICE_NOTICE, notification)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(title: String, body: String): Notification {
|
||||
val open = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
},
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
return NotificationCompat.Builder(this, App.CHANNEL_KERNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setContentIntent(open)
|
||||
// The notification is a receipt, not an alarm; swiping it away
|
||||
// leaves the kernel running, which is what the person meant by
|
||||
// swiping it.
|
||||
.setOngoing(false)
|
||||
.setSilent(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_MIN)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun notify(id: Int, title: String, body: String) {
|
||||
// The notification permission is granted at runtime from Android 13 and
|
||||
// the person can refuse it. Without this check the call throws
|
||||
// SecurityException and takes the service down with it — the opposite of
|
||||
// what a notification that could not be shown should do. Below 13 the
|
||||
// permission does not exist and posting always succeeds.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
NotificationManagerCompat.from(this).notify(id, buildNotification(title, body))
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SERVICE_NOTICE = 1
|
||||
|
||||
/** Idempotent: called on every start of the activity, and by the boot
|
||||
* path, and safe to repeat. */
|
||||
fun start(context: Context) {
|
||||
ContextCompat.startForegroundService(context, Intent(context, KernelService::class.java))
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, KernelService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,744 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.MediaStore
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.MimeTypeMap
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* What the page can ask the phone for.
|
||||
*
|
||||
* This is the whole surface, and it is deliberately tiny. Android's
|
||||
* `@JavascriptInterface` is a bridge into the app's process from a WebView whose
|
||||
* content is a web page: every method here is reachable by anything that can run
|
||||
* script in that page, so each one is written as a verb with no address
|
||||
* parameter it does not need, and none of them can name a path outside the
|
||||
* kernel's own home.
|
||||
*
|
||||
* It is deliberately *not* the Electron preload bridge. That one exposes window
|
||||
* management, a filesystem walker, an editor launcher and a browser view host —
|
||||
* all of which are meaningless on a phone, and the two that were not (open a URL,
|
||||
* save a file) already have a way to happen here: `WebViewClient` routes external
|
||||
* links to the browser, and the page's own download reaches the WebView's
|
||||
* `DownloadListener`.
|
||||
*
|
||||
* The one thing a phone must add is `importIntoHome`: the kernel runs on this
|
||||
* device and can only read paths under its own home, so a private key the person
|
||||
* has in their Documents folder has to be copied across. Nothing else the page
|
||||
* wants is out of its reach.
|
||||
*/
|
||||
class NativeBridge(
|
||||
private val context: Context,
|
||||
private val kernel: Kernel,
|
||||
private val onOpen: (String) -> Unit,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Whether the document calling may use this bridge.
|
||||
*
|
||||
* `addJavascriptInterface` makes the object reachable from whatever page the
|
||||
* WebView holds, so a link the model produced — or a cleartext page on the
|
||||
* LAN — would otherwise get `importIntoHome`, `pickFolder`, `hostCall` and
|
||||
* the clipboard. The activity answers by comparing the main frame's origin
|
||||
* against the kernel's and the one paired computer the person confirmed.
|
||||
*
|
||||
* Anything that reaches the device checks this first. The five methods that
|
||||
* do not — version, systemTheme, safeArea, setLayerOpen, setRunning — report
|
||||
* back what the page already knows about its own window and grant nothing.
|
||||
*/
|
||||
var trusted: () -> Boolean = { false }
|
||||
|
||||
/** The version the page reads to decide whether this bridge is the one it
|
||||
* knows. Bumped when a method's contract changes, not when one is added. */
|
||||
@JavascriptInterface
|
||||
fun version(): String = BRIDGE_VERSION
|
||||
|
||||
/**
|
||||
* Copy a file the person picks into the kernel's home, answering with its
|
||||
* path there — or "" when they dismissed the picker.
|
||||
*
|
||||
* `kind` names the directory inside the home, because that is a fact about
|
||||
* the kernel's layout and not about the file: an SSH private key belongs in
|
||||
* `.ssh`, and a dotenv the kernel reads for passphrases belongs at the root
|
||||
* of the home where `config.Load` looks for it.
|
||||
*
|
||||
* The path that comes back is *inside the home*, never the document
|
||||
* provider's URI. That is the point: the kernel is a child process with no
|
||||
* access to the provider, so a `content://` would be a path it cannot open.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun importIntoHome(kind: String, name: String): String {
|
||||
if (!trusted()) return ""
|
||||
val dir = when (kind) {
|
||||
"identity" -> File(kernel.homeDir(), ".ssh")
|
||||
"env" -> kernel.homeDir()
|
||||
else -> return ""
|
||||
}
|
||||
val safeName = sanitise(name)
|
||||
if (safeName.isEmpty()) return ""
|
||||
|
||||
val picked = pickFile() ?: return ""
|
||||
return try {
|
||||
dir.mkdirs()
|
||||
val target = File(dir, safeName)
|
||||
context.contentResolver.openInputStream(picked)?.use { input ->
|
||||
target.outputStream().use { output -> input.copyTo(output) }
|
||||
} ?: return ""
|
||||
// A private key with group or world read is one OpenSSH refuses to
|
||||
// use, and the refusal reads as "bad permissions" from a long way
|
||||
// away. Setting it here is what makes the file usable at all.
|
||||
if (kind == "identity") {
|
||||
runCatching {
|
||||
target.setReadable(false, false)
|
||||
target.setReadable(true, true)
|
||||
target.setWritable(false, false)
|
||||
target.setWritable(true, true)
|
||||
}
|
||||
}
|
||||
target.absolutePath
|
||||
} catch (_: Exception) {
|
||||
// A copy that failed leaves nothing behind; the caller sees "" and
|
||||
// the person can try again.
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a URL in the device's browser.
|
||||
*
|
||||
* The page asks for this when a link points somewhere outside the kernel —
|
||||
* a provider's console, a documentation page — and loading it in place would
|
||||
* strand the person in a window with no address bar and no way back.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun openExternal(url: String) {
|
||||
if (!trusted()) return
|
||||
// Only what a browser can open. A `file://` or `content://` here would
|
||||
// be the page reaching into the device through a method named for
|
||||
// leaving it.
|
||||
if (!url.startsWith("http://") && !url.startsWith("https://")) return
|
||||
onOpen(url)
|
||||
}
|
||||
|
||||
/** Put text on the clipboard. A WebView's own `navigator.clipboard` write is
|
||||
* gated behind a permission Android grants only to a focused document, so
|
||||
* the one thing the page actually offers to copy — a token, a command, a
|
||||
* path — has no other way out.
|
||||
*
|
||||
* Answers whether the write landed. A platform that refuses it raises
|
||||
* rather than answering, and an exception must not cross
|
||||
* `@JavascriptInterface` as a silent success — the page would say 已复制
|
||||
* over an empty clipboard. Caught here, the answer is the one the caller
|
||||
* can act on: false, and the button says 复制失败 instead. */
|
||||
@JavascriptInterface
|
||||
fun copyText(text: String): Boolean = if (!trusted()) false else runCatching {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("reasonix", text))
|
||||
}.isSuccess
|
||||
|
||||
/**
|
||||
* Write text where the person picks, and answer with the path it went to.
|
||||
*
|
||||
* The page's own route to a file — a blob URL on an `<a download>` — reaches
|
||||
* nothing here: a WebView has no downloads shelf, and its `DownloadListener`
|
||||
* fires only for a real navigation, not for a blob the page just built. So
|
||||
* the text crosses the bridge and the shell opens the system's document
|
||||
* picker, which is also the only way to reach a folder the person can find
|
||||
* again afterwards.
|
||||
*
|
||||
* "" is a dismissal, the same answer `importIntoHome` gives, and the page
|
||||
* reads the two the same way.
|
||||
*/
|
||||
/**
|
||||
* Put a copy of a file where a phone's own file manager will show it.
|
||||
*
|
||||
* `saveText` asks the person where to put it, which is the right question
|
||||
* on a desktop and the wrong one here: the kernel's workspace is
|
||||
* app-private storage, so the file someone wants is in a place no file
|
||||
* manager can open, and a picker that starts at "recent" is another place
|
||||
* to lose it. This answers the actual question — "where is it" — by
|
||||
* putting it in Downloads, in a folder named after the app, under a name
|
||||
* that is the file's own.
|
||||
*
|
||||
* The answer is the path relative to shared storage, so the page can say
|
||||
* where the file went rather than only that it worked. "" means the write
|
||||
* failed or the platform refused it.
|
||||
*
|
||||
* MediaStore on Android 10 and later, a plain file before that. The two
|
||||
* are not interchangeable: from 10 the app may not write another app's
|
||||
* files directly, and MediaStore is the only way in; before it there is no
|
||||
* MediaStore collection for downloads and the public directory is writable
|
||||
* with the storage permission this app does not ask for, so that branch is
|
||||
* best-effort and says so by answering "".
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun exportToDownloads(name: String, content: String): String {
|
||||
if (!trusted()) return ""
|
||||
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
|
||||
return exportFile(safeName, content).orEmpty()
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun saveText(name: String, content: String): String {
|
||||
if (!trusted()) return ""
|
||||
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
|
||||
return saveFile(safeName, content) ?: ""
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand text to whatever the device shares with — a chat app, the mail
|
||||
* client, a note app.
|
||||
*
|
||||
* The share sheet rather than a second save dialog: "where is that file"
|
||||
* is the question this answers, and on a phone a document someone wants to
|
||||
* keep or send usually goes through one of those apps rather than a folder.
|
||||
*
|
||||
* Shared as text with the filename as its subject, which is what every
|
||||
* target understands. A file attachment would need a `FileProvider` and a
|
||||
* cache copy for the same words to arrive.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun shareText(name: String, content: String): Boolean {
|
||||
if (!trusted()) return false
|
||||
val safeName = sanitise(name).ifEmpty { "reasonix.txt" }
|
||||
val posted = java.util.concurrent.CountDownLatch(1)
|
||||
var ok = false
|
||||
main.post {
|
||||
ok = runCatching { askForShare(safeName, content) }.getOrDefault(false)
|
||||
posted.countDown()
|
||||
}
|
||||
runCatching { posted.await(SHARE_TIMEOUT_SECONDS, TimeUnit.SECONDS) }
|
||||
return ok
|
||||
}
|
||||
|
||||
/**
|
||||
* The device's own light/dark answer.
|
||||
*
|
||||
* The page resolves its theme from `localStorage` first and only asks the
|
||||
* system when nothing is saved, so this is what makes a fresh install match
|
||||
* the phone instead of defaulting to light.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun systemTheme(): String {
|
||||
val night = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
|
||||
return if (night == Configuration.UI_MODE_NIGHT_YES) "dark" else "light"
|
||||
}
|
||||
|
||||
/**
|
||||
* The window's real safe-area insets, in CSS pixels, as
|
||||
* `top,right,bottom,left`.
|
||||
*
|
||||
* A WebView does not implement `env(safe-area-inset-*)`: those are an iOS
|
||||
* Safari feature, and on Android every one of them resolves to `0`. So a
|
||||
* page that pads itself with them — which `mobile.css` does — is un-padded
|
||||
* on exactly the platform this shell exists for, and the first line of the
|
||||
* interface sits under the status bar.
|
||||
*
|
||||
* The values have to come from here for a second reason too: from Android 15
|
||||
* the window is edge-to-edge whether the app asks for it or not, so the bars
|
||||
* really are drawn over the page and there is no window-manager switch that
|
||||
* could move the content back down.
|
||||
*
|
||||
* Answered as a string because that is what crosses the bridge; the page
|
||||
* sets it as a CSS custom property and `mobile.css` reads it.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun safeArea(): String {
|
||||
val insets = onInsets?.invoke() ?: return "0,0,0,0"
|
||||
return "${insets.left},${insets.top},${insets.right},${insets.bottom}"
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the pairing code a computer is showing.
|
||||
*
|
||||
* A phone cannot type what a computer renders as a QR code — it is a
|
||||
* one-time code inside a URL, and the whole reason it is a picture is that
|
||||
* nobody reads one aloud. So the page asks for the camera and gets the text
|
||||
* back, which is the same direction the computer's own dialog describes.
|
||||
*
|
||||
* The answer is the code's own text, not a parsed result: what a pairing
|
||||
* fragment means is the page's to decide, and it already knows how — the
|
||||
* `#pair=` handling ships with the interface.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun scanPairingCode(): String = if (!trusted()) "" else scanWithCamera()
|
||||
|
||||
/**
|
||||
* Load a URL in this window instead of handing it to the browser.
|
||||
*
|
||||
* The page asks for this once, right after a scan: the code it read points at
|
||||
* the computer's own Studio, and the whole point of scanning is to end up
|
||||
* looking at that computer. Going out to a browser would leave the app on one
|
||||
* screen and the paired machine on another, with the back gesture an exit
|
||||
* rather than a return.
|
||||
*
|
||||
* Only http and https are accepted. The page is this repository's own build
|
||||
* and is trusted, but a scanner reads whatever is held in front of it, so the
|
||||
* one value that arrives here from outside is checked: a `file://` or
|
||||
* `javascript:` that happened to be on a printed code must not become a
|
||||
* navigation.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun openInApp(url: String) {
|
||||
if (!trusted()) return
|
||||
val trimmed = url.trim()
|
||||
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return
|
||||
main.post { onOpenInApp?.invoke(trimmed) }
|
||||
}
|
||||
|
||||
/** How the activity loads a URL in the window it owns. Set by the activity. */
|
||||
var onOpenInApp: ((String) -> Unit)? = null
|
||||
|
||||
// ---- the native browser view host bridge ----
|
||||
//
|
||||
// The page's `host.ts` looks for `window.reasonixHost` with Promise-based
|
||||
// methods (showBrowserView, hideBrowserView, etc.). `@JavascriptInterface`
|
||||
// is synchronous, so the round trip is: JS generates an id, calls
|
||||
// `hostCall(id, method, args)`, Kotlin does the work asynchronously, then
|
||||
// pushes the result back via `evaluateJavascript` calling
|
||||
// `window.__reasonixHostReply(id, json)`. The injected script (in
|
||||
// MainActivity) wires each Promise to that reply channel.
|
||||
|
||||
/** How the activity handles an async host call. Set by the activity. */
|
||||
var onHostCall: ((id: String, method: String, args: String) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Entry point for the page's `window.reasonixHost` Promise methods.
|
||||
*
|
||||
* `id` is a unique call identifier the JS side generated; `method` is the
|
||||
* method name (e.g. "showBrowserView"); `args` is the JSON-encoded argument
|
||||
* array. The activity handles the call asynchronously and replies through
|
||||
* `evaluateJavascript` with `window.__reasonixHostReply(id, resultJson)`.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun hostCall(id: String, method: String, args: String) {
|
||||
if (!trusted()) return
|
||||
onHostCall?.invoke(id, method, args)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page has a panel up that the back gesture should close first.
|
||||
*
|
||||
* Written by the page, read by the activity's back handler. The page owns the
|
||||
* answer — it is the only thing that knows what is open, and a second
|
||||
* implementation of that question in the shell would be one that drifts — so
|
||||
* the page reports the fact and the shell keeps the action.
|
||||
*
|
||||
* Volatile because the two ends are on different threads: the page sets it
|
||||
* from the WebView's JavaScript thread, the back gesture reads it on the main
|
||||
* one, and a stale read here is a panel that does not close.
|
||||
*/
|
||||
@Volatile
|
||||
var layerOpen: Boolean = false
|
||||
private set
|
||||
|
||||
@JavascriptInterface
|
||||
fun setLayerOpen(open: Boolean) {
|
||||
layerOpen = open
|
||||
}
|
||||
|
||||
// ---- the picker, which is an Activity result in a synchronous world ----
|
||||
|
||||
private val pending = AtomicReference<Uri?>(null)
|
||||
private val latch = AtomicReference<CountDownLatch?>(null)
|
||||
|
||||
/** The code the camera read, held between the activity's answer and the
|
||||
* wait below — the same round trip the file picker takes. */
|
||||
private val scanned = AtomicReference<String?>(null)
|
||||
private val scanLatch = AtomicReference<CountDownLatch?>(null)
|
||||
|
||||
/** The main thread, because starting an Activity result must happen there. */
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* How to ask for a file. Set by the activity, which owns the Activity Result
|
||||
* API; it answers whether the ask was dispatched, not whether the person
|
||||
* picked anything — that arrives through `deliver`.
|
||||
*/
|
||||
var askForFile: () -> Boolean = { false }
|
||||
|
||||
/**
|
||||
* How the activity reports the window's insets. Set by the activity, which is
|
||||
* the only thing that can see them, and asked on every call rather than
|
||||
* cached — a rotation, a fold, or the keyboard opening all change them, and a
|
||||
* stale answer here is a stripe of interface under the status bar.
|
||||
*/
|
||||
var onInsets: (() -> Insets?)? = null
|
||||
|
||||
/**
|
||||
* How to open the camera. Set by the activity, which owns the Activity
|
||||
* Result API; like `askForFile` it answers whether the ask was dispatched,
|
||||
* and the code itself arrives through `deliverScan`.
|
||||
*/
|
||||
var askForScan: () -> Boolean = { false }
|
||||
|
||||
/**
|
||||
* How to put a file where the person picks. Set by the activity, which owns
|
||||
* the Activity Result API; it answers whether the ask was dispatched, and
|
||||
* the chosen place arrives through `deliverSave`.
|
||||
*/
|
||||
var askForSave: (name: String, content: String) -> Boolean = { _, _ -> false }
|
||||
|
||||
/**
|
||||
* How to open the share sheet. Set by the activity, which is the only thing
|
||||
* that can start an Intent; it answers whether anything on the device took
|
||||
* the text.
|
||||
*/
|
||||
var askForShare: (name: String, content: String) -> Boolean = { _, _ -> false }
|
||||
|
||||
/** The place the save dialog answered with, held between the two halves. */
|
||||
private val saveTarget = AtomicReference<Uri?>(null)
|
||||
private val saveLatch = AtomicReference<CountDownLatch?>(null)
|
||||
|
||||
/**
|
||||
* Ask where to put a file and write it there.
|
||||
*
|
||||
* The same latch round trip as `pickFile`, and for the same reason:
|
||||
* `@JavascriptInterface` cannot suspend, so the WebView's thread waits while
|
||||
* the picker is open — a modal panel the person is looking at.
|
||||
*/
|
||||
private fun saveFile(name: String, content: String): String? {
|
||||
val gate = CountDownLatch(1)
|
||||
saveLatch.set(gate)
|
||||
saveTarget.set(null)
|
||||
|
||||
val posted = CountDownLatch(1)
|
||||
var dispatched = false
|
||||
main.post {
|
||||
dispatched = runCatching { askForSave(name, content) }.getOrDefault(false)
|
||||
posted.countDown()
|
||||
}
|
||||
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
|
||||
if (!ready || !dispatched) {
|
||||
saveLatch.set(null)
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) null
|
||||
else saveTarget.get()?.toString()
|
||||
} catch (_: InterruptedException) {
|
||||
null
|
||||
} finally {
|
||||
saveLatch.set(null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called by the activity once the bytes are written. A null uri is a dismissal. */
|
||||
fun deliverSave(uri: Uri?) {
|
||||
saveTarget.set(uri)
|
||||
saveLatch.get()?.countDown()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the pairing code a computer is showing, and return it.
|
||||
*
|
||||
* The same shape as `pickFile` and for the same reason: a
|
||||
* `@JavascriptInterface` method is called on the WebView's thread and must
|
||||
* return a value, so the camera is opened on the main thread and this one
|
||||
* waits. The block lasts as long as the person is aiming, which is why the
|
||||
* timeout is generous — a scan that gave up after a few seconds would be
|
||||
* one nobody could complete.
|
||||
*
|
||||
* An empty string is "no code", which is what a refusal, a cancellation and
|
||||
* a timeout all are. The caller acts on the text, so a distinct error would
|
||||
* only be a fourth way to say the same thing.
|
||||
*/
|
||||
private fun scanWithCamera(): String {
|
||||
val gate = CountDownLatch(1)
|
||||
scanLatch.set(gate)
|
||||
scanned.set(null)
|
||||
|
||||
val posted = CountDownLatch(1)
|
||||
var dispatched = false
|
||||
main.post {
|
||||
dispatched = runCatching { askForScan() }.getOrDefault(false)
|
||||
posted.countDown()
|
||||
}
|
||||
val ready = runCatching { posted.await(SCAN_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
|
||||
if (!ready || !dispatched) {
|
||||
scanLatch.set(null)
|
||||
return ""
|
||||
}
|
||||
return try {
|
||||
if (!gate.await(SCAN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) "" else scanned.get().orEmpty()
|
||||
} catch (_: InterruptedException) {
|
||||
""
|
||||
} finally {
|
||||
scanLatch.set(null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called by the activity when the scanner answers. Null is a dismissal. */
|
||||
fun deliverScan(text: String?) {
|
||||
scanned.set(text)
|
||||
scanLatch.get()?.countDown()
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask for one file and wait for the answer.
|
||||
*
|
||||
* `@JavascriptInterface` methods cannot suspend: the WebView calls them on
|
||||
* its own thread and expects a value back. So the ask is posted to the main
|
||||
* thread and this one waits on a latch. The cost is a blocked JS thread for
|
||||
* as long as the picker is open — which is a modal panel the person is
|
||||
* looking at, with nothing else in the page running.
|
||||
*
|
||||
* A timeout is set rather than waiting forever: a picker that never answers
|
||||
* (the activity destroyed underneath it) would otherwise pin a WebView
|
||||
* thread until the process died.
|
||||
*/
|
||||
private fun pickFile(): Uri? {
|
||||
val gate = CountDownLatch(1)
|
||||
latch.set(gate)
|
||||
pending.set(null)
|
||||
|
||||
val posted = CountDownLatch(1)
|
||||
var dispatched = false
|
||||
main.post {
|
||||
dispatched = runCatching { askForFile() }.getOrDefault(false)
|
||||
posted.countDown()
|
||||
}
|
||||
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
|
||||
if (!ready || !dispatched) {
|
||||
latch.set(null)
|
||||
return null
|
||||
}
|
||||
|
||||
return try {
|
||||
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) null else pending.get()
|
||||
} catch (_: InterruptedException) {
|
||||
null
|
||||
} finally {
|
||||
latch.set(null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called by the activity when the picker answers. A null uri is a dismissal. */
|
||||
fun deliver(uri: Uri?) {
|
||||
pending.set(uri)
|
||||
latch.get()?.countDown()
|
||||
}
|
||||
|
||||
/** The folder under Downloads that this app's exports land in. */
|
||||
private fun exportFolder(): String = "Reasonix"
|
||||
|
||||
/** The MIME type this name declares, or null when the platform does not know
|
||||
* it.
|
||||
*
|
||||
* Where the type is written, the name and the type agree, and that agreement
|
||||
* is the whole fix: `.md` is answered `text/markdown` here, so MediaStore
|
||||
* has nothing to correct and the export stays `报告.md` instead of being
|
||||
* renamed `报告.md.txt` by the `text/plain` it used to be given. Where the
|
||||
* type is unknown the field is left off, which leaves MediaStore to derive
|
||||
* the same `application/octet-stream` it would have been told — the name
|
||||
* still stands on its own, which is all this is for. */
|
||||
private fun mimeFor(name: String): String? {
|
||||
val ext = name.substringAfterLast('.', "").lowercase()
|
||||
if (ext.isEmpty() || ext == name.lowercase()) return null
|
||||
return runCatching { MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) }.getOrNull()
|
||||
}
|
||||
|
||||
private fun exportFile(name: String, content: String): String? = runCatching {
|
||||
val bytes = content.toByteArray(Charsets.UTF_8)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
||||
// The type is derived here rather than declared, and it is
|
||||
// written only when the name really has an extension that maps
|
||||
// to one.
|
||||
//
|
||||
// It used to be `text/plain` for everything, and MediaStore
|
||||
// answers a name whose extension disagrees with the declared
|
||||
// type by appending its own: exporting `报告.md` landed in
|
||||
// Downloads as `报告.md.txt`, and any source file came out with
|
||||
// the wrong second extension. Deriving the type from the name
|
||||
// instead keeps the two in agreement — which is what stops the
|
||||
// rename — and a name the platform has no type for is left off
|
||||
// entirely rather than declared as `application/octet-stream`,
|
||||
// so nothing is corrected there either.
|
||||
mimeFor(name)?.let { put(MediaStore.Downloads.MIME_TYPE, it) }
|
||||
put(
|
||||
MediaStore.Downloads.RELATIVE_PATH,
|
||||
Environment.DIRECTORY_DOWNLOADS + "/" + exportFolder(),
|
||||
)
|
||||
// Hidden until the bytes are all there, so a file manager that
|
||||
// reads the folder mid-write cannot show half a document.
|
||||
put(MediaStore.Downloads.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||
?: return@runCatching null
|
||||
resolver.openOutputStream(uri)?.use { it.write(bytes) } ?: return@runCatching null
|
||||
values.clear()
|
||||
values.put(MediaStore.Downloads.IS_PENDING, 0)
|
||||
resolver.update(uri, values, null, null)
|
||||
"${Environment.DIRECTORY_DOWNLOADS}/${exportFolder()}/$name"
|
||||
} else {
|
||||
val dir = File(
|
||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
|
||||
exportFolder(),
|
||||
)
|
||||
if (!dir.exists() && !dir.mkdirs()) return@runCatching null
|
||||
val target = File(dir, name)
|
||||
target.writeBytes(bytes)
|
||||
target.absolutePath
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private fun sanitise(name: String): String {
|
||||
// A name from the page is used as a filename, so it is reduced to one:
|
||||
// no separators, no traversal, and nothing a filesystem treats as
|
||||
// special. The default is the name the field it came from suggests.
|
||||
val trimmed = name.trim().substringAfterLast('/').substringAfterLast('\\')
|
||||
if (trimmed.isEmpty() || trimmed == "." || trimmed == "..") return ""
|
||||
return trimmed.filter { it.isLetterOrDigit() || it in "._-" }.take(64)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a turn is running, so the screen can be kept awake for one.
|
||||
*
|
||||
* The page owns the answer — it is the only thing that knows if the kernel
|
||||
* is working — and the shell owns the flag, because a window flag is not
|
||||
* something a page can set. Nothing is asked at launch: a window that is
|
||||
* merely open is one the person may be reading, and holding the screen on
|
||||
* for that is holding it on for nothing.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun setRunning(running: Boolean) {
|
||||
onRunning?.invoke(running)
|
||||
}
|
||||
|
||||
/** How the activity applies that flag. Set by the activity. */
|
||||
var onRunning: ((Boolean) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Whether the app may read every file, which is what lets the kernel open a
|
||||
* folder on this phone as a workspace.
|
||||
*
|
||||
* Asked rather than assumed: the permission is granted by hand in system
|
||||
* settings, so the page has to be able to say "not yet" rather than fail on
|
||||
* the first `stat`. Answered `true` below API 30, where ordinary read
|
||||
* permission is enough and the concept does not exist.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun hasAllFilesAccess(): Boolean = filesAccess?.invoke() ?: true
|
||||
|
||||
var filesAccess: (() -> Boolean)? = null
|
||||
|
||||
/** Open the system page where that permission is granted. The only place
|
||||
* Android offers it — there is no dialog for this one. */
|
||||
@JavascriptInterface
|
||||
fun requestAllFilesAccess() {
|
||||
if (!trusted()) return
|
||||
askForFilesAccess?.invoke()
|
||||
}
|
||||
|
||||
var askForFilesAccess: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Whether this app is exempt from the system's battery optimisation.
|
||||
*
|
||||
* A turn runs in a child process under a foreground service. Under doze the
|
||||
* whole app group is frozen anyway, so the turn stops making progress while
|
||||
* the screen is off — which is the state the person left it in on purpose.
|
||||
* Unrestricted is the answer, and it is a question Android answers.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun batteryUnrestricted(): Boolean = if (!trusted()) false else (batteryFree?.invoke() ?: true)
|
||||
|
||||
var batteryFree: (() -> Boolean)? = null
|
||||
|
||||
/** Ask for that exemption. Unlike the storage one, this has a real dialog. */
|
||||
@JavascriptInterface
|
||||
fun requestBatteryUnrestricted() {
|
||||
if (!trusted()) return
|
||||
askForBattery?.invoke()
|
||||
}
|
||||
|
||||
var askForBattery: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Ask for a folder on this phone and answer with its real filesystem path.
|
||||
*
|
||||
* "" is a dismissal, the same answer `importIntoHome` gives — and, unlike
|
||||
* that one, an empty string is a normal outcome here rather than a failure.
|
||||
* The `startIn` hint is a path the kernel knows; the picker may ignore it,
|
||||
* which is the picker's business.
|
||||
*
|
||||
* The round trip is the same latch as `pickFile`, for the same reason: a
|
||||
* document-tree picker is another activity, and this call cannot suspend.
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun pickFolder(startIn: String): String {
|
||||
if (!trusted()) return ""
|
||||
val gate = CountDownLatch(1)
|
||||
folderLatch.set(gate)
|
||||
folderPending.set(null)
|
||||
|
||||
val posted = CountDownLatch(1)
|
||||
var dispatched = false
|
||||
main.post {
|
||||
dispatched = runCatching { askForFolder(startIn) }.getOrDefault(false)
|
||||
posted.countDown()
|
||||
}
|
||||
val ready = runCatching { posted.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS) }.getOrDefault(false)
|
||||
if (!ready || !dispatched) {
|
||||
folderLatch.set(null)
|
||||
return ""
|
||||
}
|
||||
return try {
|
||||
if (!gate.await(PICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) "" else folderPending.get().orEmpty()
|
||||
} catch (_: InterruptedException) {
|
||||
""
|
||||
} finally {
|
||||
folderLatch.set(null)
|
||||
}
|
||||
}
|
||||
|
||||
var askForFolder: (String) -> Boolean = { false }
|
||||
|
||||
private val folderPending = AtomicReference<String?>(null)
|
||||
private val folderLatch = AtomicReference<CountDownLatch?>(null)
|
||||
|
||||
/** Called by the activity with the folder's real path, or null on dismissal. */
|
||||
fun deliverFolder(path: String?) {
|
||||
folderPending.set(path ?: "")
|
||||
folderLatch.get()?.countDown()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val BRIDGE_VERSION = "4"
|
||||
private const val PICK_TIMEOUT_SECONDS = 5L * 60
|
||||
|
||||
/** Long, because this is however long someone takes to aim. A shorter
|
||||
* one would turn "still lining it up" into a failed scan. */
|
||||
private const val SCAN_TIMEOUT_SECONDS = 5L * 60
|
||||
|
||||
/** Only as long as the sheet takes to appear: the answer is "something
|
||||
* took it", which is known the moment the Intent resolves. */
|
||||
private const val SHARE_TIMEOUT_SECONDS = 15L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The window's insets, in CSS pixels.
|
||||
*
|
||||
* A named type rather than four numbers because the page reads them as one
|
||||
* thing: half an inset is a layout that is wrong in one direction, and a caller
|
||||
* that passed the wrong pair would be indistinguishable from a device with no
|
||||
* cutout at all.
|
||||
*/
|
||||
data class Insets(val left: Int, val top: Int, val right: Int, val bottom: Int)
|
||||
@@ -0,0 +1,66 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import androidx.camera.core.ImageProxy
|
||||
import com.google.zxing.BarcodeFormat
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.DecodeHintType
|
||||
import com.google.zxing.MultiFormatReader
|
||||
import com.google.zxing.PlanarYUVLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
|
||||
/**
|
||||
* Reading a QR code out of one camera frame.
|
||||
*
|
||||
* ZXing core and nothing else: it is pure Java, so it runs identically on a
|
||||
* phone with Google Play Services and on one whose HarmonyOS compatibility
|
||||
* layer has none. A decoder that leaned on ML Kit would work on the machine it
|
||||
* was written on and fail on the one that needs it.
|
||||
*
|
||||
* The frame arrives as YUV_420_888, whose Y plane is already the greyscale
|
||||
* bitmap ZXing wants — no conversion, no colour maths, just the bytes. That is
|
||||
* the whole reason a phone can decode 30 frames a second without warming up.
|
||||
*/
|
||||
object Qr {
|
||||
|
||||
private val reader = MultiFormatReader().apply {
|
||||
setHints(
|
||||
mapOf(
|
||||
// Only the form the computer actually renders. Leaving the
|
||||
// reader open to every 1D barcode makes each frame slower for
|
||||
// a case that cannot occur, and a slower frame is a code that
|
||||
// has already left the viewfinder.
|
||||
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
|
||||
DecodeHintType.TRY_HARDER to true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The code's text, or null when this frame holds none. */
|
||||
fun decode(image: ImageProxy): String? {
|
||||
val plane = image.planes.firstOrNull() ?: return null
|
||||
val buffer = plane.buffer
|
||||
val data = ByteArray(buffer.remaining())
|
||||
buffer.get(data)
|
||||
// `rowStride` is padded to a hardware alignment and is usually wider
|
||||
// than the picture. Passing the width as the row length is what tells
|
||||
// ZXing where each row actually ends; getting it wrong shears the image
|
||||
// and every code reads as garbage.
|
||||
val source = PlanarYUVLuminanceSource(
|
||||
data,
|
||||
plane.rowStride,
|
||||
image.height,
|
||||
0,
|
||||
0,
|
||||
image.width,
|
||||
image.height,
|
||||
false,
|
||||
)
|
||||
return runCatching {
|
||||
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text
|
||||
}.getOrNull().also {
|
||||
// The reader keeps per-frame state between calls; resetting is what
|
||||
// stops a partial match in one frame from corrupting the next.
|
||||
reader.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package io.reasonix.mobile.app
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* The camera, held open just long enough to read one pairing code.
|
||||
*
|
||||
* A phone that wants to drive a computer cannot type the code that computer
|
||||
* shows: it is a base64 fragment inside a URL, and the whole point of showing it
|
||||
* as a QR code is that nobody reads one aloud. So this is the way in — the same
|
||||
* gesture the computer's own dialog asks for, from the other side.
|
||||
*
|
||||
* The decode is ZXing rather than ML Kit on purpose. ML Kit needs Google Play
|
||||
* Services, and this app installs on phones whose HarmonyOS compatibility layer
|
||||
* has none: a GMS-backed scanner would work on a developer's phone and fail on
|
||||
* the device that needs it. ZXing core is pure Java, so the scanner behaves the
|
||||
* same on both.
|
||||
*
|
||||
* It returns the first code it reads and finishes. A pairing code is
|
||||
* single-use and short-lived, so "keep scanning after a hit" is not a feature —
|
||||
* it is a way to spend a code that a later frame would have discarded.
|
||||
*/
|
||||
class ScanActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var preview: PreviewView
|
||||
private lateinit var hint: TextView
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
|
||||
/** Set once a code is found, so the frames in flight behind it do not each
|
||||
* try to finish the activity. */
|
||||
@Volatile
|
||||
private var settled = false
|
||||
|
||||
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) start() else refuse()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val root = FrameLayout(this)
|
||||
preview = PreviewView(this).apply {
|
||||
layoutParams = FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
)
|
||||
// The frames are analysed, not composed: filling the view and
|
||||
// cropping is right here and would be wrong for a camera app.
|
||||
scaleType = PreviewView.ScaleType.FILL_CENTER
|
||||
}
|
||||
hint = TextView(this).apply {
|
||||
text = getString(R.string.scan_hint)
|
||||
setTextColor(0xFFFFFFFF.toInt())
|
||||
textSize = 14f
|
||||
gravity = Gravity.CENTER
|
||||
val pad = (16 * resources.displayMetrics.density).toInt()
|
||||
setPadding(pad, pad, pad, pad)
|
||||
// Readable over whatever the camera is pointing at, which is the
|
||||
// one background a design system cannot choose.
|
||||
setBackgroundColor(0x99000000.toInt())
|
||||
layoutParams = FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
Gravity.BOTTOM,
|
||||
)
|
||||
}
|
||||
root.addView(preview)
|
||||
root.addView(hint)
|
||||
setContentView(root)
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
start()
|
||||
} else {
|
||||
requestCamera.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
}
|
||||
|
||||
private fun refuse() {
|
||||
// No dialog of our own: the permission prompt already said no, and a
|
||||
// second window repeating it is one more tap to dismiss. The caller
|
||||
// gets the same answer as a cancelled scan.
|
||||
setResult(RESULT_CANCELED)
|
||||
finish()
|
||||
}
|
||||
|
||||
private fun start() {
|
||||
val providerFuture = ProcessCameraProvider.getInstance(this)
|
||||
providerFuture.addListener({
|
||||
val provider = runCatching { providerFuture.get() }.getOrNull() ?: return@addListener refuse()
|
||||
val previewUseCase = Preview.Builder().build().also { it.setSurfaceProvider(preview.surfaceProvider) }
|
||||
val analysis = ImageAnalysis.Builder()
|
||||
// Only the newest frame matters: a stale one describes where the
|
||||
// camera was, and a code that has already left the viewfinder
|
||||
// must not win over one that is in it now.
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.build()
|
||||
.also { it.setAnalyzer(executor, ::analyse) }
|
||||
runCatching {
|
||||
provider.unbindAll()
|
||||
provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, previewUseCase, analysis)
|
||||
}.onFailure { refuse() }
|
||||
}, ContextCompat.getMainExecutor(this))
|
||||
}
|
||||
|
||||
private fun analyse(image: ImageProxy) {
|
||||
try {
|
||||
if (settled) return
|
||||
val text = Qr.decode(image) ?: return
|
||||
if (settled) return
|
||||
settled = true
|
||||
setResult(RESULT_OK, Intent().putExtra(EXTRA_TEXT, text))
|
||||
// Finishing from the analysis thread is the whole reason `settled`
|
||||
// exists; the activity teardown has to happen on the main one.
|
||||
runOnUiThread { finish() }
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
executor.shutdown()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_TEXT = "text"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The mark, drawn rather than shipped as a bitmap: one R in the app's own ink
|
||||
on the palette's ground, which scales to every launcher's mask without a
|
||||
density bucket per size. The hole in the R is the glyph's own counter, cut
|
||||
with evenOdd rather than painted over. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#F4F1EA"
|
||||
android:fillType="evenOdd"
|
||||
android:pathData="M39,30 L39,78 L47,78 L47,60 L54.5,60 L65,78 L74.5,78 L62.5,58 C68.6,55.8 72.6,50.6 72.6,43.6 C72.6,35.4 66.8,30 57.6,30 Z M47,37 L56.4,37 C61.2,37 64.4,39.4 64.4,43.8 C64.4,48.2 61.2,50.9 56.4,50.9 L47,50.9 Z" />
|
||||
<path
|
||||
android:fillColor="#A6680C"
|
||||
android:pathData="M62,66 L74,66 L74,78 L62,78 Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The status-bar glyph, not the launcher icon: Android renders a notification
|
||||
icon as a mask, so anything that is not a solid silhouette on transparency
|
||||
comes out as a grey blob. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:tint="#FFFFFF">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M3,4h18v2H3zM3,9h18v2H3zM3,14h12v2H3zM3,19h12v2H3zM17.5,13.2l1.6,2.6 1.6,-2.6h2.3l-2.8,4.3V21h-2.2v-3.5L15.2,13.2z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
The screen between the tap and the page.
|
||||
|
||||
It exists for a reason that is not cosmetic: the kernel has to be unpacked and
|
||||
started before there is a page to show, and on a cold start that is about a
|
||||
second. A blank window for a second reads as a broken app; a line of text that
|
||||
says what is happening does not.
|
||||
|
||||
The progress bar is indeterminate and driven by nothing: the WebView's own
|
||||
progress is mirrored onto it while the page loads, and before that it simply
|
||||
turns, which is the honest description of "we do not know how long".
|
||||
-->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/page"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:paddingStart="32dp"
|
||||
android:paddingEnd="32dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/splash_wordmark"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/app_name"
|
||||
android:textColor="#8A857B"
|
||||
android:textSize="22sp"
|
||||
android:letterSpacing="0.08"
|
||||
android:fontFamily="sans-serif-medium" />
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/splash_bar"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:layout_width="132dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="26dp"
|
||||
android:indeterminate="true" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/splash_text"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="18dp"
|
||||
android:gravity="center"
|
||||
android:text="@string/splash_connecting"
|
||||
android:textColor="#8A857B"
|
||||
android:textSize="13sp"
|
||||
android:lineSpacingMultiplier="1.5" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/splash_retry"
|
||||
style="?android:attr/borderlessButtonStyle"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:minHeight="44dp"
|
||||
android:text="@string/splash_retry"
|
||||
android:textColor="#A6680C"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The adaptive launcher icon.
|
||||
|
||||
minSdk is 26, which is the release that introduced adaptive icons, so this
|
||||
is the only launcher asset the app needs: there is no device running it
|
||||
that would ask for a bitmap fallback. -->
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background" />
|
||||
<!-- The safe zone is the middle 66dp of 108dp; the glyph is drawn inside it
|
||||
so no launcher's mask can clip it. -->
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Reasonix</string>
|
||||
|
||||
<string name="channel_kernel">Kernel running</string>
|
||||
<string name="channel_kernel_desc">Shown while the Reasonix kernel runs in the background. Can be muted on its own in system settings.</string>
|
||||
|
||||
<string name="notify_running_title">Reasonix is running</string>
|
||||
<string name="notify_running_body">A task is still going. Switch back to see it.</string>
|
||||
<string name="notify_failed_title">Reasonix could not start</string>
|
||||
|
||||
<string name="err_kernel_unreachable">Could not reach the kernel. Reopen the app from your home screen.</string>
|
||||
|
||||
<string name="download_default_name">reasonix-download</string>
|
||||
<string name="download_saved">Saved: %1$s</string>
|
||||
<string name="download_failed">Save failed: %1$s</string>
|
||||
<string name="download_failed_status">Save failed: the server answered %1$d</string>
|
||||
|
||||
<string name="splash_connecting">Starting the kernel…</string>
|
||||
<string name="splash_retry">Retry</string>
|
||||
|
||||
<string name="scan_title">Scan the code on the computer</string>
|
||||
<string name="scan_hint">Point at the QR code in the computer\'s device panel to connect to it.</string>
|
||||
<string name="scan_button">Scan to connect</string>
|
||||
<string name="scan_denied">No camera permission, so scanning is unavailable. Allow it in system settings.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The dark palette's page colour. `DayNight` on the theme picks this up when
|
||||
the system is dark, which is what keeps the frame before the WebView from
|
||||
flashing light at someone using a dark phone at night. -->
|
||||
<resources>
|
||||
<color name="page">#0E1014</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The light palette's page colour, and only what the window needs before the
|
||||
WebView paints. The interface's own colours are `tokens.css`'s and are the
|
||||
page's business; these two exist so the first frame is the app's ground
|
||||
rather than the platform default white. -->
|
||||
<resources>
|
||||
<color name="page">#F4F1EA</color>
|
||||
<color name="boot">#07080C</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The launcher ground: the interface's dark page colour. It is the same in
|
||||
both themes because a launcher icon is not themed by the app. -->
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#14161C</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Every string the shell itself shows. The interface's own text belongs to
|
||||
the page and lives in its i18n bundle; these are only the few lines that
|
||||
exist before it, or when it cannot load. -->
|
||||
<resources>
|
||||
<string name="app_name">Reasonix</string>
|
||||
|
||||
<string name="channel_kernel">内核运行中</string>
|
||||
<string name="channel_kernel_desc">Reasonix 内核在后台运行时显示,可在系统设置中单独关闭。</string>
|
||||
|
||||
<string name="notify_running_title">Reasonix 正在运行</string>
|
||||
<string name="notify_running_body">任务继续进行,切回应用即可查看。</string>
|
||||
<string name="notify_failed_title">Reasonix 无法启动</string>
|
||||
|
||||
<string name="err_kernel_unreachable">连接内核失败。请返回桌面重新打开应用。</string>
|
||||
|
||||
<string name="download_default_name">reasonix-download</string>
|
||||
<string name="download_saved">已保存:%1$s</string>
|
||||
<string name="download_failed">保存失败:%1$s</string>
|
||||
<string name="download_failed_status">保存失败:服务器返回 %1$d</string>
|
||||
|
||||
<string name="splash_connecting">正在启动内核…</string>
|
||||
<string name="splash_retry">重试</string>
|
||||
|
||||
<string name="wsperm_title">需要「所有文件访问」权限</string>
|
||||
<string name="wsperm_body">要打开手机上的文件夹作为工作区,需要先允许本应用访问所有文件。点「去设置」,在列表里打开 Reasonix 的开关,然后返回这里。</string>
|
||||
<string name="wsperm_go">去设置</string>
|
||||
<string name="wsperm_later">以后再说</string>
|
||||
|
||||
<string name="scan_title">扫描电脑上的二维码</string>
|
||||
<string name="scan_hint">对准电脑上「设备访问」里的二维码,识别后即可连接这台电脑。</string>
|
||||
<string name="scan_button">扫码连接电脑</string>
|
||||
<string name="scan_denied">没有相机权限,无法扫码。请在系统设置里允许。</string>
|
||||
<string name="share_title">分享文件</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The shell's own furniture: a window background matching the page's light
|
||||
palette before the WebView paints, and a transparent system bar so the
|
||||
page's own safe-area padding is what the notch meets. The page themes
|
||||
itself; this exists only so the first frame is not a white flash. -->
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<style name="Theme.Reasonix" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<item name="android:windowBackground">@color/page</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<!-- The page draws its own edge-to-edge layout and pads itself with the
|
||||
safe-area insets from mobile.css. Laying the window out edge to edge
|
||||
while leaving the bars transparent is what makes those insets real
|
||||
numbers instead of zero. -->
|
||||
<item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="p">shortEdges</item>
|
||||
<item name="android:enforceStatusBarContrast" tools:targetApi="q">false</item>
|
||||
<item name="android:enforceNavigationBarContrast" tools:targetApi="q">false</item>
|
||||
</style>
|
||||
|
||||
<!-- The camera. A black ground because the preview has not drawn yet and a
|
||||
light window behind a dark viewfinder is a flash in the dark; the bars
|
||||
stay transparent so the preview reaches the edges, which is what makes
|
||||
a code near the top of the screen scannable. -->
|
||||
<style name="Theme.Reasonix.Scan" parent="Theme.Reasonix">
|
||||
<item name="android:windowBackground">@android:color/black</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Backups are off, and this file says why rather than leaving it implicit.
|
||||
|
||||
A Reasonix home holds provider keys, an account token and every session
|
||||
transcript. Android's auto-backup would copy all of it to the person's cloud
|
||||
drive and, on a device-to-device transfer, to a new phone — which is a
|
||||
credential leaving the device by a route nobody chose. `allowBackup="false"`
|
||||
in the manifest turns that off; these two stanzas are the belt to its braces,
|
||||
excluding everything explicitly so that a later change to `allowBackup` cannot
|
||||
quietly start copying credentials.
|
||||
|
||||
What a person wants to move between phones, the kernel already moves: its own
|
||||
export writes a file the person hands to the system's picker.
|
||||
-->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
<exclude domain="external" />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
<exclude domain="external" />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Cleartext HTTP is permitted, and the platform has no way to permit less.
|
||||
|
||||
Two kinds of page load over plain HTTP: the kernel's own page on
|
||||
`127.0.0.1:<port>`, and the same page served by a paired computer on whatever
|
||||
address its router handed out. The port is chosen when the kernel starts and
|
||||
the LAN address when a code is scanned, so neither can be written here — and a
|
||||
`domain-config` matches literals and domains, never a subnet.
|
||||
|
||||
So the boundary is not this file. `MainActivity` decides which cleartext origin
|
||||
may become the window: `shouldOverrideUrlLoading` sends every http(s) origin
|
||||
that is not the kernel's or the one just paired out to the browser, and the
|
||||
native bridge answers only those two. A plaintext page on the LAN therefore
|
||||
cannot become the document holding the bridge, which is what the reviewer's
|
||||
"deliberate path for LAN pairing" asks for.
|
||||
|
||||
HTTPS is untouched: nothing here downgrades a request, and `trust-anchors`
|
||||
keeps the system roots for every TLS connection that is made.
|
||||
-->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="true">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,15 @@
|
||||
// The build itself lives in app/build.gradle; this file declares the plugin
|
||||
// versions once so the app module can be read on its own.
|
||||
//
|
||||
// AGP 8.11.1 is the pairing for the Gradle 8.14 toolchain this machine has:
|
||||
// AGP 8.7 and older refuse a Gradle that new, and AGP 8.13+ wants a Gradle this
|
||||
// one does not have. Both numbers are pinned rather than ranged, because a
|
||||
// build that silently moved either one would be a different build.
|
||||
plugins {
|
||||
id "com.android.application" version "8.11.1" apply false
|
||||
id "org.jetbrains.kotlin.android" version "2.1.20" apply false
|
||||
}
|
||||
|
||||
tasks.register("clean", Delete) {
|
||||
delete rootProject.layout.buildDirectory
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# AndroidX is the only copy of the support libraries this project uses; the
|
||||
# non-transitive R class keeps the app's own resources from aliasing library
|
||||
# ones, which is what makes `R.string.*` unambiguous here.
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
|
||||
# The daemon is what keeps a second `gradle assembleDebug` from re-reading the
|
||||
# whole SDK, and the heap is sized for the R8 pass over the WebView and the
|
||||
# packaged page rather than for this handful of Kotlin files.
|
||||
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
|
||||
org.gradle.daemon=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
|
||||
kotlin.code.style=official
|
||||
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
@@ -0,0 +1,12 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
# Pinning the distribution's checksum is what makes the download verifiable: a
|
||||
# mirror that served a different zip would fail here instead of being unpacked
|
||||
# and run. The value is Gradle's own, from
|
||||
# https://services.gradle.org/distributions/gradle-8.14.3-bin.zip.sha256
|
||||
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Build the Reasonix kernel for Android and place it where the APK packager
|
||||
# expects a native library.
|
||||
#
|
||||
# Why a shell script and not a Gradle task: the kernel is a Go module that lives
|
||||
# outside this Gradle build, with its own toolchain version pinned in go.mod. A
|
||||
# Gradle task that invoked `go build` would make the Android build depend on a Go
|
||||
# toolchain being configured for it, and would rebuild a 21MB binary on every
|
||||
# `assembleDebug` even when nothing in the kernel changed. This runs when you
|
||||
# mean it to, and the APK task only checks that the result is there.
|
||||
#
|
||||
# Output: app/src/main/jniLibs/arm64-v8a/libreasonix.so
|
||||
# The name is not cosmetic. Android extracts files under `jniLibs/` to
|
||||
# `nativeLibraryDir` and permits execution *there*; a binary shipped in
|
||||
# `assets/` would have to be copied to app storage and chmod'd, which fails on
|
||||
# a device whose data partition is mounted noexec. `lib*.so` is the shape the
|
||||
# packager recognises as a native library, so the kernel wears it.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
android="$here/.."
|
||||
upstream="$android/.."
|
||||
out="$android/app/src/main/jniLibs/arm64-v8a/libreasonix.so"
|
||||
|
||||
if [ ! -d "$upstream" ]; then
|
||||
echo "kernel source not found: $upstream" >&2
|
||||
echo "run this from a checkout: the parent of android/ must be the kernel source." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# GOOS=android needs nothing else: the kernel is CGO-free, which is what makes a
|
||||
# single static binary possible in the first place. `-s -w` drops the symbol and
|
||||
# DWARF tables — about a third of the file — and nothing on a phone reads them.
|
||||
export GOOS=android
|
||||
export GOARCH=arm64
|
||||
export CGO_ENABLED=0
|
||||
|
||||
# The app version, read from the module's own build.gradle so the two cannot
|
||||
# drift. The official build stamps these through `-X` (see upstream's Makefile);
|
||||
# without them the kernel reports `version=dev revision=unknown`, which a phone
|
||||
# then shows next to the documentation it was built with and makes a bug report
|
||||
# from that build impossible to place. There is no `.git` here, so the revision
|
||||
# names the package the corpus shipped in rather than a commit hash — the honest
|
||||
# answer when there is no commit to name.
|
||||
app_gradle="$android/app/build.gradle"
|
||||
version_field() {
|
||||
sed -n "s/^def $1 *= *\([0-9]*\).*/\1/p" "$app_gradle" | head -n1
|
||||
}
|
||||
app_version="$(version_field versionMajor).$(version_field versionMinor).$(version_field versionPatch)"
|
||||
build_time_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
ldflags="-s -w"
|
||||
ldflags="$ldflags -X main.version=v$app_version"
|
||||
ldflags="$ldflags -X main.buildTimeUTC=$build_time_utc"
|
||||
ldflags="$ldflags -X reasonix/internal/tools/productdocs.linkedVersion=v$app_version"
|
||||
ldflags="$ldflags -X reasonix/internal/tools/productdocs.linkedRevision=apk-v$app_version"
|
||||
|
||||
echo "building the kernel (android/arm64, v$app_version) ..."
|
||||
mkdir -p "$(dirname "$out")"
|
||||
cd "$upstream"
|
||||
go build -trimpath -ldflags="$ldflags" -o "$out" ./cmd/reasonix
|
||||
|
||||
size=$(wc -c < "$out")
|
||||
echo "kernel ready: $out ($((size / 1024 / 1024)) MiB)"
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# One command from a clean checkout to an installable APK.
|
||||
#
|
||||
# The order matters and is the whole content of this script: the kernel and the
|
||||
# page are inputs to packaging, not build steps inside it, so they are produced
|
||||
# first and the Gradle task only assembles what is already there. Running
|
||||
# `gradle assembleRelease` directly on a fresh checkout fails on purpose (see
|
||||
# `requireBuildInputs` in app/build.gradle) rather than producing an APK with no
|
||||
# kernel in it.
|
||||
#
|
||||
# Usage: ./scripts/build.sh [debug|release] (default: release)
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
android="$here/.."
|
||||
variant="${1:-release}"
|
||||
|
||||
case "$variant" in
|
||||
debug|release) ;;
|
||||
*) echo "usage: $0 [debug|release]" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
"$here/build-kernel.sh"
|
||||
"$here/sync-page.sh"
|
||||
|
||||
cd "$android"
|
||||
|
||||
# The wrapper is committed, jar and all, and it is the only thing that runs the
|
||||
# build. Generating one here would tie the dependency versions to whichever
|
||||
# `gradle` happened to be on PATH, which is the opposite of a pinned build.
|
||||
if [ ! -f gradlew ]; then
|
||||
echo "gradlew is missing: this repository commits the Gradle wrapper, so the checkout is incomplete" >&2
|
||||
echo "(a release build does not use `gradle` from PATH: that would tie dependency versions to the machine)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
task="assemble$([ "$variant" = release ] && echo Release || echo Debug)"
|
||||
echo "packaging the APK ($variant) ..."
|
||||
./gradlew "$task" --no-daemon
|
||||
|
||||
apk_dir="$android/app/build/outputs/apk/$variant"
|
||||
echo
|
||||
echo "done. Installable artifacts:"
|
||||
find "$apk_dir" -name '*.apk' -maxdepth 1 -print -exec ls -lh {} \;
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Install the built APK on a connected phone and show its log.
|
||||
#
|
||||
# `adb` comes from the Android SDK rather than this project, because the SDK is
|
||||
# already how the app is built. Point ANDROID_HOME at it, or have `adb` on PATH.
|
||||
#
|
||||
# Usage: ./scripts/run.sh [debug|release]
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
android="$here/.."
|
||||
variant="${1:-release}"
|
||||
|
||||
adb="${ADB:-${ANDROID_HOME:-$HOME/AndroidSDK}/platform-tools/adb}"
|
||||
if ! command -v "$adb" >/dev/null 2>&1; then
|
||||
adb="adb"
|
||||
fi
|
||||
|
||||
apk_dir="$android/app/build/outputs/apk/$variant"
|
||||
apk=$(find "$apk_dir" -name '*.apk' -maxdepth 1 2>/dev/null | head -n1)
|
||||
if [ -z "$apk" ]; then
|
||||
echo "no $variant APK found; run ./scripts/build.sh $variant first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "installing $apk ..."
|
||||
"$adb" install -r "$apk"
|
||||
|
||||
# The device count is checked before the app is started so an emulator-less
|
||||
# machine gets "no devices" rather than a launch failure that reads like a bug.
|
||||
if [ "$("$adb" devices | grep -c 'device$')" -eq 0 ]; then
|
||||
echo "no device attached; skipping the launch." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
package="io.reasonix.mobile.app"
|
||||
[ "$variant" = debug ] && package="io.reasonix.mobile.app.debug"
|
||||
"$adb" shell monkey -p "$package" -c android.intent.category.LAUNCHER 1 >/dev/null
|
||||
|
||||
echo
|
||||
echo "following the log (Ctrl-C to stop) ..."
|
||||
"$adb" logcat -v color "ReasonixKernel:V" "AndroidRuntime:E" "*:S"
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Build the interface and copy it where the APK will carry it.
|
||||
#
|
||||
# The page that ships is the same build the desktop Studio serves — that is the
|
||||
# whole reason the mobile layout lives in `desktop/frontend-next` rather than in
|
||||
# an Android project's own web root. Nothing is edited on the way through: the
|
||||
# only thing this script does that `pnpm build` does not is copy `dist/` into the
|
||||
# app's assets.
|
||||
#
|
||||
# Output: app/src/main/assets/page/
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
android="$here/.."
|
||||
frontend="$android/../desktop/frontend-next"
|
||||
dest="$android/app/src/main/assets/page"
|
||||
|
||||
if [ ! -d "$frontend" ]; then
|
||||
echo "frontend project not found: $frontend" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd "$frontend"
|
||||
|
||||
# pnpm is the package manager the lockfile is written for; npm would resolve a
|
||||
# different tree than the one that was tested.
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "pnpm 10 is required: npm install -g pnpm@10" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -d node_modules ]; then
|
||||
echo "installing frontend dependencies ..."
|
||||
pnpm install --frozen-lockfile
|
||||
fi
|
||||
|
||||
echo "building the frontend ..."
|
||||
pnpm build
|
||||
|
||||
rm -rf "$dest"
|
||||
mkdir -p "$dest"
|
||||
cp -R dist/. "$dest/"
|
||||
|
||||
if [ ! -f "$dest/index.html" ]; then
|
||||
echo "the build produced no index.html; the frontend build probably failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
count=$(find "$dest" -type f | wc -l)
|
||||
size=$(du -sk "$dest" | cut -f1)
|
||||
echo "page ready: $dest ($count files, $((size / 1024)) MiB)"
|
||||
|
||||
# MIT requires the copyright notice and the licence text to travel with a binary
|
||||
# distribution, so the APK carries it. Generated from the repository's own
|
||||
# `LICENSE` rather than committed a second time: a checked-in copy is one more
|
||||
# thing that drifts when the root file is updated.
|
||||
root_license="$android/../LICENSE"
|
||||
if [ ! -f "$root_license" ]; then
|
||||
echo "LICENSE not found: $root_license" >&2
|
||||
exit 1
|
||||
fi
|
||||
cp "$root_license" "$android/app/src/main/assets/LICENSE"
|
||||
echo "licence: app/src/main/assets/LICENSE (copied from the repository's LICENSE)"
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Reproduce what `Kernel.kt` does, on this machine, against the page that is
|
||||
# actually packaged into the APK.
|
||||
#
|
||||
# This is the closest thing to an end-to-end test that runs without a phone: the
|
||||
# launch flags, the token file, the port file and the `--page` directory are the
|
||||
# same ones the Kotlin shell passes, and the page is read out of
|
||||
# `app/src/main/assets/page` rather than the frontend's own `dist/`. If this
|
||||
# serves a working interface, the only untested part is Android itself.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
android="$here/.."
|
||||
page="$android/app/src/main/assets/page"
|
||||
kernel="${KERNEL_BIN:-$android/../reasonix-verify.exe}"
|
||||
|
||||
work="${VERIFY_DIR:-/tmp/reasonix-verify}"
|
||||
rm -rf "$work"
|
||||
mkdir -p "$work/home/remote"
|
||||
|
||||
if [ ! -f "$kernel" ]; then
|
||||
echo "no runnable kernel; build one first:" >&2
|
||||
echo " (cd .. && go build -o reasonix-verify.exe ./cmd/reasonix)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$page/index.html" ]; then
|
||||
echo "no packaged page: $page/index.html" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 32 random bytes as hex — the same shape `Kernel.mintToken` writes.
|
||||
token=$(od -An -tx1 -N32 /dev/urandom | tr -d ' \n')
|
||||
printf '%s\n' "$token" > "$work/home/remote/launch.token"
|
||||
|
||||
export REASONIX_HOME="$work/home"
|
||||
export HOME="$work/home"
|
||||
export TMPDIR="$work"
|
||||
|
||||
echo "kernel: $kernel"
|
||||
echo "page: $page"
|
||||
echo "token: ${token:0:8}... (${#token} chars)"
|
||||
|
||||
"$kernel" serve \
|
||||
--addr 127.0.0.1:0 \
|
||||
--auth token \
|
||||
--token-file "$work/home/remote/launch.token" \
|
||||
--port-file "$work/home/remote/serve.port" \
|
||||
--pid-file "$work/home/remote/serve.pid" \
|
||||
--no-open \
|
||||
-page "$page" \
|
||||
> "$work/kernel.log" 2>&1 &
|
||||
echo $! > "$work/kernel.pid"
|
||||
|
||||
# Wait for the port file the kernel writes after binding, which is exactly the
|
||||
# wait `Kernel.awaitPort` performs.
|
||||
for _ in $(seq 1 150); do
|
||||
if [ -s "$work/home/remote/serve.port" ]; then break; fi
|
||||
if ! kill -0 "$(cat "$work/kernel.pid")" 2>/dev/null; then
|
||||
echo "the kernel exited; log:" >&2
|
||||
cat "$work/kernel.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.2
|
||||
done
|
||||
|
||||
if [ ! -s "$work/home/remote/serve.port" ]; then
|
||||
echo "the kernel reported no listening address; log:" >&2
|
||||
cat "$work/kernel.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
port=$(cat "$work/home/remote/serve.port")
|
||||
echo "listening on: $port"
|
||||
|
||||
# The two things the WebView will do: fetch the page, and exist on the origin.
|
||||
probe=$(curl -s -o /dev/null -w '%{http_code}' "http://$port/")
|
||||
echo "GET / -> $probe"
|
||||
if [ "$probe" != "200" ]; then
|
||||
echo "the page did not answer; log:" >&2
|
||||
cat "$work/kernel.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cat > "$work/entry.txt" <<EOF
|
||||
origin=http://$port
|
||||
entry=http://$port/#token=$token
|
||||
token=$token
|
||||
EOF
|
||||
|
||||
echo "entry written: $work/entry.txt"
|
||||
echo "kernel log (first 10 lines):"
|
||||
head -10 "$work/kernel.log"
|
||||
@@ -0,0 +1,31 @@
|
||||
// Reasonix Mobile — the Android shell around the Reasonix kernel.
|
||||
//
|
||||
// The shell is deliberately thin: it unpacks the kernel and the built page that
|
||||
// ship inside the APK, starts `reasonix serve` on a loopback port, and points a
|
||||
// WebView at it. Everything the person sees and does is the same page the
|
||||
// desktop Studio and `reasonix web` serve, because it is literally the same
|
||||
// build of `desktop/frontend-next` — which is what keeps one interface honest
|
||||
// across the three surfaces, and why the page is packaged rather than fetched.
|
||||
|
||||
pluginManagement {
|
||||
repositories {
|
||||
// The official repositories only. A mirror listed here would be an
|
||||
// unverified trust anchor for anything that ends up in a signed build:
|
||||
// the artifact it serves is whichever copy landed there. A machine that
|
||||
// needs a mirror belongs on a user-level init script, where the choice
|
||||
// stays with the person building rather than travelling with the source.
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "ReasonixMobile"
|
||||
include(":app")
|
||||
@@ -24,7 +24,7 @@ func validateAnswerIsolation(tasks []task) error {
|
||||
if t.answerRoot == "" {
|
||||
continue
|
||||
}
|
||||
if !sandbox.Available() {
|
||||
if !sandbox.ConfinesByDefault() {
|
||||
return fmt.Errorf("%s contains answer material, but this host has no OS read sandbox", t.answerRoot)
|
||||
}
|
||||
roots, err := answerReadRoots(t.answerRoot)
|
||||
|
||||
@@ -26,13 +26,13 @@ func TestMemoryBenchRequiresReadSandbox(t *testing.T) {
|
||||
}
|
||||
}
|
||||
err = validateAnswerIsolation(tasks)
|
||||
if sandbox.Available() && err != nil {
|
||||
if sandbox.ConfinesByDefault() && err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !sandbox.Available() && err == nil {
|
||||
if !sandbox.ConfinesByDefault() && err == nil {
|
||||
t.Fatal("MemoryBench accepted a host with no OS read sandbox")
|
||||
}
|
||||
if sandbox.Available() {
|
||||
if sandbox.ConfinesByDefault() {
|
||||
previous := benchStateBase
|
||||
benchStateBase = func() (string, error) { return filepath.Join(tasks[0].answerRoot, "cache"), nil }
|
||||
t.Cleanup(func() { benchStateBase = previous })
|
||||
@@ -43,7 +43,7 @@ func TestMemoryBenchRequiresReadSandbox(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMemoryBenchAnswerIsolationAtSandboxBoundary(t *testing.T) {
|
||||
if !sandbox.Available() {
|
||||
if !sandbox.ConfinesByDefault() {
|
||||
t.Skip("this host has no OS read sandbox")
|
||||
}
|
||||
const suite = "../../benchmarks/memorybench"
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"ime-live": "electron test/ime_live.js",
|
||||
"freeze-live": "electron test/freeze_live.js",
|
||||
"windowstate-live": "electron test/windowstate_live.js",
|
||||
"computer-live": "electron test/computer_live.js"
|
||||
"computer-live": "electron test/computer_live.js",
|
||||
"launcher-live": "node test/launcher_live.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "44.7.2",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use strict";
|
||||
const { handOver } = require("./launcher");
|
||||
|
||||
// The acts the kernel asks of the application, because only this process can do
|
||||
// them. relaunch and quit are a handover and arrive in that order, so arming
|
||||
@@ -11,6 +12,7 @@ function actHandler({ app, showWindow, log = () => {} }) {
|
||||
return (act) => {
|
||||
if (act === "show" || act === "relaunch" || act === "quit") log(`kernel act: ${act}`);
|
||||
if (act === "relaunch") {
|
||||
handOver();
|
||||
app.relaunch();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -62,11 +62,14 @@ async function startEmbedded(executable, contract, onStderr = () => {}, spawnDri
|
||||
if (child.exitCode !== null || child.signalCode !== null) throw new Error("Embedded CUA exited during startup");
|
||||
try {
|
||||
const current = await fs.lstat(socket);
|
||||
if (!current.isSocket() || (current.mode & 0o777) !== 0o600) throw new Error("Invalid private CUA socket");
|
||||
const reply = await metadata(socket);
|
||||
if (!accepts(reply, child.pid, contract)) throw new Error("Embedded CUA identity/version mismatch");
|
||||
identity = current;
|
||||
return;
|
||||
if (!current.isSocket()) throw new Error("Invalid private CUA socket");
|
||||
// The driver binds before chmod: existence alone does not establish readiness.
|
||||
if ((current.mode & 0o777) === 0o600) {
|
||||
const reply = await metadata(socket);
|
||||
if (!accepts(reply, child.pid, contract)) throw new Error("Embedded CUA identity/version mismatch");
|
||||
identity = current;
|
||||
return;
|
||||
}
|
||||
} catch (error) { if (!["ENOENT", "ECONNREFUSED"].includes(error.code)) throw error; }
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
|
||||
// A development shell belongs to the process that launched it: `pnpm start`,
|
||||
// a live test, an agent's background job. Killed outright, that launcher takes
|
||||
// nothing with it, so the shell has to notice it is gone and leave on its own.
|
||||
// Packaged shells, and shells a relaunch handed over, belong to nobody.
|
||||
const HANDED_OVER = "REASONIX_STUDIO_HANDED_OVER";
|
||||
const EVERY_MS = 1000;
|
||||
|
||||
// handOver marks the next instance as nobody's. The launcher waits on this
|
||||
// process and exits with it, so a relaunched shell would otherwise read its own
|
||||
// start as the launcher's death.
|
||||
function handOver(env = process.env) {
|
||||
env[HANDED_OVER] = "1";
|
||||
}
|
||||
|
||||
function alive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err?.code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
// POSIX gives an orphan a new parent, which settles it. Windows leaves the dead
|
||||
// pid as the parent, so there it is probed instead, and a pid already reused
|
||||
// leaves the shell running as it would without this watch.
|
||||
function watchLauncher({ packaged, env = process.env, onLost, parent = () => process.ppid, alive: isAlive = alive, everyMs = EVERY_MS }) {
|
||||
const handedOver = env[HANDED_OVER] === "1";
|
||||
delete env[HANDED_OVER];
|
||||
const launcher = parent();
|
||||
if (packaged || handedOver || launcher <= 1) return { dispose() {} };
|
||||
const timer = setInterval(() => {
|
||||
if (parent() === launcher && isAlive(launcher)) return;
|
||||
clearInterval(timer);
|
||||
onLost();
|
||||
}, everyMs);
|
||||
timer.unref?.();
|
||||
return { dispose: () => clearInterval(timer) };
|
||||
}
|
||||
|
||||
// consoleEcho writes to a console the launcher may already have closed. An
|
||||
// EPIPE nobody handles opens Electron's modal error box, which stops the main
|
||||
// process; shell.log and host.log keep every line, so a failed or backed-up
|
||||
// console is dropped rather than retried.
|
||||
function consoleEcho(stream) {
|
||||
let failed = false;
|
||||
let blocked = false;
|
||||
stream.on("error", () => {
|
||||
failed = true;
|
||||
});
|
||||
stream.on("drain", () => {
|
||||
blocked = false;
|
||||
});
|
||||
return (chunk) => {
|
||||
if (failed || blocked || stream.destroyed || stream.writableEnded) return;
|
||||
try {
|
||||
blocked = !stream.write(chunk);
|
||||
} catch {
|
||||
failed = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { watchLauncher, handOver, consoleEcho };
|
||||
@@ -13,6 +13,7 @@ const { showStarting } = require("./starting");
|
||||
const { StudioHost } = require("./hostclient");
|
||||
const { installTray } = require("./tray");
|
||||
const { instanceID, profileFor } = require("./instance");
|
||||
const { watchLauncher, consoleEcho } = require("./launcher");
|
||||
const { installApplicationMenu, installContextMenu } = require("./menu");
|
||||
const { uiLanguage } = require("./uilang");
|
||||
const { installFullScreenKey } = require("./fullscreen");
|
||||
@@ -74,6 +75,7 @@ const computerDriver = layout.computerDriver(where);
|
||||
const pageDir = layout.pageDir(where);
|
||||
|
||||
const acts = actHandler({ app, showWindow: () => showWindow(), log: (line) => logs?.shell.line(line) });
|
||||
const toConsole = consoleEcho(process.stderr);
|
||||
let kernel = null;
|
||||
let cua = null;
|
||||
let win = null;
|
||||
@@ -126,7 +128,7 @@ async function launchKernel(args) {
|
||||
},
|
||||
onStderr: (text) => {
|
||||
logs.host.raw(text);
|
||||
process.stderr.write(text);
|
||||
toConsole(text);
|
||||
},
|
||||
onExit: (code, signal) => {
|
||||
logs.shell.line(`host: exited code=${code} signal=${signal}${handshaken ? "" : " before its handshake"}`);
|
||||
@@ -141,6 +143,7 @@ async function launchKernel(args) {
|
||||
onAct: (act) => acts(act),
|
||||
});
|
||||
const current = kernel;
|
||||
logs.shell.line(`host: pid ${current.child.pid ?? "(none)"}`);
|
||||
current.child.on("error", (err) => logs.shell.line(`host: spawn failed: ${err.message}`));
|
||||
current.child.stderr.on("close", () => logs.host.flush());
|
||||
try {
|
||||
@@ -513,7 +516,7 @@ if (gpuLaunch.launchedOff) app.disableHardwareAcceleration();
|
||||
logs = openLogs(app.getPath("userData"));
|
||||
logs.shell.line(
|
||||
`shell: start version=${app.getVersion()} packaged=${app.isPackaged} platform=${process.platform}/${process.arch} ` +
|
||||
`instance=${identity || "(unknown)"} argv=${JSON.stringify(redactArgv(process.argv))}`,
|
||||
`instance=${identity || "(unknown)"} pid=${process.pid} argv=${JSON.stringify(redactArgv(process.argv))}`,
|
||||
);
|
||||
const primary = app.requestSingleInstanceLock();
|
||||
if (!primary) {
|
||||
@@ -524,6 +527,13 @@ if (!primary) {
|
||||
app.on("second-instance", showWindow);
|
||||
// macOS reopens an existing app through activation, without a second process.
|
||||
app.on("activate", showWindow);
|
||||
watchLauncher({
|
||||
packaged: app.isPackaged,
|
||||
onLost: () => {
|
||||
logs.shell.line("shell: launcher gone; quitting");
|
||||
app.quit();
|
||||
},
|
||||
});
|
||||
grants = stripPackageGrants(hostBinary, { ...where, execPath: process.execPath });
|
||||
if (grants?.stripped.length) {
|
||||
const note = `removed app-package grants that stop sandboxed processes loading: ${grants.stripped.join(", ")}`;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use strict";
|
||||
const { handOver } = require("./launcher");
|
||||
|
||||
const X11 = "--ozone-platform=x11";
|
||||
|
||||
@@ -33,6 +34,7 @@ function wantsX11(platform, env, args) {
|
||||
function relaunchForOzonePlatform(app, { platform, env, argv }) {
|
||||
const args = argv.slice(1);
|
||||
if (!wantsX11(platform, env, args)) return false;
|
||||
handOver(env);
|
||||
app.relaunch({ args: [X11, ...args] });
|
||||
app.exit(0);
|
||||
return true;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
const { BrowserWindow } = require("electron");
|
||||
|
||||
const TEXT = {
|
||||
en: ["Reasonix Studio is starting", "The first start after installing or rebooting can take a minute."],
|
||||
zh: ["Reasonix Studio 正在启动", "安装或重启电脑后的首次启动可能需要一分钟。"],
|
||||
en: ["Reasonix Studio is starting", "Waiting for the local service to be ready. This window will close automatically."],
|
||||
zh: ["Reasonix Studio 正在启动", "正在等待本地服务就绪,完成后此窗口会自动关闭。"],
|
||||
};
|
||||
|
||||
function startingPage(locale) {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
"use strict";
|
||||
const net = require("node:net");
|
||||
const fs = require("node:fs");
|
||||
const args = process.argv.slice(2);
|
||||
const socket = args[args.indexOf("--socket") + 1];
|
||||
// The socket must exist at 0600 from the first instant: a reader that looks between listen and a later chmod sees 0755.
|
||||
process.umask(0o177);
|
||||
const deferred = args.includes("--defer-permissions");
|
||||
process.umask(deferred ? 0o022 : 0o177);
|
||||
const server = net.createServer(peer => {
|
||||
if ((fs.statSync(socket).mode & 0o777) !== 0o600) process.exit(2);
|
||||
peer.on("data", () => peer.end(JSON.stringify({ ok: true, result: { pid: process.pid, embedded: true, host_bundle_id: "io.reasonix.studio", driver_version: "0.34.1", contract_version: "0.8.0", tools_list_schema_version: "1", capability_version: "1", mcp_protocol_version: "2025-06-18" } }) + "\n"));
|
||||
});
|
||||
server.listen(socket);
|
||||
process.on("message", message => {
|
||||
if (message === "secure") fs.chmodSync(socket, 0o600);
|
||||
});
|
||||
process.stdin.resume();
|
||||
process.stdin.on("end", () => server.close(() => process.exit(0)));
|
||||
@@ -0,0 +1,130 @@
|
||||
// Drives the real shell and kernel through the ways a development launch ends:
|
||||
// its launcher killed outright, before and after the handshake, its console
|
||||
// closed underneath it, and an ordinary stop. Each runs in a throwaway data home.
|
||||
// Run `pnpm build:host` first, then `pnpm launcher-live`.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const { hostBinary } = require("../src/layout.js");
|
||||
const host = hostBinary({ packaged: false, dirname: path.join(appDir, "src"), platform: process.platform, env: process.env });
|
||||
const cli = path.join(path.dirname(require.resolve("electron")), "cli.js");
|
||||
if (!existsSync(host)) throw new Error(`no kernel at ${host}; run pnpm build:host first`);
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const alive = (pid) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err.code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
async function until(predicate, what, ms) {
|
||||
const deadline = Date.now() + ms;
|
||||
while (Date.now() < deadline) {
|
||||
if (predicate()) return;
|
||||
await sleep(100);
|
||||
}
|
||||
throw new Error(what);
|
||||
}
|
||||
|
||||
// userData is <platform app data>/Reasonix Studio/<instance id>, and the id is
|
||||
// the kernel's answer for this data home.
|
||||
function profileDir(env) {
|
||||
const id = execFileSync(host, ["-instance-id"], { env, encoding: "utf8" }).trim();
|
||||
const base =
|
||||
process.platform === "darwin" ? path.join(os.homedir(), "Library", "Application Support")
|
||||
: process.platform === "win32" ? process.env.APPDATA
|
||||
: process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
||||
return path.join(base, "Reasonix Studio", id);
|
||||
}
|
||||
|
||||
async function scenario(name, { kernel = host, end }) {
|
||||
const home = mkdtempSync(path.join(os.tmpdir(), "reasonix-launcher-live-"));
|
||||
const page = path.join(home, "page");
|
||||
mkdirSync(page);
|
||||
writeFileSync(path.join(page, "index.html"), "<!doctype html><title>launcher live</title>");
|
||||
const env = { ...process.env, REASONIX_HOME: home, REASONIX_STATE_HOME: path.join(home, "state"), REASONIX_STUDIO_PAGE: page, REASONIX_STUDIO_HOST: kernel };
|
||||
const profile = profileDir(env);
|
||||
const shellLog = () => {
|
||||
try {
|
||||
return readFileSync(path.join(profile, "logs", "shell.log"), "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
const launcher = spawn(process.execPath, [cli, appDir], { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
launcher.stdout.resume();
|
||||
launcher.stderr.resume();
|
||||
const pids = [];
|
||||
try {
|
||||
await until(() => /host: pid \d+/.test(shellLog()), "the shell never started its kernel", 60000);
|
||||
const log = shellLog();
|
||||
pids.push(Number(/shell: start .* pid=(\d+)/.exec(log)[1]), Number(/host: pid (\d+)/.exec(log)[1]));
|
||||
await end({ launcher, shellLog });
|
||||
await until(() => pids.every((pid) => !alive(pid)), `${name}: the shell or its kernel outlived the launch`, 20000);
|
||||
assert.doesNotMatch(shellLog(), /uncaught/i);
|
||||
console.log(` ok ${name}`);
|
||||
} catch (err) {
|
||||
console.log(` FAIL ${name}: ${err.message}\n${shellLog().split("\n").slice(-10).join("\n")}`);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
launcher.kill("SIGKILL");
|
||||
for (const pid of pids) if (alive(pid)) process.kill(pid, "SIGKILL");
|
||||
await sleep(500);
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const handshaken = ({ shellLog }) => until(() => /host: handshake/.test(shellLog()), "no handshake", 60000);
|
||||
|
||||
await scenario("a launcher killed after the handshake takes the shell with it", {
|
||||
end: async (run) => {
|
||||
await handshaken(run);
|
||||
run.launcher.kill("SIGKILL");
|
||||
await until(() => /launcher gone/.test(run.shellLog()), "the shell never noticed its launcher was gone", 10000);
|
||||
},
|
||||
});
|
||||
|
||||
// A kernel that takes its time to handshake: the launch is still starting when
|
||||
// its launcher goes.
|
||||
if (process.platform !== "win32") {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "reasonix-slow-host-"));
|
||||
const slow = path.join(dir, "host.sh");
|
||||
writeFileSync(slow, `#!/bin/sh\nsleep 3\nexec ${JSON.stringify(host)} "$@"\n`, { mode: 0o755 });
|
||||
await scenario("a launcher killed before the handshake takes the starting shell with it", {
|
||||
kernel: slow,
|
||||
end: async (run) => {
|
||||
assert.doesNotMatch(run.shellLog(), /host: handshake/);
|
||||
run.launcher.kill("SIGKILL");
|
||||
},
|
||||
});
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
await scenario("a shell whose console was closed still stops when asked", {
|
||||
end: async (run) => {
|
||||
await handshaken(run);
|
||||
run.launcher.stdout.destroy();
|
||||
run.launcher.stderr.destroy();
|
||||
// The kernel logs a request every few seconds, and each one is echoed.
|
||||
await sleep(8000);
|
||||
run.launcher.kill("SIGTERM");
|
||||
},
|
||||
});
|
||||
|
||||
await scenario("a launcher asked to stop stops the shell", {
|
||||
end: async (run) => {
|
||||
await handshaken(run);
|
||||
run.launcher.kill("SIGTERM");
|
||||
},
|
||||
});
|
||||
@@ -1573,6 +1573,135 @@ test("a host that exits before its handshake is logged and shown, not swallowed"
|
||||
}
|
||||
});
|
||||
|
||||
test("a development shell leaves once the process that launched it is gone", () => {
|
||||
const { watchLauncher } = require("../src/launcher.js");
|
||||
mock.timers.enable({ apis: ["setInterval"] });
|
||||
try {
|
||||
// POSIX hands an orphan to another parent; Windows leaves the dead pid in place.
|
||||
for (const [why, end] of [["reparented", (s) => { s.ppid = 1; }], ["died in place", (s) => { s.alive = false; }]]) {
|
||||
const state = { ppid: 4242, alive: true };
|
||||
let lost = 0;
|
||||
watchLauncher({ packaged: false, env: {}, onLost: () => lost++, parent: () => state.ppid, alive: () => state.alive });
|
||||
mock.timers.tick(5000);
|
||||
assert.equal(lost, 0, `${why}: left while the launcher was still there`);
|
||||
end(state);
|
||||
mock.timers.tick(1000);
|
||||
assert.equal(lost, 1, `${why}: stayed after its launcher was gone`);
|
||||
mock.timers.tick(5000);
|
||||
assert.equal(lost, 1, `${why}: told more than once`);
|
||||
}
|
||||
|
||||
const state = { ppid: 4242 };
|
||||
let lost = 0;
|
||||
const watch = watchLauncher({ packaged: false, env: {}, onLost: () => lost++, parent: () => state.ppid, alive: () => true });
|
||||
watch.dispose();
|
||||
state.ppid = 1;
|
||||
mock.timers.tick(5000);
|
||||
assert.equal(lost, 0, "a disposed watch still acted");
|
||||
} finally {
|
||||
mock.timers.reset();
|
||||
}
|
||||
});
|
||||
|
||||
test("a packaged, handed-over or parentless shell belongs to no launcher", () => {
|
||||
const { watchLauncher, handOver } = require("../src/launcher.js");
|
||||
mock.timers.enable({ apis: ["setInterval"] });
|
||||
try {
|
||||
const handed = {};
|
||||
handOver(handed);
|
||||
for (const [why, options] of [
|
||||
["packaged", { packaged: true, env: {}, parent: () => 4242 }],
|
||||
["handed over by a relaunch", { packaged: false, env: handed, parent: () => 4242 }],
|
||||
["started by init", { packaged: false, env: {}, parent: () => 1 }],
|
||||
]) {
|
||||
let lost = 0;
|
||||
let ppid = options.parent();
|
||||
watchLauncher({ ...options, onLost: () => lost++, parent: () => ppid, alive: () => false });
|
||||
ppid = 7;
|
||||
mock.timers.tick(5000);
|
||||
assert.equal(lost, 0, why);
|
||||
}
|
||||
assert.deepEqual(handed, {}, "the hand-over mark reached this shell's own children");
|
||||
} finally {
|
||||
mock.timers.reset();
|
||||
}
|
||||
});
|
||||
|
||||
test("a relaunch hands the shell over before it asks for the restart", () => {
|
||||
const { actHandler } = require("../src/acts.js");
|
||||
const { relaunchForOzonePlatform } = require("../src/ozone.js");
|
||||
const key = "REASONIX_STUDIO_HANDED_OVER";
|
||||
const saved = process.env[key];
|
||||
delete process.env[key];
|
||||
try {
|
||||
const seen = [];
|
||||
actHandler({ app: { relaunch: () => seen.push(process.env[key]) }, showWindow: () => {} })("relaunch");
|
||||
assert.deepEqual(seen, ["1"]);
|
||||
} finally {
|
||||
if (saved === undefined) delete process.env[key];
|
||||
else process.env[key] = saved;
|
||||
}
|
||||
const env = { XDG_SESSION_TYPE: "wayland", DISPLAY: ":0" };
|
||||
const seen = [];
|
||||
relaunchForOzonePlatform({ relaunch: () => seen.push(env[key]), exit: () => {} }, { platform: "linux", env, argv: ["x"] });
|
||||
assert.deepEqual(seen, ["1"]);
|
||||
});
|
||||
|
||||
test("output for a console the launcher closed is dropped, never thrown", () => {
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { consoleEcho } = require("../src/launcher.js");
|
||||
const stream = Object.assign(new EventEmitter(), { written: [], full: false, broken: false });
|
||||
stream.write = (chunk) => {
|
||||
if (stream.broken) throw Object.assign(new Error("write EIO"), { code: "EIO" });
|
||||
stream.written.push(chunk);
|
||||
return !stream.full;
|
||||
};
|
||||
const echo = consoleEcho(stream);
|
||||
echo("a");
|
||||
stream.full = true;
|
||||
echo("b");
|
||||
echo("c");
|
||||
assert.deepEqual(stream.written, ["a", "b"], "a backed-up console kept queueing");
|
||||
stream.emit("drain");
|
||||
stream.full = false;
|
||||
echo("d");
|
||||
stream.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
|
||||
echo("e");
|
||||
assert.deepEqual(stream.written, ["a", "b", "d"], "a failed console was written to again");
|
||||
|
||||
const sync = Object.assign(new EventEmitter(), { broken: true, calls: 0 });
|
||||
sync.write = () => {
|
||||
sync.calls++;
|
||||
throw Object.assign(new Error("write EIO"), { code: "EIO" });
|
||||
};
|
||||
const echoSync = consoleEcho(sync);
|
||||
assert.doesNotThrow(() => echoSync("x"));
|
||||
echoSync("y");
|
||||
assert.equal(sync.calls, 1);
|
||||
});
|
||||
|
||||
test("a shell whose console pipe was closed keeps running", async () => {
|
||||
const { spawn } = require("node:child_process");
|
||||
const script = `
|
||||
const { consoleEcho } = require(${JSON.stringify(require.resolve("../src/launcher.js"))});
|
||||
const echo = consoleEcho(process.stderr);
|
||||
process.stdin.once("data", () => {
|
||||
let n = 0;
|
||||
const timer = setInterval(() => {
|
||||
echo("x".repeat(512) + "\\n");
|
||||
if (++n === 50) { clearInterval(timer); process.stdout.write("survived\\n"); }
|
||||
}, 2);
|
||||
});`;
|
||||
const child = spawn(process.execPath, ["-e", script], { stdio: ["pipe", "pipe", "pipe"] });
|
||||
child.stderr.destroy();
|
||||
let out = "";
|
||||
child.stdout.on("data", (chunk) => { out += chunk; });
|
||||
child.stdin.end("go\n");
|
||||
const code = await new Promise((resolve) => child.on("exit", resolve));
|
||||
assert.equal(code, 0);
|
||||
assert.equal(out, "survived\n");
|
||||
});
|
||||
|
||||
test("the launch credential cookie is put back when something removes it, and only then", async () => {
|
||||
const { keepCredential } = require("../src/credential.js");
|
||||
const { EventEmitter } = require("node:events");
|
||||
@@ -2516,6 +2645,109 @@ test("CUA embedded control stops the old service before admitting a fresh one",
|
||||
assert.equal(fs.existsSync(owned.abortSocket), false);
|
||||
});
|
||||
|
||||
test("CUA waits for socket permissions on initial launch and abort restart", { skip: process.platform === "win32" }, async (t) => {
|
||||
const { spawn } = require("node:child_process");
|
||||
const net = require("node:net");
|
||||
const promises = require("node:fs/promises");
|
||||
const { startEmbedded, metadata, stopProcess } = require("../src/cua");
|
||||
const fake = path.join(path.dirname(require("node:url").fileURLToPath(import.meta.url)), "cua-service-fixture.js");
|
||||
const children = [];
|
||||
const observed = new Set();
|
||||
const ready = new Set();
|
||||
let owned;
|
||||
t.after(async () => {
|
||||
await owned?.stop();
|
||||
for (const child of children) await stopProcess(child);
|
||||
});
|
||||
const lstat = promises.lstat;
|
||||
t.mock.method(promises, "lstat", async (...args) => {
|
||||
const current = await lstat(...args);
|
||||
if (path.basename(args[0]) === "driver.sock" && (current.mode & 0o777) !== 0o600) {
|
||||
const child = children.at(-1);
|
||||
if (!observed.has(child.pid)) {
|
||||
observed.add(child.pid);
|
||||
child.send("secure");
|
||||
}
|
||||
} else if (path.basename(args[0]) === "driver.sock") {
|
||||
ready.add(children.at(-1).pid);
|
||||
}
|
||||
return current;
|
||||
});
|
||||
const connect = net.createConnection;
|
||||
t.mock.method(net, "createConnection", (...args) => {
|
||||
if (path.basename(args[0]) === "driver.sock") assert.ok(ready.has(children.at(-1).pid), "metadata was requested before private permissions were observed");
|
||||
return connect(...args);
|
||||
});
|
||||
owned = await startEmbedded(process.execPath, cuaContract, () => {}, (_exe, args, options) => {
|
||||
const child = spawn(process.execPath, [fake, ...args, "--defer-permissions"], { ...options, stdio: [...options.stdio, "ipc"] });
|
||||
children.push(child);
|
||||
return child;
|
||||
});
|
||||
const before = await metadata(owned.socket);
|
||||
const reply = await new Promise((resolve, reject) => {
|
||||
const peer = net.createConnection(owned.abortSocket);
|
||||
let text = "";
|
||||
peer.once("error", reject);
|
||||
peer.on("connect", () => peer.write('{"op":"abort"}\n'));
|
||||
peer.on("data", bytes => { text += bytes; if (text.includes("\n")) { peer.destroy(); resolve(JSON.parse(text)); } });
|
||||
});
|
||||
assert.equal(reply.ok, true);
|
||||
const after = await metadata(owned.socket);
|
||||
assert.notEqual(after.result.pid, before.result.pid);
|
||||
assert.deepEqual([...observed], [before.result.pid, after.result.pid]);
|
||||
assert.equal((await lstat(owned.socket)).mode & 0o777, 0o600);
|
||||
assert.throws(() => process.kill(before.result.pid, 0));
|
||||
});
|
||||
|
||||
test("CUA permission readiness remains bounded without connecting to a non-private socket", { skip: process.platform === "win32" }, async (t) => {
|
||||
const { spawn } = require("node:child_process");
|
||||
const promises = require("node:fs/promises");
|
||||
const { startEmbedded, stopProcess } = require("../src/cua");
|
||||
const fake = path.join(path.dirname(require("node:url").fileURLToPath(import.meta.url)), "cua-service-fixture.js");
|
||||
let child;
|
||||
t.after(async () => { if (child) await stopProcess(child); });
|
||||
const now = Date.now();
|
||||
let expired = false;
|
||||
t.mock.method(Date, "now", () => now + (expired ? 10001 : 0));
|
||||
const lstat = promises.lstat;
|
||||
t.mock.method(promises, "lstat", async (...args) => {
|
||||
const current = await lstat(...args);
|
||||
if (path.basename(args[0]) === "driver.sock" && (current.mode & 0o777) !== 0o600) expired = true;
|
||||
return current;
|
||||
});
|
||||
await assert.rejects(startEmbedded(process.execPath, cuaContract, () => {}, (_exe, args, options) => {
|
||||
child = spawn(process.execPath, [fake, ...args, "--defer-permissions"], options);
|
||||
return child;
|
||||
}), /Embedded CUA failed readiness/);
|
||||
assert.equal(expired, true);
|
||||
assert.equal(child.exitCode, 0);
|
||||
});
|
||||
|
||||
for (const kind of ["file", "symlink"]) {
|
||||
test(`CUA readiness rejects a ${kind} instead of waiting for permissions`, { skip: process.platform === "win32" }, async (t) => {
|
||||
const { spawn } = require("node:child_process");
|
||||
const { startEmbedded, stopProcess } = require("../src/cua");
|
||||
let child, socket;
|
||||
t.after(async () => {
|
||||
if (child) await stopProcess(child);
|
||||
if (socket) fs.rmSync(path.dirname(socket), { recursive: true, force: true });
|
||||
});
|
||||
const script = `
|
||||
const fs = require("node:fs");
|
||||
const socket = process.argv[1];
|
||||
if (process.argv[2] === "symlink") fs.symlinkSync("missing-target", socket);
|
||||
else fs.writeFileSync(socket, "", { mode: 0o600 });
|
||||
process.stdin.resume();
|
||||
process.stdin.on("end", () => process.exit(0));`;
|
||||
await assert.rejects(startEmbedded(process.execPath, cuaContract, () => {}, (_exe, args, options) => {
|
||||
socket = args[args.indexOf("--socket") + 1];
|
||||
child = spawn(process.execPath, ["-e", script, socket, kind], options);
|
||||
return child;
|
||||
}), /Invalid private CUA socket/);
|
||||
assert.equal(child.exitCode, 0);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
test("CUA repeated quit waits for owned driver cleanup", async () => {
|
||||
const { createQuitGate } = require("../src/cua");
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// The ask-on-external-text switch has its own settings block under tools, starts off, turns on with one click, and says what it leaves out.
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const BASE = process.env.PERF_URL ?? "http://localhost:4399/perf.html";
|
||||
const shotDir = process.env.SHOTS;
|
||||
const fails = [];
|
||||
const check = (name, ok, detail = "") => {
|
||||
console.log(`${ok ? " ok" : "FAIL"} ${name}${detail ? " — " + detail : ""}`);
|
||||
if (!ok) fails.push(name);
|
||||
};
|
||||
|
||||
const browser = await chromium.launch();
|
||||
for (const scheme of ["light", "dark"]) {
|
||||
for (const [pref, label] of [["zh", "询问来自外部的文字"], ["en", "Ask about text from outside"]]) {
|
||||
for (const width of [1280, 420]) {
|
||||
const tag = `${scheme} ${pref} ${width}px`;
|
||||
const page = await browser.newPage({ viewport: { width, height: 1000 }, locale: pref === "zh" ? "zh-CN" : "en-US", colorScheme: scheme, reducedMotion: "reduce" });
|
||||
page.on("pageerror", (e) => fails.push("页面异常: " + e.message));
|
||||
await page.goto(`${BASE}?pref=${pref}&turns=2`, { waitUntil: "networkidle" });
|
||||
await page.waitForSelector(".app");
|
||||
await page.evaluate(() => document.querySelector('[data-action="chrome.settings"]')?.click());
|
||||
await page.waitForSelector(".prefs-nav button");
|
||||
await page.evaluate(() => { const b = [...document.querySelectorAll(".prefs-nav button")].find((x) => /工具与权限|Tools/.test(x.textContent)); b?.click(); });
|
||||
const sw = page.getByRole("switch", { name: label });
|
||||
await sw.waitFor();
|
||||
check(`${tag}: it starts off`, (await sw.getAttribute("aria-checked")) === "false");
|
||||
await sw.scrollIntoViewIfNeeded();
|
||||
const said = await page.evaluate(() => document.body.textContent);
|
||||
check(`${tag}: it says what it does not cover and that a headless run refuses`, pref === "zh" ? said.includes("改写过或编码过的文字不在其内") && said.includes("会被拒绝而不是执行") : said.includes("reworded or encoded") && said.includes("refused instead of run"));
|
||||
if (shotDir) { await page.mouse.move(width - 3, 995); await page.waitForTimeout(250); await page.locator("#set-external-origin").first().screenshot({ path: `${shotDir}/${scheme}-${pref}-${width}-off.png` }).catch(() => page.screenshot({ path: `${shotDir}/${scheme}-${pref}-${width}-off.png` })); }
|
||||
await sw.click();
|
||||
await page.waitForFunction((l) => document.querySelector(`[role="switch"][aria-label="${l}"]`)?.getAttribute("aria-checked") === "true", label);
|
||||
check(`${tag}: one click turns it on`, true);
|
||||
if (shotDir) { await page.mouse.move(width - 3, 995); await page.waitForTimeout(250); await page.locator("#set-external-origin").first().screenshot({ path: `${shotDir}/${scheme}-${pref}-${width}-on.png` }).catch(() => {}); }
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
if (fails.length) { console.log(`\n${fails.length} failed`); process.exit(1); }
|
||||
console.log("\nall passed");
|
||||
@@ -1,7 +1,8 @@
|
||||
// Frame cost of folding the left rail with 1/3/6 panes that each hold a long transcript. The rail width is
|
||||
// animated per frame, so every mounted pane is laid out again unless a hidden pane is skipped. Guard: the
|
||||
// median frame with PERF_GUARD panes stays within FRAME_RATIO_MAX of the one-pane median, and a pane that
|
||||
// was hidden comes back at the scroll position it left.
|
||||
// median frame with PERF_GUARD panes stays within FRAME_RATIO_MAX of the one-pane median, a pane that
|
||||
// was hidden comes back at the scroll position it left, and the transcript does not inherit the animated
|
||||
// column widths: with a long transcript the fold costs style recalculation of every element under it.
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const CPU = Number(process.env.PERF_CPU ?? 4);
|
||||
@@ -71,6 +72,27 @@ for (const n of COUNTS) {
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
const inherited = await (async () => {
|
||||
const ctx = await browser.newContext({ locale: "zh-CN", viewport: { width: 1440, height: 900 } });
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(`${URL}?panes=1`, { waitUntil: "networkidle" });
|
||||
await page.waitForSelector(".flow");
|
||||
const seen = await page.evaluate(async () => {
|
||||
const read = () => ["--rail-w", "--nav-w", "--side-w"].map((v) => getComputedStyle(document.querySelector(".flow")).getPropertyValue(v)).join(" ");
|
||||
const app = () => getComputedStyle(document.querySelector(".app")).getPropertyValue("--rail-w");
|
||||
const out = { flow: [read()], app: [app()] };
|
||||
const mac = /Mac/.test(navigator.platform);
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "\\", ctrlKey: !mac, metaKey: mac, bubbles: true, cancelable: true }));
|
||||
for (const wait of [90, 400]) {
|
||||
await new Promise((r) => setTimeout(r, wait));
|
||||
out.flow.push(read());
|
||||
out.app.push(app());
|
||||
}
|
||||
return out;
|
||||
});
|
||||
await ctx.close();
|
||||
return seen;
|
||||
})();
|
||||
await browser.close();
|
||||
console.table(rows);
|
||||
const one = rows.find((r) => r.panes === 1), many = rows.find((r) => r.panes === GUARD);
|
||||
@@ -78,6 +100,8 @@ const fails = [];
|
||||
if (one && many && Number(many.p50) > Number(one.p50) * FRAME_RATIO_MAX) {
|
||||
fails.push(`median frame with ${GUARD} panes is ${many.p50} ms against ${one.p50} ms with one (limit x${FRAME_RATIO_MAX})`);
|
||||
}
|
||||
if (new Set(inherited.app).size < 2) fails.push(`the rail width did not change during the fold (${inherited.app.join(" -> ")}), so the guard measured nothing`);
|
||||
else if (new Set(inherited.flow).size > 1) fails.push(`the transcript inherits the animated column widths (${inherited.flow.join(" -> ")}); every element under it is restyled on each frame of the fold`);
|
||||
if (kept !== null && Math.abs(kept - 400) > 2) fails.push(`a pane hidden at scrollTop 400 came back at ${kept}`);
|
||||
if (fails.length) {
|
||||
console.error(fails.join("\n"));
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// A running, halted or finished session row marks its state once, in the slot at its left edge. The row
|
||||
// draws a bar there (::before) and also owns a status dot (.pip); showing both puts two shapes on top of
|
||||
// each other. Guard: for every state, at most one of the two is rendered, in light and dark.
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const URL = process.env.ROW_URL ?? "http://127.0.0.1:5541/";
|
||||
const STATES = ["running", "halt", "done"];
|
||||
const browser = await chromium.launch();
|
||||
const fails = [];
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const page = await (await browser.newContext({ locale: "zh-CN", viewport: { width: 1280, height: 800 }, colorScheme: theme })).newPage();
|
||||
await page.goto(URL, { waitUntil: "networkidle" });
|
||||
await page.getByText("稍后再说").first().click().catch(() => {});
|
||||
await page.waitForSelector('.rail .sessrow[aria-selected="true"]');
|
||||
for (const state of STATES) {
|
||||
const seen = await page.evaluate((s) => {
|
||||
const row = document.querySelector('.rail .sessrow[aria-selected="true"]');
|
||||
row.setAttribute("data-run", s);
|
||||
const pip = row.querySelector(":scope > .pip");
|
||||
const bar = getComputedStyle(row, "::before");
|
||||
return {
|
||||
dot: !!pip && getComputedStyle(pip).display !== "none",
|
||||
bar: bar.content !== "none" && bar.display !== "none",
|
||||
};
|
||||
}, state);
|
||||
if (seen.dot && seen.bar) fails.push(`${theme} ${state}: the status dot and the bar are both drawn at the row's left edge`);
|
||||
if (!seen.dot && !seen.bar) fails.push(`${theme} ${state}: the row shows no state marker at all`);
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
if (fails.length) {
|
||||
console.error(fails.join("\n"));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("one state marker per row, in light and dark, for", STATES.join(", "));
|
||||
@@ -0,0 +1,57 @@
|
||||
// The current session's row must read as current at a glance: its fill is clearly stronger than a hovered row's
|
||||
// and a plain row's, a neutral ring (not a state colour) outlines it, and hovering it does not weaken either.
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const root = new URL("../src/", import.meta.url);
|
||||
const names = [...(await readFile(new URL("main.tsx", root), "utf8")).matchAll(/import "\.\/styles\/([\w.-]+\.css)"/g)].map((m) => m[1]);
|
||||
const sheets = await Promise.all(names.map((n) => readFile(new URL(`styles/${n}`, root), "utf8")));
|
||||
const MIN_SELECTED_OVER_REST = 1.2;
|
||||
const MIN_SELECTED_OVER_HOVER = 1.12;
|
||||
const rows = [["第一个会话", "done"], ["第二个会话", "done", "sel"], ["第三个会话", "done"], ["有未读的会话", "", "", "unread"], ["正在运行的会话", "running"]];
|
||||
const fixture = `<div class="rail" style="width:260px;padding:8px"><div class="kids">${rows.map(([t, run, sel, unread]) =>
|
||||
`<div class="sessrow sessrow-context" tabindex="0" ${run ? `data-run="${run}"` : ""} ${sel ? 'aria-selected="true"' : ""} ${unread ? "data-unread" : ""}><span class="sesstitle"><span>${t}</span></span><time class="sessmeta sessage">1 小时</time></div>`).join("")}</div></div>`;
|
||||
const luminance = ([r, g, b]) => [r, g, b].map((c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }).reduce((s, v, i) => s + v * [0.2126, 0.7152, 0.0722][i], 0);
|
||||
const contrast = (a, b) => { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05); };
|
||||
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const page = await browser.newPage({ viewport: { width: 400, height: 400 } });
|
||||
await page.setContent(fixture);
|
||||
await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme);
|
||||
for (const content of sheets) await page.addStyleTag({ content });
|
||||
await page.addStyleTag({ content: "*{transition:none!important;animation:none!important}" });
|
||||
const sample = async (i, hover) => {
|
||||
const row = page.locator(".sessrow").nth(i);
|
||||
await (hover ? row.hover() : page.mouse.move(390, 390));
|
||||
const box = await row.boundingBox();
|
||||
const png = await page.screenshot({ clip: { x: box.x + box.width - 60, y: box.y + 2, width: 4, height: 4 } });
|
||||
return page.evaluate(async (b64) => {
|
||||
const img = new Image();
|
||||
img.src = `data:image/png;base64,${b64}`;
|
||||
await img.decode();
|
||||
const c = document.createElement("canvas");
|
||||
c.width = c.height = 4;
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0);
|
||||
return [...ctx.getImageData(1, 1, 1, 1).data].slice(0, 3);
|
||||
}, png.toString("base64"));
|
||||
};
|
||||
const rest = await sample(2, false), selected = await sample(1, false), hovered = await sample(2, true), selectedHovered = await sample(1, true);
|
||||
assert.ok(contrast(selected, rest) >= MIN_SELECTED_OVER_REST, `${theme}: selected over a plain row is ${contrast(selected, rest).toFixed(3)}`);
|
||||
assert.ok(contrast(selected, hovered) >= MIN_SELECTED_OVER_HOVER, `${theme}: selected over a hovered row is ${contrast(selected, hovered).toFixed(3)}`);
|
||||
assert.deepEqual(selectedHovered, selected, `${theme}: hovering the selected row changes its fill`);
|
||||
const ring = await page.evaluate(() => {
|
||||
const [on, off] = [document.querySelectorAll(".sessrow")[1], document.querySelectorAll(".sessrow")[2]];
|
||||
return [getComputedStyle(on).outlineStyle, getComputedStyle(off).outlineStyle];
|
||||
});
|
||||
assert.notEqual(ring[0], "none", `${theme}: the selected row has no ring`);
|
||||
assert.equal(ring[1], "none", `${theme}: a plain row has a ring`);
|
||||
await page.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
console.log("the selected session row is distinct from hover and plain rows, in light and dark");
|
||||
@@ -16,7 +16,7 @@ import { parse } from "@babel/parser";
|
||||
// about a quarter of the product's inputs, including ones that write kernel
|
||||
// state. A ceiling measured against that set could only ever fall for the
|
||||
// wrong reason.
|
||||
const SOURCES = import.meta.glob(["./**/*.{ts,tsx}", "!./**/*.test.*", "!./actions.ts"], {
|
||||
const SOURCES = import.meta.glob(["./**/*.{ts,tsx}", "!./**/*.test.*", "!./actions.ts", "!./actions_schedule.ts"], {
|
||||
query: "?raw",
|
||||
import: "default",
|
||||
eager: true,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { SCHEDULE_ACTIONS } from "./actions_schedule";
|
||||
|
||||
// The census oracle is independent of production literals so disagreements fail.
|
||||
// An id names the intent; data-target and data-value name its entity and choice.
|
||||
|
||||
@@ -141,12 +143,11 @@ export const ACTIONS: UIAction[] = [
|
||||
{ id: "workspace.menu", kind: "view", target: "entity", proof: "interaction" },
|
||||
{ id: "machine.menu", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "session.pin", kind: "view", target: "entity", proof: "interaction" },
|
||||
{ id: "session.pause", kind: "kernel-mutation", target: "entity", proof: "interaction" },
|
||||
{ id: "session.mark-read", kind: "kernel-mutation", target: "entity", proof: "interaction" }, { id: "session.pause", kind: "kernel-mutation", target: "entity", proof: "interaction" },
|
||||
// Closing a conversation's pane ends its runtime and keeps the transcript;
|
||||
// refused while a turn runs, so it never stops work.
|
||||
{ id: "session.close", kind: "kernel-mutation", target: "entity", proof: "interaction" },
|
||||
{ id: "session.branch", kind: "kernel-mutation", target: "entity", proof: "interaction" },
|
||||
{ id: "session.archive", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "session.branch", kind: "kernel-mutation", target: "entity", proof: "interaction" }, { id: "session.archive", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "session.copy-info", kind: "shell-native", target: "entity", proof: "interaction" },
|
||||
{ id: "session.export", kind: "shell-native", target: "entity", proof: "browser" },
|
||||
{ id: "session.delete", kind: "destructive", target: "entity", proof: "authority-effect" },
|
||||
@@ -449,6 +450,7 @@ export const ACTIONS: UIAction[] = [
|
||||
// state — which is why it is one id and why it is not a mutation.
|
||||
{ id: "external.open", kind: "shell-native", target: "none", proof: "interaction" },
|
||||
{ id: "remote-host.remove", kind: "destructive", target: "none", proof: "authority-effect" },
|
||||
{ id: "remote-host.move", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "workspace.reveal", kind: "shell-native", target: "entity", proof: "interaction" },
|
||||
{ id: "workspace.open-with", kind: "shell-native", target: "entity", proof: "interaction" },
|
||||
{ id: "workbench.open-with-menu", kind: "view", target: "none", proof: "interaction" },
|
||||
@@ -737,6 +739,7 @@ export const ACTIONS: UIAction[] = [
|
||||
{ id: "push.preview", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "push.confirm", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "push.close", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "permissions.ask-on-external-origin", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "plan-approval.auto", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "default-mode.plan", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "tool-list.toggle", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
@@ -789,6 +792,7 @@ export const ACTIONS: UIAction[] = [
|
||||
// ── The two side panels. Reached from the keyboard here, and from each
|
||||
// gutter's own grip, which this pass has not annotated yet.
|
||||
{ id: "rail.toggle", kind: "view", target: "none", proof: "interaction" },
|
||||
...SCHEDULE_ACTIONS,
|
||||
];
|
||||
|
||||
// No action in Studio is reachable from the keyboard alone: every shortcut in
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { UIAction } from "./actions";
|
||||
|
||||
export const SCHEDULE_ACTIONS: UIAction[] = [
|
||||
{ id: "schedule.resume-all", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "schedule.pause-all", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "schedule.pause", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "schedule.resume", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "schedule.renew", kind: "kernel-mutation", target: "entity", proof: "authority-effect" },
|
||||
{ id: "schedule.delete", kind: "destructive", target: "entity", proof: "authority-effect" },
|
||||
{ id: "schedule.delete-ask", kind: "view", target: "entity", proof: "interaction" },
|
||||
{ id: "schedule.result", kind: "view", target: "entity", proof: "interaction" },
|
||||
{ id: "schedule.result-close", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.retry", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.new", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.folder", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.prompt", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.label", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.every", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.cancel", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.preview", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
{ id: "schedule.back", kind: "view", target: "none", proof: "interaction" },
|
||||
{ id: "schedule.create", kind: "kernel-mutation", target: "none", proof: "authority-effect" },
|
||||
];
|
||||
@@ -179,7 +179,7 @@
|
||||
{
|
||||
"kind": "notice",
|
||||
"text": "finishing what this turn still owes",
|
||||
"detail": "This turn ended with work still outstanding:\n- run a relevant verification command after the latest write for the current role setting (not documentation-only: \"note.txt\" changed)\nDo the remaining work, then verify it. Mark each finished item with complete_step — that is what advances the list; a todo_write that flips an item to completed is rejected. If an item should no longer be done — the request changed, or it was superseded — send a todo_write without it. If one turns on a decision only the user can make, put it to them with ask; not having heard back is not an answer to assume one from. If one cannot go on until the user says something only they can say, call await_user naming it — the list is kept and this message stops. If one cannot be done as specified, call conclude_blocked with the evidence for why.",
|
||||
"detail": "This turn ended with work still outstanding:\n- the verification owed after the latest write is still owed, as already explained: run a relevant verification command after it\nDo the remaining work, then verify it. Mark each finished item with complete_step — that is what advances the list; a todo_write that flips an item to completed is rejected. If an item should no longer be done — the request changed, or it was superseded — send a todo_write without it. If one turns on a decision only the user can make, put it to them with ask; not having heard back is not an answer to assume one from. If one cannot go on until the user says something only they can say, call await_user naming it — the list is kept and this message stops. If one cannot be done as specified, call conclude_blocked with the evidence for why.",
|
||||
"level": "info"
|
||||
},
|
||||
{
|
||||
@@ -372,7 +372,7 @@
|
||||
{
|
||||
"kind": "notice",
|
||||
"text": "finishing what this turn still owes",
|
||||
"detail": "This turn ended with work still outstanding:\n- run a relevant verification command after the latest write for the current role setting (not documentation-only: \"note.txt\" changed)\nDo the remaining work, then verify it. Mark each finished item with complete_step — that is what advances the list; a todo_write that flips an item to completed is rejected. If an item should no longer be done — the request changed, or it was superseded — send a todo_write without it. If one turns on a decision only the user can make, put it to them with ask; not having heard back is not an answer to assume one from. If one cannot go on until the user says something only they can say, call await_user naming it — the list is kept and this message stops. If one cannot be done as specified, call conclude_blocked with the evidence for why.",
|
||||
"detail": "This turn ended with work still outstanding:\n- the verification owed after the latest write is still owed, as already explained: run a relevant verification command after it\nDo the remaining work, then verify it. Mark each finished item with complete_step — that is what advances the list; a todo_write that flips an item to completed is rejected. If an item should no longer be done — the request changed, or it was superseded — send a todo_write without it. If one turns on a decision only the user can make, put it to them with ask; not having heard back is not an answer to assume one from. If one cannot go on until the user says something only they can say, call await_user naming it — the list is kept and this message stops. If one cannot be done as specified, call conclude_blocked with the evidence for why.",
|
||||
"level": "info"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -262,6 +262,70 @@ export const EN: Record<string, string> = {
|
||||
"界面大小": "Interface size",
|
||||
"等待浏览器登录…": "Waiting for the browser sign-in…",
|
||||
"等待浏览器授权…": "Waiting for the browser authorization…",
|
||||
"每小时": "Every hour",
|
||||
"每 2 小时": "Every 2 hours",
|
||||
"每 6 小时": "Every 6 hours",
|
||||
"每 12 小时": "Every 12 hours",
|
||||
"每天": "Every day",
|
||||
"每周": "Every week",
|
||||
"一次:{at}": "Once: {at}",
|
||||
"每 {n} 分钟": "Every {n} minutes",
|
||||
"已到期": "Expired",
|
||||
"已熔断": "Stopped by the safety breaker",
|
||||
"你暂停了它": "You paused it",
|
||||
"连续失败后自动暂停": "Paused automatically after repeated failures",
|
||||
"额度保护自动暂停": "Paused automatically to protect the budget",
|
||||
"用完了总额度": "The lifetime budget is used up",
|
||||
"记录损坏": "Its record is damaged",
|
||||
"等你决定": "Waiting for you",
|
||||
"额度用尽": "Budget used up",
|
||||
"被中断": "Interrupted",
|
||||
"已跳过": "Skipped",
|
||||
"即将开始": "About to start",
|
||||
"错过了时间": "Missed its time",
|
||||
"额度窗口已满": "The budget window is full",
|
||||
"有任务在运行": "Another run was in progress",
|
||||
"定时运行": "Scheduled runs",
|
||||
"按你确认的时间,只读地运行任务:它能读这个文件夹里的文件,不能写任何东西;需要你批准的事会挂起等你,不会替你答复。": "Runs tasks read-only at the time you confirmed: it can read files in the folder and write nothing; anything that needs your approval is parked for you and never answered for you.",
|
||||
"全部定时运行已暂停": "All scheduled runs are paused",
|
||||
"定时运行进行中": "Scheduled runs are on",
|
||||
"最多 {n} 个;每次至少间隔 {m} 分钟;每天合计最多 {k} 个令牌。": "At most {n}; at least {m} minutes apart; at most {k} tokens a day in total.",
|
||||
"全部恢复": "Resume all",
|
||||
"全部暂停": "Pause all",
|
||||
"还没有定时运行。": "No scheduled runs yet.",
|
||||
"定时运行列表": "Scheduled runs",
|
||||
"已用 {a} / {b} 令牌,{d} 到期": "Used {a} of {b} tokens; ends {d}",
|
||||
"暂停": "Pause",
|
||||
"恢复": "Resume",
|
||||
"续期": "Renew",
|
||||
"最近的运行": "Recent runs",
|
||||
"令牌": "tokens",
|
||||
"查看结果": "View result",
|
||||
"运行结果": "Result",
|
||||
"以下是模型写的内容,只作参考,不是 Reasonix 的说明。": "The text below was written by the model; treat it as a reference, not as something Reasonix says.",
|
||||
"报告太长,已截断。": "The report was too long and was cut.",
|
||||
"还没有受信任的项目。先在 Studio 或终端界面里打开一个项目并信任它,再回来选。": "There is no trusted project yet. Open one in Studio or the terminal UI and trust it, then come back to choose it.",
|
||||
"选择一个受信任的项目": "Choose a trusted project",
|
||||
"无法读取定时运行:{reason}": "Could not read the scheduled runs: {reason}",
|
||||
"无法刷新定时运行:{reason}(下面是上一次读到的内容)": "Could not refresh the scheduled runs: {reason} (what is below is what was read last)",
|
||||
"等你决定的事": "Waiting for your decision",
|
||||
"这些都没有被执行,也没有被代答。": "None of these was run or answered for you.",
|
||||
"新建定时运行": "New scheduled run",
|
||||
"文件夹(它只能读这里)": "Folder (it can only read here)",
|
||||
"要做什么": "What to do",
|
||||
"名称(可选)": "Name (optional)",
|
||||
"多久一次": "How often",
|
||||
"确认创建": "Confirm and create",
|
||||
"请确认": "Please confirm",
|
||||
"第一次运行": "First run",
|
||||
"文件夹": "Folder",
|
||||
"(只读:它能读这里的文件,不写任何东西)": "(read-only: it can read files here and writes nothing)",
|
||||
"每次最多": "Each run at most",
|
||||
"{a} 令牌,{b} 步,{c} 秒": "{a} tokens, {b} steps, {c} s",
|
||||
"总共最多": "In total at most",
|
||||
"每天 {a} 令牌,一共 {b} 令牌,{d} 自动到期": "{a} tokens a day, {b} in all, ends on its own {d}",
|
||||
"需要你批准的事会挂起等你,不会替你答复。": "Anything that needs your approval is parked for you and never answered for you.",
|
||||
"返回修改": "Back",
|
||||
"授权更多权限": "Grant more access",
|
||||
"追踪导出": "Trace export",
|
||||
"把每轮对话以 OpenTelemetry 追踪的形式发给你自己的观测系统。默认关闭;只发送结构、耗时、数量和名称,不发送提示词、工具参数、结果或文件路径。": "Send each turn to your own observability stack as OpenTelemetry traces. Off by default; only structure, timing, counts and names are sent, never prompts, tool arguments, results or file paths.",
|
||||
@@ -286,6 +350,20 @@ export const EN: Record<string, string> = {
|
||||
"这不是可用的请求头名称": "That is not a usable header name",
|
||||
"凭据环境变量必须以 OTEL_ 或 REASONIX_OTEL_ 开头": "The credential variable must start with OTEL_ or REASONIX_OTEL_",
|
||||
"追踪导出设置没有保存成功": "The trace export settings were not saved",
|
||||
"这个客户端不能修改定时运行": "This client cannot change scheduled runs",
|
||||
"定时任务只能在你确认预览后创建": "A schedule is created only after you confirm its preview",
|
||||
"要创建的内容和你确认的预览不一致": "What is being created is not what you confirmed",
|
||||
"找不到这个定时任务或结果": "No such schedule or result",
|
||||
"间隔低于允许的最小值": "The interval is under the minimum",
|
||||
"定时任务数量已达上限": "The schedule limit is reached",
|
||||
"请只设置“每隔多久”或“某个时间”其中一个": "Set either an interval or a time, not both and not neither",
|
||||
"这个文件夹不存在": "That folder does not exist",
|
||||
"定时运行只能读已受信任的项目文件夹": "A scheduled run can only read a project folder you have trusted",
|
||||
"这个模型还没有配置": "That model is not configured",
|
||||
"这个定时任务的内容不合法": "The schedule is not valid",
|
||||
"定时任务由更新的版本写入,这里只读": "The schedules were written by a newer version and are read-only here",
|
||||
"这个定时任务当前不可用(已暂停或已过期)": "The schedule is not active (paused or expired)",
|
||||
"定时任务没有保存成功": "The schedule was not saved",
|
||||
"接受并以后都自动接受这个服务器的改动": "Accept, and accept this server's changes by themselves from now on",
|
||||
"自动接受这个服务器的改动": "Changes from this server are accepted by themselves",
|
||||
"这个服务器的改动会自动接受,并在通知里告诉你。": "This server's changes are accepted by themselves, and you are told in a notice.",
|
||||
@@ -1481,6 +1559,7 @@ export const EN: Record<string, string> = {
|
||||
"导出会话": "Export session",
|
||||
"取消置顶": "Unpin",
|
||||
"置顶会话": "Pin session",
|
||||
"标为已读": "Mark as read",
|
||||
"删除会话": "Delete session",
|
||||
"会话范围": "Session scope",
|
||||
"运行统计": "Run metrics",
|
||||
|
||||
@@ -238,7 +238,13 @@ export const EN_KERNEL: Record<string, string> = {
|
||||
"bubblewrap 能启动,但无法为命令创建独立的网络命名空间(需要 CAP_NET_ADMIN,默认容器没有)。请给容器 CAP_NET_ADMIN,或在设置里开启沙盒网络让命令共用主机网络,或关闭命令沙盒——关闭后命令不受限制地运行,容器或主机就是唯一的边界": "bubblewrap starts, but cannot give a command its own network namespace (that needs CAP_NET_ADMIN, which a default container lacks). Grant the container CAP_NET_ADMIN, turn on sandbox network in Settings so commands share the host network, or turn the command sandbox off, after which commands run unconfined and the container or host is the only boundary",
|
||||
"bubblewrap 在 PATH 里但无法启动(可能不可执行,或自检没在时限内完成)。请确认 bwrap --version 能运行,或在设置里关闭命令沙盒——关闭后命令不受限制地运行,容器或主机就是唯一的边界": "bubblewrap is on PATH but could not be started (it may not be executable here, or its check did not finish in time). Make sure bwrap --version runs, or turn the command sandbox off in Settings, after which commands run unconfined and the container or host is the only boundary",
|
||||
"本机的 sandbox-exec 不可用,命令将不受限制地运行": "sandbox-exec is unusable on this machine, so commands run unconfined",
|
||||
"Windows 上尚无操作系统级沙箱,命令将不受限制地运行": "Windows has no OS-level sandbox here yet, so commands run unconfined",
|
||||
"Windows 上的命令沙箱默认关闭,命令将不受限制地运行;在“沙箱”设置里打开后才会限制写入": "The Windows command sandbox is off by default, so commands run unconfined; turn it on in Settings > Sandbox to bound their writes",
|
||||
"Windows 沙箱记录已损坏,不会静默重新开始;删掉它再重启,或关闭 Windows 沙箱": "The Windows sandbox's record is damaged and will not start over silently; delete it and restart, or turn the Windows sandbox off",
|
||||
"Windows 拒绝修改沙箱需要写入的文件夹的权限;确认你是该文件夹的所有者,或关闭 Windows 沙箱": "Windows refused to change the permissions of a folder the sandbox needs to write to; check that you own it, or turn the Windows sandbox off",
|
||||
"当前会话没有交互式登录(例如 SSH 或服务会话),无法建立受限令牌;请在桌面里运行,或关闭 Windows 沙箱": "This session has no interactive logon (for example an SSH or service session), so no restricted token can be made; run from the desktop, or turn the Windows sandbox off",
|
||||
"Windows 沙箱的授权记录放在了命令可写的文件夹里(例如工作区是你的整个用户文件夹),命令可能改写之后的授权;请打开更小的文件夹,或关闭 Windows 沙箱": "The Windows sandbox keeps its grant record inside a folder commands may write (for example the workspace is your whole user folder), so a command could rewrite what is granted next; open a narrower folder, or turn the Windows sandbox off",
|
||||
"Windows 无法创建沙箱命令所用的受限令牌;关闭 Windows 沙箱可让命令不受限制地运行": "Windows could not create the restricted token commands run under; turn the Windows sandbox off to run them unconfined",
|
||||
"Windows 沙箱已开启,但这次启动没有完成准备;关闭 Windows 沙箱可让命令不受限制地运行": "The Windows sandbox is on but this launch was not prepared for it; turn it off to run commands unconfined",
|
||||
"该平台尚无可用的沙箱后端,命令将不受限制地运行": "This platform has no usable sandbox backend yet, so commands run unconfined",
|
||||
"当前还有任务在运行,结束后才能更改工作区文件夹": "Finish the current work before changing the workspace folders.",
|
||||
"这台服务器没有开启工作区文件夹编辑": "Workspace folder editing is not enabled on this server.",
|
||||
|
||||
@@ -385,6 +385,8 @@ export const EN_SETTINGS: Record<string, string> = {
|
||||
"还有 {n} 个窗格正在运行,它们会在下次重建时采用这个改动。": "{n} panes are still running and will take this change at their next rebuild.",
|
||||
"实际可写": "Actually writable",
|
||||
"命令执行方式": "How commands run",
|
||||
"在 Windows 上启用后,命令无法在清单之外创建或改写文件、写注册表;但删除或重命名清单之外的文件、读取文件、联网,以及 ssh-agent、docker 管道和任务计划程序等系统服务不受限制,Everyone 本来就能写的位置和被授权的工具链缓存命令也能写。需要交互式桌面会话,并会在清单里的文件夹上加一条权限项(可用 reasonix sandbox revoke 收回)。":
|
||||
"On Windows, once on, commands cannot create or overwrite files outside the list or write the registry; deleting or renaming files outside the list, reading files, the network, and system services such as the ssh-agent and docker pipes or the task scheduler are not restricted, and neither are places Everyone can already write or the toolchain caches that are granted. It needs an interactive desktop session and adds a permission entry on the folders in the list (take it back with reasonix sandbox revoke).",
|
||||
"启用沙箱后,命令无法写入清单之外的位置。上方的可写目录清单由操作系统实施,不依赖 agent 自觉遵守。":
|
||||
"Inside the sandbox a command cannot write outside the list at all. The writable directories above are enforced by the operating system, not by the agent's cooperation.",
|
||||
"本机没有可用的操作系统沙箱": "This machine has no usable OS sandbox",
|
||||
@@ -437,7 +439,7 @@ export const EN_SETTINGS: Record<string, string> = {
|
||||
"等待其他会话释放写入权的最长时间": "Longest wait for another session to release the write claim",
|
||||
"另一个会话占着要写的路径时,这里的写入会一直等;设了分钟数,超过就失败,并给模型一个 workspace.claim_timeout 的明确原因。默认 0,一直等到本轮结束;想设上限,建议 120。之后新开的会话才采用新值。": "While another session holds a path this write needs, the write waits. With a number of minutes set, it fails past that and the model is told why with workspace.claim_timeout. Default 0 waits as long as the turn lasts; 120 is a sensible limit. Only sessions opened afterwards use it.",
|
||||
"分钟": "minutes",
|
||||
"没声明写入范围的操作(bash、MCP、没写 write_paths 的子代理)不再占住整个工作区,所以同一个项目里的多个会话可以同时工作,不必互相等待。代价:声明了路径的写入(如编辑文件)仍按路径互斥,但 bash 和 MCP 的写入没有事前的路径围栏,只在事后观察,两个会话用它们改同一个文件时可能互相覆盖。默认关闭(严格模式);只对之后新开的会话生效。": "An operation that declares no write scope (bash, MCP, a sub-agent with no write_paths) no longer holds the whole workspace, so several sessions in one project can work at the same time without waiting. The cost: writes that declare a path (such as editing a file) still exclude each other by path, but bash and MCP writes have no path fence beforehand and are only observed afterwards, so two sessions using them on one file can overwrite each other. Off by default (strict mode); applies only to sessions opened afterwards.",
|
||||
"没声明写入范围的操作(bash、MCP、没写 write_paths 的子代理)不再占住整个工作区,所以同一个项目里的多个会话可以同时工作,不必互相等待。代价:声明了路径的写入(如编辑文件)仍按路径互斥(落在工作区之外的路径只和同一路径的写入互斥),但 bash 和 MCP 的写入没有事前的路径围栏,只在事后观察,两个会话用它们改同一个文件时可能互相覆盖。默认关闭(严格模式);只对之后新开的会话生效。": "An operation that declares no write scope (bash, MCP, a sub-agent with no write_paths) no longer holds the whole workspace, so several sessions in one project can work at the same time without waiting. The cost: writes that declare a path (such as editing a file) still exclude each other by path (a path outside the workspace only excludes writes to that same path), but bash and MCP writes have no path fence beforehand and are only observed afterwards, so two sessions using them on one file can overwrite each other. Off by default (strict mode); applies only to sessions opened afterwards.",
|
||||
"无法读取子代理写入范围设置。": "Could not read the sub-agent write scope setting.",
|
||||
"子代理的写入范围": "Sub-agent write scope",
|
||||
"后台子代理写文件时如何占用工作区。默认严格:没有声明 write_paths 的子代理占住整个工作区,其他写入要等它结束。修改会重建运行时,任务运行期间无法变更。": "How a background sub-agent holds the workspace while it writes. Strict by default: a sub-agent that names no write_paths holds the whole workspace and other writers wait for it. Changing it rebuilds the runtime and cannot be done while a task runs.",
|
||||
@@ -1344,6 +1346,11 @@ export const EN_SETTINGS: Record<string, string> = {
|
||||
"移动": "Move",
|
||||
"先关闭这个会话,再移动它": "Close this conversation first, then move it",
|
||||
"移动到项目…": "Move to a project…",
|
||||
"无法读取这项设置。": "This setting could not be read.",
|
||||
"询问来自外部的文字": "Ask about text from outside",
|
||||
"外部文字": "Outside text",
|
||||
"网页和工具结果里的文字可能是别人写给 agent 的指令。开启后,照抄这些文字的调用先问你。": "Text in web pages and tool results can be instructions someone wrote for the agent. When on, a call that copies that text asks you first.",
|
||||
"调用逐字复制了网页或工具结果里的文字时,Auto 和 YOLO 也先问你。只认用户配置;已授权的 MCP 服务器、改写过或编码过的文字不在其内。无人可问时(无头 YOLO),这类调用会被拒绝而不是执行。修改会重建运行时,任务运行期间无法变更。默认关闭。": "When a call copies text word for word from a web page or a tool result, Auto and YOLO ask you first. Only your user config counts; servers you have authorised, and text that was reworded or encoded, are not covered. When nobody can be asked (headless YOLO) such a call is refused instead of run. Changing it rebuilds the runtime and cannot be done while a task runs. Off by default.",
|
||||
"检查点(回退快照)、后台任务日志和排队中的消息不随会话移动,原件会被移除。": "Checkpoints (rewind snapshots), background-task logs and queued messages do not travel; the originals are removed.",
|
||||
"对话已经移过去了,但原来的那份没能删除,请手动删除。": "The conversation was moved, but the original could not be removed; please delete it by hand.",
|
||||
"运行 Claude Code mod": "Run Claude Code mods",
|
||||
@@ -1377,6 +1384,8 @@ export const EN_SETTINGS: Record<string, string> = {
|
||||
"读你的对话": "Reads your conversation",
|
||||
"往模型面前排提示": "Queues prompts in front of the model",
|
||||
"以它自己的名义,不冒充你": "Under its own name, never as you",
|
||||
"来自外部的文字": "Text from outside",
|
||||
"这条调用里的文字,和本次任务从外部读到的内容(网页或工具结果)逐字相同。自动放行、全部放行和记住的答案都不能代你回答;请只批准这一次调用,或拒绝。": "Text in this call is copied word for word from content the task read from outside (a web page or a tool result). Auto, full access and remembered answers cannot answer for you; approve this one call, or decline.",
|
||||
"(没有列出)": "(none listed)",
|
||||
"名字无法列出的事件": "Events whose names cannot be listed",
|
||||
"它用到的接口": "API it uses",
|
||||
|
||||
@@ -23,6 +23,7 @@ export const EN_STORAGE: Record<string, string> = {
|
||||
"These files are still where they were; nothing was moved or deleted. Copy a path to deal with it yourself, or fix it and import again.",
|
||||
体积超过读取上限: "Larger than the size limit for reading",
|
||||
"不是本版本能读取的会话格式": "Not a session format this version can read",
|
||||
"没有记录它属于哪个项目,所以没有导入": "It records no project it belongs to, so it was not imported",
|
||||
"来自本版本尚不支持的存储版本": "Written by a storage version this version does not support yet",
|
||||
没有读取权限: "No permission to read it",
|
||||
文件已损坏: "The file is damaged",
|
||||
|
||||
@@ -454,6 +454,20 @@ const SAID: Record<string, string> = {
|
||||
"observability.header_invalid": "这不是可用的请求头名称",
|
||||
"observability.header_env_invalid": "凭据环境变量必须以 OTEL_ 或 REASONIX_OTEL_ 开头",
|
||||
"observability.save_failed": "追踪导出设置没有保存成功",
|
||||
"schedule.editing_disabled": "这个客户端不能修改定时运行",
|
||||
"schedule.confirmation_required": "定时任务只能在你确认预览后创建",
|
||||
"schedule.digest_mismatch": "要创建的内容和你确认的预览不一致",
|
||||
"schedule.not_found": "找不到这个定时任务或结果",
|
||||
"schedule.interval_too_short": "间隔低于允许的最小值",
|
||||
"schedule.limit_reached": "定时任务数量已达上限",
|
||||
"schedule.bad_trigger": "请只设置“每隔多久”或“某个时间”其中一个",
|
||||
"schedule.no_folder": "这个文件夹不存在",
|
||||
"schedule.workspace_unknown": "定时运行只能读已受信任的项目文件夹",
|
||||
"schedule.model_unconfigured": "这个模型还没有配置",
|
||||
"schedule.invalid": "这个定时任务的内容不合法",
|
||||
"schedule.schema_readonly": "定时任务由更新的版本写入,这里只读",
|
||||
"schedule.not_active": "这个定时任务当前不可用(已暂停或已过期)",
|
||||
"schedule.save_failed": "定时任务没有保存成功",
|
||||
"mcp.no_scope_upgrade": "这个服务器没有要求更多权限",
|
||||
"mcp.signin_busy": "这个服务器已经在登录中",
|
||||
"mcp.signin_no_host": "服务器给出的登录页没有主机名,已停止",
|
||||
@@ -666,7 +680,13 @@ const SAID: Record<string, string> = {
|
||||
"sandbox.bwrap_network_denied": "bubblewrap 能启动,但无法为命令创建独立的网络命名空间(需要 CAP_NET_ADMIN,默认容器没有)。请给容器 CAP_NET_ADMIN,或在设置里开启沙盒网络让命令共用主机网络,或关闭命令沙盒——关闭后命令不受限制地运行,容器或主机就是唯一的边界",
|
||||
"sandbox.bwrap_unrunnable": "bubblewrap 在 PATH 里但无法启动(可能不可执行,或自检没在时限内完成)。请确认 bwrap --version 能运行,或在设置里关闭命令沙盒——关闭后命令不受限制地运行,容器或主机就是唯一的边界",
|
||||
"sandbox.no_sandbox_exec": "本机的 sandbox-exec 不可用,命令将不受限制地运行",
|
||||
"sandbox.unsupported_on_windows": "Windows 上尚无操作系统级沙箱,命令将不受限制地运行",
|
||||
"sandbox.unsupported_on_windows": "Windows 上的命令沙箱默认关闭,命令将不受限制地运行;在“沙箱”设置里打开后才会限制写入",
|
||||
"sandbox.win_grant_unreadable": "Windows 沙箱记录已损坏,不会静默重新开始;删掉它再重启,或关闭 Windows 沙箱",
|
||||
"sandbox.win_grant_denied": "Windows 拒绝修改沙箱需要写入的文件夹的权限;确认你是该文件夹的所有者,或关闭 Windows 沙箱",
|
||||
"sandbox.win_no_logon_sid": "当前会话没有交互式登录(例如 SSH 或服务会话),无法建立受限令牌;请在桌面里运行,或关闭 Windows 沙箱",
|
||||
"sandbox.win_record_exposed": "Windows 沙箱的授权记录放在了命令可写的文件夹里(例如工作区是你的整个用户文件夹),命令可能改写之后的授权;请打开更小的文件夹,或关闭 Windows 沙箱",
|
||||
"sandbox.win_launcher": "Windows 无法创建沙箱命令所用的受限令牌;关闭 Windows 沙箱可让命令不受限制地运行",
|
||||
"sandbox.win_not_prepared": "Windows 沙箱已开启,但这次启动没有完成准备;关闭 Windows 沙箱可让命令不受限制地运行",
|
||||
"sandbox.unsupported_platform": "该平台尚无可用的沙箱后端,命令将不受限制地运行",
|
||||
"workspace_roots.busy": "当前还有任务在运行,结束后才能更改工作区文件夹",
|
||||
"workspace_roots.editing_disabled": "这台服务器没有开启工作区文件夹编辑",
|
||||
|
||||
@@ -9,6 +9,9 @@ export interface PermissionLists {
|
||||
allow: string[];
|
||||
ask: string[];
|
||||
deny: string[];
|
||||
// Ask before a call that copies text an external result gave the task. On a
|
||||
// save, absent leaves it as it is.
|
||||
askOnExternalOrigin?: boolean;
|
||||
}
|
||||
|
||||
export interface DormantPermissionRule {
|
||||
|
||||
@@ -2,6 +2,9 @@ import definitions from "../../../../internal/contract/agentcomposition/builtins
|
||||
|
||||
export type CompositionKind = "tools" | "skills" | "mcp" | "extensions" | "hooks" | "commands";
|
||||
export interface CompositionModule { id: string; parameters?: Record<string, unknown> }
|
||||
// A module the editor offers: the id is what a preset stores; the description is what the module
|
||||
// says about itself, for the person choosing, and is never saved.
|
||||
export interface CompositionChoice { id: string; description?: string }
|
||||
export interface CompositionSelection { mode: "inherit" | "select"; members: CompositionModule[] }
|
||||
export interface AgentComposition {
|
||||
schemaVersion: number;
|
||||
@@ -21,7 +24,7 @@ export interface AgentPresetCatalog {
|
||||
presets: AgentPresetVersion[];
|
||||
default: string;
|
||||
diagnostics: { code: string; module?: string; detail: string }[];
|
||||
modules?: Partial<Record<CompositionKind,CompositionModule[]>>;
|
||||
modules?: Partial<Record<CompositionKind,CompositionChoice[]>>;
|
||||
}
|
||||
export interface AgentPresetImport {definition:AgentComposition;diagnostics:AgentPresetCatalog["diagnostics"]}
|
||||
export interface CompositionSummary { id: string; name: string; revision: string; digest: string; started: boolean; unavailable?: string }
|
||||
|
||||
@@ -34,12 +34,16 @@ it("keeps local project moves and host-qualified pin/archive calls on their owni
|
||||
await hub.pinSession("/same/session.jsonl", false, "gpu box");
|
||||
await hub.archiveSession("/same/session.jsonl", true);
|
||||
await hub.archiveSession("/same/session.jsonl", false, "gpu box");
|
||||
await hub.markSessionRead("/same/session.jsonl");
|
||||
await hub.markSessionRead("/same/session.jsonl", "gpu box");
|
||||
await hub.moveSessionTo("/same/session.jsonl", "/other-project");
|
||||
expect(fetch.mock.calls.map(([path, init]) => [path, JSON.parse(init.body)])).toEqual([
|
||||
["/tree/sessions/pin", { path: "/same/session.jsonl", pinned: true }],
|
||||
["/remotes/gpu%20box/sessions/pin", { path: "/same/session.jsonl", pinned: false }],
|
||||
["/tree/sessions/archive", { path: "/same/session.jsonl", archived: true }],
|
||||
["/remotes/gpu%20box/sessions/archive", { path: "/same/session.jsonl", archived: false }],
|
||||
["/tree/sessions/viewed", { path: "/same/session.jsonl" }],
|
||||
["/remotes/gpu%20box/sessions/viewed", { path: "/same/session.jsonl" }],
|
||||
["/tree/sessions/move-to", { path: "/same/session.jsonl", target: "/other-project" }],
|
||||
]);
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
|
||||
@@ -64,7 +64,7 @@ export interface TreeSession {
|
||||
versions?: TreeSession[];
|
||||
}
|
||||
|
||||
export type LegacySkipReason = "too_large" | "unreadable_format" | "schema_unsupported" | "permission" | "corrupt" | "copy_failed";
|
||||
export type LegacySkipReason = "too_large" | "unreadable_format" | "schema_unsupported" | "permission" | "corrupt" | "copy_failed" | "no_project";
|
||||
|
||||
// A 1.x session the import could not read. The entry at `path` was neither
|
||||
// moved nor deleted.
|
||||
@@ -187,6 +187,9 @@ export interface HubPort extends SharePort {
|
||||
archiveSession(path: string, archived: boolean, host?: string): Promise<void>;
|
||||
// Tells the kernel which conversations automatic archiving must leave alone.
|
||||
pinSession(path: string, pinned: boolean, host?: string): Promise<void>;
|
||||
// Clears one saved conversation's unread mark without opening it; a remote host
|
||||
// that predates the route refuses and the caller reports it.
|
||||
markSessionRead(path: string, host?: string): Promise<void>;
|
||||
// Adds pins made before the kernel kept them. The first call also opens the
|
||||
// gate: until then the kernel archives nothing on its own.
|
||||
syncPins(paths: string[]): Promise<void>;
|
||||
@@ -222,6 +225,8 @@ export interface HubPort extends SharePort {
|
||||
removeRemoteWorkspace(host: string, path: string): Promise<void>;
|
||||
saveRemoteHost(entry: RemoteHostEdit): Promise<void>;
|
||||
removeRemoteHost(name: string): Promise<void>;
|
||||
// Puts a machine before another in the book, or last when before is empty.
|
||||
placeRemoteHost(name: string, before: string): Promise<void>;
|
||||
// ssh_config aliases this machine can already reach and the book has not
|
||||
// taken yet. Filling it by hand when the addresses are written down next
|
||||
// door is the step people skip.
|
||||
@@ -398,6 +403,10 @@ export class SseHub implements HubPort {
|
||||
await this.post<void>(host ? `/remotes/${encodeURIComponent(host)}/sessions/pin` : "/tree/sessions/pin", { path, pinned });
|
||||
}
|
||||
|
||||
async markSessionRead(path: string, host?: string) {
|
||||
await this.post<void>(host ? `/remotes/${encodeURIComponent(host)}/sessions/viewed` : "/tree/sessions/viewed", { path });
|
||||
}
|
||||
|
||||
async syncPins(paths: string[]) {
|
||||
await this.post<void>("/tree/sessions/pins", { paths });
|
||||
}
|
||||
@@ -487,6 +496,10 @@ export class SseHub implements HubPort {
|
||||
await this.post<void>("/remotes/remove", { name });
|
||||
}
|
||||
|
||||
async placeRemoteHost(name: string, before: string) {
|
||||
await this.post<void>(`/remotes/${encodeURIComponent(name)}/place`, { before });
|
||||
}
|
||||
|
||||
remoteCandidates() {
|
||||
return this.get<string[]>("/remotes/candidates");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Adjudications, BrowserToolsSettings, SubagentClaimsSettings, SubagentSteerSettings, WriteLeaseSettings, PlanApprovalSettings, DefaultModeSettings, ToolSettings, PeerReceipt, PeersState, PeersSettings, PeersSettingsEdit, PeerRemember, ConfigProblem, ConfigRepair, PermissionLists, PermissionRules, SandboxSettings, UpdateMode } from "./port";
|
||||
import type { AskTimeoutSettings, ModStatus, ModsSettings, ModsSettingsEdit, SessionRefSettings, AutoArchiveSettings, ChangedFilesSettings, FeedbackLevelNotices, FoldWorkSettings, TurnNarrationSettings, ObservabilityPatch, ObservabilitySettings, WebAccessPatch, WebAccessSettings, SearxngProbe, DisplayCurrencyMode, DisplayCurrencySettings, ProgressWatchSettings, WorkspaceRoots, ReceiptSettings } from "./boundary";
|
||||
import { mockMods } from "./mock_mods";
|
||||
import type { ScheduleBoard, ScheduleDraft, SchedulePreview, ScheduleResultView, ScheduleView } from "./schedule";
|
||||
import { HttpError } from "./http_error";
|
||||
import { MockShell } from "./mock_shell";
|
||||
import { MockCompositions } from "./mock_composition";
|
||||
@@ -88,7 +89,9 @@ export class MockBoundary extends MockShell {
|
||||
for (const rule of [...lists.deny, ...lists.ask, ...lists.allow]) {
|
||||
if (!/^[^()]+(\(.*\))?$/.test(rule.trim())) throw new Error(`invalid permission rule "${rule}"`);
|
||||
}
|
||||
this.rules = { ...this.rules, ...lists };
|
||||
// An absent switch is left as it is, the way the kernel treats a save without it.
|
||||
const { askOnExternalOrigin, ...rest } = lists;
|
||||
this.rules = { ...this.rules, ...rest, askOnExternalOrigin: askOnExternalOrigin ?? this.rules.askOnExternalOrigin ?? false };
|
||||
return { ...this.rules };
|
||||
}
|
||||
|
||||
@@ -234,6 +237,63 @@ export class MockBoundary extends MockShell {
|
||||
|
||||
protected peerState: PeersState = { enabled: false, peers: [], held: [] };
|
||||
|
||||
private scheduled: ScheduleBoard = {
|
||||
pausedAll: false,
|
||||
policy: { minIntervalMinutes: 60, maxSchedules: 8, globalTokensDay: 1_200_000, expiryDays: 30 },
|
||||
folders: [{ path: "/Users/you/src/app", name: "app" }, { path: "/Users/you/src/docs", name: "docs" }],
|
||||
schedules: [
|
||||
{ id: "sch_a1b2c3d4", label: "Morning briefing", status: "active", everySec: 86_400, workspace: "/Users/you/src/app", model: "deepseek/deepseek-v4-pro",
|
||||
prompt: "Summarize what changed in the repository since yesterday and list open TODOs.", perRunTokens: 250_000, lifetimeTokens: 3_000_000, spentLifetimeTokens: 410_000,
|
||||
expiresAtUnix: 1_793_000_000 },
|
||||
{ id: "sch_e5f6a7b8", label: "Docs drift", status: "paused", pausedReason: "consecutive_failures", everySec: 604_800, workspace: "/Users/you/src/docs", model: "deepseek/deepseek-v4-pro",
|
||||
prompt: "Check the docs against the code and report what is out of date.", perRunTokens: 250_000, lifetimeTokens: 3_000_000, spentLifetimeTokens: 1_240_000,
|
||||
consecutiveFailures: 3, expiresAtUnix: 1_793_000_000 },
|
||||
],
|
||||
runs: [
|
||||
{ triggerId: "sch_a1b2c3d4/1790000000", scheduleId: "sch_a1b2c3d4", slotUnix: 1_790_000_000, state: "succeeded", chargedTokens: 118_400, endedUnix: 1_790_000_260 },
|
||||
{ triggerId: "sch_a1b2c3d4/1789913600", scheduleId: "sch_a1b2c3d4", slotUnix: 1_789_913_600, state: "blocked", chargedTokens: 64_000, endedUnix: 1_789_913_700 },
|
||||
{ triggerId: "sch_e5f6a7b8/1789400000", scheduleId: "sch_e5f6a7b8", slotUnix: 1_789_400_000, state: "skipped", skipReason: "missed", chargedTokens: 0 },
|
||||
],
|
||||
};
|
||||
|
||||
async schedules(): Promise<ScheduleBoard> {
|
||||
return structuredClone(this.scheduled);
|
||||
}
|
||||
|
||||
async previewSchedule(d: ScheduleDraft): Promise<SchedulePreview> {
|
||||
return { firstRunUnix: 1_790_100_000, workspace: d.workspace, model: d.model || "deepseek/deepseek-v4-pro", prompt: d.prompt, perRunTokens: 250_000, perRunSteps: 40,
|
||||
perRunWallSec: 900, perDayMax: 1_000_000, lifetimeTokens: 3_000_000, expiresAtUnix: 1_792_700_000, confirm: "mock-confirm" };
|
||||
}
|
||||
|
||||
async createSchedule(d: ScheduleDraft, confirm: string): Promise<ScheduleView> {
|
||||
// A refused write is the only thing that shows the read-only state, so a rendered check reaches it by this label.
|
||||
if (d.label === "no-edit-grant") throw new HttpError(403, "x", { code: "schedule.editing_disabled", error: "this window has no edit grant" });
|
||||
if (confirm !== "mock-confirm") throw new HttpError(409, "x", { code: "schedule.digest_mismatch", error: "what is being created is not what was previewed" });
|
||||
const sc: ScheduleView = { id: "sch_" + Math.random().toString(16).slice(2, 10), label: d.label, status: "active", everySec: d.everySec, atUnix: d.atUnix, workspace: d.workspace,
|
||||
model: d.model || "deepseek/deepseek-v4-pro", prompt: d.prompt, perRunTokens: 250_000, lifetimeTokens: 3_000_000, spentLifetimeTokens: 0, expiresAtUnix: 1_792_700_000 };
|
||||
this.scheduled.schedules = [...this.scheduled.schedules, sc];
|
||||
return sc;
|
||||
}
|
||||
|
||||
async scheduleAction(id: string, verb: "pause" | "resume" | "renew" | "delete"): Promise<ScheduleBoard> {
|
||||
const sc = this.scheduled.schedules.find((s) => s.id === id);
|
||||
if (!sc) throw new HttpError(404, "x", { code: "schedule.not_found", error: "no such schedule" });
|
||||
if (verb === "delete") this.scheduled.schedules = this.scheduled.schedules.filter((s) => s.id !== id);
|
||||
else if (verb === "pause") { sc.status = "paused"; sc.pausedReason = "user"; }
|
||||
else if (verb === "resume") { sc.status = "active"; sc.pausedReason = undefined; sc.consecutiveFailures = undefined; }
|
||||
return structuredClone(this.scheduled);
|
||||
}
|
||||
|
||||
async setSchedulesPaused(paused: boolean): Promise<ScheduleBoard> {
|
||||
this.scheduled.pausedAll = paused;
|
||||
return structuredClone(this.scheduled);
|
||||
}
|
||||
|
||||
async scheduleResult(triggerId: string): Promise<ScheduleResultView> {
|
||||
if (!this.scheduled.runs.some((r) => r.triggerId === triggerId)) throw new HttpError(404, "x", { code: "schedule.not_found", error: "no such result" });
|
||||
return { triggerId, report: "Three files changed since yesterday. Two TODOs were added in `internal/store`.", pending: [{ kind: "approval", summary: "Wanted to run a shell command", detail: "git log --stat" }], enforcement: "tool-filter", recordedUnix: 1_790_000_260 };
|
||||
}
|
||||
|
||||
async peers(): Promise<PeersState> {
|
||||
return { ...this.peerState, peers: [...this.peerState.peers], held: [...this.peerState.held], threads: [...(this.peerState.threads ?? [])] };
|
||||
}
|
||||
|
||||
@@ -5,6 +5,20 @@ import type { AgentComposition, AgentPresetVersion, AgentPresetCatalog, Composit
|
||||
|
||||
type Library = { revision:number; user:AgentPresetVersion[]; projects:Map<string,AgentPresetVersion[]>; personalDefault:string; workspaceDefaults:Map<string,string> };
|
||||
|
||||
const MOCK_MODULES: AgentPresetCatalog["modules"] = {
|
||||
tools: [
|
||||
{ id: "bash", description: "Run a shell command in the workspace and return its output." },
|
||||
{ id: "bash_output", description: "Read new output from a shell command that is still running." },
|
||||
{ id: "browser_act", description: "Click, type or scroll on the page open in the built-in browser." },
|
||||
{ id: "edit_file", description: "Replace an exact piece of text in a file." },
|
||||
{ id: "task" },
|
||||
],
|
||||
skills: [
|
||||
{ id: "review", description: "Review the changes on this branch and report problems by severity." },
|
||||
{ id: "tidy-notes", description: "Tidy the notes folder" },
|
||||
],
|
||||
};
|
||||
|
||||
export class MockCompositions {
|
||||
private current: CompositionSummary | null = null;
|
||||
private started = false;
|
||||
@@ -13,7 +27,7 @@ export class MockCompositions {
|
||||
get compositionStarted() { return this.started; }
|
||||
fork(workspace:string) { return new MockCompositions(this.library,workspace); }
|
||||
private get catalog():AgentPresetCatalog {
|
||||
return {presets:[...builtinCompositions().map((definition)=>({definition,revision:revisions[definition.id as keyof typeof revisions]})),...this.library.user,...(this.library.projects.get(this.workspace) ?? [])],default:this.library.workspaceDefaults.get(this.workspace) ?? this.library.personalDefault,diagnostics:[]};
|
||||
return {presets:[...builtinCompositions().map((definition)=>({definition,revision:revisions[definition.id as keyof typeof revisions]})),...this.library.user,...(this.library.projects.get(this.workspace) ?? [])],default:this.library.workspaceDefaults.get(this.workspace) ?? this.library.personalDefault,diagnostics:[],modules:MOCK_MODULES};
|
||||
}
|
||||
private summary(v:AgentPresetVersion):CompositionSummary { return {id:v.definition.id,name:v.definition.name,revision:v.revision,digest:`mock-${v.revision}`,started:false}; }
|
||||
private fail(status:number,code:string):never { throw new HttpError(status,"",{code:`agent_composition.${code}`}); }
|
||||
|
||||
@@ -17,7 +17,7 @@ export class MockHub implements HubPort {
|
||||
];
|
||||
private readonly roots = ["~/projects/DeepSeek-Reasonix", "~/projects/my-website"];
|
||||
private seq = 1;
|
||||
private readonly flags = new Map<string, Pick<TreeSession, "pinned" | "archived">>();
|
||||
private readonly flags = new Map<string, Pick<TreeSession, "pinned" | "archived" | "unread">>();
|
||||
|
||||
private decorate(tree: TreeWorkspace[], host = ""): TreeWorkspace[] {
|
||||
return tree.map((ws) => ({ ...ws, sessions: ws.sessions.map((session) => ({ ...session,
|
||||
@@ -153,6 +153,10 @@ export class MockHub implements HubPort {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
placeRemoteHost() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
remoteCandidates() {
|
||||
return Promise.resolve(["attic", "old-laptop"]);
|
||||
}
|
||||
@@ -284,6 +288,12 @@ export class MockHub implements HubPort {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
markSessionRead(path: string, host = "") {
|
||||
const key = JSON.stringify([host, path]);
|
||||
this.flags.set(key, { ...this.flags.get(key), unread: false });
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
syncPins(_paths: string[]) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ import type { PluginExport, PluginInstallRequest, PluginPackage, PluginPlan } fr
|
||||
import type { MarketDetail, MarketList, MarketOwnRequest, MarketPackage, MarketPlan, MarketPublished, MarketQuery, MarketRequest, MarketSubmission, MarketVote } from "./market";
|
||||
import type { Appearance, ThemeImport, ThemePack } from "./look";
|
||||
import type { AskTimeoutSettings, ModStatus, ModsSettings, ModsSettingsEdit, SessionRefSettings, AutoArchiveSettings, ChangedFilesSettings, FeedbackLevelNotices, FoldWorkSettings, TurnNarrationSettings, ObservabilityPatch, ObservabilitySettings, WebAccessPatch, WebAccessSettings, SearxngProbe, BrowserToolsSettings, SubagentClaimsSettings, SubagentSteerSettings, WriteLeaseSettings, PlanApprovalSettings, DefaultModeSettings, ToolSettings, PeerReceipt, PeersState, PeersSettings, PeersSettingsEdit, PeerRemember, ConfigProblem, ConfigRepair, DisplayCurrencyMode, DisplayCurrencySettings, PermissionLists, PermissionRules, ProgressWatchSettings, SandboxSettings, WorkspaceRoots, ReceiptSettings } from "./boundary";
|
||||
import type { ScheduleBoard, ScheduleDraft, SchedulePreview, ScheduleResultView, ScheduleView } from "./schedule";
|
||||
import type { Protocol, ProviderCheck, ProviderCheckDraft, ProviderDraft, ProviderEdit, ProviderEntry, ProviderModelCheck, ProviderModelCheckRequest, ProviderProbe, ProviderSetup, ProviderRemoval, ProviderPreset, ProviderPresetInstall } from "./provider";
|
||||
export type { ModelEffort, ModelLimit, ModelRate, Protocol, ProviderCheck, ProviderCheckDraft, ProviderDraft, ProviderEdit, ProviderEntry, ProviderModelCheck, ProviderModelCheckRequest, ProviderProbe, ProviderSetup, ProviderRemoval, ProviderPreset, ProviderPresetInstall } from "./provider";
|
||||
import type { StoragePlan, StorageQuery, StorageState } from "./storage";
|
||||
@@ -57,6 +58,7 @@ import type { FeedbackBoard, FeedbackBoardMe, FeedbackEnv, FeedbackImage, Feedba
|
||||
import type { PersonaDraft, PersonaSettings } from "./boundary";
|
||||
|
||||
export type * from "./plugin";
|
||||
export type * from "./schedule";
|
||||
export type * from "./market";
|
||||
export type * from "./feedback";
|
||||
|
||||
@@ -311,6 +313,12 @@ export interface AgentPort {
|
||||
saveToolDisabled(name: string, disabled: boolean): Promise<ToolSettings>;
|
||||
writeLease(): Promise<WriteLeaseSettings>;
|
||||
saveWriteLease(edit: { optimistic?: boolean; maxWaitMinutes?: number }): Promise<WriteLeaseSettings>;
|
||||
schedules(): Promise<ScheduleBoard>;
|
||||
previewSchedule(draft: ScheduleDraft): Promise<SchedulePreview>;
|
||||
createSchedule(draft: ScheduleDraft, confirm: string): Promise<ScheduleView>;
|
||||
scheduleAction(id: string, verb: "pause" | "resume" | "renew" | "delete"): Promise<ScheduleBoard>;
|
||||
setSchedulesPaused(paused: boolean): Promise<ScheduleBoard>;
|
||||
scheduleResult(triggerId: string): Promise<ScheduleResultView>;
|
||||
peers(): Promise<PeersState>;
|
||||
sendPeerMessage(to: string, text: string): Promise<PeerReceipt>;
|
||||
resolvePeerMessage(id: string, approve: boolean, remember?: PeerRemember): Promise<void>;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Scheduled runs: read-only tasks a person confirmed, run at a time they chose.
|
||||
// Times are Unix seconds. A report is the model's own text: it is labelled as
|
||||
// such and drawn without loading remote content.
|
||||
|
||||
export interface ScheduleDraft {
|
||||
label: string;
|
||||
everySec?: number;
|
||||
atUnix?: number;
|
||||
workspace: string;
|
||||
prompt: string;
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface ScheduleView {
|
||||
id: string;
|
||||
label: string;
|
||||
status: string;
|
||||
pausedReason?: string;
|
||||
everySec?: number;
|
||||
atUnix?: number;
|
||||
workspace: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
perRunTokens: number;
|
||||
lifetimeTokens: number;
|
||||
spentLifetimeTokens: number;
|
||||
consecutiveFailures?: number;
|
||||
expiresAtUnix: number;
|
||||
}
|
||||
|
||||
export interface ScheduleRunView {
|
||||
triggerId: string;
|
||||
scheduleId: string;
|
||||
slotUnix: number;
|
||||
state: string;
|
||||
skipReason?: string;
|
||||
chargedTokens: number;
|
||||
endedUnix?: number;
|
||||
}
|
||||
|
||||
export interface SchedulePolicyView {
|
||||
minIntervalMinutes: number;
|
||||
maxSchedules: number;
|
||||
globalTokensDay: number;
|
||||
expiryDays: number;
|
||||
}
|
||||
|
||||
export interface ScheduleBoard {
|
||||
pausedAll: boolean;
|
||||
pausedReason?: string;
|
||||
schedules: ScheduleView[];
|
||||
runs: ScheduleRunView[];
|
||||
policy: SchedulePolicyView;
|
||||
// The trusted projects a schedule may be given. A creation names one of these
|
||||
// and nothing else; the kernel refuses any other path.
|
||||
folders: ScheduleFolder[];
|
||||
}
|
||||
|
||||
export interface ScheduleFolder {
|
||||
path: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface SchedulePreview {
|
||||
firstRunUnix: number;
|
||||
workspace: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
perRunTokens: number;
|
||||
perRunSteps: number;
|
||||
perRunWallSec: number;
|
||||
perDayMax: number;
|
||||
lifetimeTokens: number;
|
||||
expiresAtUnix: number;
|
||||
confirm: string;
|
||||
}
|
||||
|
||||
export interface SchedulePendingView {
|
||||
kind: string;
|
||||
summary: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface ScheduleResultView {
|
||||
triggerId: string;
|
||||
report: string;
|
||||
reportTruncated?: boolean;
|
||||
pending: SchedulePendingView[];
|
||||
pendingDropped?: number;
|
||||
enforcement: string;
|
||||
recordedUnix: number;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { SseShell } from "./sse_shell";
|
||||
import type { AgentComposition, AgentPresetVersion, AgentPresetCatalog, CompositionSummary } from "./composition";
|
||||
import type { ScheduleBoard, ScheduleDraft, SchedulePreview, ScheduleResultView, ScheduleView } from "./schedule";
|
||||
import type { PersonaDraft, PersonaSettings } from "./boundary";
|
||||
import type { Adjudications, BrowserToolsSettings, SubagentClaimsSettings, SubagentSteerSettings, WriteLeaseSettings, PlanApprovalSettings, DefaultModeSettings, ToolSettings, PeerReceipt, PeersState, PeersSettings, PeersSettingsEdit, PeerRemember, ConfigProblem, ConfigRepair, PermissionLists, PermissionRules, SandboxSettings } from "./port";
|
||||
import type { AskTimeoutSettings, ModStatus, ModsSettings, ModsSettingsEdit, SessionRefSettings, AutoArchiveSettings, ChangedFilesSettings, FeedbackLevelNotices, FoldWorkSettings, TurnNarrationSettings, ObservabilityPatch, ObservabilitySettings, WebAccessPatch, WebAccessSettings, SearxngProbe, DisplayCurrencyMode, DisplayCurrencySettings, ProgressWatchSettings, WorkspaceRoots, ReceiptSettings } from "./boundary";
|
||||
@@ -78,6 +79,24 @@ export class SseBoundary extends SseShell {
|
||||
saveWriteLease(edit: { optimistic?: boolean; maxWaitMinutes?: number }) {
|
||||
return this.post0<WriteLeaseSettings>("/write-lease", edit);
|
||||
}
|
||||
schedules() {
|
||||
return this.get<ScheduleBoard>("/schedules");
|
||||
}
|
||||
previewSchedule(draft: ScheduleDraft) {
|
||||
return this.post0<SchedulePreview>("/schedules/preview", draft);
|
||||
}
|
||||
createSchedule(draft: ScheduleDraft, confirm: string) {
|
||||
return this.post0<ScheduleView>("/schedules", { ...draft, confirm });
|
||||
}
|
||||
scheduleAction(id: string, verb: "pause" | "resume" | "renew" | "delete") {
|
||||
return this.post0<ScheduleBoard>(`/schedules/${encodeURIComponent(id)}/${verb}`, {});
|
||||
}
|
||||
setSchedulesPaused(paused: boolean) {
|
||||
return this.post0<ScheduleBoard>(paused ? "/schedules/pause-all" : "/schedules/resume-all", {});
|
||||
}
|
||||
scheduleResult(triggerId: string) {
|
||||
return this.get<ScheduleResultView>(`/schedules/result?trigger=${encodeURIComponent(triggerId)}`);
|
||||
}
|
||||
peers() {
|
||||
return this.get<PeersState>("/peers");
|
||||
}
|
||||
|
||||
@@ -291,6 +291,14 @@ describe("rebuilding a reopened transcript", () => {
|
||||
expect(got[0].text).toBe("继续");
|
||||
});
|
||||
|
||||
it("strips a session-scratch block from a replayed turn", () => {
|
||||
const got = users([
|
||||
{ role: "user", content: "<session-scratch>\nThis session has a private scratch directory, $TMPDIR.\n</session-scratch>\n继续" },
|
||||
]);
|
||||
expect(got).toHaveLength(1);
|
||||
expect(got[0].text).toBe("继续");
|
||||
});
|
||||
|
||||
it("leaves an ordinary turn as its text", () => {
|
||||
const got = users([{ role: "user", content: "第一句话" }]);
|
||||
expect(got).toHaveLength(1);
|
||||
|
||||
@@ -651,7 +651,7 @@ function withReceipt(items: Item[], r?: Receipt): Item[] {
|
||||
// eleven. The server strips these before /history now — this is what covers
|
||||
// sessions already on disk.
|
||||
const CONTROL =
|
||||
/<(reasoning-language|turn-narration|response-language|execution-policy|memory-update|background-jobs|active-goal|autoresearch-runtime|hook-context|available-skills|current-date|project-instructions|project-rules|scoped-rules|capability-route|interrupted-turn-recovery|workspace|scheduled-run|mcp-prompt-failure|refused-calls)[\s\S]*?<\/\1>\s*/g;
|
||||
/<(reasoning-language|turn-narration|response-language|execution-policy|memory-update|background-jobs|active-goal|autoresearch-runtime|hook-context|available-skills|current-date|session-scratch|project-instructions|project-rules|scoped-rules|capability-route|interrupted-turn-recovery|workspace|scheduled-run|mcp-prompt-failure|refused-calls)[\s\S]*?<\/\1>\s*/g;
|
||||
const stripControl = (s: string) => s.replace(CONTROL, "").trim();
|
||||
|
||||
// A plan that ran to the end is spent: struck through in the rail it reads as
|
||||
|
||||
@@ -129,6 +129,10 @@ rules are written in.
|
||||
|
||||
## Pickers and menus
|
||||
|
||||
- The preset editor's drop-downs draw their own arrow, 14px in from the border.
|
||||
The native arrow's inset belongs to the platform, and on Windows it sat close
|
||||
enough to the border to read as clipped; the text keeps room for the arrow.
|
||||
|
||||
- A menu drawn outside its anchor's box cannot be dismissed by the pointer
|
||||
leaving that box: the offset between them belongs to neither, and crossing it
|
||||
is how the menu is reached, so it closes exactly when it is being aimed at.
|
||||
@@ -225,6 +229,9 @@ rules are written in.
|
||||
follow that radius and a short mark cannot. It is one mark in three colours —
|
||||
accent, warn, ok — so the row says which state it is in without the row
|
||||
itself becoming the signal.
|
||||
- The tick is the only state mark in the rail, running included. The row's
|
||||
status dot is not drawn there: it sat on top of the tick and pushed the title
|
||||
one step right. `perf/session-row-marker.mjs` holds it.
|
||||
- Finishing is the one rail state that is an event rather than a state, so it
|
||||
alone is animated, and only for the run this window watched cross into
|
||||
`done`. A session that was already done when the rail mounted, or that comes
|
||||
@@ -286,6 +293,13 @@ rules are written in.
|
||||
on the pane that reads it.
|
||||
- A tweened inherited property on `.app` restyles every node under it on every
|
||||
frame, which made opening the workbench stutter with a long transcript.
|
||||
- The rail, nav and side widths are tweened inherited properties on `.app` too.
|
||||
Nothing under the transcript reads them, so `.flow` resets them.
|
||||
- Without the reset, a fold at 300 turns cost about 430 ms of style
|
||||
recalculation against 3 ms of layout; with it the median frame fell from 128 ms
|
||||
to 46 ms (4x CPU throttle, the perf fixture).
|
||||
- `perf/rail-toggle-panes.mjs` holds it by reading the widths inside `.flow`
|
||||
while the rail folds. `.srail-peek` is outside `.flow` and still reads `--rail-w`.
|
||||
- The gutter writes the width on the pane for the same reason (`DOCK.owner`).
|
||||
- The side track is closed unless a panel mounts in it. It was written open and
|
||||
closed by `[data-side="off"]`, and the attribute stayed wired to the built-in
|
||||
@@ -1547,6 +1561,10 @@ A sub-agent row, by the list's own width:
|
||||
- Taking the room only while shown means the title shortens when the buttons appear, never before. Pinning stays an overlay at the left, so the pin never moves the title.
|
||||
- An unread dot is an overlay 11px from the right edge: an unread row keeps 22px after its age (or after its badge, 26px) for it, and the dot hides while the buttons are shown.
|
||||
- A legacy `margin-right: 44px` on the age made room for a delete button the rail has long since hidden; the rail's rule sets it to zero.
|
||||
- The current session reads as current in its fill and a 1px neutral outline, never in a state colour. The fill is a 13% text tint against hover's 4%.
|
||||
- The outline is drawn inside the border box (`outline-offset: -1px`): the row's transparent 2px left border would push an inset shadow off the edge.
|
||||
- Hovering the selected row changes neither the fill nor the outline; keyboard focus swaps the outline for the focus ring.
|
||||
- `perf/session-selected-row.mjs` holds the contrast floors in a real browser, light and dark: 1.2 over a plain row, 1.12 over a hovered one.
|
||||
- `perf/sessionrows.mjs` measures this in a real browser: with no button showing, a row with an age leaves at most 2px (8px with a badge) of its right side unused, and the buttons take no width at rest.
|
||||
|
||||
## Session rename dialog
|
||||
|
||||
@@ -874,6 +874,7 @@
|
||||
margin-top: auto; margin-inline: auto;
|
||||
width: calc(100% - var(--srail-w) * 2); max-width: var(--wide);
|
||||
padding: 12px var(--flow-pad) 16px;
|
||||
--nav-w: initial; --rail-w: initial; --side-w: initial;
|
||||
}
|
||||
|
||||
.chunk { display: flow-root }
|
||||
|
||||
@@ -81,6 +81,8 @@
|
||||
.composition-module { margin-block: 8px; }
|
||||
.composition-module .in { flex: 1; min-width: 100px; }
|
||||
.composition-modules select + select { margin-top: 8px; }
|
||||
.composition-editor select { appearance: none; padding-inline-end: 40px; background-repeat: no-repeat; background-position: right 14px center; background-size: 12px 12px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='%238a8d86' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2.5 4.5 6 8l3.5-3.5'/%3E%3C/svg%3E"); }
|
||||
.composition-modules > :is(select, .composition-module) + button { margin-top: 12px; }
|
||||
.preset-page-footer { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-shrink: 0; border-top: 1px solid var(--hair); padding: 16px 32px; background: var(--surface); }
|
||||
.preset-page-footer p { margin: 0; color: var(--muted); font-size: var(--fs-meta); line-height: 1.6; }
|
||||
.preset-page-footer > div { display: flex; gap: 10px; flex-shrink: 0; }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const CSS = Object.values(
|
||||
import.meta.glob("./composition-presets.css", { query: "?raw", import: "default", eager: true }) as Record<string, string>,
|
||||
)[0];
|
||||
|
||||
function rule(selector: string): string {
|
||||
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return CSS.match(new RegExp(String.raw`(?:^|\n)${escaped}\s*\{([^}]*)\}`))?.[1] ?? "";
|
||||
}
|
||||
|
||||
describe("the preset editor's drop-downs", () => {
|
||||
it("draw their own arrow, set in from the right border, with room for it beside the text", () => {
|
||||
const select = rule(".composition-editor select");
|
||||
expect(select, "no rule for the editor's selects").not.toBe("");
|
||||
expect(select).toMatch(/appearance:\s*none/);
|
||||
expect(select).toMatch(/background-position:\s*right\s+14px\s+center/);
|
||||
const padding = Number(select.match(/padding-inline-end:\s*(\d+)px/)?.[1] ?? 0);
|
||||
expect(padding).toBeGreaterThanOrEqual(36);
|
||||
});
|
||||
|
||||
it("leave the add-module button a gap below the list above it", () => {
|
||||
const gap = rule(".composition-modules > :is(select, .composition-module) + button");
|
||||
expect(Number(gap.match(/margin-top:\s*(\d+)px/)?.[1] ?? 0)).toBeGreaterThanOrEqual(10);
|
||||
});
|
||||
});
|
||||
@@ -44,7 +44,8 @@ describe("the Studio shell closes over the active theme", () => {
|
||||
|
||||
it("gives selection a stronger neutral fill than hover and no extra bar", () => {
|
||||
const rows = Object.values(ROWS)[0];
|
||||
expect(rows).toMatch(/\.sessrow\[aria-selected="true"\][^{]*\{[^}]*var\(--text\) 8%/);
|
||||
expect(rows).toMatch(/\.sessrow\[aria-selected="true"\][^{]*\{[^}]*var\(--text\) 13%/);
|
||||
expect(rows).toMatch(/\.sessrow\[aria-selected="true"\]:not\(:focus-visible\)[^{]*\{[^}]*outline: 1px solid/);
|
||||
expect(rows).toMatch(/\.sessrow:hover[^{]*\{[^}]*var\(--text\) 4%/);
|
||||
expect(rows).not.toContain("inset 2px");
|
||||
expect(Object.values(CSS)[0]).not.toMatch(/\.sessrow\[aria-selected="true"\]::before/);
|
||||
|
||||
@@ -2733,6 +2733,9 @@ button, input, select, textarea { font-size: calc(13.3333px * var(--fs-scale, 1)
|
||||
color: var(--text);
|
||||
font: 500 calc(10.5px * var(--fs-scale, 1))/1.5 var(--mono);
|
||||
}
|
||||
.flow .call[data-approval] .apv-hd[data-whole] .sub {
|
||||
-webkit-line-clamp: unset;
|
||||
}
|
||||
.flow .call[data-approval] .apv-dt {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
.rail .kids { margin: 0 15px 0 22px; padding-left: 10px; border-left: 0; }
|
||||
.rail .sessrow { min-height: 34px; margin: 1px 0 1px 3px; }
|
||||
.rail .sessrow > .pip { display: none; }
|
||||
.rail .sessrow[data-run="running"] > .pip { display: block; }
|
||||
.rail .rmtws-node .sessdel { opacity: 0; }
|
||||
.rail .rmtws-node .sessrow:is(:hover, :focus-within) .sessdel { opacity: 1; }
|
||||
.rail .sessage { margin-left: auto; margin-right: 0; font-size: var(--fs-micro); }
|
||||
@@ -55,7 +54,8 @@
|
||||
.rail .sessrow[data-unread]:not(:has(> .sesscopies)) > .sessage { margin-inline-end: 22px; }
|
||||
.rail .sessmore { width: calc(100% - 12px); margin: 2px 0 5px 3px; padding-left: 9px; text-align: left; }
|
||||
.rail .sessrow:hover { background: color-mix(in srgb, var(--text) 4%, transparent); }
|
||||
.rail .sessrow[aria-selected="true"] { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); font-weight: var(--w-reg); box-shadow: none; }
|
||||
.rail .sessrow[aria-selected="true"] { background: color-mix(in srgb, var(--text) 13%, transparent); color: var(--text); font-weight: var(--w-reg); box-shadow: none; }
|
||||
.rail .sessrow[aria-selected="true"]:not(:focus-visible) { outline: 1px solid color-mix(in srgb, var(--text) 22%, transparent); outline-offset: -1px; }
|
||||
.rail .sessrow:not([data-unread]) .sesstitle { font-weight: var(--w-reg); }
|
||||
.project-connection { display: flex; align-items: center; gap: 5px; margin: 0 22px 4px 48px; color: var(--warn-ink); font: var(--w-reg) var(--fs-micro)/1.5 var(--ui); }
|
||||
.project-connection .studio-icon { width: 12px; height: 12px; flex: none; }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// @vitest-environment jsdom
|
||||
import "./testkit";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { CompositionEditor } from "./CompositionEditor";
|
||||
import { MockPort } from "../port/mock";
|
||||
import type { AgentComposition, AgentPresetCatalog } from "../port/composition";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
async function open() {
|
||||
const port = new MockPort();
|
||||
const catalog: AgentPresetCatalog = await port.agentPresets();
|
||||
const draft: AgentComposition = structuredClone(catalog.presets.find((v) => v.definition.id.startsWith("user:") || true)!.definition);
|
||||
draft.id = "user:picker";
|
||||
draft.tools = { mode: "select", members: [] };
|
||||
let current = draft;
|
||||
const view = render(
|
||||
<CompositionEditor draft={current} modules={catalog.modules} disabled={false} creating
|
||||
onChange={(next: AgentComposition) => { current = next; view.rerender(<CompositionEditor draft={current} modules={catalog.modules} disabled={false} creating onChange={() => {}} onValidityChange={() => {}} />); }}
|
||||
onValidityChange={() => {}} />,
|
||||
);
|
||||
return { catalog, get saved() { return current; } };
|
||||
}
|
||||
|
||||
it("shows what a module is for beside its name, and says nothing where its source says nothing", async () => {
|
||||
await open();
|
||||
const pick = screen.getAllByRole<HTMLSelectElement>("combobox").find((s) => /添加模块/.test(s.getAttribute("aria-label") ?? ""))!;
|
||||
const labels = [...pick.options].map((o) => o.textContent);
|
||||
expect(labels).toContain("bash — Run a shell command in the workspace and return its output.");
|
||||
expect(labels).toContain("task");
|
||||
const bash = [...pick.options].find((o) => o.value === "bash")!;
|
||||
expect(bash.title).toBe("Run a shell command in the workspace and return its output.");
|
||||
});
|
||||
|
||||
it("stores only the id of the module it adds, never its description", async () => {
|
||||
const state = await open();
|
||||
const pick = screen.getAllByRole<HTMLSelectElement>("combobox").find((s) => /添加模块/.test(s.getAttribute("aria-label") ?? ""))!;
|
||||
await userEvent.selectOptions(pick, "bash");
|
||||
expect(state.saved.tools.members).toEqual([{ id: "bash" }]);
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { t } from "../i18n";
|
||||
import type {
|
||||
AgentComposition,
|
||||
AgentPresetCatalog,
|
||||
CompositionModule,
|
||||
CompositionChoice,
|
||||
CompositionKind,
|
||||
CompositionSelection,
|
||||
} from "../port/composition";
|
||||
@@ -151,7 +151,7 @@ function ModuleEditor({
|
||||
onValidityChange,
|
||||
}: {
|
||||
kind: CompositionKind;
|
||||
choices: CompositionModule[];
|
||||
choices: CompositionChoice[];
|
||||
value: CompositionSelection;
|
||||
disabled: boolean;
|
||||
onChange: (value: CompositionSelection) => void;
|
||||
@@ -211,8 +211,8 @@ function ModuleEditor({
|
||||
{choices
|
||||
.filter((m) => !value.members.some((s) => s.id === m.id))
|
||||
.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.id}
|
||||
<option key={m.id} value={m.id} title={m.description || undefined}>
|
||||
{m.description ? `${m.id} — ${m.description}` : m.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import "./testkit";
|
||||
import { ExternalOrigin } from "./ExternalOrigin";
|
||||
import { MockPort } from "../port/mock";
|
||||
import type { AgentPort } from "../port/port";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const toggle = () => screen.findByRole("switch", { name: "询问来自外部的文字" });
|
||||
|
||||
describe("the ask-on-external-text switch", () => {
|
||||
it("starts off, says what it covers and what it does not, and saves the opposite of what it shows", async () => {
|
||||
const p = new MockPort() as unknown as AgentPort;
|
||||
const save = vi.spyOn(p, "savePermissions");
|
||||
const changed = vi.fn();
|
||||
render(<ExternalOrigin port={p} onChanged={changed} />);
|
||||
const sw = await toggle();
|
||||
expect(sw.getAttribute("aria-checked")).toBe("false");
|
||||
expect(screen.getByText(/已授权的 MCP 服务器、改写过或编码过的文字不在其内/)).toBeTruthy();
|
||||
expect(screen.getByText(/无人可问时(无头 YOLO),这类调用会被拒绝而不是执行/)).toBeTruthy();
|
||||
await userEvent.click(sw);
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ askOnExternalOrigin: true }));
|
||||
await waitFor(() => expect(sw.getAttribute("aria-checked")).toBe("true"));
|
||||
expect(changed).toHaveBeenCalledTimes(1);
|
||||
await userEvent.click(sw);
|
||||
expect(save).toHaveBeenLastCalledWith(expect.objectContaining({ askOnExternalOrigin: false }));
|
||||
});
|
||||
|
||||
it("saves the rule lists as the kernel holds them now, not as they were when the page loaded", async () => {
|
||||
const p = new MockPort() as unknown as AgentPort;
|
||||
render(<ExternalOrigin port={p} onChanged={() => {}} />);
|
||||
const sw = await toggle();
|
||||
await p.savePermissions({ mode: "ask", deny: ["bash(rm *)"], ask: [], allow: ["read_file"] });
|
||||
const save = vi.spyOn(p, "savePermissions");
|
||||
await userEvent.click(sw);
|
||||
expect(save).toHaveBeenCalledWith({ mode: "ask", deny: ["bash(rm *)"], ask: [], allow: ["read_file"], askOnExternalOrigin: true });
|
||||
});
|
||||
|
||||
it("a rules save that does not mention the switch leaves it as it is", async () => {
|
||||
const p = new MockPort() as unknown as AgentPort;
|
||||
const on = await p.savePermissions({ mode: "ask", deny: [], ask: [], allow: [], askOnExternalOrigin: true });
|
||||
expect(on.askOnExternalOrigin).toBe(true);
|
||||
const after = await p.savePermissions({ mode: "ask", deny: [], ask: ["bash"], allow: [] });
|
||||
expect(after.askOnExternalOrigin).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the switch where it was and says why when the save is refused", async () => {
|
||||
const p = new MockPort() as unknown as AgentPort;
|
||||
p.savePermissions = async () => {
|
||||
throw new Error("disk full");
|
||||
};
|
||||
render(<ExternalOrigin port={p} onChanged={() => {}} />);
|
||||
const sw = await toggle();
|
||||
await userEvent.click(sw);
|
||||
await screen.findByText(/disk full/);
|
||||
expect(sw.getAttribute("aria-checked")).toBe("false");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { reason, savedNotApplied } from "../i18n/kernel";
|
||||
import type { AgentPort } from "../port/port";
|
||||
import { SaveNote, type SaveNoteState } from "./SaveNote";
|
||||
import { Switch } from "./Switch";
|
||||
|
||||
// One switch over asking before a call that copies text an external result
|
||||
// gave the task. The save sends the lists as the kernel holds them now, because
|
||||
// the rules editor saves the same record and a stale copy would overwrite it.
|
||||
export function ExternalOrigin({ port, onChanged }: { port: AgentPort; onChanged: () => void }) {
|
||||
const [on, setOn] = useState<boolean | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<SaveNoteState | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
port.permissions().then((p) => setOn(p.askOnExternalOrigin === true)).catch(() => setOn(null));
|
||||
}, [port]);
|
||||
|
||||
if (on === null) return <div className="empty">{t("无法读取这项设置。")}</div>;
|
||||
|
||||
const flip = async () => {
|
||||
setBusy(true);
|
||||
setNote(null);
|
||||
try {
|
||||
const { mode, deny, ask, allow } = await port.permissions();
|
||||
const saved = await port.savePermissions({ mode, deny, ask, allow, askOnExternalOrigin: !on });
|
||||
setOn(saved.askOnExternalOrigin === true);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setNote({ text: reason(e), unapplied: savedNotApplied(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="box">
|
||||
<div className="lrow">
|
||||
<span className="tx">
|
||||
<span className="lb">{t("询问来自外部的文字")}</span>
|
||||
<span className="ds">{t("调用逐字复制了网页或工具结果里的文字时,Auto 和 YOLO 也先问你。只认用户配置;已授权的 MCP 服务器、改写过或编码过的文字不在其内。无人可问时(无头 YOLO),这类调用会被拒绝而不是执行。修改会重建运行时,任务运行期间无法变更。默认关闭。")}</span>
|
||||
</span>
|
||||
<Switch data-action="permissions.ask-on-external-origin" on={on} busy={busy} label={t("询问来自外部的文字")} onClick={() => void flip()} />
|
||||
</div>
|
||||
<SaveNote note={note} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ const REASON: Record<LegacySkipReason, string> = {
|
||||
permission: "没有读取权限",
|
||||
corrupt: "文件已损坏",
|
||||
copy_failed: "复制到新位置时失败",
|
||||
no_project: "没有记录它属于哪个项目,所以没有导入",
|
||||
};
|
||||
|
||||
export function LegacySkips({ skipped }: { skipped: LegacySkip[] }) {
|
||||
|
||||
@@ -129,6 +129,20 @@ function RemoteHostsView({ hub, hosts, runtimes, active, onOpen, onFocus, reload
|
||||
}
|
||||
};
|
||||
|
||||
// The rail lists machines in the book's order, so a step is a placement in the
|
||||
// book relative to the machines shown here, which may skip some that are hidden.
|
||||
const place = async (host: RemoteHost, before: string) => {
|
||||
setBusy("move:" + host.name);
|
||||
try {
|
||||
await hub.placeRemoteHost(host.name, before);
|
||||
await reload();
|
||||
} catch (e) {
|
||||
onError(e);
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
};
|
||||
|
||||
const readBook = async (host: string) => {
|
||||
setBusy("read:" + host);
|
||||
try {
|
||||
@@ -150,7 +164,11 @@ function RemoteHostsView({ hub, hosts, runtimes, active, onOpen, onFocus, reload
|
||||
|
||||
return (
|
||||
<>
|
||||
{hosts.flatMap((host) => {
|
||||
{hosts.flatMap((host, position) => {
|
||||
const moves = {
|
||||
...(position > 0 ? { [-1]: () => void place(host, hosts[position - 1].name) } : {}),
|
||||
...(position < hosts.length - 1 ? { 1: () => void place(host, hosts[position + 2]?.name ?? "") } : {}),
|
||||
};
|
||||
const panes = runtimes.filter((rt) => rt.host === host.name);
|
||||
const tree = trees[host.name];
|
||||
const spaces = remoteProjects(host, tree, panes, scope, needle, listedIds, hideLegacy);
|
||||
@@ -187,7 +205,7 @@ function RemoteHostsView({ hub, hosts, runtimes, active, onOpen, onFocus, reload
|
||||
</button>
|
||||
<RemoteProjectMenu name={ws.name} root={ws.root} host={host.name} defaultRoot={host.workspace} busy={!!busy}
|
||||
onRefresh={() => void readBook(host.name)}
|
||||
onRemove={ws.booked ? () => void drop(host, ws) : undefined} />
|
||||
onRemove={ws.booked ? () => void drop(host, ws) : undefined} onMove={moves} />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
@@ -212,6 +230,7 @@ function RemoteHostsView({ hub, hosts, runtimes, active, onOpen, onFocus, reload
|
||||
onOpen={() => void open(host, session.workspaceRoot || ws.root, session.path)} onFocus={onFocus}
|
||||
onWrite={(kind, row) => void mutations.run(JSON.stringify([host.name, session.path]), kind, row, async () => {
|
||||
if (kind === "pin") await hub.pinSession(session.path, !session.pinned, host.name);
|
||||
else if (kind === "read") await hub.markSessionRead(session.path, host.name);
|
||||
else {
|
||||
if (held && !session.archived) await onClose([held.id]);
|
||||
await hub.archiveSession(session.path, !session.archived, host.name);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { pinToViewport } from "./place";
|
||||
import { StudioIcon } from "./StudioIcon";
|
||||
import { workspaceMenuKeys } from "./WorkspaceOrder";
|
||||
|
||||
export function RemoteProjectMenu({ name, root, host, defaultRoot, busy, onRefresh, onRemove }: {
|
||||
export function RemoteProjectMenu({ name, root, host, defaultRoot, busy, onRefresh, onRemove, onMove }: {
|
||||
name: string;
|
||||
root: string;
|
||||
host: string;
|
||||
@@ -14,6 +14,8 @@ export function RemoteProjectMenu({ name, root, host, defaultRoot, busy, onRefre
|
||||
busy: boolean;
|
||||
onRefresh: () => void;
|
||||
onRemove?: () => void;
|
||||
// Steps this row's machine up or down the book; a direction with no neighbour is absent.
|
||||
onMove?: Partial<Record<-1 | 1, () => void>>;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
@@ -39,6 +41,13 @@ export function RemoteProjectMenu({ name, root, host, defaultRoot, busy, onRefre
|
||||
<button role="menuitem" data-action="remote.read" data-target={host} disabled={busy} onClick={() => { close(); onRefresh(); }}>
|
||||
<StudioIcon name="refresh" /><span>{t("刷新 {name} 上的会话", { name: host })}</span>
|
||||
</button>
|
||||
{onMove && ([-1, 1] as const).map((direction) => (
|
||||
<button key={direction} role="menuitem" data-action="remote-host.move" data-target={host} data-value={direction}
|
||||
disabled={busy || !onMove[direction]} onClick={() => { close(); onMove[direction]?.(); }}>
|
||||
<StudioIcon name="arrow" data-flip={direction === 1 ? "" : undefined} />
|
||||
<span>{t(direction === -1 ? "上移 {name}" : "下移 {name}", { name: host })}</span>
|
||||
</button>
|
||||
))}
|
||||
{onRemove && <button role="menuitem" data-action="remote-host.remove" disabled={busy}
|
||||
onClick={() => { close(); onRemove(); }}><StudioIcon name="close" /><span>{t("从列表移除")}</span><small>{t("不删除文件")}</small></button>}
|
||||
</div>
|
||||
|
||||
@@ -24,7 +24,7 @@ export function RemoteSessionRow({ host, target, session, held, active, busy, pe
|
||||
live: boolean;
|
||||
onOpen: () => void;
|
||||
onFocus: (id: string) => void;
|
||||
onWrite: (kind: "pin" | "archive", row: HTMLElement | null) => void;
|
||||
onWrite: (kind: "pin" | "archive" | "read", row: HTMLElement | null) => void;
|
||||
onDelete: (row: HTMLElement | null) => void;
|
||||
}) {
|
||||
const [at, setAt] = useState<{ x: number; y: number } | null>(null);
|
||||
@@ -36,7 +36,7 @@ export function RemoteSessionRow({ host, target, session, held, active, busy, pe
|
||||
useDismiss(!!at, row, close, menu);
|
||||
useLayoutEffect(() => { if (at && menu.current) pinToViewport(menu.current, at.x, at.y, 12); }, [at]);
|
||||
useEffect(() => { if (at) menu.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus(); }, [at]);
|
||||
const write = (kind: "pin" | "archive") => {
|
||||
const write = (kind: "pin" | "archive" | "read") => {
|
||||
if (pending || busy || kind === "archive" && live) return;
|
||||
setAt(null);
|
||||
onWrite(kind, row.current);
|
||||
@@ -73,6 +73,11 @@ export function RemoteSessionRow({ host, target, session, held, active, busy, pe
|
||||
<button role="menuitem" data-action="session.pin" data-target={target} disabled={!!pending || busy} onClick={() => { close(); write("pin"); }}>
|
||||
<StudioIcon name="pin" /><span>{t(session.pinned ? "取消置顶" : "置顶会话")}</span>
|
||||
</button>
|
||||
{session.unread && (
|
||||
<button role="menuitem" data-action="session.mark-read" data-target={target} disabled={!!pending || busy} onClick={() => { close(); write("read"); }}>
|
||||
<StudioIcon name="check" /><span>{t("标为已读")}</span>
|
||||
</button>
|
||||
)}
|
||||
<button role="menuitem" data-action="session.archive" data-target={target} data-value={session.archived ? "restore" : "archive"}
|
||||
disabled={!!pending || busy || live} onClick={() => { close(); write("archive"); }}>
|
||||
<StudioIcon name="archive" /><span>{t(session.archived ? "取消归档" : "归档会话")}</span>
|
||||
|
||||
@@ -194,7 +194,11 @@ export function CommandMode({
|
||||
return (
|
||||
<div className="sec">
|
||||
<h3>{t("命令执行方式")}</h3>
|
||||
{box.available ? (
|
||||
{box.available && box.platform === "windows" ? (
|
||||
<p className="note">
|
||||
{t("在 Windows 上启用后,命令无法在清单之外创建或改写文件、写注册表;但删除或重命名清单之外的文件、读取文件、联网,以及 ssh-agent、docker 管道和任务计划程序等系统服务不受限制,Everyone 本来就能写的位置和被授权的工具链缓存命令也能写。需要交互式桌面会话,并会在清单里的文件夹上加一条权限项(可用 reasonix sandbox revoke 收回)。")}
|
||||
</p>
|
||||
) : box.available ? (
|
||||
<p className="note">
|
||||
{t("启用沙箱后,命令无法写入清单之外的位置。上方的可写目录清单由操作系统实施,不依赖 agent 自觉遵守。")}
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { reason } from "../i18n/kernel";
|
||||
import { HttpError } from "../port/http_error";
|
||||
import type { AgentPort, ScheduleBoard, ScheduleDraft, SchedulePreview, ScheduleResultView, ScheduleRunView, ScheduleView } from "../port/port";
|
||||
import { Group } from "./Group";
|
||||
|
||||
const EVERY: [number, string][] = [[3600, "每小时"], [7200, "每 2 小时"], [21600, "每 6 小时"], [43200, "每 12 小时"], [86400, "每天"], [604800, "每周"]];
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
const when = (unix: number) => new Date(unix * 1000).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
|
||||
const base = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
|
||||
|
||||
function trigger(s: ScheduleView): string {
|
||||
if (s.atUnix) return t("一次:{at}", { at: when(s.atUnix) });
|
||||
const hit = EVERY.find(([sec]) => sec === s.everySec);
|
||||
return hit ? t(hit[1]) : t("每 {n} 分钟", { n: Math.round((s.everySec ?? 0) / 60) });
|
||||
}
|
||||
|
||||
const STATUS: Record<string, string> = { active: "运行中", paused: "已暂停", expired: "已到期", "circuit-open": "已熔断" };
|
||||
const PAUSE: Record<string, string> = { user: "你暂停了它", consecutive_failures: "连续失败后自动暂停", breaker: "额度保护自动暂停", lifetime_budget: "用完了总额度", corrupt: "记录损坏" };
|
||||
const RUN: Record<string, string> = {
|
||||
succeeded: "已完成", failed: "失败", blocked: "等你决定", budget_stopped: "额度用尽", interrupted: "被中断", skipped: "已跳过", claimed: "即将开始", running: "运行中",
|
||||
};
|
||||
const SKIP: Record<string, string> = { missed: "错过了时间", budget_window: "额度窗口已满", lease_held: "有任务在运行", concurrency: "有任务在运行" };
|
||||
|
||||
/** Read-only tasks a person confirmed, run at a time they chose. A creation is
|
||||
* shown back as a preview with the most it can spend, and only that preview's
|
||||
* own confirmation creates it. A report is the model's text: it is labelled as
|
||||
* such and drawn as plain text, never as markup. */
|
||||
export function ScheduledRuns({ port }: { port: AgentPort }) {
|
||||
const [board, setBoard] = useState<ScheduleBoard | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [readOnly, setReadOnly] = useState(false);
|
||||
const [form, setForm] = useState<ScheduleDraft | null>(null);
|
||||
const [preview, setPreview] = useState<SchedulePreview | null>(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState("");
|
||||
const [result, setResult] = useState<ScheduleResultView | null>(null);
|
||||
|
||||
const [loadError, setLoadError] = useState("");
|
||||
|
||||
// A failed read keeps the last board and says why: the block vanishing would
|
||||
// leave a person who just created a schedule unable to tell whether it exists.
|
||||
const refresh = useCallback(
|
||||
() => port.schedules().then((b) => { setBoard(b); setLoadError(""); }).catch((e) => setLoadError(reason(e))),
|
||||
[port],
|
||||
);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const load = () => { if (alive) void refresh(); };
|
||||
load();
|
||||
const id = setInterval(load, POLL_MS);
|
||||
return () => { alive = false; clearInterval(id); };
|
||||
}, [refresh]);
|
||||
|
||||
const run = useCallback(async (fn: () => Promise<unknown>) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await fn();
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
if (e instanceof HttpError && e.reason?.code === "schedule.editing_disabled") setReadOnly(true);
|
||||
setError(reason(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [refresh]);
|
||||
|
||||
const unreadable = loadError && (
|
||||
<div className="peerform" role="alert">
|
||||
<div className="why">{board ? t("无法刷新定时运行:{reason}(下面是上一次读到的内容)", { reason: loadError }) : t("无法读取定时运行:{reason}", { reason: loadError })}</div>
|
||||
<span className="acts"><button className="act" data-action="schedule.retry" onClick={() => void refresh()}>{t("重试")}</button></span>
|
||||
</div>
|
||||
);
|
||||
if (!board) {
|
||||
return unreadable ? (
|
||||
<Group id="scheduled-runs" title={t("定时运行")} hint={t("按你确认的时间,只读地运行任务:它能读这个文件夹里的文件,不能写任何东西;需要你批准的事会挂起等你,不会替你答复。")}>
|
||||
<div className="box">{unreadable}</div>
|
||||
</Group>
|
||||
) : null;
|
||||
}
|
||||
const locked = busy || readOnly;
|
||||
const name = (s: ScheduleView) => s.label || base(s.workspace);
|
||||
const scheduleName = (r: ScheduleRunView) => { const s = board.schedules.find((x) => x.id === r.scheduleId); return s ? name(s) : r.scheduleId; };
|
||||
const draft = (patch: Partial<ScheduleDraft>) => setForm((f) => (f ? { ...f, ...patch } : f));
|
||||
|
||||
return (
|
||||
<Group id="scheduled-runs" title={t("定时运行")} hint={t("按你确认的时间,只读地运行任务:它能读这个文件夹里的文件,不能写任何东西;需要你批准的事会挂起等你,不会替你答复。")}>
|
||||
<div className="box">
|
||||
{unreadable}
|
||||
<div className="lrow">
|
||||
<span className="tx">
|
||||
<span className="lb">{board.pausedAll ? t("全部定时运行已暂停") : t("定时运行进行中")}</span>
|
||||
<span className="ds">{t("最多 {n} 个;每次至少间隔 {m} 分钟;每天合计最多 {k} 个令牌。", { n: board.policy.maxSchedules, m: board.policy.minIntervalMinutes, k: board.policy.globalTokensDay.toLocaleString() })}</span>
|
||||
</span>
|
||||
{board.pausedAll ? (
|
||||
<button className="act" data-action="schedule.resume-all" disabled={locked} onClick={() => void run(() => port.setSchedulesPaused(false))}>{t("全部恢复")}</button>
|
||||
) : (
|
||||
<button className="act" data-action="schedule.pause-all" disabled={busy} onClick={() => void run(() => port.setSchedulesPaused(true))}>{t("全部暂停")}</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{board.schedules.length === 0 && <div className="peernote">{t("还没有定时运行。")}</div>}
|
||||
<ul className="wa-list" aria-label={t("定时运行列表")}>
|
||||
{board.schedules.map((s) => (
|
||||
<li key={s.id}>
|
||||
<span className="tx">
|
||||
<span className="lb">{name(s)}</span>
|
||||
<span className="ds">{trigger(s)} · {t(STATUS[s.status] ?? s.status)}{s.pausedReason ? " · " + t(PAUSE[s.pausedReason] ?? s.pausedReason) : ""}</span>
|
||||
<span className="ds">{s.workspace} · {s.model}</span>
|
||||
<span className="ds">{t("已用 {a} / {b} 令牌,{d} 到期", { a: s.spentLifetimeTokens.toLocaleString(), b: s.lifetimeTokens.toLocaleString(), d: when(s.expiresAtUnix) })}</span>
|
||||
</span>
|
||||
<span className="acts">
|
||||
{s.status === "active" ? (
|
||||
<button className="act" data-action="schedule.pause" data-target={s.id} disabled={busy} onClick={() => void run(() => port.scheduleAction(s.id, "pause"))}>{t("暂停")}</button>
|
||||
) : (
|
||||
<button className="act" data-action="schedule.resume" data-target={s.id} disabled={locked} onClick={() => void run(() => port.scheduleAction(s.id, "resume"))}>{t("恢复")}</button>
|
||||
)}
|
||||
<button className="act" data-action="schedule.renew" data-target={s.id} disabled={locked} onClick={() => void run(() => port.scheduleAction(s.id, "renew"))}>{t("续期")}</button>
|
||||
{confirmDelete === s.id ? (
|
||||
<button className="act danger" data-action="schedule.delete" data-target={s.id} disabled={busy} onClick={() => void run(async () => { await port.scheduleAction(s.id, "delete"); setConfirmDelete(""); })}>{t("确认删除")}</button>
|
||||
) : (
|
||||
<button className="act ghost" data-action="schedule.delete-ask" data-target={s.id} disabled={busy} onClick={() => setConfirmDelete(s.id)}>{t("删除")}</button>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{board.runs.length > 0 && (
|
||||
<>
|
||||
<div className="peernote"><b>{t("最近的运行")}</b></div>
|
||||
<ul className="wa-list" aria-label={t("最近的运行")}>
|
||||
{board.runs.slice(0, 8).map((r) => (
|
||||
<li key={r.triggerId}>
|
||||
<span className="tx">
|
||||
<span className="lb">{scheduleName(r)} · {t(RUN[r.state] ?? r.state)}</span>
|
||||
<span className="ds">{when(r.slotUnix)} · {r.chargedTokens.toLocaleString()} {t("令牌")}{r.skipReason ? " · " + t(SKIP[r.skipReason] ?? r.skipReason) : ""}</span>
|
||||
</span>
|
||||
{r.state !== "skipped" && r.state !== "claimed" && (
|
||||
<button className="act" data-action="schedule.result" data-target={r.triggerId} disabled={busy} onClick={() => void run(async () => setResult(await port.scheduleResult(r.triggerId)))}>{t("查看结果")}</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="peerform" role="region" aria-label={t("运行结果")}>
|
||||
<div className="peernote"><b>{t("运行结果")}</b> · {when(result.recordedUnix)}</div>
|
||||
<div className="peernote">{t("以下是模型写的内容,只作参考,不是 Reasonix 的说明。")}</div>
|
||||
<pre className="peerbody" data-testid="schedule-report">{result.report}</pre>
|
||||
{result.reportTruncated && <div className="peernote">{t("报告太长,已截断。")}</div>}
|
||||
{result.pending.length > 0 && (
|
||||
<>
|
||||
<div className="peernote"><b>{t("等你决定的事")}</b></div>
|
||||
<div className="peernote">{t("以下是模型写的内容,只作参考,不是 Reasonix 的说明。")}</div>
|
||||
<ul className="wa-list" data-testid="schedule-pending">
|
||||
{result.pending.map((p, i) => (
|
||||
<li key={i}><span className="tx"><span className="lb">{p.summary}</span>{p.detail && <span className="ds">{p.detail}</span>}</span></li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="peernote">{t("这些都没有被执行,也没有被代答。")}</div>
|
||||
</>
|
||||
)}
|
||||
<span className="acts"><button className="act ghost" data-action="schedule.result-close" onClick={() => setResult(null)}>{t("关闭")}</button></span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!form && (
|
||||
<div className="peerform">
|
||||
<span className="acts">
|
||||
<button className="act" data-action="schedule.new" disabled={locked || board.schedules.length >= board.policy.maxSchedules}
|
||||
onClick={() => { setError(""); setPreview(null); setForm({ label: "", everySec: 86400, workspace: "", prompt: "" }); }}>{t("新建定时运行")}</button>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{form && !preview && (
|
||||
<div className="peerform" role="group" aria-label={t("新建定时运行")}>
|
||||
<label className="peernote" htmlFor="sched-folder">{t("文件夹(它只能读这里)")}</label>
|
||||
{board.folders.length === 0 ? (
|
||||
<div className="peernote" id="sched-folder">{t("还没有受信任的项目。先在 Studio 或终端界面里打开一个项目并信任它,再回来选。")}</div>
|
||||
) : (
|
||||
<select id="sched-folder" className="peerfield" data-action-change="schedule.folder" value={form.workspace} disabled={busy}
|
||||
onChange={(e) => draft({ workspace: e.target.value })}>
|
||||
<option value="">{t("选择一个受信任的项目")}</option>
|
||||
{board.folders.map((f) => <option key={f.path} value={f.path}>{f.name} — {f.path}</option>)}
|
||||
</select>
|
||||
)}
|
||||
<label className="peernote" htmlFor="sched-prompt">{t("要做什么")}</label>
|
||||
<textarea id="sched-prompt" className="peerfield" data-action-change="schedule.prompt" value={form.prompt} disabled={busy}
|
||||
onChange={(e) => draft({ prompt: e.target.value })} />
|
||||
<label className="peernote" htmlFor="sched-label">{t("名称(可选)")}</label>
|
||||
<input id="sched-label" className="peerfield" data-action-change="schedule.label" value={form.label} disabled={busy} onChange={(e) => draft({ label: e.target.value })} />
|
||||
<label className="peernote" htmlFor="sched-every">{t("多久一次")}</label>
|
||||
<select id="sched-every" className="peerfield" data-action-change="schedule.every" value={form.everySec ?? 86400} disabled={busy}
|
||||
onChange={(e) => draft({ everySec: Number(e.target.value) })}>
|
||||
{EVERY.map(([sec, label]) => <option key={sec} value={sec} disabled={sec < board.policy.minIntervalMinutes * 60}>{t(label)}</option>)}
|
||||
</select>
|
||||
<span className="acts">
|
||||
<button className="act ghost" data-action="schedule.cancel" disabled={busy} onClick={() => setForm(null)}>{t("取消")}</button>
|
||||
<button className="act" data-action="schedule.preview" data-primary="" disabled={busy || !form.workspace.trim() || !form.prompt.trim()}
|
||||
onClick={() => void run(async () => setPreview(await port.previewSchedule({ ...form, workspace: form.workspace.trim(), prompt: form.prompt.trim() })))}>{t("预览")}</button>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{form && preview && (
|
||||
<div className="peerform" role="group" aria-label={t("确认创建")}>
|
||||
<div className="peernote"><b>{t("请确认")}</b></div>
|
||||
<ul className="wa-list">
|
||||
<li><span className="tx"><span className="lb">{t("第一次运行")}</span><span className="ds">{when(preview.firstRunUnix)}</span></span></li>
|
||||
<li><span className="tx"><span className="lb">{t("文件夹")}</span><span className="ds">{preview.workspace} {t("(只读:它能读这里的文件,不写任何东西)")}</span></span></li>
|
||||
<li><span className="tx"><span className="lb">{t("模型")}</span><span className="ds">{preview.model}</span></span></li>
|
||||
<li><span className="tx"><span className="lb">{t("要做什么")}</span><span className="ds">{preview.prompt}</span></span></li>
|
||||
<li><span className="tx"><span className="lb">{t("每次最多")}</span><span className="ds">{t("{a} 令牌,{b} 步,{c} 秒", { a: preview.perRunTokens.toLocaleString(), b: preview.perRunSteps, c: preview.perRunWallSec })}</span></span></li>
|
||||
<li><span className="tx"><span className="lb">{t("总共最多")}</span><span className="ds">{t("每天 {a} 令牌,一共 {b} 令牌,{d} 自动到期", { a: preview.perDayMax.toLocaleString(), b: preview.lifetimeTokens.toLocaleString(), d: when(preview.expiresAtUnix) })}</span></span></li>
|
||||
</ul>
|
||||
<div className="peernote">{t("需要你批准的事会挂起等你,不会替你答复。")}</div>
|
||||
<span className="acts">
|
||||
<button className="act ghost" data-action="schedule.back" disabled={busy} onClick={() => setPreview(null)}>{t("返回修改")}</button>
|
||||
<button className="act" data-action="schedule.create" data-primary="" disabled={locked}
|
||||
onClick={() => void run(async () => { await port.createSchedule({ ...form, workspace: form.workspace.trim(), prompt: form.prompt.trim() }, preview.confirm); setForm(null); setPreview(null); })}>{t("确认创建")}</button>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{readOnly && <div className="peernote" role="status">{t("这些设置现在是只读的:这个窗口没有被授予编辑权限。")}</div>}
|
||||
{error && <div className="why" role="alert">{error}</div>}
|
||||
</div>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
@@ -10,9 +10,9 @@ afterEach(cleanup);
|
||||
|
||||
const session = (over: Partial<TreeSession> = {}): TreeSession => ({ path: "/s/a.jsonl", name: "a", title: "第一个", turns: 1, ...over });
|
||||
|
||||
function draw(s: TreeSession, extra: { live?: boolean; pinned?: boolean; exporting?: boolean; naming?: boolean; branch?: boolean } = {}) {
|
||||
function draw(s: TreeSession, extra: { markRead?: () => void; live?: boolean; pinned?: boolean; exporting?: boolean; naming?: boolean; branch?: boolean } = {}) {
|
||||
const on = { onPin: vi.fn(), onRename: vi.fn(), onAutoName: vi.fn(), onPause: vi.fn(), onClose: vi.fn(), onArchive: vi.fn(), onCopyInfo: vi.fn(), onExport: vi.fn(), onDelete: vi.fn(), onBranch: vi.fn() };
|
||||
render(<SessionMenu session={s} label="第一个" live={extra.live ?? false} pinned={extra.pinned ?? false} exporting={extra.exporting ?? false} autoNaming={extra.naming ?? false} {...on} onBranch={extra.branch === false ? undefined : on.onBranch} />);
|
||||
render(<SessionMenu session={s} label="第一个" live={extra.live ?? false} pinned={extra.pinned ?? false} exporting={extra.exporting ?? false} autoNaming={extra.naming ?? false} {...on} onBranch={extra.branch === false ? undefined : on.onBranch} onMarkRead={extra.markRead} />);
|
||||
return on;
|
||||
}
|
||||
|
||||
@@ -63,3 +63,13 @@ it("shows naming in progress and cannot be started twice", () => {
|
||||
draw(session(), { naming: true });
|
||||
expect((screen.getByRole("menuitem", { name: /命名中/ }) as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("offers mark as read only where the row is unread, and reports the choice", async () => {
|
||||
draw(session());
|
||||
expect(screen.queryByRole("menuitem", { name: /标为已读/ })).toBeNull();
|
||||
cleanup();
|
||||
const markRead = vi.fn();
|
||||
draw(session({ unread: true }), { markRead });
|
||||
await userEvent.click(screen.getByRole("menuitem", { name: /标为已读/ }));
|
||||
expect(markRead).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -13,6 +13,8 @@ export interface SessionMenuProps {
|
||||
exporting: boolean;
|
||||
autoNaming: boolean;
|
||||
onPin: () => void;
|
||||
/** Absent where the row is not unread. */
|
||||
onMarkRead?: () => void;
|
||||
onRename: () => void;
|
||||
onAutoName: () => void;
|
||||
onPause: () => void;
|
||||
@@ -33,7 +35,7 @@ export interface SessionMenuProps {
|
||||
* sidebar's clipping cannot cut it. Every action closes the menu itself:
|
||||
* the parent's handlers do that, this only says which one was chosen. */
|
||||
export const SessionMenu = forwardRef<HTMLDivElement, SessionMenuProps>(function SessionMenu(
|
||||
{ session, label, live, pinned, exporting, autoNaming, onPin, onRename, onAutoName, onPause, onClose, onArchive, onBranch, onCopyInfo, onExport, onDelete, onMove, canMove, onMoveTo },
|
||||
{ session, label, live, pinned, exporting, autoNaming, onPin, onMarkRead, onRename, onAutoName, onPause, onClose, onArchive, onBranch, onCopyInfo, onExport, onDelete, onMove, canMove, onMoveTo },
|
||||
ref,
|
||||
) {
|
||||
const target = session.path;
|
||||
@@ -47,6 +49,11 @@ export const SessionMenu = forwardRef<HTMLDivElement, SessionMenuProps>(function
|
||||
<button role="menuitem" data-action="session.pin" data-target={target} onClick={onPin}>
|
||||
<StudioIcon name="pin" /><span>{pinned ? t("取消置顶") : t("置顶会话")}</span>
|
||||
</button>
|
||||
{onMarkRead && (
|
||||
<button role="menuitem" data-action="session.mark-read" data-target={target} onClick={onMarkRead}>
|
||||
<StudioIcon name="check" /><span>{t("标为已读")}</span>
|
||||
</button>
|
||||
)}
|
||||
{onMove && canMove && ([-1, 1] as const).map((direction) => (
|
||||
<button key={direction} role="menuitem" data-action="session.move" data-target={target} data-value={direction}
|
||||
disabled={direction === -1 ? !canMove.up : !canMove.down} onClick={() => onMove(direction)}>
|
||||
|
||||
@@ -7,13 +7,12 @@ import { useRuntimeReload } from "./RuntimeReload";
|
||||
import type { AccountState, AgentPort, Appearance as Look, CapabilityScope, McpEntry, ModelEntry, PluginPackage, SessionStatus, SkillEntry } from "../port/port";
|
||||
import { useSettingsSearch } from "./useSettingsSearch";
|
||||
import { bytes, tokens as fmtTokens } from "../i18n/format";
|
||||
import { SECTION_NAME } from "./prefsnav";
|
||||
import { SECTION_NAME, type Section } from "./prefsnav";
|
||||
import { SettingsNav } from "./SettingsNav";
|
||||
import { Group, SCOPE_SAID } from "./Group";
|
||||
import { PlanApproval, DefaultMode } from "./PlanApproval";
|
||||
import { PeersSection } from "./PeersSection";
|
||||
import { SessionCoordination } from "./SessionCoordination";
|
||||
import type { Section } from "./prefsnav";
|
||||
import { AddServer } from "./AddServer";
|
||||
import { PhoneAccess } from "./PhoneAccess";
|
||||
import { PhoneReminders } from "./PhoneReminders";
|
||||
@@ -30,8 +29,10 @@ import { Switch } from "./Switch";
|
||||
import { ServerRow } from "./ServerRow";
|
||||
import { SkillGroups } from "./SkillRow";
|
||||
import { Hooks } from "./Hooks";
|
||||
import { ScheduledRuns } from "./ScheduledRuns";
|
||||
import { Network } from "./Network";
|
||||
import { Shell as ShellPicker } from "./Shell";
|
||||
import { ExternalOrigin } from "./ExternalOrigin";
|
||||
import { Rules, ToolList } from "./Rules";
|
||||
import { ConfigTrouble } from "./ConfigTrouble";
|
||||
import { Compaction } from "./Compaction";
|
||||
@@ -574,6 +575,12 @@ export function Settings({ hub, onError, port, networkPort, localWorkspacePort,
|
||||
</div>
|
||||
<p className="note">{approvalNote(status?.toolApprovalMode)}</p>
|
||||
</Group>
|
||||
<Group id="external-origin"
|
||||
title={t("外部文字")}
|
||||
hint={t("网页和工具结果里的文字可能是别人写给 agent 的指令。开启后,照抄这些文字的调用先问你。")}
|
||||
>
|
||||
<ExternalOrigin port={port} onChanged={onChanged} />
|
||||
</Group>
|
||||
<Group id="plan-approval"
|
||||
title={t("计划批准")}
|
||||
hint={t("计划模式提交计划后,默认等你点批准才开始执行。长时间无人值守的任务可以改成自动批准。")}
|
||||
@@ -612,12 +619,13 @@ export function Settings({ hub, onError, port, networkPort, localWorkspacePort,
|
||||
{at === "peers" && <PeersSection port={port} hub={hub} />}
|
||||
|
||||
{at === "hooks" && (
|
||||
<Group id="hooks"
|
||||
title={t("自动化")}
|
||||
hint={t("在 agent 执行任务前后运行自定义命令。这些命令在本机以当前用户权限运行;可拦截 agent 的两个事件已在下方标出。")}
|
||||
>
|
||||
<Hooks port={port} onChanged={afterExtChange} />
|
||||
</Group>
|
||||
<>
|
||||
<Group id="hooks" title={t("自动化")}
|
||||
hint={t("在 agent 执行任务前后运行自定义命令。这些命令在本机以当前用户权限运行;可拦截 agent 的两个事件已在下方标出。")}>
|
||||
<Hooks port={port} onChanged={afterExtChange} />
|
||||
</Group>
|
||||
<ScheduledRuns port={port} />
|
||||
</>
|
||||
)}
|
||||
{at === "ext" && (
|
||||
<>
|
||||
|
||||
@@ -256,7 +256,7 @@ function WorkspacesView({ hub, tree, treeRead, answered = null, runtimes, active
|
||||
const mutate = (session: TreeSession, kind: SessionMutation) => {
|
||||
if (sessionMenu) dismissMenu();
|
||||
const row = [...(treeKeys.ref.current?.querySelectorAll<HTMLElement>('[role="treeitem"]') ?? [])].find((el) => el.dataset.target === session.path) ?? null;
|
||||
void mutations.run(session.path, kind, row, () => kind === "pin" ? onPin(session.path) : onArchive(session.path, !session.archived, session.runtimeId));
|
||||
void mutations.run(session.path, kind, row, () => kind === "read" ? hub.markSessionRead(session.path).then(reload) : kind === "pin" ? onPin(session.path) : onArchive(session.path, !session.archived, session.runtimeId));
|
||||
};
|
||||
const archive = (session: TreeSession) => mutate(session, "archive");
|
||||
|
||||
@@ -658,6 +658,7 @@ function WorkspacesView({ hub, tree, treeRead, answered = null, runtimes, active
|
||||
exporting={busy === "export:" + session.path}
|
||||
autoNaming={busy === "name:" + session.path}
|
||||
onPin={() => mutate(session, "pin")}
|
||||
onMarkRead={session.unread ? () => mutate(session, "read") : undefined}
|
||||
onRename={() => { setSessionMenu(""); onRename(session.path, session.title || session.name); }}
|
||||
onAutoName={() => void autoName(session)}
|
||||
onPause={() => { onPause(session.runtimeId!); setSessionMenu(""); }}
|
||||
|
||||
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user