diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00c6a5f..c125ee8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,19 @@
# Changelog
+## v0.12.0 · 2026-11-20
+
+The app's side of starting and stopping cleanly, and two fixes to agent tabs and to start-up on macOS.
+
+- On Windows the engine is tied to the app through the system: an app ended in Task Manager, or any other way, takes its engine with it at once.
+- When the app cannot start its engine, the message now says what went wrong, shows the engine's last lines and its exit code, and gives the full path of the engine's log. A copy that is already open is still named as the likely cause when that is the reason.
+- The app waits at most 90 seconds for its engine to be ready, then says so instead of waiting without end.
+- On Windows the engine is built with no console window beside the app. `FORMENCODER_ENGINE_WINDOWED=0` at build time keeps the console.
+- Fixed: two Antigravity tabs open at once each keep their own connection to the app, and closing one no longer cuts off the other. Each tab works in a folder of its own.
+- Fixed, on macOS: an engine left over from an earlier start that had ended but was not yet cleaned up by the system kept the next start waiting and then refused it. It now counts as gone.
+- The Agents panel's guide now says that Codex, Cursor and Antigravity each get a button of their own when they are on this computer.
+- Not run for this release: Windows, macOS, the desktop app (its Windows code was type-checked here, not built or run) and a packaged engine. The checks ran on Linux from source, with stand-ins for the agent programs.
+- The version string inside the three browser demo bundles was not changed in this release; they still say 0.11.0.
+
## v0.11.0 · 2026-11-20
Starting and stopping cleanly, on Windows too: the engine's side. One engine of the app per data folder, an engine that leaves when its app is gone, a log file, and a start failure that is said before the app closes. The app's side of the same work (below, under "Not in this release") is still to come.
diff --git a/README.md b/README.md
index ee8425a..997dec3 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
-
+
@@ -102,7 +102,7 @@ FormEncoder loads extensions made to the Form Extension Contract (API 1): FormPo
## Under the hood
-Version 0.11.0 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell
+Version 0.12.0 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell
- **Engine:** seven `fencoder` Rust crates in `native/`, loaded by the Python service as the `fe_core` extension.
- **FFmpeg:** a pinned LGPL build, run as a separate program and never linked.
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 69b6ffe..d6f0dc1 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -396,3 +396,32 @@ Refers to `backend/app/routers/terminal.py` (`pump`) · kind: fix · logged: unr
- In `pump`, a hand-over of output that raises `RuntimeError` ends the read loop, and the hand-over of the end notice ignores the same error. The wait for the child stays where it was, so the child is still reaped.
- Seen: the whole backend suite with this change, 279 passed, and its output held no `Event loop is closed` line. Whether the line shows on this machine without the change was not looked at.
+
+## An engine that has ended but was not yet collected counts as gone where there is no /proc (unreleased, after 0.11.0)
+
+Refers to `backend/app/core/startup.py` (`finished`, `gone_by`), `backend/tests/test_startup.py` · kind: fix · logged: unreleased · 2026-11-20
+
+- Why: FormCut's macOS job failed three start-up tests with "could not stop an engine that was left running". `end` had ended the holder, but `gone_by` kept seeing it: `_alive_posix` asks `kill(pid, 0)`, which still answers for a process that has ended and that its parent has not collected, and it tells such a process apart only by reading `/proc`, which macOS does not have. This file is the same one, so the same wait would run out here.
+- `finished(pid)` asks `ps -o stat= -p ` where there is no `/proc` (never on Windows, never on Linux) and answers true for a state that starts with `Z`. `gone_by` stops waiting when the process is not alive or is finished. `alive` is unchanged, so the two second watch on the app starts no program.
+- Seen on Linux with `PROC` pointed at a folder that does not exist: with `finished` answering false, `claim` on a holder whose shell is gone is refused with that sentence; with the change it replaces the holder. One new test, `test_startup.py` 16 passed. Not run on macOS.
+
+## Each Antigravity tab has a folder of its own (unreleased, after 0.11.0)
+
+Refers to `backend/app/services/agent_programs.py` (`TAB_FOLDERS`, `TAB_GUIDE`, `tab_folder`, `_servers`, `write_tab_entry`, `clear_tab_folder`), `backend/app/routers/terminal.py` (`Hub.open`, `Term._start`, `Term._forget`), `backend/tests/test_dock_engine.py` · kind: fix · logged: unreleased · 2026-11-20
+
+- Why: every Antigravity tab ran in the agent workspace and wrote its entry `formencoder_tab` into that folder's `.agents/mcp_config.json`. A second tab replaced the first one's entry, and closing the second removed the entry while the first tab was still open (the "known limit" of the entry above).
+- Each tab now runs in `[data folder]/agent-tabs/antigravity/[engine process id]-[tab id]`. The process id is in the name because tab ids start again at `t1` in every engine, and a headless engine may share the data folder with the app's engine. The entry is written there, `agy` is started there, and a `cwd` in the request is still ignored for this kind.
+- The agent workspace is still prepared first (the entry's command is the workspace's `formencoder` shim), and its `AGENTS.md` is copied into the tab's folder, so the program finds the same guide it found when it ran in the workspace. Nothing read says whether Antigravity reads `AGENTS.md`; the copy costs nothing if it does not.
+- When the program ends or the tab closes: the entry is taken out as before (only while it carries the tab's token); then the MCP file is removed if it holds nothing else, the `.agents` folder if it is empty, the guide if it is still the copy, and the folder if it is empty. A folder that holds anything else is kept. `clear_tab_folder` does nothing for a folder that is not two levels below a folder named `agent-tabs`. A restart writes the entry again and so makes the folder again.
+- `_servers` took a file that is not JSON as a `ValueError` that nothing caught (a bare 500, and the tab's token stayed issued). It is now the same `OSError` sentence as a file of the wrong shape, which the tab route answers as "The program could not start: [path] is not an MCP servers file formencoder can read, so it was left alone".
+- The workspace's own `.agents/mcp_config.json`, if a person has one, is no longer read or written by a tab.
+- Seen with the stand-in `agy` of the test folder: one tab has its entry at mode 0600 and the guide in its own folder, the stand-in prints with the token present, and after close the folder is gone and a seeded file in the workspace is byte for byte the seed; two tabs open at once hold a token each in a file each, closing the second leaves the first one's entry and its token still runs a changing call unasked, closing the first removes its folder. `test_dock_engine.py` and `test_dock_module.py`: 28 passed.
+- Not run: a real `agy`, Windows (a folder that is still a running program's working folder cannot be removed there, so an empty folder may stay behind), macOS.
+
+## A Windows engine is packaged with no console window (unreleased, after 0.11.0)
+
+Refers to `setup/freeze_backend`, `setup/freeze_backend.bat` · kind: change · logged: unreleased · 2026-11-20
+
+- Why: the owner's decision for the family (D3): a Windows engine is built with no console window, as FormWeb's is. FormEncoder's freeze scripts had no switch, so the switch is added with its default turned round: on Windows PyInstaller gets `--noconsole` unless `FORMENCODER_ENGINE_WINDOWED=0`. The bash script adds it only where `fe_os` says windows; macOS and Linux builds are unchanged.
+- The shell reads the engine's output through pipes, which a program with no console still gets. Where it has none at all, `formencoder_engine.py` already puts `os.devnull` in place of a missing stdin, stdout or stderr before anything else runs.
+- Seen: `--selfcheck` run from the source with `sys.stdout`, `sys.stderr` and `sys.stdin` set to None exits 0. `bash -n setup/freeze_backend` clean; the `.bat` was read, not run. Not run: no Windows build has shown the windowed engine.
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index ae6db5f..ea370a8 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1 +1 @@
-__version__ = "0.11.0"
+__version__ = "0.12.0"
diff --git a/backend/app/core/startup.py b/backend/app/core/startup.py
index 762640f..65f21bc 100644
--- a/backend/app/core/startup.py
+++ b/backend/app/core/startup.py
@@ -194,9 +194,26 @@ def same(pid: int, born: float) -> bool:
return alive(pid) and (not born or (seen > 0 and abs(seen - born) <= SLACK))
+def finished(pid: int) -> bool:
+ if WINDOWS or os.path.isdir(PROC):
+ return False
+ try:
+ told = subprocess.run(
+ ["ps", "-o", "stat=", "-p", str(pid)],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ timeout=END_WAIT,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+ return told.stdout.strip().startswith("Z")
+
+
def gone_by(pid: int, seconds: float) -> bool:
until = time.monotonic() + seconds
- while alive(pid):
+ while alive(pid) and not finished(pid):
if time.monotonic() >= until:
return False
time.sleep(STEP)
diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py
index b946763..e72faeb 100644
--- a/backend/app/routers/terminal.py
+++ b/backend/app/routers/terminal.py
@@ -210,7 +210,7 @@ def _start(self, cols: int, rows: int) -> None:
self.token = consent.issue() if self.trusted else None
if self.kind == "antigravity" and self.token:
try:
- finder.write_tab_entry(self.cwd, _tab_entry(self.base, self.token))
+ finder.write_tab_entry(self.cwd, _tab_entry(self.base, self.token), workspace.root() / finder.TAB_GUIDE)
except OSError:
consent.revoke(self.token)
self.token = None
@@ -292,6 +292,7 @@ def close(self) -> None:
def _forget(self) -> None:
if self.kind == "antigravity":
finder.remove_tab_entry(self.cwd, self.token)
+ finder.clear_tab_folder(self.cwd, workspace.root() / finder.TAB_GUIDE)
def row(self) -> dict:
return {"id": self.id, "title": self.title, "cwd": self.cwd, "created": self.created, "exited": self.exited, "owned": self.owned, "offset": self.offset, "opener": self.opener,
@@ -325,7 +326,9 @@ def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: s
kind: str = "shell", window: bool = False, argv: list[str] | None = None, program: str | None = None) -> Term:
self._n += 1
tid = f"t{self._n}"
- place = cwd or str(workspace.ensure())
+ own = kind == "antigravity"
+ home = workspace.ensure() if own or not cwd else None
+ place = str(finder.tab_folder(kind, tid)) if own else cwd or str(home)
term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted, kind, window, argv, program)
self.terms[tid] = term
if run:
diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py
index b93ba90..b6fdce4 100644
--- a/backend/app/services/agent_programs.py
+++ b/backend/app/services/agent_programs.py
@@ -4,6 +4,7 @@
import os
from pathlib import Path
+from ..core import config
from . import agent_lookup
PROGRAMS = {
@@ -20,6 +21,8 @@
}
OTHERWISE = ""
TAB_ENTRY = "formencoder_tab"
+TAB_FOLDERS = "agent-tabs"
+TAB_GUIDE = "AGENTS.md"
TOKEN_VAR = "FORMENCODER_AGENT_TOKEN"
@@ -54,12 +57,19 @@ def program(kind: str) -> str | None:
return found.path if found.state == "runs" else None
+def tab_folder(kind: str, tab: str) -> Path:
+ return config.data_dir() / TAB_FOLDERS / kind / f"{os.getpid()}-{tab}"
+
+
def _mcp_file(folder: str | os.PathLike) -> Path:
return Path(folder) / ".agents" / "mcp_config.json"
def _servers(path: Path) -> dict:
- data = json.loads(path.read_text(encoding="utf-8") or "{}") if path.exists() else {}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8") or "{}") if path.exists() else {}
+ except ValueError:
+ data = None
if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict):
raise OSError(f"{path} is not an MCP servers file formencoder can read, so it was left alone")
return data
@@ -73,11 +83,31 @@ def _replace(path: Path, data: dict) -> None:
os.replace(part, path)
-def write_tab_entry(folder: str | os.PathLike, entry: dict) -> None:
+def write_tab_entry(folder: str | os.PathLike, entry: dict, guide: str | os.PathLike | None = None) -> None:
path = _mcp_file(folder)
data = _servers(path)
data.setdefault("mcpServers", {})[TAB_ENTRY] = entry
_replace(path, data)
+ if guide and Path(guide).is_file():
+ (Path(folder) / TAB_GUIDE).write_text(Path(guide).read_text(encoding="utf-8"), encoding="utf-8")
+
+
+def clear_tab_folder(folder: str | os.PathLike, guide: str | os.PathLike | None = None) -> None:
+ base = Path(folder)
+ if base.parent.parent.name != TAB_FOLDERS:
+ return
+ path = _mcp_file(base)
+ try:
+ if path.exists() and _servers(path) == {"mcpServers": {}}:
+ path.unlink()
+ if path.parent.is_dir():
+ path.parent.rmdir()
+ copy = base / TAB_GUIDE
+ if copy.is_file() and guide and Path(guide).is_file() and copy.read_text(encoding="utf-8") == Path(guide).read_text(encoding="utf-8"):
+ copy.unlink()
+ base.rmdir()
+ except (OSError, ValueError):
+ return
def remove_tab_entry(folder: str | os.PathLike, token: str | None) -> None:
diff --git a/backend/tests/test_dock_engine.py b/backend/tests/test_dock_engine.py
index d671f35..bf8f29d 100644
--- a/backend/tests/test_dock_engine.py
+++ b/backend/tests/test_dock_engine.py
@@ -158,26 +158,81 @@ def test_an_agent_tab_runs_the_program_with_its_own_token_which_dies_with_the_ta
@POSIX_ONLY
-def test_an_antigravity_tab_has_its_entry_in_the_workspace_file_until_it_closes(client, stand_ins):
+def test_an_antigravity_tab_has_its_entry_in_a_folder_of_its_own_until_it_closes(client, stand_ins):
+ from pathlib import Path
+
from app.agent import consent, workspace
+ from app.core import config
from app.routers.terminal import hub
- path = workspace.ensure() / ".agents" / "mcp_config.json"
+ shared = workspace.ensure() / ".agents" / "mcp_config.json"
seed = json.dumps({"mcpServers": {"other": {"command": "/bin/true", "args": []}}, "theme": "kept"}, indent=2) + "\n"
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(seed, encoding="utf-8")
+ shared.parent.mkdir(parents=True, exist_ok=True)
+ shared.write_text(seed, encoding="utf-8")
row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "antigravity", "cwd": "/tmp"}).json()
term = hub.terms[row["id"]]
- assert row["kind"] == "antigravity" and term.cwd == str(workspace.root())
+ folder = Path(term.cwd)
+ assert row["kind"] == "antigravity" and folder == config.data_dir() / "agent-tabs" / "antigravity" / f"{os.getpid()}-{row['id']}"
+ path = folder / ".agents" / "mcp_config.json"
held = json.loads(path.read_text(encoding="utf-8"))
- assert list(held["mcpServers"]) == ["other", "formencoder_tab"] and held["theme"] == "kept" and held["mcpServers"]["other"] == {"command": "/bin/true", "args": []}
+ assert list(held["mcpServers"]) == ["formencoder_tab"]
entry = held["mcpServers"]["formencoder_tab"]
assert entry["command"] == workspace.mcp_command()[0] and entry["args"] == ["mcp", "--profile", "core"]
assert entry["env"]["FORMENCODER_AGENT_TOKEN"] == term.token and consent.inapp(term.token)
assert path.stat().st_mode & 0o777 == 0o600
+ assert (folder / "AGENTS.md").read_text(encoding="utf-8") == (workspace.root() / "AGENTS.md").read_text(encoding="utf-8")
+ assert "token-present=yes" in printed(client, row["id"], "token-present")
token = term.token
client.delete(f"/api/terminal/sessions/{row['id']}", headers=LOCAL)
- assert path.read_text(encoding="utf-8") == seed and not consent.inapp(token)
+ assert not folder.exists() and not consent.inapp(token)
+ assert shared.read_text(encoding="utf-8") == seed
+ shared.unlink()
+
+
+@POSIX_ONLY
+def test_two_antigravity_tabs_keep_an_entry_each_and_closing_one_leaves_the_others(client, stand_ins):
+ from pathlib import Path
+
+ from app.agent import consent
+ from app.routers.terminal import hub
+
+ first = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "antigravity"}).json()
+ second = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "antigravity"}).json()
+ one, two = hub.terms[first["id"]], hub.terms[second["id"]]
+ files = [Path(term.cwd) / ".agents" / "mcp_config.json" for term in (one, two)]
+ assert one.cwd != two.cwd and one.token != two.token
+
+ def token_in(path):
+ return json.loads(path.read_text(encoding="utf-8"))["mcpServers"]["formencoder_tab"]["env"]["FORMENCODER_AGENT_TOKEN"]
+
+ assert [token_in(path) for path in files] == [one.token, two.token]
+ kept = one.token
+ client.delete(f"/api/terminal/sessions/{second['id']}", headers=LOCAL)
+ assert not Path(two.cwd).exists()
+ assert token_in(files[0]) == kept and consent.inapp(kept) and not changing_call(client, kept).get("isError")
+ client.delete(f"/api/terminal/sessions/{first['id']}", headers=LOCAL)
+ assert not Path(one.cwd).exists() and not consent.inapp(kept)
+
+
+def test_a_tab_folder_that_holds_something_else_is_kept_and_a_file_that_is_not_json_gives_a_sentence(tmp_path):
+ from app.services import agent_programs as finder
+
+ folder = tmp_path / "agent-tabs" / "antigravity" / "1-t1"
+ finder.write_tab_entry(folder, {"env": {finder.TOKEN_VAR: "abc"}})
+ (folder / "notes.txt").write_text("mine")
+ finder.remove_tab_entry(folder, "abc")
+ finder.clear_tab_folder(folder)
+ assert sorted(p.name for p in folder.iterdir()) == ["notes.txt"]
+ elsewhere = tmp_path / "somewhere" / "else" / "t1"
+ finder.write_tab_entry(elsewhere, {"env": {finder.TOKEN_VAR: "abc"}})
+ finder.remove_tab_entry(elsewhere, "abc")
+ finder.clear_tab_folder(elsewhere)
+ assert (elsewhere / ".agents" / "mcp_config.json").is_file()
+ (folder / ".agents").mkdir()
+ (folder / ".agents" / "mcp_config.json").write_text("{not json")
+ with pytest.raises(OSError, match="is not an MCP servers file formencoder can read, so it was left alone"):
+ finder.write_tab_entry(folder, {"env": {}})
+ assert (folder / ".agents" / "mcp_config.json").read_text() == "{not json"
def test_agents_install_adds_formencoder_to_antigravity_and_leaves_a_foreign_entry_alone(tmp_path):
diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py
index 407e5f8..03ba397 100644
--- a/backend/tests/test_startup.py
+++ b/backend/tests/test_startup.py
@@ -122,6 +122,23 @@ def test_a_lock_that_names_a_process_which_is_not_the_engine_is_replaced_and_the
stop(other, mine)
+def test_a_holder_that_ended_but_was_not_collected_counts_as_gone_where_there_is_no_proc(tmp_path, monkeypatch):
+ from app.core import startup
+
+ engine, shell, mine = stand_in(), stand_in(), stand_in()
+ try:
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps(record(startup, engine, shell)))
+ stop(shell)
+ monkeypatch.setattr(startup, "PROC", str(tmp_path / "no-proc"))
+ assert startup.finished(engine.pid) is False
+ path, replaced = startup.claim(tmp_path, mine.pid)
+ assert replaced == engine.pid
+ assert startup.finished(engine.pid) is True
+ assert json.loads(path.read_text())["pid"] == os.getpid()
+ finally:
+ stop(engine, shell, mine)
+
+
def test_the_two_ways_of_reading_a_start_time_agree(monkeypatch):
from app.core import startup
diff --git a/form-functions.json b/form-functions.json
index 93e9013..c522f9b 100644
--- a/form-functions.json
+++ b/form-functions.json
@@ -2,7 +2,7 @@
"format": "form-functions",
"format_version": 1,
"app": "formencoder",
- "app_version": "0.11.0",
+ "app_version": "0.12.0",
"functions": [
{
"id": "encode",
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index 90089ad..c66db8e 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -290,3 +290,23 @@ Refers to `src/dock/` (16 entries, copied from FormVis ddc893ae, never edited he
- Known differences in the DOM that come with the module, not seen in a window here: every control carries `data-dock-part`, agent tabs carry `is-program`.
- Checked: `tsc --noEmit` with the app's flags clean; `vite build` into a scratch folder completed. Not looked at in a browser in this change: the fourth button, its menu row and the tab were not seen in a window. The engine side was run with a stand-in `agy` (see `backend/HASHOUT_LOG.md`).
- Words, with the texts that name the supported programs: the Agents panel's policy line in `src/panels/agents.ts` says Claude Code, Codex, Cursor and Antigravity tabs are trusted. The README's picture of the Agents panel still shows three set-up buttons, so its description was left as it is.
+
+## The shell's Windows side: the engine in a job, a start failure that says why, a limit on the wait (unreleased, after 0.11.0)
+
+Refers to `src-tauri/src/main.rs` (`EngineStep`, `start_limit`, `kill_backend`, `engine_failed`, the setup closure), `src-tauri/src/engine_start.rs`, `src-tauri/src/win_job.rs`, `src-tauri/Cargo.toml`, `src-tauri/Cargo.lock` · kind: feature · logged: unreleased · 2026-11-20
+
+- Why: 0.11.0 shipped the engine side of the Windows work only. A Windows engine outlived an app that was ended from the Task Manager, a failed start said one fixed sentence, and the wait for the engine's address had no limit.
+- The way taken is FormVis's: the engine is still started through tauri-plugin-shell's sidecar, so the job takes the process by its id. `win_job.rs` (Windows only) makes one job object with kill-on-close, `hold_pid` opens the engine's process with `PROCESS_SET_QUOTA | PROCESS_TERMINATE` and assigns it, and `end` ends the job before the child is killed. When the app ends any way at all the job's last handle closes and Windows ends the engine. If the job cannot be made or the assign fails, the start goes on as before.
+- The shell gives the engine its own process id in `FORMENCODER_PARENT_PID`, the name `app/core/startup.py` already watches (`engine_start::SHELL_ENV`).
+- The engine's events go through one channel with the timers: 90 seconds for the address (`ADDRESS_WAIT`, the owner's D1), then 10 seconds for the window key (the grace the old loop had), and one second after the engine ends for its last lines to arrive. `Tail` keeps the last 12 lines, at most 300 characters each, drops control characters and every line that carries the window key.
+- A failed start shows one error dialog titled FormEncoder: the sentence for what went wrong (program missing, could not be started, stopped with its code, the busy code 2 with the old advice to use the open window, a wait that ran out with its length, the window that could not be built), the engine's last lines or "The engine wrote nothing before that.", and the log's full path. The path is worked out the way `app/core/config.py` and `app/core/runtime.py` do it: `FORMENCODER_DATA_DIR` (a leading `~` is the home folder), else `Formencoder` in the home folder (`USERPROFILE` on Windows, as Python's `Path.home()` reads it), then `logs/formencoder-engine.log`. The splash closes after the dialog, so a window is open until then.
+- `windows-sys` 0.61.2, the version 28 packages in the lock already use, is the only new crate; the one line in the shell's own entry of `Cargo.lock` was put in by hand and matched byte for byte by `cargo update --workspace --offline` on the old lock in a scratch copy.
+- Checked: the two new files in the scratch crate, `cargo check --target x86_64-pc-windows-msvc` clean, `cargo test` 5 passed (the sentences, the tail, the log path, the home folder). Not run: the shell itself was not compiled (no webview packages here), nothing on Windows or macOS.
+
+## The shared dock is module 2.2.1 (unreleased, after 0.11.0)
+
+Refers to `frontend/src/dock/` (every file, from FormVis commit 23b018892caa30eae5654a2f98611bd81f0f77ad) · kind: change · logged: unreleased · 2026-11-20
+
+- Why: the panel's guide spoke of Claude Code only. In 2.2.1 the two guide sentences (`tourInstalledBody`, `tourReadyBody` in `strings.ts`) add that Codex, Cursor and Antigravity each get a button of their own when they are on this computer. `CONTRACT.md` and `MANIFEST.json` change with them; the other files are byte for byte as in 2.2.0.
+- Copied unchanged with `git show [commit]:frontend/src/dock/[file]`, each of the 16 files. FormEncoder carries no translations of the panel's sentences and pins no module version of its own, so nothing else changed.
+- Checked: `dock_problems()` of `setup/agents.py` finds nothing, `./formencoder agents sync --check` in step, `test_dock_module.py` 10 passed. The guide was not looked at in a window.
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 265dbc5..169ccf3 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formencoder",
- "version": "0.11.0",
+ "version": "0.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formencoder",
- "version": "0.11.0",
+ "version": "0.12.0",
"license": "Apache-2.0",
"dependencies": {
"@fontsource/inter": "5.3.0",
diff --git a/frontend/package.json b/frontend/package.json
index 6b842f2..9a4f8ac 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "formencoder",
"private": true,
- "version": "0.11.0",
+ "version": "0.12.0",
"description": "formencoder · the media encoder of the form family",
"license": "Apache-2.0",
"type": "module",
diff --git a/frontend/src/dock/CONTRACT.md b/frontend/src/dock/CONTRACT.md
index a52a17e..81f3a05 100644
--- a/frontend/src/dock/CONTRACT.md
+++ b/frontend/src/dock/CONTRACT.md
@@ -1,6 +1,6 @@
# The dock's engine contract
-Module version 2.2.0. This file travels with the shared dock folder and is the same in every app.
+Module version 2.2.1. This file travels with the shared dock folder and is the same in every app.
The dock's frontend never talks to an engine. It calls the functions of `DockAdapter` (adapter.ts), and each app's adapter turns them into its engine's routes, sockets or event streams. This file says what an engine has to provide so that an adapter can deliver each function, in words that do not depend on the engine's language. Paths, header names and transports are each app's own. Where a clause says "the adapter", the engine may do the work instead; where it says "the engine", the adapter cannot make it up.
@@ -68,6 +68,10 @@ An adapter written for 2.1.0 compiles and behaves as before: copying the 2.2.0 f
- **Part names.** Every control of the module carries `data-dock-part`; the attribute and the names are `DOCK_PUBLIC.partAttribute`, `parts` and `partsByKind` (`launch.[kind]`, `menu.launch.[kind]`, `tab.[kind]`). Automation and command layers use these and no class name.
- **A status line for a tab.** A terminal record may carry `status`, and a channel may give `onStatus(handler)` and call the handler with new text ("reconnecting", an exit code). The text of the tab in front shows in the head between the tabs and the buttons, clipped; an empty string clears it.
+## Module 2.2.1
+
+The guide's two sentences for a computer that has Claude Code (`tourInstalledBody` and `tourReadyBody`) now end by naming the other three programs: "Codex, Cursor and Antigravity each get a button of their own here when they are on this computer." Nothing else in the folder changed, and an adapter written for 2.2.0 needs no change; an app that translates the module's sentences translates these two again.
+
## The manifest
`MANIFEST.json` in this folder lists the module version and the SHA-256 of every other file here, this one included. The source app (FormVis) writes it; every other app only checks it: read the file names and hashes from the manifest, hash each file's bytes, and fail naming any file that differs, is missing or is extra. The check is small enough to write in any language an app's tools use.
diff --git a/frontend/src/dock/MANIFEST.json b/frontend/src/dock/MANIFEST.json
index 819f4ea..c2ee1fa 100644
--- a/frontend/src/dock/MANIFEST.json
+++ b/frontend/src/dock/MANIFEST.json
@@ -1,8 +1,8 @@
{
"module": "dock",
- "version": "2.2.0",
+ "version": "2.2.1",
"files": {
- "CONTRACT.md": "ccef67fcf0017569c0bf68df0eae2e1e3ddf376117ac929789b803713c427df6",
+ "CONTRACT.md": "9791fa9d5eb7ef7e09543d34c2d097cfe6559b7fa1792f251afb9abfa7ac0bd7",
"adapter.ts": "1128c16892424485fe68bb2bf92ebc7229a9c2ff749db2fcd2419662d9c3ada9",
"agents.ts": "db666d1042555f8bbda4a697dbfc475df23779d0c5a25abd532bcfa43ae81043",
"chat.ts": "994878030b9fbff729734d34e2baa5b018e7d0b8555c24bfb7c98962c50446fa",
@@ -14,7 +14,7 @@
"keys.ts": "1adfc7daefa35b0e6eb8957250dca3926ded1c59fd51db7d60da6346caf0d561",
"placement.ts": "0f7e03ef0b720af07995111f30dcb5ed124529d44cf5cb67ae4bfb1f96c7f880",
"state.ts": "bef508e8343737f67adfbd7ae8cb8efb446968dfd4e7e0aff37da11f996955d7",
- "strings.ts": "19a6a32f235b61dfed6179e2271a6d599f4357c9a6b9c09118bb65990d1e114f",
+ "strings.ts": "3654a59c4d005125e248dd322f467d4ad3c513f4fd86f6dfe76f5565408ac50e",
"terminal.ts": "8bf886a7ad4dc69323e803acc13641a66e1d8614e9b85a6a60977fa30d8a56fc",
"tour.ts": "2f83994051f4370c5d1630a827b4539eb12fd50e7fe9531f5641a4bf75615782"
}
diff --git a/frontend/src/dock/strings.ts b/frontend/src/dock/strings.ts
index 1aae816..ec8296c 100644
--- a/frontend/src/dock/strings.ts
+++ b/frontend/src/dock/strings.ts
@@ -84,13 +84,13 @@ export const STRINGS = {
tourChatTitle: 'Ask for something in plain words',
tourChatBody: 'Type what you want in this line, for example "{example}", and press Enter. Claude does it in {app}.',
tourInstalledTitle: 'Claude Code is installed',
- tourInstalledBody: 'Claude Code is installed. The robot button here opens it; the first time, it may ask you to sign in.',
+ tourInstalledBody: 'Claude Code is installed. The robot button here opens it; the first time, it may ask you to sign in. Codex, Cursor and Antigravity each get a button of their own here when they are on this computer.',
tourMissingTitle: 'Claude Code is not on this computer yet',
tourMissingBody: 'For the bigger jobs, {app} uses a free program called Claude Code. To add it, copy the line below, open your computer\'s command window, paste it and press Enter.',
tourSignInTitle: 'Sign in to Claude Code once',
tourSignInBody: 'Claude Code is installed but not signed in. Press the robot button here: a window opens where you type /login and follow the steps. You only do this once.',
tourReadyTitle: 'Claude Code is ready',
- tourReadyBody: 'Claude Code is installed and signed in. The robot button here opens it when you want it to take on a bigger job.',
+ tourReadyBody: 'Claude Code is installed and signed in. The robot button here opens it when you want it to take on a bigger job. Codex, Cursor and Antigravity each get a button of their own here when they are on this computer.',
tourAskTitle: 'You decide what other programs may change',
tourAskBody: 'If another AI program on this computer wants to change your {noun}, {app} asks you first in a box in the middle of the window. Choose Deny, Allow once or Always allow. You can change your answer later under Outside agents in the menu here.',
tourSideTitle: 'Put the panel where you like it',
diff --git a/frontend/src/version.ts b/frontend/src/version.ts
index 526f948..458af1f 100644
--- a/frontend/src/version.ts
+++ b/frontend/src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.11.0';
+export const VERSION = '0.12.0';
diff --git a/native/Cargo.lock b/native/Cargo.lock
index c8fcaee..ce6ee0b 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -157,7 +157,7 @@ dependencies = [
[[package]]
name = "fencoder-commands"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"fencoder-core",
"fencoder-engine",
@@ -170,7 +170,7 @@ dependencies = [
[[package]]
name = "fencoder-core"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"ab_glyph",
"chrono",
@@ -183,7 +183,7 @@ dependencies = [
[[package]]
name = "fencoder-engine"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"fencoder-core",
"fencoder-io",
@@ -194,7 +194,7 @@ dependencies = [
[[package]]
name = "fencoder-io"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"chrono",
"fencoder-core",
@@ -207,7 +207,7 @@ dependencies = [
[[package]]
name = "fencoder-plan"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"chrono",
"fencoder-core",
@@ -218,7 +218,7 @@ dependencies = [
[[package]]
name = "fencoder-py"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"fencoder-commands",
"fencoder-core",
@@ -232,7 +232,7 @@ dependencies = [
[[package]]
name = "fencoder-run"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"fencoder-core",
"fencoder-io",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index e3f146a..8b04349 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -11,7 +11,7 @@ members = [
]
[workspace.package]
-version = "0.11.0"
+version = "0.12.0"
edition = "2024"
rust-version = "1.95"
license = "Apache-2.0"
diff --git a/native/fencoder-py/pyproject.toml b/native/fencoder-py/pyproject.toml
index da53e18..6e289ab 100644
--- a/native/fencoder-py/pyproject.toml
+++ b/native/fencoder-py/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "maturin"
[project]
name = "fe-core"
-version = "0.11.0"
+version = "0.12.0"
description = "formencoder's own encoding engine for the formencoder engine service"
license = { text = "Apache-2.0" }
requires-python = ">=3.10"
diff --git a/setup/freeze_backend b/setup/freeze_backend
index 54d7504..3d616c0 100755
--- a/setup/freeze_backend
+++ b/setup/freeze_backend
@@ -10,8 +10,10 @@ cd "$FORMENCODER_ROOT/backend"
sep=":"
[ "$(fe_os)" = windows ] && sep=";"
ext="$(fe_exe)"
+console=()
+if [ "$(fe_os)" = windows ] && [ "${FORMENCODER_ENGINE_WINDOWED:-1}" != 0 ]; then console=(--noconsole); fi
rm -rf build/pyinstaller dist-engine
-pyinstaller --noconfirm --clean --onefile --name formencoder-engine \
+pyinstaller --noconfirm --clean --onefile "${console[@]}" --name formencoder-engine \
--distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \
--add-data "$FORMENCODER_ROOT/frontend/dist${sep}frontend_dist" \
--add-data "$FORMENCODER_ROOT/backend/app/agent/templates${sep}agent_templates" \
diff --git a/setup/freeze_backend.bat b/setup/freeze_backend.bat
index fe7c5fc..0e0079d 100644
--- a/setup/freeze_backend.bat
+++ b/setup/freeze_backend.bat
@@ -9,10 +9,12 @@ python -c "import fe_core" >nul 2>nul || ( echo [formencoder] the encoding engin
if defined FORMENCODER_TARGET ( set "TRIPLE=%FORMENCODER_TARGET%" ) else ( for /f "tokens=2" %%t in ('rustc -vV ^| findstr /b "host:"') do set "TRIPLE=%%t" )
if not defined TRIPLE ( echo [formencoder] rustc not found, install Rust or set FORMENCODER_TARGET & exit /b 1 )
if not exist frontend\dist\index.html call setup\build_frontend.bat
+set "CONSOLE="
+if not "%FORMENCODER_ENGINE_WINDOWED%"=="0" set "CONSOLE=--noconsole"
cd backend
if exist build\pyinstaller rmdir /s /q build\pyinstaller
if exist dist-engine rmdir /s /q dist-engine
-pyinstaller --noconfirm --clean --onefile --name formencoder-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\backend\app\agent\templates;agent_templates" --add-data "%ROOT%\.claude\skills;skills" --add-data "%ROOT%\backend\app\resources;resources" --add-data "%ROOT%\src-tauri\binaries\ffmpeg-licence.json;." --collect-all fe_core --collect-submodules app --collect-submodules uvicorn --collect-submodules keyring --collect-submodules winpty "%ROOT%\backend\formencoder_engine.py" || exit /b 1
+pyinstaller --noconfirm --clean --onefile %CONSOLE% --name formencoder-engine--distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\backend\app\agent\templates;agent_templates" --add-data "%ROOT%\.claude\skills;skills" --add-data "%ROOT%\backend\app\resources;resources" --add-data "%ROOT%\src-tauri\binaries\ffmpeg-licence.json;." --collect-all fe_core --collect-submodules app --collect-submodules uvicorn --collect-submodules keyring --collect-submodules winpty "%ROOT%\backend\formencoder_engine.py" || exit /b 1
if not exist "%ROOT%\src-tauri\binaries" mkdir "%ROOT%\src-tauri\binaries"
copy /y dist-engine\formencoder-engine.exe "%ROOT%\src-tauri\binaries\formencoder-engine-%TRIPLE%.exe" >nul
"%ROOT%\src-tauri\binaries\formencoder-engine-%TRIPLE%.exe" --selfcheck
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 213fb21..622c163 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -893,7 +893,7 @@ dependencies = [
[[package]]
name = "formencoder"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"objc2",
"objc2-app-kit",
@@ -904,6 +904,7 @@ dependencies = [
"tauri-plugin-dialog",
"tauri-plugin-shell",
"tauri-plugin-updater",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index f64c0f9..af7e841 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formencoder"
-version = "0.11.0"
+version = "0.12.0"
description = "formencoder desktop shell"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
@@ -18,6 +18,9 @@ tauri-plugin-updater = "2"
regex = "1"
serde_json = "1"
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading"] }
+
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWindow", "NSView", "NSResponder", "objc2-core-foundation", "NSColor"] }
diff --git a/src-tauri/src/engine_start.rs b/src-tauri/src/engine_start.rs
new file mode 100644
index 0000000..2c32f1c
--- /dev/null
+++ b/src-tauri/src/engine_start.rs
@@ -0,0 +1,195 @@
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+pub const APP: &str = "FormEncoder";
+pub const SHELL_ENV: &str = "FORMENCODER_PARENT_PID";
+pub const ADDRESS_WAIT: Duration = Duration::from_secs(90);
+pub const KEY_WAIT: Duration = Duration::from_secs(10);
+pub const EXIT_WAIT: Duration = Duration::from_secs(1);
+pub const BUSY_CODE: i32 = 2;
+const DATA_ENV: &str = "FORMENCODER_DATA_DIR";
+const HOME_NAME: &str = "Formencoder";
+const LOG_FOLDER: &str = "logs";
+const LOG_NAME: &str = "formencoder-engine.log";
+const KEY_MARK: &str = "window-key";
+const TAIL_LINES: usize = 12;
+const LINE_CHARS: usize = 300;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Wait {
+ Address,
+ Key,
+}
+
+impl Wait {
+ pub fn limit(self) -> Duration {
+ match self {
+ Wait::Address => ADDRESS_WAIT,
+ Wait::Key => KEY_WAIT,
+ }
+ }
+
+ pub fn what(self) -> &'static str {
+ match self {
+ Wait::Address => "its engine to say which address it serves on",
+ Wait::Key => "its engine to hand over the key for the window",
+ }
+ }
+}
+
+#[derive(Debug, PartialEq)]
+pub enum Failure {
+ Missing,
+ NotStarted(String),
+ Stopped(Option),
+ TimedOut(Wait),
+ Window,
+}
+
+#[derive(Default)]
+pub struct Tail(VecDeque);
+
+impl Tail {
+ pub fn push(&mut self, line: &str) {
+ if line.contains(KEY_MARK) {
+ return;
+ }
+ let clean: String = line.chars().filter(|c| !c.is_control()).take(LINE_CHARS).collect();
+ if clean.trim().is_empty() {
+ return;
+ }
+ if self.0.len() == TAIL_LINES {
+ self.0.pop_front();
+ }
+ self.0.push_back(clean);
+ }
+
+ pub fn lines(&self) -> Vec {
+ self.0.iter().cloned().collect()
+ }
+}
+
+pub fn sentence(failure: &Failure) -> String {
+ match failure {
+ Failure::Missing => format!("{APP} could not start: its engine program is missing from the install. Installing {APP} again puts it back."),
+ Failure::NotStarted(reason) => format!("{APP} could not start its engine: {reason}"),
+ Failure::Stopped(Some(BUSY_CODE)) => format!(
+ "{APP} could not start: another copy of its engine holds its data folder. If {APP} is already open, use that window: only one copy can use its data folder at a time."
+ ),
+ Failure::Stopped(Some(code)) => format!("{APP} could not start: its engine stopped with code {code} before the window could open."),
+ Failure::Stopped(None) => format!("{APP} could not start: its engine stopped before the window could open."),
+ Failure::TimedOut(wait) => format!("{APP} could not start: it waited {} seconds for {} and that did not happen.", wait.limit().as_secs(), wait.what()),
+ Failure::Window => format!("{APP} could not open its window."),
+ }
+}
+
+pub fn message(failure: &Failure, tail: &[String], log: Option<&Path>) -> String {
+ let mut text = sentence(failure);
+ if !tail.is_empty() {
+ text.push_str("\n\nThe engine's last lines:\n");
+ text.push_str(&tail.join("\n"));
+ } else if matches!(failure, Failure::Stopped(_) | Failure::TimedOut(_)) {
+ text.push_str("\n\nThe engine wrote nothing before that.");
+ }
+ if let Some(path) = log {
+ text.push_str("\n\nThe engine's log: ");
+ text.push_str(&path.to_string_lossy());
+ }
+ text
+}
+
+pub fn data_folder(var: &dyn Fn(&str) -> Option, home: Option<&Path>) -> Option {
+ let raw = var(DATA_ENV).map(|value| value.trim().to_string()).filter(|value| !value.is_empty());
+ match raw {
+ Some(raw) => match (raw.strip_prefix('~'), home) {
+ (Some(rest), Some(home)) if rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\') => {
+ Some(home.join(rest.trim_start_matches(['/', '\\'])))
+ }
+ _ => Some(PathBuf::from(raw)),
+ },
+ None => home.map(|home| home.join(HOME_NAME)),
+ }
+}
+
+pub fn log_path(var: &dyn Fn(&str) -> Option, home: Option<&Path>) -> Option {
+ data_folder(var, home).map(|folder| folder.join(LOG_FOLDER).join(LOG_NAME))
+}
+
+pub fn home_folder(os: &str, var: &dyn Fn(&str) -> Option) -> Option {
+ let name = if os == "windows" { "USERPROFILE" } else { "HOME" };
+ var(name).filter(|value| !value.is_empty()).map(PathBuf::from)
+}
+
+pub fn engine_log() -> Option {
+ let var = |name: &str| std::env::var(name).ok();
+ let home = home_folder(std::env::consts::OS, &var);
+ log_path(&var, home.as_deref())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn only(name: &'static str, value: &'static str) -> impl Fn(&str) -> Option {
+ move |asked| (asked == name).then(|| value.to_string())
+ }
+
+ #[test]
+ fn the_tail_keeps_the_last_lines_and_never_the_window_key() {
+ let mut tail = Tail::default();
+ for n in 0..15 {
+ tail.push(&format!("line {n}"));
+ }
+ tail.push("formencoder-window-key: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
+ tail.push(" ");
+ tail.push(&"x".repeat(1000));
+ let lines = tail.lines();
+ assert_eq!(lines.len(), TAIL_LINES);
+ assert_eq!(lines[0], "line 4");
+ assert_eq!(lines[TAIL_LINES - 1].len(), LINE_CHARS);
+ assert!(lines.iter().all(|line| !line.contains("window-key")));
+ }
+
+ #[test]
+ fn every_failure_has_its_sentence_the_last_lines_and_the_log() {
+ let log = Path::new("/data/logs/formencoder-engine.log");
+ let said = vec!["formencoder is already running on /data (engine process 7).".to_string()];
+ let busy = message(&Failure::Stopped(Some(BUSY_CODE)), &said, Some(log));
+ assert!(busy.starts_with("FormEncoder could not start: another copy of its engine holds its data folder. If FormEncoder is already open, use that window"));
+ assert!(busy.contains("The engine's last lines:\nformencoder is already running on /data (engine process 7)."));
+ assert!(busy.ends_with("The engine's log: /data/logs/formencoder-engine.log"));
+ assert!(message(&Failure::Stopped(Some(3)), &[], Some(log)).contains("stopped with code 3"));
+ assert!(message(&Failure::Stopped(None), &[], None).ends_with("The engine wrote nothing before that."));
+ assert!(message(&Failure::Missing, &[], None).ends_with("puts it back."));
+ assert!(sentence(&Failure::NotStarted("Access is denied.".to_string())).ends_with("its engine: Access is denied."));
+ assert_eq!(sentence(&Failure::Window), "FormEncoder could not open its window.");
+ }
+
+ #[test]
+ fn a_wait_that_runs_out_says_how_long_and_for_what() {
+ assert!(sentence(&Failure::TimedOut(Wait::Address)).contains("waited 90 seconds for its engine to say which address it serves on"));
+ assert!(sentence(&Failure::TimedOut(Wait::Key)).contains("waited 10 seconds for its engine to hand over the key for the window"));
+ }
+
+ #[test]
+ fn the_log_is_where_the_engine_writes_it() {
+ let home = Path::new("/home/u");
+ let none = |_: &str| None;
+ let tail = Path::new("logs").join("formencoder-engine.log");
+ assert_eq!(log_path(&none, Some(home)), Some(home.join("Formencoder").join(&tail)));
+ assert_eq!(log_path(&only("FORMENCODER_DATA_DIR", " /d/x "), None), Some(Path::new("/d/x").join(&tail)));
+ assert_eq!(log_path(&only("FORMENCODER_DATA_DIR", "~/x"), Some(home)), Some(home.join("x").join(&tail)));
+ assert_eq!(log_path(&only("FORMENCODER_DATA_DIR", "~"), Some(home)), Some(home.join(&tail)));
+ assert_eq!(log_path(&only("FORMENCODER_DATA_DIR", " "), Some(home)), Some(home.join("Formencoder").join(&tail)));
+ assert_eq!(log_path(&none, None), None);
+ }
+
+ #[test]
+ fn the_home_folder_is_read_the_way_the_engine_reads_it() {
+ assert_eq!(home_folder("windows", &only("USERPROFILE", "C:\\Users\\u")), Some(PathBuf::from("C:\\Users\\u")));
+ assert_eq!(home_folder("windows", &only("HOME", "/home/u")), None);
+ assert_eq!(home_folder("linux", &only("HOME", "/home/u")), Some(PathBuf::from("/home/u")));
+ assert_eq!(home_folder("macos", &only("HOME", "")), None);
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 1326653..92cfb70 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1,6 +1,9 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod engine_start;
mod reveal;
+#[cfg(windows)]
+mod win_job;
use std::sync::Mutex;
@@ -16,8 +19,21 @@ const FALLBACK_LOGICAL: (f64, f64) = (1440.0, 900.0);
const MIN_LOGICAL: (f64, f64) = (1100.0, 700.0);
const SCREEN_FRACTION: f64 = 0.9;
+type EngineStep = Result>;
+
+fn start_limit(late: &tauri::async_runtime::Sender, limit: std::time::Duration, wait: Option) {
+ let late = late.clone();
+ std::thread::spawn(move || {
+ std::thread::sleep(limit);
+ let _ = late.blocking_send(Err(wait));
+ });
+}
+
fn kill_backend(handle: &tauri::AppHandle) {
- if let Some(child) = handle.state::().0.lock().unwrap().take() {
+ let child = handle.state::().0.lock().ok().and_then(|mut slot| slot.take());
+ if let Some(child) = child {
+ #[cfg(windows)]
+ win_job::end();
let _ = child.kill();
}
}
@@ -28,6 +44,20 @@ fn close_splash(handle: &tauri::AppHandle) {
}
}
+fn engine_failed(handle: &tauri::AppHandle, failure: engine_start::Failure, tail: &engine_start::Tail) {
+ let text = engine_start::message(&failure, &tail.lines(), engine_start::engine_log().as_deref());
+ eprintln!("formencoder: {text}");
+ let _ = handle
+ .dialog()
+ .message(text)
+ .title(engine_start::APP)
+ .kind(tauri_plugin_dialog::MessageDialogKind::Error)
+ .blocking_show();
+ close_splash(handle);
+ kill_backend(handle);
+ std::process::exit(1);
+}
+
fn check_for_updates(handle: tauri::AppHandle) {
let configured = handle
.config()
@@ -79,65 +109,89 @@ fn main() {
.setup(|app| {
let handle = app.handle().clone();
reveal::round_splash(&handle);
- let mut sidecar = app
- .shell()
- .sidecar("formencoder-engine")
- .expect("sidecar binary is bundled")
- .env("FORMENCODER_PORT", "0")
- .env("FORMENCODER_WINDOW_KEY_STDOUT", "1")
- .env("FORMENCODER_PARENT_PID", std::process::id().to_string());
- if let Some(files) = opened_files() {
- sidecar = sidecar.env("FORMENCODER_OPEN", files);
- }
- let (mut rx, child) = sidecar.spawn().expect("the formencoder engine failed to spawn");
- app.state::().0.lock().unwrap().replace(child);
+ let engine = app.shell().sidecar("formencoder-engine").map_err(|_| engine_start::Failure::Missing);
+ let started = engine.and_then(|engine| {
+ let mut sidecar = engine
+ .env("FORMENCODER_PORT", "0")
+ .env("FORMENCODER_WINDOW_KEY_STDOUT", "1")
+ .env(engine_start::SHELL_ENV, std::process::id().to_string());
+ if let Some(files) = opened_files() {
+ sidecar = sidecar.env("FORMENCODER_OPEN", files);
+ }
+ sidecar.spawn().map_err(|err| engine_start::Failure::NotStarted(err.to_string()))
+ });
+ let (mut rx, child) = match started {
+ Ok(pair) => pair,
+ Err(failure) => {
+ std::thread::spawn(move || engine_failed(&handle, failure, &engine_start::Tail::default()));
+ return Ok(());
+ }
+ };
+ #[cfg(windows)]
+ win_job::hold_pid(child.pid());
+ *app.state::().0.lock().unwrap() = Some(child);
tauri::async_runtime::spawn(async move {
let pattern = regex::Regex::new(r"http://127\.0\.0\.1:(\d+)").unwrap();
let key_pattern = regex::Regex::new(r"formencoder-window-key: ([A-Za-z0-9_-]{32,})").unwrap();
+ let (tx, mut events) = tauri::async_runtime::channel::(64);
+ let late = tx.clone();
+ tauri::async_runtime::spawn(async move {
+ while let Some(event) = rx.recv().await {
+ if tx.send(Ok(event)).await.is_err() {
+ break;
+ }
+ }
+ let _ = tx.send(Err(None)).await;
+ });
+ start_limit(&late, engine_start::Wait::Address.limit(), Some(engine_start::Wait::Address));
let mut port: Option = None;
let mut key: Option = None;
- while let Some(event) = rx.recv().await {
- let line = match event {
- CommandEvent::Stdout(bytes) => {
+ let mut waiting = false;
+ let mut stopped = false;
+ let mut tail = engine_start::Tail::default();
+ let mut failure = engine_start::Failure::Stopped(None);
+ while let Some(step) = events.recv().await {
+ let text = match step {
+ Ok(CommandEvent::Stdout(bytes)) => {
let text = String::from_utf8_lossy(&bytes).into_owned();
if key.is_none() {
key = key_pattern.captures(&text).map(|found| found[1].to_string());
}
text
}
- CommandEvent::Stderr(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
- CommandEvent::Terminated(_) => break,
- _ => continue,
- };
- if let Some(captures) = pattern.captures(&line) {
- port = captures[1].parse().ok();
- if port.is_some() {
+ Ok(CommandEvent::Stderr(bytes)) => String::from_utf8_lossy(&bytes).into_owned(),
+ Ok(CommandEvent::Terminated(ended)) => {
+ failure = engine_start::Failure::Stopped(ended.code);
+ stopped = true;
+ start_limit(&late, engine_start::EXIT_WAIT, None);
+ continue;
+ }
+ Ok(_) => continue,
+ Err(None) => break,
+ Err(Some(_)) if stopped => break,
+ Err(Some(engine_start::Wait::Address)) if port.is_some() => continue,
+ Err(Some(wait)) => {
+ failure = engine_start::Failure::TimedOut(wait);
break;
}
+ };
+ for line in text.lines() {
+ tail.push(line);
}
- }
- let grace = std::time::Instant::now() + std::time::Duration::from_secs(10);
- while port.is_some() && key.is_none() && std::time::Instant::now() < grace {
- match rx.try_recv() {
- Ok(CommandEvent::Stdout(bytes)) => {
- key = key_pattern
- .captures(&String::from_utf8_lossy(&bytes))
- .map(|found| found[1].to_string());
- }
- Ok(_) => {}
- Err(_) => {
- let _ = tauri::async_runtime::spawn_blocking(|| {
- std::thread::sleep(std::time::Duration::from_millis(20))
- })
- .await;
- }
+ if port.is_none() {
+ port = pattern.captures(&text).and_then(|found| found[1].parse::().ok());
+ }
+ if port.is_some() && key.is_some() {
+ break;
+ }
+ if port.is_some() && !waiting {
+ waiting = true;
+ start_limit(&late, engine_start::Wait::Key.limit(), Some(engine_start::Wait::Key));
}
}
- if key.is_none() {
- port = None;
- }
- match port {
+ drop(late);
+ match port.filter(|_| key.is_some()) {
Some(found) => {
let url: tauri::Url = format!("http://127.0.0.1:{found}")
.parse()
@@ -172,19 +226,14 @@ fn main() {
.build();
match built {
Ok(window) => reveal::conceal(&window),
- Err(_) => close_splash(&handle),
+ Err(_) => {
+ engine_failed(&handle, engine_start::Failure::Window, &engine_start::Tail::default());
+ return;
+ }
}
check_for_updates(handle.clone());
}
- None => {
- handle
- .dialog()
- .message("FormEncoder could not start its engine. If FormEncoder is already open, use that window: only one copy can use its data folder at a time. Otherwise open FormEncoder again. The engine's log is logs/formencoder-engine.log in the FormEncoder data folder.")
- .blocking_show();
- close_splash(&handle);
- kill_backend(&handle);
- std::process::exit(1);
- }
+ None => engine_failed(&handle, failure, &tail),
}
});
Ok(())
diff --git a/src-tauri/src/win_job.rs b/src-tauri/src/win_job.rs
new file mode 100644
index 0000000..1fb27ea
--- /dev/null
+++ b/src-tauri/src/win_job.rs
@@ -0,0 +1,59 @@
+use std::sync::OnceLock;
+
+use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
+use windows_sys::Win32::System::JobObjects::{
+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject,
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
+};
+use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
+
+static JOB: OnceLock = OnceLock::new();
+
+fn create() -> usize {
+ unsafe {
+ let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());
+ if handle.is_null() {
+ return 0;
+ }
+ let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ let set = SetInformationJobObject(
+ handle,
+ JobObjectExtendedLimitInformation,
+ std::ptr::addr_of!(limits).cast(),
+ std::mem::size_of::() as u32,
+ );
+ if set == 0 {
+ CloseHandle(handle);
+ return 0;
+ }
+ handle as usize
+ }
+}
+
+fn job() -> Option {
+ let raw = *JOB.get_or_init(create);
+ (raw != 0).then_some(raw as HANDLE)
+}
+
+pub fn hold_pid(pid: u32) -> bool {
+ let Some(handle) = job() else {
+ return false;
+ };
+ unsafe {
+ let process = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid);
+ if process.is_null() {
+ return false;
+ }
+ let held = AssignProcessToJobObject(handle, process) != 0;
+ CloseHandle(process);
+ held
+ }
+}
+
+pub fn end() -> bool {
+ match JOB.get().copied() {
+ Some(raw) if raw != 0 => unsafe { TerminateJobObject(raw as HANDLE, 1) != 0 },
+ _ => false,
+ }
+}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 056ecab..2ad381d 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "FormEncoder",
- "version": "0.11.0",
+ "version": "0.12.0",
"identifier": "dev.formai.formencoder",
"build": {
"frontendDist": "../frontend/dist"