diff --git a/.agents/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md b/.agents/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md index 558a808..ece9715 100644 --- a/.agents/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md +++ b/.agents/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md @@ -15,7 +15,7 @@ These run in the formtxt folder. Run them yourself only when you have a shell to | --- | --- | | Start FormTxt (engine and window) for development | `./formtxt` | | Install or update the engine and window dependencies | `./formtxt install` | -| Connect Claude Code, Codex and Cursor to FormTxt for this user | `./formtxt agents install` (add `--dry-run` first to see the changes) | +| Connect Claude Code, Codex, Cursor and Antigravity to FormTxt for this user | `./formtxt agents install` (add `--dry-run` first to see the changes) | | Run the MCP server as a client would (stdio) | `./formtxt mcp` (starts the engine if none is running) | | Run one command from a shell | `./formtxt cli run key=value` (the window must be open) | | Windows | the same as `formtxt.bat mcp`, `formtxt.bat agents install` | diff --git a/.agents/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md b/.agents/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md index 75c37bd..8320c27 100644 --- a/.agents/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md +++ b/.agents/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md @@ -17,7 +17,7 @@ FormTxt's terminal dock follows the Form family standard set by formvis: the eng | `backend/app/routers/mcp.py` | `/mcp` with `list_commands`, `describe_command`, `run_command` over the mirrored catalogue and `bridge.call`. `WINDOW_ONLY` refuses the dock's commands to every agent; outside agents are asked once through the bridge (`__consent__`, three minutes) unless `agentsAllowed`; a refusal holds ten minutes. `GET /api/mcp/status` | | `backend/app/main.py` | binds the PTY loop at start; stops the chat and closes every PTY at shutdown | | `frontend/src/dock/` (the family's shared module, copied whole from FormVis, never edited here; `./formtxt agents check` fails when a file differs from its `MANIFEST.json`), `dock-adapter.ts`, `styles/dock-tokens.css`, `styles/terminal.css` | the dock and the Chat tab (window side), at the bottom or in a right column, state under `formtxt.dock` | -| `backend/app/services/agent_programs.py` | Codex (`codex`) and Cursor (`cursor-agent`) found on the PATH or by the login shell, reported as `agents` in `/api/claude-code/status`; `POST /api/terminal/agent` opens one in a tab with its own in-app token in `FORMTXT_INAPP_TOKEN` and `FORMTXT_MCP_URL` in the child's environment, revoked when the tab closes | +| `backend/app/services/agent_programs.py` | Codex (`codex`), Cursor (`cursor-agent`) and Antigravity (`agy`) found by the family's finder (`agent_lookup.py`), reported as `agents` in `/api/claude-code/status`; `POST /api/terminal/agent` opens one in a tab with its own in-app token in `FORMTXT_INAPP_TOKEN` and `FORMTXT_MCP_URL` in the child's environment, revoked when the tab closes; an Antigravity tab runs in `agent-tabs/antigravity` in the data folder with the entry `formtxt_tab` in its `.agents/mcp_config.json`, taken out at close | | `setup/mcp_stdio.py` | `./formtxt mcp`; starts `./formtxt backend` detached (log `formtxt-engine.log` in the temporary folder) when no engine answers; `FORMTXT_MCP_AUTOSTART=0` turns it off | ## Rules diff --git a/.claude/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md b/.claude/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md index 558a808..ece9715 100644 --- a/.claude/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md +++ b/.claude/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md @@ -15,7 +15,7 @@ These run in the formtxt folder. Run them yourself only when you have a shell to | --- | --- | | Start FormTxt (engine and window) for development | `./formtxt` | | Install or update the engine and window dependencies | `./formtxt install` | -| Connect Claude Code, Codex and Cursor to FormTxt for this user | `./formtxt agents install` (add `--dry-run` first to see the changes) | +| Connect Claude Code, Codex, Cursor and Antigravity to FormTxt for this user | `./formtxt agents install` (add `--dry-run` first to see the changes) | | Run the MCP server as a client would (stdio) | `./formtxt mcp` (starts the engine if none is running) | | Run one command from a shell | `./formtxt cli run key=value` (the window must be open) | | Windows | the same as `formtxt.bat mcp`, `formtxt.bat agents install` | diff --git a/.claude/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md b/.claude/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md index 75c37bd..8320c27 100644 --- a/.claude/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md +++ b/.claude/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md @@ -17,7 +17,7 @@ FormTxt's terminal dock follows the Form family standard set by formvis: the eng | `backend/app/routers/mcp.py` | `/mcp` with `list_commands`, `describe_command`, `run_command` over the mirrored catalogue and `bridge.call`. `WINDOW_ONLY` refuses the dock's commands to every agent; outside agents are asked once through the bridge (`__consent__`, three minutes) unless `agentsAllowed`; a refusal holds ten minutes. `GET /api/mcp/status` | | `backend/app/main.py` | binds the PTY loop at start; stops the chat and closes every PTY at shutdown | | `frontend/src/dock/` (the family's shared module, copied whole from FormVis, never edited here; `./formtxt agents check` fails when a file differs from its `MANIFEST.json`), `dock-adapter.ts`, `styles/dock-tokens.css`, `styles/terminal.css` | the dock and the Chat tab (window side), at the bottom or in a right column, state under `formtxt.dock` | -| `backend/app/services/agent_programs.py` | Codex (`codex`) and Cursor (`cursor-agent`) found on the PATH or by the login shell, reported as `agents` in `/api/claude-code/status`; `POST /api/terminal/agent` opens one in a tab with its own in-app token in `FORMTXT_INAPP_TOKEN` and `FORMTXT_MCP_URL` in the child's environment, revoked when the tab closes | +| `backend/app/services/agent_programs.py` | Codex (`codex`), Cursor (`cursor-agent`) and Antigravity (`agy`) found by the family's finder (`agent_lookup.py`), reported as `agents` in `/api/claude-code/status`; `POST /api/terminal/agent` opens one in a tab with its own in-app token in `FORMTXT_INAPP_TOKEN` and `FORMTXT_MCP_URL` in the child's environment, revoked when the tab closes; an Antigravity tab runs in `agent-tabs/antigravity` in the data folder with the entry `formtxt_tab` in its `.agents/mcp_config.json`, taken out at close | | `setup/mcp_stdio.py` | `./formtxt mcp`; starts `./formtxt backend` detached (log `formtxt-engine.log` in the temporary folder) when no engine answers; `FORMTXT_MCP_AUTOSTART=0` turns it off | ## Rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f05e0a..fb216d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.35.0 · 2026-11-19 + +- Antigravity, Google's `agy` program, is the fourth agent program FormTxt works with, beside Claude Code, Codex and Cursor. The terminal panel has an Antigravity tab when the program is found on this computer. +- `./formtxt agents install` also adds FormTxt to Antigravity. It keeps everything else in Antigravity's settings file, leaves alone a server named formtxt that it did not write, and a second run changes nothing. +- FormTxt finds Claude Code, Codex, Cursor and Antigravity however it was started. Started from the Dock, the Finder or the Start menu it used to report a program installed by Homebrew, npm or a version manager as not installed, and a program it did find could still fail to start in a tab or in Chat. +- When a tab or Chat cannot start because a program is missing, FormTxt says where it looked and how to install it. When the program is there but does not start, it says so and shows the program's own error line. +- An Antigravity tab runs in a folder of FormTxt's own, not in the folder of the open document. +- Windows: the engine starts when it is built without a console. An engine with no output to write to could stop at its first line. +- The terminal panel is brought up to date with the other Form apps. +- For people who build FormTxt: its tests can no longer start a real agent program on the computer that runs them. + ## 0.34.0 · 2026-11-19 - Mail merge data can come from a SQLite database file: pick a table or write one SELECT. The file is opened read-only and the query is kept with the document. diff --git a/CLAUDE.md b/CLAUDE.md index 52de3e6..88c56df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ Documents in the form family: an open, local-first Word and Google Docs alternat - Editing documents through FormTxt: the MCP server `formtxt` (`./formtxt mcp`, already in `.mcp.json`) offers `list_commands`, `describe_command` and `run_command` over the same catalogue; load the `formtxt-driving` skill. The window must be open; the first `run_command` from an outside agent asks the person once, and their answer is the `agentsAllowed` setting. - Changing FormTxt's code: load the `formtxt-harness` skill; its `terminal-operator` sub-skill covers the dock, PTYs and Claude Code. - Inside the app, the terminal dock runs shells and the person's own Claude Code in engine-owned PTYs (`backend/app/services/terminal.py`, `claude_code.py`, routes under `/api/terminal` and `/api/agent/claude`). A Claude Code tab gets this engine's `/mcp` with a per-run token in its environment, so it is not asked for consent. `view.terminal`, `view.newTerminal`, `agent.claudeCode`, `agent.chat` and `cloud.set` are window-only: `run_command` refuses them (`WINDOW_ONLY` in `backend/app/routers/mcp.py`). -- Skills live in `.claude/skills` and are mirrored to `.agents/skills` by `./formtxt agents sync`, which also writes `agents/manifest.json` (tools, skills and dock for the family spec; the dock part is declared in `setup/agents.py`); `./formtxt agents check` and `./formtxt mcpb check` must pass. `./formtxt agents install` registers the server with Claude Code, Codex and Cursor for this user. +- Skills live in `.claude/skills` and are mirrored to `.agents/skills` by `./formtxt agents sync`, which also writes `agents/manifest.json` (tools, skills and dock for the family spec; the dock part is declared in `setup/agents.py`); `./formtxt agents check` and `./formtxt mcpb check` must pass. `./formtxt agents install` registers the server with Claude Code, Codex, Cursor and Antigravity for this user. ## Commits diff --git a/README.md b/README.md index 9b1b74d..c213872 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.34.0 + version 0.35.0 TypeScript and Vite Python and FastAPI macOS, Windows, Linux @@ -24,7 +24,7 @@ Run it from source

-Version 0.34.0 · Apache-2.0 · macOS, Windows, Linux (browser, or the desktop app built with ./build_app) +Version 0.35.0 · Apache-2.0 · macOS, Windows, Linux (browser, or the desktop app built with ./build_app)
@@ -107,7 +107,7 @@ The editor's commands live in one catalogue, and the window and the terminal cal ./formtxt cli list # the command catalogue ./formtxt cli describe tools.stats # one command and its arguments ./formtxt cli run edit.replaceAll find=draft replace=final # run a command in the open window, as an outside agent -./formtxt mcp # MCP server on stdio for Claude Code, Codex and Cursor +./formtxt mcp # MCP server on stdio for Claude Code, Codex, Cursor and Antigravity ./formtxt agents install # register that server and the formtxt-driving skill for this user ``` diff --git a/agents/manifest.json b/agents/manifest.json index 44fa68f..ebedd7f 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -46,6 +46,7 @@ "claude-code", "codex", "cursor", + "antigravity", "activity" ] }, diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index e837e4e..1e35eef 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,11 +2,61 @@ Living log of comment content, rationale and removed code for the engine. Source files stay comment-free; read this first, then edit surgically. -Current build version: v0.34.0 -Last updated: 2026-11-19 · v0.34.0: database merge data, list reports and report run, changes only from the window, the outside-agent question with Allow once and Block all agents, Codex and Cursor tabs (sections below, headed "v0.34.0, not released yet" as they were written). Before: 2026-11-17 · v0.33.0 has no change in the engine; the AMOLED Black theme is in the frontend log. Before: 2026-11-14 · v0.32.1: the macOS freeze keeps the Python library loadable inside the app bundle (section below). Before: 2026-11-13 · v0.32.0 has no change in the engine; `setup/icon_rules.py` also checks the insertable icon and emoji data (frontend log). Before: 2026-11-13 · v0.31.0: MCP, terminals and Claude Code in the engine, the agent kit (section below). Before: 2026-11-13 · the v0.30.8 fixes to the engine entry and scripts (section below). Before: 2026-11-12 · the v0.30.7 review fixes. Before: 2026-10-31 · .js, .mjs and .css keep their types on Windows; the Linux packages pull in the media plugins. Before: macOS engine signed for notarization +Current build version: v0.35.0 +Last updated: 2026-11-19 · v0.35.0: the family's finder for the agent programs at 1.0.1, an Antigravity tab, agents install for Antigravity, tests that find only stand-ins, the engine starting with no output streams (sections below, headed "after v0.34.0" as they were written). Before: 2026-11-19 · v0.34.0: database merge data, list reports and report run, changes only from the window, the outside-agent question with Allow once and Block all agents, Codex and Cursor tabs (sections below, headed "v0.34.0, not released yet" as they were written). Before: 2026-11-17 · v0.33.0 has no change in the engine; the AMOLED Black theme is in the frontend log. Before: 2026-11-14 · v0.32.1: the macOS freeze keeps the Python library loadable inside the app bundle (section below). Before: 2026-11-13 · v0.32.0 has no change in the engine; `setup/icon_rules.py` also checks the insertable icon and emoji data (frontend log). Before: 2026-11-13 · v0.31.0: MCP, terminals and Claude Code in the engine, the agent kit (section below). Before: 2026-11-13 · the v0.30.8 fixes to the engine entry and scripts (section below). Before: 2026-11-12 · the v0.30.7 review fixes. Before: 2026-10-31 · .js, .mjs and .css keep their types on Windows; the Linux packages pull in the media plugins. Before: macOS engine signed for notarization --- +## after v0.34.0 · the supported agent programs are named as four (2026-11-19) + +- `formtxt` (the launcher's usage text, the `agents` line), `README.md` (the `./formtxt mcp` line under Built for agents), `CLAUDE.md` (the agents kit line), `.claude/skills/formtxt-driving/sub-skills/terminal/SUB-SKILL.md` and `.claude/skills/formtxt-harness/sub-skills/terminal-operator/SUB-SKILL.md` (mirrored to `.agents/skills` by `./formtxt agents sync`) · where the list was Claude Code, Codex and Cursor it is now Claude Code, Codex, Cursor and Antigravity. The harness page's line about `agent_programs.py` also says the programs are found by the family's finder and where an Antigravity tab runs. +- Left alone: the trademark sentence at the foot of `README.md` and in `NOTICE.md` (it names the owners of three marks; adding a fourth owner is the owner's call), `AGENTS.md` (it names the config files the repository ships, not the programs), CHANGELOG and log history, everything in `frontend/src/dock`. + +## after v0.34.0 · the engine starts when it has no output streams (2026-11-19) + +- formtxt_engine.py (top of the file, before any import of FormTxt's own) · when `sys.stdin`, `sys.stdout` or `sys.stderr` is `None`, it is replaced by the null device opened as text. A Windows engine built without a console has no streams, and the first `print` or log line then stops it at start; a tester saw that in another Form engine. The way FormWeb's entry does it. +- Seen on Linux: Python started with its three streams closed reports all three as `None`; the entry started that way on port 4742 with its own data folder answered `/api/health` with 200, and before the change the same start gave no answer and exit code 1. Started normally on port 4743 it still printed uvicorn's lines. No test added. Not run on Windows, and not as a frozen engine. + +## after v0.34.0 · an Antigravity tab, and agents install adds FormTxt to Antigravity (2026-11-19) + +- routers/terminal.py :: `AgentBody.kind` · takes `antigravity` beside `codex` and `cursor`. +- services/agent_programs.py :: `TABS`, `tab_folder`, `_mcp_file`, `_servers`, `_replace`, `write_tab_entry`, `remove_tab_entry`, `open_terminal` · `TABS` is `("codex", "cursor", "antigravity")`. An Antigravity tab starts `agy` the way a Codex or Cursor tab starts: found by the finder, started through `agent_lookup.start_argv`, with the tab's token in `FORMTXT_INAPP_TOKEN`. Antigravity reads its MCP servers from a file, so before the start the entry `formtxt_tab` (`serverUrl` and the header `x-formtxt-inapp` with the tab's token) is written into `.agents/mcp_config.json` of the tab's working folder: everything else in the file is kept, the file is replaced whole at mode 0600, and the entry is taken out when the tab closes if it still carries that tab's token, when the token is also revoked. A file that is not an MCP servers file is left alone and the tab is refused. +- Decision, the working folder. FormTxt's Codex and Cursor tabs run in the open document's folder; the Cursor tab's `.cursor/mcp.json` there names variables, never the token. Antigravity's file has to hold the token itself, so that tab runs in a folder of FormTxt's own, `agent-tabs/antigravity` in the data folder, and a token is never written beside the person's documents. This is FormVis's choice, not what FormTxt does for its Cursor tab. +- setup/agents.py :: `DOCK`, `ours`, `install_antigravity`, `install`, `main` · `./formtxt agents install` takes `antigravity` and includes it when no client is named. It writes FormTxt's MCP server (the launcher with the argument `mcp`) into `~/.gemini/config/mcp_config.json`: the rest of the file is kept, the file is backed up and replaced whole, a second run changes nothing. An entry of its own at another path is brought up to date; a server named `formtxt` that FormTxt did not write, and a file that is not an MCP servers file, are left alone and reported; when only `~/.gemini/antigravity-cli/mcp_config.json` is there, the documented file is written and the result says the older one was seen and left alone. No skill is copied for Antigravity. `DOCK["tabs"]` gains `antigravity`, and `./formtxt agents sync` regenerated `agents/manifest.json`. +- Seen first, on an engine from source (port 4741, its own data folder and home, a stand-in `agy` first on PATH that answers `--version` and prints a banner; a real `agy` was never started): `GET /api/agents/status?fresh=true` gave `antigravity` as `runs`, version 1.2.3, `signedIn` null; `POST /api/terminal/agent` without the window key was 403; with it the record had kind `antigravity`, title Antigravity and the folder above; the stream showed the stand-in's banner; the file held its seeded server and key beside `formtxt_tab` at mode 0600; after `DELETE` the file was exactly as seeded. `agents install antigravity` with a made-up home: dry run, first run, second run, an own entry at another path, a foreign entry, only the older file, a file that is not JSON. +- Tests, added after that: four in `tests/test_agent_programs.py`. `tests/test_agent_lookup.py` expected 422 for an Antigravity tab and `TABS` of two; it now expects the 404 with the finder's sentence and the three, which is the only reason it changed. +- Not run: a real `agy` (whether it reads `serverUrl` and `headers` from the folder's file, whether it wants the folder trusted first), a call to `/mcp` with the tab's token, Windows, macOS. + +## after v0.34.0 · no test can start a real agent program (2026-11-19) + +- tests/conftest.py :: `AGENT_STAND_INS`, `AGENT_CALLS`, `AGENT_SHELL`, `only_stand_in_agent_programs`, `pytest_sessionfinish`, `pytest_terminal_summary` · before any test module is imported the run gets a PATH of its own stand-ins folder and the system's four folders, a stand-in login shell as `SHELL`, and none of the six folder variables the finder reads. The stand-ins (`claude`, `codex`, `cursor-agent`, `agent`, `agy`) answer `--version`, exit 1 for anything else, and write one line per start to a file in the run's sandbox. The autouse fixture empties the finder's system install folders for every test. The run ends with one line: how many times a stand-in was started, and which. The way FormPath's conftest does it. `dock_start` still narrows this further for the tests that use it. +- Why: a test that reached the lookup with the machine's own PATH and login shell in reach could run the real Claude Code with `--version`. +- Later the same day: the narrowed PATH had also taken `node` away, so the test of the dock's `state.ts` in `tests/test_dock_manifest.py` skipped where it had run. The run now gets a `tools` folder in its sandbox, second on PATH, holding one link to the `node` that was on PATH before it was narrowed; the folder `node` came from, which on this machine also holds a real `claude`, stays off PATH. + +## after v0.34.0 · the family's finder at version 1.0.1 (2026-11-19) + +- services/agent_lookup.py · replaced whole by the copy from FormVis ddc893ae, VERSION 1.0.1, SHA-256 `62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51`. Against 1.0.0 two lines differ: the version, and `_last_line`, which no longer takes env's hint line "use -[v]S to pass options" as a program's error line. Nothing in it is edited here. +- setup/agents.py :: `LOOKUP_HASHES` · holds both versions, 1.0.0 and 1.0.1, so the check accepts either file whole and names any other. +- tests/test_dock_manifest.py :: `test_the_check_names_the_shared_finder_edited_in_place_or_missing` · read the version from the file; it had 1.0.0 written in its sentence. `tests/conftest.py` `dock_start` already removes `NPM_CONFIG_PREFIX`, `npm_config_prefix`, `PNPM_HOME`, `VOLTA_HOME`, `BUN_INSTALL` and `NVM_SYMLINK` (`FOLDER_VARS`). + +## after v0.34.0 · the engine finds and starts Claude Code, Codex and Cursor through the family's finder, and the status reports Antigravity (2026-11-19) + +- Fault: FormTxt started from the Dock, the Finder or the Start menu gets the system's short program path, not the one a Terminal has. `claude_code.cli` asked `shutil.which("claude")`, five folders under the home folder and `command -v claude` in a login shell that was not interactive; `agent_programs.find` asked `shutil.which` and the same shell. A program installed by Homebrew, npm or a version manager was then "not installed", and a program that was found could still fail to start, because its tab and Chat ran with the engine's PATH (a `#!/usr/bin/env node` script with no `node` on it). "Found" also counted as "installed" without the program ever being run. +- services/claude_code.py :: `OVERRIDES`, `SHELL_WAIT`, `CHECK_WAIT`, `OTHERWISE`, `setting`, `located`, `usable`, `said` (new) · `located(kind, fresh)` is the one lookup everything uses: `agent_lookup.find` (override variable, engine PATH, the known install folders, the person's shell PATH read once) and then `agent_lookup.check`, which runs `--version` the way a tab starts the program. `usable(kind)` asks once more, fresh, when the first answer is not `runs`. `said(found)` is the finder's sentence with the program's install line. FormTxt has no path setting for these programs, so `setting()` answers `None` and `OTHERWISE` is empty; none is added here. Override variables: `FORMTXT_CLAUDE_BIN` (as before), and new `FORMTXT_CODEX_BIN`, `FORMTXT_CURSOR_BIN`, `FORMTXT_ANTIGRAVITY_BIN`. +- services/claude_code.py :: `child_env(path)`, `cli`, `_signed_in`, `info`, `start`, `program`, `terminal_env(token, path, extra)`, `terminal_argv`, `open_terminal` · the same names and answers, with bodies that call the finder. `child_env` and `terminal_env` take the program's path and build PATH as the program's own folder, the repository, the shell PATH, the known folders that exist, then the engine's PATH. `info` answers the old fields plus `finding` (`runs`, `broken`, `missing`), `how`, `looked`, `error` and `said`; `installed` is true only when `--version` ran with exit code 0; its 60 s cache stays. Chat (`start`) refuses with `info()["said"]` and starts through `agent_lookup.start_argv` (the login shell, `exec`) with `child_env(path)`. `open_terminal` raises `LookupError(said(found))`. `KEEP_ENV` is the finder's. +- Removed from services/claude_code.py: `_from_login_shell`, `CANDIDATES = (".claude/local/claude", ".local/bin/claude", ".npm-global/bin/claude", ".bun/bin/claude", ".volta/bin/claude")`, `SYSTEM_PATHS = ("/opt/homebrew/bin/claude", "/usr/local/bin/claude", "/usr/bin/claude")` (the finder's table holds these and more), the imports `shlex`, `shutil` and `Path`, and the sentence `Claude Code is not installed. Install it with: ` in `start`. `MISSING` is still defined and no longer used by the engine. +- services/agent_programs.py :: `PROGRAMS`, `TABS`, `find`, `status(fresh)`, `version`, `report`, `open_terminal` · `PROGRAMS` gains `antigravity` (Google's `agy`), so both status answers report it like Codex and Cursor: found or not, where it looked, `signedIn` always null because there is no status command. `TABS` is `("codex", "cursor")`: there is no Antigravity tab, label or MCP file, and `POST /api/terminal/agent` still accepts only those two kinds (422 for any other). `status` and `report` answer per program `agent_lookup.answer(...)` plus `signedIn`, `install` and `title`; `report` keeps its 60 s cache. `open_terminal` uses `usable`, `agent_lookup.start_argv` and `claude_code.terminal_env(token, path, {FORMTXT_MCP_URL})`, so a Codex or Cursor tab now also leaves out the `CLAUDE*` variables a Claude Code tab leaves out. Removed: the `shutil.which` and `command -v` lookup in `find`, and ` is not installed on this computer.` +- routers/claude_code.py :: `window_status` · passes `fresh` on to `agent_programs.status`, so `GET /api/claude-code/status?fresh=true` asks again for every program. +- Checked on an engine from source (port 4735, its own data folder, started with `env -i`, a made-up home, a stand-in login shell named zsh, PATH exactly `/usr/bin:/bin:/usr/sbin:/sbin`, node-style stand-in programs each with a stand-in `node` beside it): `GET /api/agents/status?fresh=true` and `GET /api/claude-code/status?fresh=true` gave all four as `runs`, `how: folder` (`~/.local/bin` for claude, cursor-agent and agy, `~/.nvm/versions/node/v22.3.0/bin` for codex), version 1.2.3, Claude Code signed in and the others null; moved to a folder named only in the stand-in shell's interactive file, all four `runs`, `how: shell`; removed, `missing` with the list of places and the sentence; a Codex script whose interpreter is missing, `broken` with the error line. Tabs through `POST /api/terminal/agent` (codex, cursor) and `POST /api/terminal/claude`, read over the stream socket: each printed that the stand-in `node` ran it and that its own folder was first on PATH; `antigravity` was 422. Chat through `POST /api/agent/claude/start`: ready, session id read, a sent message answered, the token in the child's environment. With the programs gone the tab routes answered 404 and Chat 409 with the finder's sentence. Not run: the real Claude Code, Codex, Cursor or Antigravity, macOS, Windows, a frozen engine, a real zsh, bash or fish with real rc files. +- Tests. `tests/conftest.py` gains `stand_in` and the `dock_start` fixture (made-up home, stand-in shell, the system's four folders on PATH, no override or folder variables, no system install folders, the caches cleared). `tests/test_agent_programs.py` and `tests/test_agent_status.py` pinned the old lookup and were changed for that reason only: their stand-ins now answer `--version` (a program that does not is `broken`, not installed), the fixture that replaced `terminal.login_shell` is the `dock_start` environment, since the finder asks the shell itself, and the two sets of names include `antigravity`. They also no longer leave the machine's own PATH and login shell in reach of the lookup. `tests/test_agent_lookup.py` is new (five tests, written after the behaviour above was seen). Suite: 195 passed before, 203 after. + +## after v0.34.0 · the family's finder for the agent programs, held to its recorded hash (2026-11-19) + +- services/agent_lookup.py (new, 443 lines) · the family's one finder for Claude Code, Codex, Cursor and Antigravity, copied whole and byte for byte from FormVis 146dddd1 `backend/app/services/agent_lookup.py`, VERSION 1.0.0, SHA-256 `252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3`. It uses the standard library only and imports nothing from the app; everything of FormTxt's is passed in as arguments. Nothing in it is edited here, ever: it changes only as a whole new version with a new recorded hash. Its own docstrings stay as they came, since removing them would change the hash. +- setup/agents.py :: `LOOKUP_REL`, `LOOKUP`, `LOOKUP_HASHES`, `lookup_problems`, `sync`, `check` · `lookup_problems()` reads the `VERSION = "..."` line, hashes the file's bytes and answers `backend/app/services/agent_lookup.py: does not match the hash recorded for version X (the shared finder changes only as a whole new version)` or `...: missing (the shared finder for the agent programs)`. `agents check`, `agents sync --check` and `agents sync` all print it and exit 1. The repository already checks files out with LF endings (`.gitattributes`: `* text=auto eol=lf`), which the hash of the bytes relies on. The hash is not in `frontend/src/dock/MANIFEST.json`: that folder belongs to the dock module. +- setup/agents.py :: `lookup`, `install_claude` · `agents install` no longer asks a bare `shutil.which("claude")`, which misses a Claude Code installed by a version manager when the script runs with a short PATH. It loads the finder from its file (no engine needed), finds and checks `claude` (`FORMTXT_CLAUDE_BIN` is the override), and runs `claude mcp get`, `remove` and `add` through the finder's `run` in the finder's child environment. When the program is missing or does not start, the line it prints is the finder's sentence, then "Once it runs: claude mcp add ...". Removed: `the claude command is not installed here; once it is, run: ...`. +- Checked on Linux, Python 3.13: the copied file's SHA-256 is the recorded one; `agents check` and `agents sync --check` clean in the repository; on a copy of the kit, one added newline in the finder gave the "does not match" line and exit 1 from `check` and from `sync`, and the file removed gave the "missing" line and exit 1. `agents install claude` with a made-up home, a stand-in login shell, PATH `/usr/bin:/bin:/usr/sbin:/sbin` and a node-style stand-in `claude` under `~/.local/bin` that records its calls: the dry run called `--version` and `mcp get formtxt` only, the real run then called `mcp add --scope user formtxt -- <launcher> mcp`; with no program anywhere the dry run printed the "was not found. Looked in: ..." sentence. Not run: the real Claude Code, macOS, Windows. Tests in `tests/test_dock_manifest.py` (three, added after the above was seen). + ## v0.34.0, not released yet · the Mac engine carries its Python library once, as a plain file, so Apple's notary accepts the app (2026-11-19) - Fault, seen on FormTools 0.9.0 on 2026-11-19 (the first Mac build with notarization on, formcompiler 0.16.0): Apple's notary answered `Invalid`, "The signature of the binary is invalid", for `engine/_internal/Python.framework/Versions/3.14/Python`. `setup/freeze_backend` here signed the engine with the same steps (the v0.32.1 section below), and FormTxt's Mac builds since then were made while notarization was off, so the notary has not seen a FormTxt engine signed this way. It would refuse it for the same reason. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index eab0e9c..e0d0ed6 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.34.0" +__version__ = "0.35.0" diff --git a/backend/app/routers/claude_code.py b/backend/app/routers/claude_code.py index 69d44fb..d592cd8 100644 --- a/backend/app/routers/claude_code.py +++ b/backend/app/routers/claude_code.py @@ -37,7 +37,7 @@ def status(request: Request, fresh: bool = False) -> dict: def window_status(request: Request, fresh: bool = False) -> dict: require_local(request) tab = next((s.describe() for s in terminal.SESSIONS.values() if s.kind == "claude"), None) - return claude_code.info(fresh=fresh) | {"folder": claude_code.workdir(document_folder()), "terminal": tab, "agents": agent_programs.status()} + return claude_code.info(fresh=fresh) | {"folder": claude_code.workdir(document_folder()), "terminal": tab, "agents": agent_programs.status(fresh)} @programs_router.get("/status") diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index 370a100..b8e6ec6 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -70,7 +70,7 @@ class ClaudeBody(BaseModel): class AgentBody(BaseModel): - kind: Literal["codex", "cursor"] + kind: Literal["codex", "cursor", "antigravity"] cols: int = Field(100, ge=10, le=500) rows: int = Field(30, ge=4, le=200) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py new file mode 100644 index 0000000..ea34eba --- /dev/null +++ b/backend/app/services/agent_lookup.py @@ -0,0 +1,443 @@ +"""One finder and one starter for the agent programs a Form engine runs for the person: Claude Code, Codex, Cursor's agent +and Antigravity, held as a table (PROGRAMS) so another program is one more entry. + +A program started from the Dock, the Finder, the Start menu or a desktop launcher gets the system's short PATH, not the one a +terminal has, so a bare PATH search reports programs installed by Homebrew, npm, a version manager or into the home folder as +missing. This file looks in order: the person's setting, the app's development override variable, the engine's PATH, the known +install folders for the system, then the person's own shell PATH (read once and kept). It builds the one environment every +start uses (the program's own folder first on PATH, so a node script finds the node beside it), starts tabs, Chat and checks +the same way, answers "installed" three ways (runs, found but does not start, not found) and keeps the record of where it +looked so the message can say so. + +Shared by the Form family: standard library only, nothing imported from the app, copied unchanged between engines and held +to the hash recorded for VERSION. The app passes in what is its own: the setting's value, the names of its override +variables, its base environment and how long to wait.""" + +from __future__ import annotations + +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path + +VERSION = "1.0.1" +PROGRAMS: dict = { + "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", + "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", + "home": (".claude/local", ".claude/bin"), "windows": ("home:.claude/local", "home:.claude/bin", "local:Programs/claude", "roaming:Programs/claude")}, + "codex": {"title": "Codex", "names": ("codex",), "setting": "codexBin", "install": "npm install -g @openai/codex", + "windows": ("local:Programs/OpenAI/Codex/bin",), "mac_files": ("Codex.app/Contents/Resources/codex", "Codex.app/Contents/Resources/bin/codex")}, + "cursor": {"title": "Cursor", "names": ("cursor-agent", "agent"), "setting": "cursorBin", "install": "curl https://cursor.com/install -fsS | bash", + "home": (".local/share/cursor-agent/versions/*",), "windows": ("local:cursor-agent",), "real": {"agent": "cursor"}}, + "antigravity": {"title": "Antigravity", "names": ("agy",), "setting": "antigravityBin", + "install": "curl -fsSL https://antigravity.google/cli/install.sh | bash", "install_windows": "irm https://antigravity.google/cli/install.ps1 | iex", + "windows_search": ("antigravity", "agy")}, +} +KEEP_ENV = frozenset({"CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CONFIG_DIR"}) +LIBRARY_VARS = ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH") +WINDOWS_ENDINGS = (".exe", ".cmd", ".bat") +MARK = "__FORM_AGENT_LOOKUP__" +HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"} +RETRY_SECONDS = 60.0 + +_lock = threading.RLock() +_shell: dict = {} +_checked: dict = {} + + +@dataclass +class Found: + program: str + title: str + path: str | None = None + how: str = "" + state: str = "missing" + version: str | None = None + error: str = "" + looked: list[str] = field(default_factory=list) + + +def register(key: str, title: str, names: tuple | list, **more) -> None: + """Adds a program to the table, or replaces one, without changing this file. The keys of an entry: title (the name + shown to people), names (the program's file names, first wins), setting (the family's name for its path setting), + install and install_windows (the install command), home (folders under the home folder on macOS and Linux; a * stands + for version folders, newest first), windows (folders as local:, roaming: or home: and a path), mac_files (files inside + an application bundle), windows_search (name fragments of folders one and two levels under %LOCALAPPDATA%) and real + (for a name other programs also use: the word its real path must contain).""" + PROGRAMS[key] = {"title": title, "names": tuple(names), **more} + + +def install(program: str, platform: str | None = None) -> str: + spec = PROGRAMS[program] + return (spec.get("install_windows") if windows(platform) else "") or spec.get("install", "") + + +def forget() -> None: + with _lock: + _shell.clear() + _checked.clear() + + +def windows(platform: str | None = None) -> bool: + return (platform or sys.platform).startswith("win") + + +def runnable(path: str | os.PathLike, platform: str | None = None) -> bool: + p = Path(path).expanduser() + return p.is_file() and (windows(platform) or os.access(p, os.X_OK)) + + +def short(path: str | os.PathLike, home: str | os.PathLike | None = None) -> str: + text, base = str(path), str(home or Path.home()) + return "~" + text[len(base):] if base not in ("", os.sep) and (text == base or text.startswith(base + os.sep)) else text + + +def _version_key(p: Path) -> tuple: + return tuple(int(x) for x in re.findall(r"\d+", p.name)) or (0,) + + +def _versions(base: Path, tail: str = "") -> list[Path]: + try: + kept = [d for d in base.iterdir() if d.is_dir()] + except OSError: + return [] + return [d / tail if tail else d for d in sorted(kept, key=_version_key, reverse=True)] + + +def system_folders(platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + if windows(platform): + return [] + if platform == "darwin": + return [Path("/opt/homebrew/bin"), Path("/usr/local/bin"), Path("/opt/local/bin")] + return [Path("/usr/local/bin"), Path("/usr/bin"), Path("/snap/bin"), Path("/home/linuxbrew/.linuxbrew/bin")] + + +def folders(program: str, home: str | os.PathLike | None = None, env: dict | None = None, platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + home = Path(home) if home else Path.home() + env = os.environ if env is None else env + win = windows(platform) + spec = PROGRAMS[program] + out: list[Path] = [] + for key in ("NPM_CONFIG_PREFIX", "npm_config_prefix"): + if env.get(key): + out.append(Path(env[key]) if win else Path(env[key]) / "bin") + for key, tail in (("PNPM_HOME", ""), ("VOLTA_HOME", "bin"), ("BUN_INSTALL", "bin"), ("NVM_SYMLINK", "")): + if env.get(key): + out.append(Path(env[key]) / tail if tail else Path(env[key])) + if win: + roots = {"home": home, "roaming": Path(env.get("APPDATA") or home / "AppData" / "Roaming"), "local": Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local")} + out += [home / ".local" / "bin", roots["roaming"] / "npm", roots["local"] / "npm", roots["local"] / "pnpm", roots["local"] / "Volta" / "bin", + home / ".bun" / "bin", home / ".volta" / "bin"] + for place in spec.get("windows", ()): + root, _, rest = place.partition(":") + out.append(roots[root].joinpath(*rest.split("/"))) + return list(dict.fromkeys(out)) + out += [home / ".local" / "bin", home / ".npm-global" / "bin", home / ".bun" / "bin", home / ".volta" / "bin", home / ".local" / "share" / "pnpm"] + if platform == "darwin": + out.append(home / "Library" / "pnpm") + out += _versions(home / ".nvm" / "versions" / "node", "bin") + out += _versions(home / ".local" / "share" / "fnm" / "node-versions", "installation/bin") + out += _versions(home / "Library" / "Application Support" / "fnm" / "node-versions", "installation/bin") + out += _versions(home / ".asdf" / "installs" / "nodejs", "bin") + out += _versions(home / ".local" / "share" / "mise" / "installs" / "node", "bin") + out += [home / ".asdf" / "shims", home / ".local" / "share" / "mise" / "shims"] + for place in spec.get("home", ()): + base, star, tail = place.partition("*") + out += _versions(home.joinpath(*base.strip("/").split("/")), tail.strip("/")) if star else [home.joinpath(*place.split("/"))] + out += system_folders(platform) + return list(dict.fromkeys(out)) + + +def _searched(root: Path, fragments: tuple) -> list[Path]: + out: list[Path] = [] + named = lambda d: any(f in d.name.lower() for f in fragments) + try: + first = sorted(d for d in root.iterdir() if d.is_dir()) + except OSError: + return out + for one in first: + if named(one): + out.append(one) + try: + out += [two for two in sorted(one.iterdir()) if two.is_dir() and (named(one) or named(two))] + except OSError: + continue + return out + + +def candidates(program: str, home: str | os.PathLike | None = None, env: dict | None = None, platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + home = Path(home) if home else Path.home() + env = os.environ if env is None else env + spec = PROGRAMS[program] + endings = WINDOWS_ENDINGS if windows(platform) else ("",) + places = folders(program, home, env, platform) + if windows(platform) and spec.get("windows_search"): + places += _searched(Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local"), tuple(spec["windows_search"])) + out = [folder / (name + ending) for folder in dict.fromkeys(places) for name in spec["names"] for ending in endings] + if platform == "darwin": + out += [apps.joinpath(*inside.split("/")) for apps in (Path("/Applications"), home / "Applications") for inside in spec.get("mac_files", ())] + return out + + +def _trusted(program: str, path: str | os.PathLike) -> bool: + name = Path(path).name.lower() + stem = name.rsplit(".", 1)[0] if name.endswith(WINDOWS_ENDINGS) else name + word = PROGRAMS[program].get("real", {}).get(stem) + return not word or word in os.path.realpath(path).lower() + + +def _on_path(program: str, path: str) -> str | None: + if not path: + return None + for name in PROGRAMS[program]["names"]: + hit = shutil.which(name, path=path) + if hit and _trusted(program, hit): + return os.path.abspath(hit) + return None + + +def login_shell(env: dict | None = None, platform: str | None = None) -> str: + env = os.environ if env is None else env + chosen = env.get("SHELL") + if chosen: + return chosen + if (platform or sys.platform) == "darwin" and os.path.exists("/bin/zsh"): + return "/bin/zsh" + return shutil.which("bash") or "/bin/sh" + + +def _stop(proc: subprocess.Popen) -> None: + try: + os.killpg(proc.pid, signal.SIGKILL) + except (OSError, AttributeError): + pass + try: + proc.kill() + except OSError: + pass + try: + proc.communicate(timeout=2) + except (OSError, ValueError, subprocess.SubprocessError): + pass + + +def _ask_shell(shell: str, flags: list[str], env: dict, timeout: float) -> list[str] | None: + script = f"printf '%s%s%s' {MARK} (string join : $PATH) {MARK}" if Path(shell).name == "fish" else f'printf "%s%s%s" {MARK} "$PATH" {MARK}' + try: + proc = subprocess.Popen([shell, *flags, "-c", script], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + env=env, text=True, errors="replace", start_new_session=True) + except OSError: + return None + try: + out, _ = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _stop(proc) + return None + hit = re.search(re.escape(MARK) + "(.*?)" + re.escape(MARK), out or "", re.S) + parts = [p for p in hit.group(1).split(os.pathsep) if p] if hit else [] + return parts or None + + +def _registry_path() -> list[str]: + try: + import winreg + except ImportError: + return [] + out: list[str] = [] + for root, key in ((winreg.HKEY_CURRENT_USER, "Environment"), (winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")): + try: + with winreg.OpenKey(root, key) as opened: + value, _kind = winreg.QueryValueEx(opened, "Path") + except OSError: + continue + out += [p.strip() for p in winreg.ExpandEnvironmentStrings(str(value)).split(";") if p.strip()] + return list(dict.fromkeys(out)) + + +def shell_path(env: dict | None = None, timeout: float = 10.0, fresh: bool = False, platform: str | None = None) -> tuple[list[str], str]: + """The person's own PATH: on macOS and Linux what their login, interactive shell ends up with (login only when the + interactive start gives nothing), on Windows the user and system Path values in the registry. Asked once and kept; an + empty answer is asked again after a minute, or at once with fresh.""" + env = dict(os.environ if env is None else env) + with _lock: + if _shell and not fresh and (_shell["path"] or time.monotonic() - _shell["at"] < RETRY_SECONDS): + return list(_shell["path"]), _shell["note"] + if windows(platform): + path = _registry_path() + note = "the Path values in the registry" if path else "the Path values in the registry (none could be read)" + else: + shell = login_shell(env, platform) + name = Path(shell).name + path = _ask_shell(shell, ["-l", "-i"], env, timeout) + note = f"your shell ({name}, login and interactive)" + if path is None: + path = _ask_shell(shell, ["-l"], env, timeout) + note = f"your shell ({name}, login only: the interactive start gave no PATH within {timeout:g} s)" + if path is None: + path, note = [], f"your shell ({name} gave no PATH within {timeout:g} s)" + _shell.update(path=list(path), note=note, at=time.monotonic()) + return list(path), note + + +def find(program: str, setting: str | None = None, override_vars: tuple = (), env: dict | None = None, home: str | os.PathLike | None = None, + platform: str | None = None, shell_timeout: float = 10.0, fresh: bool = False) -> Found: + """Where the program is, in the family's order. setting is the person's path for it ("" when empty, None when the app + has no such setting); override_vars are the names of the app's development override variables, read from env.""" + env = os.environ if env is None else env + platform = platform or sys.platform + spec = PROGRAMS[program] + found = Found(program, spec["title"]) + + def at(path: str | os.PathLike, how: str) -> Found: + found.path, found.how, found.state = str(path), how, "found" + return found + + if setting is not None: + chosen = setting.strip() + if chosen and runnable(chosen, platform): + return at(Path(chosen).expanduser(), "setting") + found.looked.append(f"your setting ({chosen}, which is not a program that can run)" if chosen else "your setting (empty)") + for var in override_vars: + value = (env.get(var) or "").strip() + if value and runnable(value, platform): + return at(Path(value).expanduser(), "override") + if value: + found.looked.append(f"{var} ({value}, which is not a program that can run)") + engine_path = env.get("PATH", "") + hit = _on_path(program, engine_path) + if hit: + return at(hit, "path") + found.looked.append(f"PATH ({engine_path or 'empty'})") + places = candidates(program, home, env, platform) + for place in places: + if runnable(place, platform) and _trusted(program, place): + return at(place, "folder") + found.looked.append(", ".join(dict.fromkeys(short(place.parent, home) for place in places))) + dirs, note = shell_path(env, shell_timeout, fresh, platform) + hit = _on_path(program, os.pathsep.join(dirs)) + if hit: + return at(hit, "shell") + found.looked.append(note) + return found + + +def child_env(path: str | os.PathLike | None = None, base: dict | None = None, extra: dict | None = None, front: tuple | list = (), + home: str | os.PathLike | None = None, platform: str | None = None, shell_timeout: float = 10.0, keep: frozenset | set = KEEP_ENV) -> dict: + """The environment every start of an agent program gets. PATH is the program's own folder, the app's own folders + (front), the person's shell PATH, the known install folders that exist, then the engine's PATH. CLAUDE* variables other + than keep are left out, and a frozen engine's library path is put back as it was. extra is applied last.""" + base = dict(os.environ if base is None else base) + env = {k: v for k, v in base.items() if not k.startswith("CLAUDE") or k in keep} + for name in LIBRARY_VARS: + original = base.get(name + "_ORIG") + if original is not None: + env[name] = original + elif getattr(sys, "frozen", False) or base.get("_MEIPASS2"): + env.pop(name, None) + dirs, _note = shell_path(base, shell_timeout, False, platform) + known = [str(f) for program in PROGRAMS for f in folders(program, home, base, platform) if f.is_dir()] + parts = ([str(Path(path).parent)] if path else []) + [str(f) for f in front] + dirs + known + base.get("PATH", "").split(os.pathsep) + env["PATH"] = os.pathsep.join(dict.fromkeys(p for p in parts if p)) + env.update(extra or {}) + return env + + +def _quote(word: str, fish: bool) -> str: + if word and re.fullmatch(r"[A-Za-z0-9_@%+=:,./-]+", word): + return word + if fish: + return "'" + word.replace("\\", "\\\\").replace("'", "\\'") + "'" + return "'" + word.replace("'", "'\"'\"'") + "'" + + +def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: + """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux + (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + words = [str(c) for c in cmd] + env = os.environ if env is None else env + if windows(platform): + return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + shell = login_shell(env, platform) + fish = Path(shell).name == "fish" + return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] + + +def run(cmd: list, env: dict, timeout: float = 15.0, platform: str | None = None) -> subprocess.CompletedProcess: + return subprocess.run(start_argv(cmd, env, platform), capture_output=True, text=True, errors="replace", timeout=timeout, env=env, stdin=subprocess.DEVNULL) + + +def _last_line(text: str) -> str: + lines = [line.strip() for line in (text or "").splitlines() if line.strip() and "use -[v]S to pass options" not in line] + return lines[-1][:300] if lines else "" + + +def _version(text: str) -> str | None: + words = (text or "").split() + return next((w for w in words if any(ch.isdigit() for ch in w)), words[0] if words else None) + + +def _stamp(path: str) -> tuple: + try: + st = os.stat(path) + return (path, st.st_mtime_ns, st.st_size) + except OSError: + return (path, 0, 0) + + +def check(found: Found, env: dict | None = None, timeout: float = 15.0, fresh: bool = False, platform: str | None = None) -> Found: + """Whether a found program starts: `--version` in the child environment, started as a tab would start it. The state + becomes runs (with the version) or broken (with the error line). An answer is kept for that file until it changes or + fresh asks again; a broken answer is asked again after a minute.""" + if not found.path: + return found + key = _stamp(found.path) + with _lock: + kept = None if fresh else _checked.get(key) + if kept is not None and kept[0] != "runs" and time.monotonic() - kept[3] >= RETRY_SECONDS: + kept = None + if kept is None: + env = child_env(found.path, platform=platform) if env is None else env + try: + out = run([found.path, "--version"], env, timeout, platform) + if out.returncode == 0: + kept = ("runs", _version(out.stdout), "", time.monotonic()) + else: + kept = ("broken", None, _last_line(out.stderr) or _last_line(out.stdout) or f"it ended with code {out.returncode}", time.monotonic()) + except subprocess.TimeoutExpired: + kept = ("broken", None, f"it gave no answer to --version in {timeout:g} seconds", time.monotonic()) + except OSError as exc: + kept = ("broken", None, exc.strerror or str(exc), time.monotonic()) + with _lock: + _checked[key] = kept + found.state, found.version, found.error = kept[0], kept[1], kept[2] + return found + + +def sentence(found: Found, install: str = "", otherwise: str = "") -> str: + """The truthful message, built from the record. install is the app's install command for the program; otherwise is + what else the person can do in this app, as a clause ("give its path in Preferences").""" + if found.state == "missing": + ways = ([f"install it with: {install}"] if install else []) + ([otherwise] if otherwise else []) + tail = " " + ", or ".join(ways) + "." if ways else "" + return f"{found.title} was not found. Looked in: {'; '.join(found.looked)}." + (tail[:1] + tail[1:2].upper() + tail[2:] if tail else "") + where = f"{found.path} ({HOW.get(found.how, found.how)})" + if found.state == "broken": + tail = f" To use another copy, {otherwise}." if otherwise else "" + return f"{found.title} was found at {where} but does not start: {found.error}.{tail}" + return f"{found.title} is at {where}." + + +def answer(found: Found, install: str = "", otherwise: str = "") -> dict: + """The fields a status route adds for one program: installed is true only when the program runs, and finding is + the three-way answer (runs, broken, missing).""" + return {"installed": found.state == "runs", "path": found.path, "version": found.version, "finding": found.state, "how": found.how, + "looked": list(found.looked), "error": found.error, "said": sentence(found, install, otherwise)} diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 3cb5d7a..32e3194 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -2,48 +2,84 @@ import json import os -import shlex -import shutil import subprocess import time from pathlib import Path -from app.services import agents, claude_code, terminal +from app.core import config +from app.services import agent_lookup, agents, claude_code, terminal PROGRAMS = { "codex": {"bin": "codex", "title": "Codex", "install": "npm install -g @openai/codex"}, "cursor": {"bin": "cursor-agent", "title": "Cursor", "install": "curl https://cursor.com/install -fsS | bash"}, + "antigravity": {"bin": "agy", "title": "Antigravity", "install": agent_lookup.install("antigravity")}, } +TABS = ("codex", "cursor", "antigravity") MCP_URL_VAR = "FORMTXT_MCP_URL" SERVER = "formtxt_tab" _cache: dict = {"at": 0.0, "value": None} def find(kind: str) -> str | None: - binary = PROGRAMS[kind]["bin"] - found = shutil.which(binary, path=terminal.base_env().get("PATH")) - if found or os.name == "nt": - return found + return claude_code.located(kind).path + + +def tab_folder(kind: str) -> Path: + folder = config.data_dir() / "agent-tabs" / kind + folder.mkdir(parents=True, exist_ok=True) + return folder + + +def _mcp_file(folder: Path) -> Path: + return folder / ".agents" / "mcp_config.json" + + +def _servers(path: Path) -> dict: + data = json.loads(path.read_text(encoding="utf-8") or "{}") if path.exists() else {} + if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict): + raise OSError(f"{path} is not an MCP servers file FormTxt can read, so it was left alone") + return data + + +def _replace(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + part = path.with_name(path.name + f".part-{os.getpid()}") + with os.fdopen(os.open(part, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as fh: + fh.write(json.dumps(data, indent=2) + "\n") + os.replace(part, path) + + +def write_tab_entry(folder: Path, port: int, token: str) -> None: + path = _mcp_file(folder) + data = _servers(path) + data.setdefault("mcpServers", {})[SERVER] = {"serverUrl": f"http://127.0.0.1:{port}/mcp", "headers": {agents.INAPP_HEADER: token}} + _replace(path, data) + + +def remove_tab_entry(folder: Path, token: str) -> None: + path = _mcp_file(folder) try: - out = subprocess.run(terminal.login_shell() + ["-c", f"command -v {shlex.quote(binary)}"], capture_output=True, text=True, timeout=10, - env=claude_code.child_env(), stdin=subprocess.DEVNULL) - except (OSError, subprocess.SubprocessError): - return None - lines = out.stdout.strip().splitlines()[-1:] if out.returncode == 0 else [] - return lines[0] if lines and os.path.isabs(lines[0]) and os.access(lines[0], os.X_OK) else None + data = _servers(path) + entry = data.get("mcpServers", {}).get(SERVER) + if not isinstance(entry, dict) or (entry.get("headers") or {}).get(agents.INAPP_HEADER) != token: + return + del data["mcpServers"][SERVER] + _replace(path, data) + except (OSError, ValueError): + return -def status() -> dict: +def status(fresh: bool = False) -> dict: out = {} for kind, p in PROGRAMS.items(): - path = find(kind) - out[kind] = {"installed": path is not None, "path": path, "version": None, "signedIn": None, "install": "" if path else p["install"], "title": p["title"]} + found = claude_code.located(kind, fresh) + out[kind] = agent_lookup.answer(found, p["install"], claude_code.OTHERWISE) | {"signedIn": None, "install": "" if found.state == "runs" else p["install"], "title": p["title"]} return out def version(path: str) -> str | None: try: - out = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=10, env=claude_code.child_env(), stdin=subprocess.DEVNULL) + out = agent_lookup.run([path, "--version"], claude_code.child_env(path), claude_code.CHECK_WAIT) except (OSError, subprocess.SubprocessError): return None return next((word for word in out.stdout.split() if word[:1].isdigit()), None) @@ -53,8 +89,8 @@ def report(fresh: bool = False) -> dict: if fresh or _cache["value"] is None or time.time() - _cache["at"] >= 60: found = {} for kind, p in PROGRAMS.items(): - path = find(kind) - found[kind] = {"installed": path is not None, "path": path, "version": version(path) if path else None, "signedIn": None, "install": p["install"], "title": p["title"]} + located = claude_code.located(kind, fresh) + found[kind] = agent_lookup.answer(located, p["install"], claude_code.OTHERWISE) | {"signedIn": None, "install": p["install"], "title": p["title"]} _cache.update(at=time.time(), value=found) return {"claude": {**claude_code.info(fresh=fresh), "title": "Claude Code"}, **_cache["value"]} @@ -88,22 +124,29 @@ def cursor_config(folder: str) -> str | None: def open_terminal(kind: str, port: int, cols: int, rows: int, document_folder: str | None = None) -> dict: - if kind not in PROGRAMS: + if kind not in TABS: raise ValueError(f"No agent program called {kind}") - path = find(kind) - if path is None: - raise LookupError(f"{PROGRAMS[kind]['title']} is not installed on this computer.") - command = [path] + (codex_args(port) if kind == "codex" else []) - argv = command if os.name == "nt" else terminal.login_shell() + ["-c", "exec " + shlex.join(command)] - folder = claude_code.workdir(document_folder) + found = claude_code.usable(kind) + if found.state != "runs": + raise LookupError(claude_code.said(found)) + path = found.path + argv = agent_lookup.start_argv([path] + (codex_args(port) if kind == "codex" else [])) + own = tab_folder(kind) if kind == "antigravity" else None + folder = str(own) if own else claude_code.workdir(document_folder) if kind == "cursor": cursor_config(folder) token = agents.issue() - env = terminal.base_env() | {claude_code.INAPP_VAR: token, MCP_URL_VAR: f"http://127.0.0.1:{port}/mcp"} + env = claude_code.terminal_env(token, path, {MCP_URL_VAR: f"http://127.0.0.1:{port}/mcp"}) try: + if own: + write_tab_entry(own, port, token) session = terminal.open_session(folder, cols, rows, PROGRAMS[kind]["title"], argv, env, kind) except BaseException: agents.revoke(token) + if own: + remove_tab_entry(own, token) raise session.on_close.append(lambda: agents.revoke(token)) + if own: + session.on_close.append(lambda: remove_tab_entry(own, token)) return session.describe() diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index b1fbfa9..ca0b3ce 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -2,21 +2,20 @@ import json import logging import os -import shlex -import shutil import subprocess import sys import threading import time -from pathlib import Path from app.core import config -from app.services import agents, terminal +from app.services import agent_lookup, agents, terminal log = logging.getLogger("formtxt.claude_code") -KEEP_ENV = {"CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CONFIG_DIR"} -CANDIDATES = (".claude/local/claude", ".local/bin/claude", ".npm-global/bin/claude", ".bun/bin/claude", ".volta/bin/claude") -SYSTEM_PATHS = ("/opt/homebrew/bin/claude", "/usr/local/bin/claude", "/usr/bin/claude") +KEEP_ENV = agent_lookup.KEEP_ENV +OVERRIDES = {"claude": ("FORMTXT_CLAUDE_BIN",), "codex": ("FORMTXT_CODEX_BIN",), "cursor": ("FORMTXT_CURSOR_BIN",), "antigravity": ("FORMTXT_ANTIGRAVITY_BIN",)} +SHELL_WAIT = 10.0 +CHECK_WAIT = 15.0 +OTHERWISE = "" MODES = {"ask": "manual", "auto-edits": "acceptEdits", "plan": "plan"} INSTALL = "irm https://claude.ai/install.ps1 | iex" if sys.platform == "win32" else "curl -fsSL https://claude.ai/install.sh | bash" MISSING = f"Claude Code is not installed. Install it with: {INSTALL}" @@ -27,40 +26,37 @@ _cache: dict = {"at": 0.0, "value": None} -def child_env() -> dict: - env = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE") or k in KEEP_ENV} - env["CLAUDE_PROJECT_DIR"] = str(config.REPO_DIR) - env["PATH"] = str(config.REPO_DIR) + os.pathsep + env.get("PATH", "") - return env +def child_env(path: str | None = None) -> dict: + return agent_lookup.child_env(path, front=[config.REPO_DIR], extra={"CLAUDE_PROJECT_DIR": str(config.REPO_DIR)}, shell_timeout=SHELL_WAIT) + + +def setting(kind: str) -> str | None: + return None + + +def located(kind: str, fresh: bool = False) -> agent_lookup.Found: + found = agent_lookup.find(kind, setting=setting(kind), override_vars=OVERRIDES.get(kind, ()), shell_timeout=SHELL_WAIT, fresh=fresh) + return agent_lookup.check(found, child_env(found.path), CHECK_WAIT, fresh) + + +def usable(kind: str) -> agent_lookup.Found: + found = located(kind) + return found if found.state == "runs" else located(kind, fresh=True) + + +def said(found: agent_lookup.Found) -> str: + return agent_lookup.sentence(found, agent_lookup.install(found.program), OTHERWISE) def cli() -> str | None: - found = os.environ.get("FORMTXT_CLAUDE_BIN") or shutil.which("claude") - if found: - return found - home = Path.home() - for p in [home / c for c in CANDIDATES] + [Path(s) for s in SYSTEM_PATHS]: - if p.is_file() and os.access(p, os.X_OK): - return str(p) - return _from_login_shell() - - -def _from_login_shell() -> str | None: - if os.name == "nt": - return None - try: - out = subprocess.run(terminal.login_shell() + ["-c", "command -v claude"], capture_output=True, text=True, timeout=10, env=child_env(), stdin=subprocess.DEVNULL) - except (OSError, subprocess.SubprocessError): - return None - found = out.stdout.strip().splitlines()[-1:] if out.returncode == 0 else [] - return found[0] if found and os.path.isabs(found[0]) else None + return located("claude").path def _signed_in(path: str) -> bool | None: if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"): return True try: - out = subprocess.run([path, "auth", "status"], capture_output=True, text=True, timeout=15, env=child_env()) + out = agent_lookup.run([path, "auth", "status"], child_env(path), CHECK_WAIT) except (OSError, subprocess.SubprocessError): return None try: @@ -73,16 +69,9 @@ def _signed_in(path: str) -> bool | None: def info(fresh: bool = False) -> dict: if not fresh and _cache["value"] is not None and time.time() - _cache["at"] < 60: return _cache["value"] - path, version, signed = cli(), None, None - if path: - try: - out = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=15, env=child_env()) - version = (out.stdout.strip().split() or [None])[0] - except (OSError, subprocess.SubprocessError): - path = None - if path: - signed = _signed_in(path) - _cache["value"], _cache["at"] = {"installed": bool(path), "path": path, "version": version, "signedIn": signed, "install": INSTALL}, time.time() + found = located("claude", fresh) + signed = _signed_in(found.path) if found.state == "runs" else None + _cache["value"], _cache["at"] = agent_lookup.answer(found, INSTALL, OTHERWISE) | {"signedIn": signed, "install": INSTALL}, time.time() return _cache["value"] @@ -304,7 +293,7 @@ def start(mode: str = "ask", fresh: bool = False, port: int | None = None) -> di raise ValueError("The mode is ask, auto-edits or plan.") found = info() if not found["installed"]: - raise LookupError(f"Claude Code is not installed. Install it with: {found['install']}") + raise LookupError(found["said"]) running = AGENT.proc is not None and AGENT.proc.poll() is None if running and AGENT.mode == mode and not fresh: return AGENT.describe() @@ -333,7 +322,7 @@ def start(mode: str = "ask", fresh: bool = False, port: int | None = None) -> di agents.revoke(AGENT.token) AGENT.token = agents.issue() if port else "" try: - proc = subprocess.Popen(args, cwd=str(config.REPO_DIR), env=child_env() | ({INAPP_VAR: AGENT.token} if port else {}), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) + proc = subprocess.Popen(agent_lookup.start_argv(args), cwd=str(config.REPO_DIR), env=child_env(found["path"]) | ({INAPP_VAR: AGENT.token} if port else {}), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) except OSError as exc: agents.revoke(AGENT.token) AGENT.token = "" @@ -388,8 +377,8 @@ def stop(quiet: bool = False) -> dict: def program() -> str | None: - path = cli() - return path if path and os.path.isfile(path) and os.access(path, os.X_OK) else None + found = located("claude") + return found.path if found.state == "runs" else None TAB_SERVER = "formtxt_tab" @@ -399,8 +388,8 @@ def inapp_mcp_config(port: int) -> str: return json.dumps({"mcpServers": {TAB_SERVER: {"type": "http", "url": f"http://127.0.0.1:{port}/mcp", "headers": {agents.INAPP_HEADER: "${" + INAPP_VAR + "}"}}}}) -def terminal_env(token: str) -> dict: - return {k: v for k, v in terminal.base_env().items() if not k.startswith("CLAUDE") or k in KEEP_ENV} | {INAPP_VAR: token} +def terminal_env(token: str, path: str | None = None, extra: dict | None = None) -> dict: + return agent_lookup.child_env(path, base=terminal.base_env(), front=[config.REPO_DIR], extra={INAPP_VAR: token} | (extra or {}), shell_timeout=SHELL_WAIT) def terminal_argv(path: str, port: int, prompt: str | None, resume: str | None) -> list[str]: @@ -409,9 +398,7 @@ def terminal_argv(path: str, port: int, prompt: str | None, resume: str | None) cmd += ["--strict-mcp-config", "--resume", resume] if prompt: cmd += ["--", prompt] - if os.name == "nt": - return cmd - return terminal.login_shell() + ["-c", "exec " + shlex.join(cmd)] + return agent_lookup.start_argv(cmd) def workdir(document_folder: str | None = None) -> str: @@ -426,14 +413,15 @@ def open_terminal(port: int, prompt: str | None = None, resume: str | None = Non if prompt: terminal.write(running.id, prompt.replace("\r\n", "\n").replace("\r", "\n") + "\r") return running.describe() - path = program() - if path is None: - raise LookupError(MISSING) + found = usable("claude") + if found.state != "runs": + raise LookupError(said(found)) + path = found.path title = "Claude Code (from Chat)" if resume else "Claude Code" folder = str(config.REPO_DIR) if resume else workdir(document_folder) token = agents.issue() try: - session = terminal.open_session(folder, cols, rows, title, terminal_argv(path, port, prompt, resume), terminal_env(token), "claude") + session = terminal.open_session(folder, cols, rows, title, terminal_argv(path, port, prompt, resume), terminal_env(token, path), "claude") except BaseException: agents.revoke(token) raise diff --git a/backend/formtxt_engine.py b/backend/formtxt_engine.py index 59886e7..0b1fe2c 100644 --- a/backend/formtxt_engine.py +++ b/backend/formtxt_engine.py @@ -2,6 +2,13 @@ import os import sys +if sys.stdin is None: + sys.stdin = open(os.devnull, encoding="utf-8") +if sys.stdout is None: + sys.stdout = open(os.devnull, "w", encoding="utf-8") +if sys.stderr is None: + sys.stderr = open(os.devnull, "w", encoding="utf-8") + def resource_dir() -> str: return getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b322c2c..87cb1c3 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -46,13 +46,54 @@ os.environ["USERPROFILE"] = str(_SANDBOX / "home") for _key in [k for k in os.environ if k.startswith(f"{ENV_PREFIX}_") and k not in (DATA_ENV, PORT_ENV)]: os.environ.pop(_key) +AGENT_STAND_INS = ("claude", "codex", "cursor-agent", "agent", "agy") +AGENT_CALLS = _SANDBOX / "agent-calls.log" +AGENT_SHELL = """#!/bin/sh +script="" +while [ $# -gt 0 ]; do + case "$1" in -c) shift; script="$1" ;; esac + shift +done +if [ -n "$script" ]; then exec /bin/sh -c "$script"; fi +exec /bin/sh +""" +_agent_calls: list[str] = [] +if os.name != "nt": + for _name in ("bin", "shell", "tools"): + (_SANDBOX / _name).mkdir() + _node = shutil.which("node") + if _node: + (_SANDBOX / "tools" / "node").symlink_to(os.path.realpath(_node)) + for _name in AGENT_STAND_INS: + (_SANDBOX / "bin" / _name).write_text(f'#!/bin/sh\necho "{_name} $*" >> "{AGENT_CALLS}"\nif [ "$1" = "--version" ]; then echo "0.0.0 (stand-in)"; exit 0; fi\nexit 1\n') + (_SANDBOX / "bin" / _name).chmod(0o755) + (_SANDBOX / "shell" / "zsh").write_text(AGENT_SHELL) + (_SANDBOX / "shell" / "zsh").chmod(0o755) + os.environ["SHELL"] = str(_SANDBOX / "shell" / "zsh") + os.environ["PATH"] = os.pathsep.join([str(_SANDBOX / "bin"), str(_SANDBOX / "tools"), "/usr/bin", "/bin", "/usr/sbin", "/sbin"]) + for _key in ("NPM_CONFIG_PREFIX", "npm_config_prefix", "PNPM_HOME", "VOLTA_HOME", "BUN_INSTALL", "NVM_SYMLINK"): + os.environ.pop(_key, None) sys.path.insert(0, str(BACKEND)) +@pytest.fixture(autouse=True) +def only_stand_in_agent_programs(monkeypatch): + agent_lookup = importlib.import_module("app.services.agent_lookup") + monkeypatch.setattr(agent_lookup, "system_folders", lambda platform=None: []) + + def pytest_sessionfinish(session, exitstatus): + try: + _agent_calls.extend(AGENT_CALLS.read_text(encoding="utf-8").splitlines()) + except OSError: + pass shutil.rmtree(_SANDBOX, ignore_errors=True) +def pytest_terminal_summary(terminalreporter): + terminalreporter.write_line(f"agent program stand-ins started {len(_agent_calls)} time(s): " + (", ".join(sorted(set(_agent_calls))) or "none")) + + def own_origin(): return f"http://127.0.0.1:{ENGINE_PORT}" @@ -141,3 +182,49 @@ def engine(): proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() + + +STAND_IN_SHELL = """#!/bin/sh +script="" +while [ $# -gt 0 ]; do + if [ "$1" = "-c" ]; then shift; script="$1"; fi + shift +done +if [ -f "$HOME/.shell-path" ]; then PATH="$(cat "$HOME/.shell-path"):$PATH"; export PATH; fi +exec /bin/sh -c "$script" +""" +STAND_IN = """#!/bin/sh +if [ "$1" = "--version" ]; then echo "9.9.9 (stand-in)"; exit 0; fi +echo "stand-in started" +read line +""" +SYSTEM_PATH = "/usr/bin:/bin:/usr/sbin:/sbin" +FOLDER_VARS = ("NPM_CONFIG_PREFIX", "npm_config_prefix", "PNPM_HOME", "VOLTA_HOME", "BUN_INSTALL", "NVM_SYMLINK") + + +def stand_in(path, text=STAND_IN): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + path.chmod(0o755) + return path + + +@pytest.fixture +def dock_start(tmp_path, monkeypatch): + from app.services import agent_lookup, agent_programs, claude_code + + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("SHELL", str(stand_in(tmp_path / "zsh", STAND_IN_SHELL))) + monkeypatch.setenv("PATH", SYSTEM_PATH) + for name in [n for names in claude_code.OVERRIDES.values() for n in names] + list(FOLDER_VARS): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(agent_lookup, "system_folders", lambda platform=None: []) + claude_code._cache.update(at=0.0, value=None) + agent_programs._cache.update(at=0.0, value=None) + agent_lookup.forget() + yield home + claude_code._cache.update(at=0.0, value=None) + agent_programs._cache.update(at=0.0, value=None) + agent_lookup.forget() diff --git a/backend/tests/test_agent_lookup.py b/backend/tests/test_agent_lookup.py new file mode 100644 index 0000000..a0181a5 --- /dev/null +++ b/backend/tests/test_agent_lookup.py @@ -0,0 +1,97 @@ +import os +import time + +import pytest + +from conftest import SYSTEM_PATH, stand_in + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="the stand-ins are shell scripts") +NODE_STYLE = '#!/usr/bin/env node\nif [ "$1" = "--version" ]; then echo "7.7.7 (node-style stand-in)"; exit 0; fi\necho "first on PATH: ${PATH%%:*}"\nread line\n' +STAND_IN_NODE = '#!/bin/sh\nscript="$1"; shift; exec /bin/sh "$script" "$@"\n' +SIGNED_IN = '#!/bin/sh\nif [ "$1" = "auth" ]; then echo \'{"loggedIn": true}\'; exit 0; fi\necho "2.9.9 (stand-in)"\n' +BROKEN = "#!/usr/bin/env node-that-is-not-here\n" + + +def test_started_from_the_dock_the_status_reports_four_programs_with_how_each_was_found_and_where_it_looked(client, dock_start): + stand_in(dock_start / ".local/bin/claude", SIGNED_IN) + stand_in(dock_start / ".nvm/versions/node/v22.3.0/bin/codex") + stand_in(dock_start / "odd tools" / "cursor-agent") + (dock_start / ".shell-path").write_text(str(dock_start / "odd tools")) + status = client.get("/api/agents/status?fresh=true").json() + assert set(status) == {"claude", "codex", "cursor", "antigravity"} + assert status["claude"] == status["claude"] | {"installed": True, "finding": "runs", "how": "folder", "version": "2.9.9", "signedIn": True, "path": str(dock_start / ".local/bin/claude")} + assert status["codex"] == status["codex"] | {"installed": True, "finding": "runs", "how": "folder", "version": "9.9.9", "signedIn": None} + assert status["cursor"] == status["cursor"] | {"installed": True, "finding": "runs", "how": "shell", "path": str(dock_start / "odd tools" / "cursor-agent")} + assert status["cursor"]["said"] == f"Cursor is at {dock_start / 'odd tools' / 'cursor-agent'} (your shell's PATH)." + missing = status["antigravity"] + assert missing == missing | {"installed": False, "finding": "missing", "path": None, "version": None, "signedIn": None, "title": "Antigravity", "how": ""} + assert missing["looked"][0] == f"PATH ({SYSTEM_PATH})" and "~/.local/bin, ~/.npm-global/bin" in missing["looked"][1] and missing["looked"][-1] == "your shell (zsh, login and interactive)" + assert missing["said"].startswith(f"Antigravity was not found. Looked in: PATH ({SYSTEM_PATH}); ~/.local/bin, ") and missing["said"].endswith(f"Install it with: {missing['install']}.") + window = client.get("/api/claude-code/status?fresh=true").json() + assert (window["finding"], window["how"], window["installed"]) == ("runs", "folder", True) + assert {kind: (entry["finding"], entry["install"] == "") for kind, entry in window["agents"].items()} == {"codex": ("runs", True), "cursor": ("runs", True), "antigravity": ("missing", False)} + chat = client.get("/api/agent/claude/status").json() + assert (chat["finding"], chat["how"], chat["running"]) == ("runs", "folder", False) and "state" in chat + + +def test_a_program_that_is_found_but_does_not_start_is_not_installed_and_says_why(client, dock_start): + place = stand_in(dock_start / ".local/bin/codex", BROKEN) + codex = client.get("/api/agents/status?fresh=true").json()["codex"] + assert (codex["installed"], codex["finding"], codex["path"], codex["version"]) == (False, "broken", str(place), None) + assert "node-that-is-not-here" in codex["error"] and codex["said"].startswith(f"Codex was found at {place} (a known install folder) but does not start: ") + + +def test_a_tab_starts_a_node_style_program_with_its_own_folder_first_on_the_path(client, dock_start): + from app.services import claude_code, terminal + + place = stand_in(dock_start / ".nvm/versions/node/v22.3.0/bin/codex", NODE_STYLE) + stand_in(place.parent / "node", STAND_IN_NODE) + res = client.post("/api/terminal/agent", json={"kind": "codex", "cols": 80, "rows": 20}) + assert res.status_code == 200 + session = terminal.SESSIONS[res.json()["id"]] + try: + assert session.env["PATH"].split(os.pathsep)[0] == str(place.parent) and session.argv[:2] == [os.environ["SHELL"], "-l"] + for _ in range(50): + if "first on PATH" in session.scrollback(): + break + time.sleep(0.1) + assert f"first on PATH: {place.parent}" in session.scrollback() + finally: + assert client.delete(f"/api/terminal/{session.id}").status_code == 200 + assert claude_code.child_env(str(place))["PATH"].split(os.pathsep)[0] == str(place.parent) + + +def test_a_claude_code_tab_starts_the_program_found_in_a_known_folder(client, dock_start): + from app.services import terminal + + place = stand_in(dock_start / ".local/bin/claude", NODE_STYLE) + stand_in(place.parent / "node", STAND_IN_NODE) + res = client.post("/api/terminal/claude", json={"fresh": True, "cols": 80, "rows": 20}) + assert res.status_code == 200 and res.json()["kind"] == "claude" + session = terminal.SESSIONS[res.json()["id"]] + try: + assert session.env["PATH"].split(os.pathsep)[0] == str(place.parent) and session.env["FORMTXT_INAPP_TOKEN"] + for _ in range(50): + if "first on PATH" in session.scrollback(): + break + time.sleep(0.1) + assert f"first on PATH: {place.parent}" in session.scrollback() + finally: + assert client.delete(f"/api/terminal/{session.id}").status_code == 200 + + +def test_opening_a_tab_or_chat_for_a_missing_or_broken_program_answers_with_the_finders_sentence(client, dock_start): + from app.services import agent_programs + + res = client.post("/api/terminal/agent", json={"kind": "codex"}) + assert res.status_code == 404 and res.json()["detail"].startswith(f"Codex was not found. Looked in: PATH ({SYSTEM_PATH}); ") + res = client.post("/api/terminal/claude", json={"fresh": True}) + assert res.status_code == 404 and res.json()["detail"].startswith("Claude Code was not found. Looked in: ") + stand_in(dock_start / ".local/bin/claude", BROKEN) + res = client.post("/api/terminal/claude", json={"fresh": True}) + assert res.status_code == 404 and " but does not start: " in res.json()["detail"] + res = client.post("/api/agent/claude/start", json={"mode": "ask"}) + assert res.status_code == 409 and res.json()["detail"].startswith("Claude Code was found at ") + res = client.post("/api/terminal/agent", json={"kind": "antigravity"}) + assert res.status_code == 404 and res.json()["detail"].startswith("Antigravity was not found. Looked in: ") + assert set(agent_programs.PROGRAMS) == {"codex", "cursor", "antigravity"} and agent_programs.TABS == ("codex", "cursor", "antigravity") diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index ad93dc8..c903bbf 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -1,35 +1,32 @@ +import importlib.util +import json import os import time import pytest from app.core import window_key +from conftest import REPO, SYSTEM_PATH, stand_in @pytest.fixture -def stand_ins(tmp_path, monkeypatch): +def stand_ins(tmp_path, dock_start, monkeypatch): folder = tmp_path / "bin" - folder.mkdir() for name in ("codex", "cursor-agent"): - script = folder / name - script.write_text('#!/bin/sh\necho "stand-in started"\nread line\n') - script.chmod(0o755) - monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{os.environ.get('PATH', '')}") + stand_in(folder / name) + monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{SYSTEM_PATH}") return folder @pytest.fixture -def no_login_shell(monkeypatch): - from app.services import agent_programs - - monkeypatch.setattr(agent_programs.terminal, "login_shell", lambda: ["/bin/sh", "-c", "exit 1", "--"]) +def no_login_shell(dock_start): + return dock_start -def test_the_status_says_codex_and_cursor_are_missing_with_how_to_get_them(client, no_login_shell, monkeypatch): - monkeypatch.setenv("PATH", "/usr/bin:/bin") +def test_the_status_says_codex_and_cursor_are_missing_with_how_to_get_them(client, no_login_shell): agents = client.get("/api/claude-code/status").json()["agents"] - assert set(agents) == {"codex", "cursor"} - for kind in ("codex", "cursor"): + assert set(agents) == {"codex", "cursor", "antigravity"} + for kind in ("codex", "cursor", "antigravity"): assert agents[kind]["installed"] is False and agents[kind]["path"] is None and agents[kind]["install"] @@ -55,8 +52,7 @@ def test_a_program_tab_gets_its_own_token_in_its_environment_never_on_its_comman assert not agents.is_inapp(token) -def test_a_missing_program_or_an_unknown_kind_is_refused(client, no_login_shell, monkeypatch): - monkeypatch.setenv("PATH", "/usr/bin:/bin") +def test_a_missing_program_or_an_unknown_kind_is_refused(client, no_login_shell): assert client.post("/api/terminal/agent", json={"kind": "codex"}).status_code == 404 assert client.post("/api/terminal/agent", json={"kind": "vim"}).status_code == 422 @@ -64,3 +60,83 @@ def test_a_missing_program_or_an_unknown_kind_is_refused(client, no_login_shell, def test_starting_a_program_tab_needs_the_window_key(bare, stand_ins): res = bare.post("/api/terminal/agent", json={"kind": "codex"}) assert res.status_code == 403 and res.json() == {"detail": window_key.REFUSED} + + +@pytest.mark.skipif(os.name == "nt", reason="the stand-ins are shell scripts") +def test_an_antigravity_tab_gets_its_entry_in_its_own_folder_and_loses_it_when_it_closes(client, stand_ins): + from app.services import agent_programs, agents, terminal + + stand_in(stand_ins / "agy") + folder = agent_programs.tab_folder("antigravity") + path = folder / ".agents" / "mcp_config.json" + path.parent.mkdir(parents=True, exist_ok=True) + seeded = {"mcpServers": {"other": {"command": "other"}}, "theme": "kept"} + path.write_text(json.dumps(seeded)) + res = client.post("/api/terminal/agent", json={"kind": "antigravity", "cols": 80, "rows": 20}) + assert res.status_code == 200 and res.json()["kind"] == "antigravity" and res.json()["title"] == "Antigravity" + assert res.json()["cwd"] == str(folder) + session = terminal.SESSIONS[res.json()["id"]] + token = session.env["FORMTXT_INAPP_TOKEN"] + kept = json.loads(path.read_text()) + assert kept["theme"] == "kept" and kept["mcpServers"]["other"] == {"command": "other"} + assert kept["mcpServers"]["formtxt_tab"]["headers"] == {"x-formtxt-inapp": token} and kept["mcpServers"]["formtxt_tab"]["serverUrl"].endswith("/mcp") + assert path.stat().st_mode & 0o777 == 0o600 + assert agents.is_inapp(token) and all(token not in part for part in session.argv) + assert client.delete(f"/api/terminal/{session.id}").status_code == 200 + time.sleep(0.1) + assert json.loads(path.read_text()) == seeded + assert not agents.is_inapp(token) + + +def test_a_tab_entry_that_is_not_this_tabs_is_left_alone(tmp_path): + from app.services import agent_programs + + agent_programs.write_tab_entry(tmp_path, 8210, "first") + agent_programs.write_tab_entry(tmp_path, 8210, "second") + agent_programs.remove_tab_entry(tmp_path, "first") + path = tmp_path / ".agents" / "mcp_config.json" + assert json.loads(path.read_text())["mcpServers"]["formtxt_tab"]["headers"] == {"x-formtxt-inapp": "second"} + agent_programs.remove_tab_entry(tmp_path, "second") + assert json.loads(path.read_text()) == {"mcpServers": {}} + + +def _kit(): + spec = importlib.util.spec_from_file_location("installed_agents", REPO / "setup" / "agents.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_agents_install_adds_formtxt_to_antigravity_and_keeps_the_rest(tmp_path): + kit = _kit() + cfg = tmp_path / ".gemini" / "config" / "mcp_config.json" + said = [] + kit.install_antigravity(tmp_path, True, said) + assert not cfg.exists() and said[-1] == f" MCP server formtxt -> {cfg}" + cfg.parent.mkdir(parents=True) + cfg.write_text(json.dumps({"mcpServers": {"other": {"command": "x"}}, "theme": "kept"})) + kit.install_antigravity(tmp_path, False, said) + now = json.loads(cfg.read_text()) + assert now == {"mcpServers": {"other": {"command": "x"}, "formtxt": {"command": kit.LAUNCH, "args": kit.ARGS}}, "theme": "kept"} + before = cfg.read_bytes() + kit.install_antigravity(tmp_path, False, said) + assert said[-1] == f" MCP server formtxt already in {cfg}" and cfg.read_bytes() == before + + +def test_agents_install_leaves_alone_what_it_did_not_write_for_antigravity(tmp_path): + kit = _kit() + cfg = tmp_path / ".gemini" / "config" / "mcp_config.json" + older = tmp_path / ".gemini" / "antigravity-cli" / "mcp_config.json" + older.parent.mkdir(parents=True) + older.write_text("{}") + said = [] + kit.install_antigravity(tmp_path, True, said) + assert said[1] == f" an older file was seen at {older} and left alone; the documented file is {cfg}" and older.read_text() == "{}" + cfg.parent.mkdir(parents=True) + foreign = json.dumps({"mcpServers": {"formtxt": {"command": "/elsewhere/other", "args": ["serve"]}}}) + cfg.write_text(foreign) + kit.install_antigravity(tmp_path, False, said) + assert said[-1] == f" {cfg} has a server named formtxt that FormTxt did not write; left alone" and cfg.read_text() == foreign + cfg.write_text("nope") + kit.install_antigravity(tmp_path, False, said) + assert said[-1] == f" {cfg} is not an MCP servers file FormTxt can read; left alone" and cfg.read_text() == "nope" diff --git a/backend/tests/test_agent_status.py b/backend/tests/test_agent_status.py index d235f38..3ad717d 100644 --- a/backend/tests/test_agent_status.py +++ b/backend/tests/test_agent_status.py @@ -4,30 +4,26 @@ import pytest +from conftest import SYSTEM_PATH, stand_in -@pytest.fixture -def programs(tmp_path, monkeypatch): - from app.services import agent_programs, claude_code +@pytest.fixture +def programs(tmp_path, dock_start, monkeypatch): folder = tmp_path / "bin" - folder.mkdir() lines = {"claude": "9.9.9 (Claude Code)", "codex": "codex-cli 0.99.1", "cursor-agent": "2026.11.01-abc123"} for name, line in lines.items(): - script = folder / name - script.write_text(f'#!/bin/sh\ncase "$1" in --version) echo "{line}"; exit 0;; auth) echo \'{{"loggedIn": true}}\'; exit 0;; esac\nread line\n') - script.chmod(0o755) - monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{os.environ.get('PATH', '')}") + stand_in(folder / name, f'#!/bin/sh\ncase "$1" in --version) echo "{line}"; exit 0;; auth) echo \'{{"loggedIn": true}}\'; exit 0;; esac\nread line\n') + monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{SYSTEM_PATH}") monkeypatch.setenv("FORMTXT_CLAUDE_BIN", str(folder / "claude")) - yield folder - claude_code._cache.update(at=0.0, value=None) - agent_programs._cache.update(at=0.0, value=None) + return folder @pytest.mark.skipif(os.name == "nt", reason="the stand-ins are shell scripts") def test_one_call_reports_the_three_agent_programs(client, programs): status = client.get("/api/agents/status?fresh=true").json() - assert set(status) == {"claude", "codex", "cursor"} - assert status["claude"] == status["claude"] | {"installed": True, "version": "9.9.9", "signedIn": True} + assert set(status) == {"claude", "codex", "cursor", "antigravity"} + assert status["antigravity"] == status["antigravity"] | {"installed": False, "finding": "missing", "path": None, "signedIn": None, "title": "Antigravity"} + assert status["claude"] == status["claude"] | {"installed": True, "version": "9.9.9", "signedIn": True, "how": "override"} assert status["codex"] == status["codex"] | {"installed": True, "version": "0.99.1", "signedIn": None, "install": "npm install -g @openai/codex"} assert status["cursor"] == status["cursor"] | {"installed": True, "version": "2026.11.01-abc123", "path": str(programs / "cursor-agent")} assert all(entry["install"] for entry in status.values()) diff --git a/backend/tests/test_dock_manifest.py b/backend/tests/test_dock_manifest.py index 1347ed1..3fa9145 100644 --- a/backend/tests/test_dock_manifest.py +++ b/backend/tests/test_dock_manifest.py @@ -1,4 +1,5 @@ import hashlib +import importlib.util import json import re import shutil @@ -71,3 +72,44 @@ def test_the_old_dock_key_is_moved_once_and_sizes_stay_apart(): assert out["keys"] == ["formtxt.dock"] assert out["moved"] == {"open": True, "side": "bottom", "h": 300, "w": 440, "tab": "", "seen": True} assert out["right"] == {"open": True, "side": "right", "h": 300, "w": 520, "tab": ""} + + +LOOKUP = "backend/app/services/agent_lookup.py" + + +def _agents(root): + spec = importlib.util.spec_from_file_location("checked_agents", root / "setup" / "agents.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_the_shared_finder_matches_the_hash_recorded_for_its_version(): + module = _agents(REPO) + version = re.search(r'^VERSION = "([^"]+)"$', (REPO / LOOKUP).read_text(encoding="utf-8"), re.M).group(1) + assert module.LOOKUP_HASHES[version] == hashlib.sha256((REPO / LOOKUP).read_bytes()).hexdigest() + assert module.lookup_problems() == [] + + +def test_the_check_names_the_shared_finder_edited_in_place_or_missing(tmp_path): + copy = tmp_path / "repo" + (copy / "backend" / "app" / "services").mkdir(parents=True) + shutil.copytree(REPO / "setup", copy / "setup", ignore=shutil.ignore_patterns("__pycache__")) + shutil.copy(REPO / LOOKUP, copy / LOOKUP) + module = _agents(copy) + assert module.lookup_problems() == [] + with open(copy / LOOKUP, "a", encoding="utf-8") as f: + f.write("\n") + version = re.search(r'^VERSION = "([^"]+)"$', (REPO / LOOKUP).read_text(encoding="utf-8"), re.M).group(1) + changed = f"{LOOKUP}: does not match the hash recorded for version {version} (the shared finder changes only as a whole new version)" + assert module.lookup_problems() == [changed] + for action in (["check"], ["sync", "--check"]): + done = subprocess.run([sys.executable, "-B", "setup/agents.py", *action], cwd=copy, capture_output=True, text=True) + assert done.returncode == 1 and changed in done.stderr + (copy / LOOKUP).unlink() + assert module.lookup_problems() == [f"{LOOKUP}: missing (the shared finder for the agent programs)"] + + +def test_the_shared_finder_imports_nothing_from_the_app(): + imports = set(re.findall(r"^\s*(?:from|import)\s+([\w.]+)", (REPO / LOOKUP).read_text(encoding="utf-8"), re.M)) + assert imports == {"__future__", "dataclasses", "os", "pathlib", "re", "shutil", "signal", "subprocess", "sys", "threading", "time", "winreg"} diff --git a/formtxt b/formtxt index e6fb4cd..c5b11e6 100755 --- a/formtxt +++ b/formtxt @@ -21,7 +21,7 @@ usage: ./formtxt [command] [options] cli list|describe|run the editor's command catalogue from a terminal; run <id> [key=value ...] needs the window open report run template=<id> db=<path> sql=<select> [out=<file>] merge a template with a SQLite query in the engine and write a PDF, .docx or .ftxt; no window needed mcp [--where] [--version] [--url URL] FormTxt over MCP's stdio transport, for Claude Code and other MCP clients - agents sync|check|install [--dry-run] mirror .claude/skills into .agents/skills and write agents/manifest.json; check the kit; register FormTxt with Claude Code, Codex and Cursor + agents sync|check|install [--dry-run] mirror .claude/skills into .agents/skills and write agents/manifest.json; check the kit; register FormTxt with Claude Code, Codex, Cursor and Antigravity mcpb check | build DIR validate the Claude Desktop extension manifest; write formtxt-<version>.mcpb into DIR clean [--all] remove build output (--all also venv and node_modules) icons --check fail when interface code, an insertable icon or an emoji draws a sparkle (banned app-wide) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 154a527..b28f229 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,9 +2,16 @@ Living log of comment content, rationale and removed code for the frontend. Source files stay comment-free; read this first, then edit surgically. -Current build version: v0.34.0 -Last updated: 2026-11-19 · v0.34.0: the family's terminal dock at the bottom or the right, its question about outside agents, Block all agents, database merge data, repeating rows, groups and totals, report run (entries below, headed "v0.34.0, not released yet" as they were written); the three browser demo pages were not rebuilt, so they still say 0.32.0 and carry the old dock. Before: 2026-11-17 · v0.33.0: AMOLED Black, a true-black theme, and Dark Page at full inversion under it (entries below); the three browser demo pages were not rebuilt, so they still say 0.32.0 and do not offer the theme. Before: 2026-11-14 · v0.32.1 has no change in the window; the macOS freeze fix is in the backend log, and the three browser demo pages were not rebuilt, so they still say 0.32.0. Before: 2026-11-13 · v0.32.0: Read and Focus mode show the document again, the sparkle ban covers insertable icons and emoji, the inline mark in the title bar and About, browser demo pages (entries below). Before: 2026-11-13 · the v0.31.0 family release pass: Home, the terminal dock with Claude Code, demos, no sparkle icon (entries below). Before: 2026-11-13 · the v0.30.8 review fixes, second pass. +Current build version: v0.35.0 +Last updated: 2026-11-19 · v0.35.0: the family's dock module 2.2.0 with Antigravity as the fourth agent tab, and the finder's sentences read as a missing program (entries below, headed "after v0.34.0" as they were written); the three browser demo pages were not rebuilt, so they still say 0.32.0 and carry the old dock. Before: 2026-11-19 · v0.34.0: the family's terminal dock at the bottom or the right, its question about outside agents, Block all agents, database merge data, repeating rows, groups and totals, report run (entries below, headed "v0.34.0, not released yet" as they were written); the three browser demo pages were not rebuilt, so they still say 0.32.0 and carry the old dock. Before: 2026-11-17 · v0.33.0: AMOLED Black, a true-black theme, and Dark Page at full inversion under it (entries below); the three browser demo pages were not rebuilt, so they still say 0.32.0 and do not offer the theme. Before: 2026-11-14 · v0.32.1 has no change in the window; the macOS freeze fix is in the backend log, and the three browser demo pages were not rebuilt, so they still say 0.32.0. Before: 2026-11-13 · v0.32.0: Read and Focus mode show the document again, the sparkle ban covers insertable icons and emoji, the inline mark in the title bar and About, browser demo pages (entries below). Before: 2026-11-13 · the v0.31.0 family release pass: Home, the terminal dock with Claude Code, demos, no sparkle icon (entries below). Before: 2026-11-13 · the v0.30.8 review fixes, second pass. +- after v0.34.0 (family dock, module 2.2.0, and Antigravity as the fourth agent tab). `dock/` (the family's shared module 2.2.0, copied whole and byte for byte from FormVis ddc893ae `frontend/src/dock/`: 16 entries with `MANIFEST.json`, `agents.ts` is new, `MANIFEST.json` and 9 others changed), `dock-adapter.ts` :: `formtxtDock`. + - The module takes its agent kinds from the adapter. The adapter is typed `DockAdapter<'antigravity'>` and `tabs().builtin` ends with `'antigravity'`. Nothing else in the adapter changed: `agentStatus()` already passes on the engine's `/agents/status` answer, which has the `antigravity` key (`installed`, `version`, `install`, `signedIn: null`), and `terminal.open` already sends every kind that is not `shell` or `claude` to `POST /terminal/agent`, which now takes `antigravity`. `app.ts` holds the dock without a written type, so it is inferred. + - Not done: `note` (the engine's own sentence on the row of a missing program), the automation ids on `data-dock-part`, `status` on a terminal record. `keyHeaders` stays, FormTxt uses it. + - Known difference in the DOM, from the module: every control has `data-dock-part`, agent tabs carry `is-program`, and a kind the adapter does not list has no hidden button or row. + - Checked: `tsc --noEmit` exit 0. Not looked at in a browser; the engine side was run with a stand-in `agy` (backend log). + +- after v0.34.0 (the agent finder's sentences). `dock-adapter.ts` :: `errors.kind`. The engine now refuses a tab or Chat for a program it cannot find or start with the finder's own sentence (`Codex was not found. Looked in: ...`, `Claude Code was found at ... but does not start: ...`) where it said `... is not installed`. The test for `notInstalled` is `/not installed|was not found\. Looked in|but does not start/i` (it was `/not installed/i`), so the dock still opens its program menu for these refusals; the sentence itself already reaches the person through `errors.message`. Nothing in `dock/` is touched and no node is created, moved or rebuilt. Left as it was: the adapter's `t` still answers the module's English, so the menu row for a missing program and the Chat lead still use the module's general sentences, not the finder's `said` per program (FormVis's adapter keeps the last `said` per program for that; it is more than one change and was not made here). `tsc --noEmit` clean; not opened in a browser. - v0.34.0, not released yet (family dock, module 2.1.0). `dock/` (the family's shared module 2.1.0, copied whole and byte for byte from FormVis 8bbdf61b `frontend/src/dock/`, the same 15 file names, 11 of them changed, none added or gone), `dock-adapter.ts`, `app.ts`, `ui/shortcuts.ts` :: `Shortcuts.dockKeeps`, `styles/terminal.css`, `backend/tests/test_dock_manifest.py`. - Keys. The module now answers the question itself, so the adapter's copy of its rule is removed: `import { ownsEvent } from './dock/keys';` and `export function dockKeeps(e: KeyboardEvent): boolean { return ownsEvent(e) && !isDockChord(e) && !passKey(e); }`, with `import { dockKeeps } from '../dock-adapter';` in `ui/shortcuts.ts`. `Shortcuts` has a `dockKeeps` member that answers false until `app.ts` sets it to `(e) => dock.keeps(e)` right after the dock is built; the capture-phase listener asks it where it asked the adapter. - The guide. `legacy: ['formtxt.terminal']` is now `legacy: jsonLegacy(['formtxt.terminal'], true)`: a layout moved from the old key is stored with `seen: true`, so a person who already had a dock opens it on a shell, as before, and is not shown the first-run guide. A new person still gets it. A layout that a 2.0.1 build already moved has no old key left and is not asked again (2.0.1 was never released). diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 6e589b9..d2c43eb 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formtxt", - "version": "0.34.0", + "version": "0.35.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formtxt", - "version": "0.34.0", + "version": "0.35.0", "license": "Apache-2.0", "dependencies": { "@fontsource/ibm-plex-sans": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index 4f5d65c..9697983 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formtxt", "private": true, - "version": "0.34.0", + "version": "0.35.0", "description": "FormTxt: documents in the form family, an open alternative to Word and Google Docs", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts index 6103f6e..56fc0b2 100644 --- a/frontend/src/dock-adapter.ts +++ b/frontend/src/dock-adapter.ts @@ -81,7 +81,7 @@ function socketChannel(socket: WebSocket): DockChannel { }; } -export function formtxtDock(openSettings: () => void): DockAdapter { +export function formtxtDock(openSettings: () => void): DockAdapter<'antigravity'> { return { words: { app: 'FormTxt', noun: 'document', lead: LEAD, example: 'rewrite this paragraph in plain words', start: './formtxt' }, strings: { consentChanged: 'The Allow outside agents setting was changed outside {app}, so {app} asks again.' }, @@ -93,7 +93,7 @@ export function formtxtDock(openSettings: () => void): DockAdapter { isDockChord, chordLabel: () => `${isMac ? 'Cmd' : 'Ctrl'}+J`, passKey, - tabs: () => ({ builtin: ['chat', 'shell', 'claude', 'codex', 'cursor'] }), + tabs: () => ({ builtin: ['chat', 'shell', 'claude', 'codex', 'cursor', 'antigravity'] }), classes: { iconButton: 'ft-tt-btn', button: 'ft-btn sm', primaryButton: 'ft-btn sm cta', input: 'ft-input', select: 'ft-input', note: 'ft-note' }, t: (_key, english) => english, onTheme: (handler) => { document.addEventListener('nm:ui-settings-changed', handler); }, @@ -105,7 +105,7 @@ export function formtxtDock(openSettings: () => void): DockAdapter { if (!(err instanceof EngineError)) return null; if (err.status === 403) return 'refused'; if ((err.status === 404 || err.status === 405) && /^(Not Found|Method Not Allowed)$/i.test(err.message)) return 'oldEngine'; - if (/not installed/i.test(err.message)) return 'notInstalled'; + if (/not installed|was not found\. Looked in|but does not start/i.test(err.message)) return 'notInstalled'; if (err.status === 409) return 'busy'; return err.status === 502 || err.status === 503 || err.status === 504 ? 'unreachable' : null; }, diff --git a/frontend/src/dock/CONTRACT.md b/frontend/src/dock/CONTRACT.md index be1995e..a52a17e 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.1.0. This file travels with the shared dock folder and is the same in every app. +Module version 2.2.0. 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. @@ -56,6 +56,18 @@ Nothing an engine provides changed in 2.1.0: the sixteen clauses read as they di - **Names.** The classes, attributes and tokens an app may rely on are `DOCK_PUBLIC` in adapter.ts and nowhere else; 2.1.0 added the classes `has-ask-line`, `ft-dock-ask`, `ft-dock-ask-own`, `ft-dock-head`, `ft-dock-tab`, `ft-dock-stage`, `ft-icon`, `is-on`, `is-own` and the tokens `--dock-stage-pad`, `--dock-ask-ctl-h`, `--dock-tab-accent`, each token defaulting to the value 2.0 had written. - **Type check.** Before a module version is cut, and as a step of every port, the folder is compiled with `noUnusedLocals`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `noImplicitOverride` and `noImplicitReturns` on. +## Module 2.2.0: the agent kinds are a list, and Antigravity is the fourth + +An adapter written for 2.1.0 compiles and behaves as before: copying the 2.2.0 folder into an app changes nothing there until its adapter names a further kind. Every type an adapter uses is the 2.1.0 type unless the adapter gives the type argument described below. `keyHeaders` became optional. + +- **The list.** `agents.ts` holds the kinds the module knows: `claude` (Claude Code), `codex` (Codex), `cursor` (Cursor) and `antigravity` (Antigravity, Google's `agy` program), each with its label, its picture and its two sentences. Claude Code keeps its own button, the ask line and the guide. Every other kind gets a head button and a row in the More agents menu. +- **Offering a kind.** A kind is shown when the adapter lists its id in `tabs().builtin` and `agentStatus()` reports it; both. So clause 10's answer may hold further keys, `{ claude?, codex?, cursor?, antigravity?, ... }`, and a key the adapter does not also list is ignored. The module then calls `terminal.open('antigravity', { cols, rows })`, and clause 3's `kind` may be that id. An adapter that adds kinds is typed `DockAdapter<'antigravity'>` (a union for several); `Dock`, `DockTabs`, `DockTerminal` and `DockAgentStatus` follow from it. +- **What the engine needs for a further kind.** Clause 10 for it (found, version, install line, `signedIn` null when it cannot tell, which is always so for Antigravity: it has no status command), clause 4 for its tab, and clause 11: Antigravity reads its MCP servers from a file, so the tab's entry (named `[app]_tab`, with the tab's token) goes into `.agents/mcp_config.json` of the tab's working folder, mode 0600, every other entry kept, and is taken out when the tab closes. +- **A kind that is not in the list** needs no change in this folder: the adapter lists its id, and its status carries `label`. It is drawn with the terminal picture and the sentences of the other programs. +- **`DockProgramStatus.note`** is a whole sentence shown in the kind's menu row in place of the module's (where the engine looked for the program, why it does not start, a step that is not a command). The install line still shows under it. +- **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. + ## 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 fdeee27..819f4ea 100644 --- a/frontend/src/dock/MANIFEST.json +++ b/frontend/src/dock/MANIFEST.json @@ -1,20 +1,21 @@ { "module": "dock", - "version": "2.1.0", + "version": "2.2.0", "files": { - "CONTRACT.md": "3fa57822b0024100bd4f5db5e06525f774539c4595493da171f1bd14871d2e05", - "adapter.ts": "fe8e9212273a49ffefa37baac056bab5d499581ae78f995ab691ac9867d5fd6a", - "chat.ts": "91fef36e0ee61a1681194fe441458cd766660277718b0ba854e2960fddc5ca1b", - "consent.ts": "83873a14cb337ea679f0f372c4865428ab8cf136cecce8f8c7ab159a656c777b", - "dock.css": "7fbb58622379689a0fcf980e726a4f452ccf8d3acb394e9b6cf04f7a0c8d77d7", - "dock.ts": "d3ff0afa24c06afd6f80ba478e4b4f8e90f5a150ec9f9f96a3d4b14179b6849f", + "CONTRACT.md": "ccef67fcf0017569c0bf68df0eae2e1e3ddf376117ac929789b803713c427df6", + "adapter.ts": "1128c16892424485fe68bb2bf92ebc7229a9c2ff749db2fcd2419662d9c3ada9", + "agents.ts": "db666d1042555f8bbda4a697dbfc475df23779d0c5a25abd532bcfa43ae81043", + "chat.ts": "994878030b9fbff729734d34e2baa5b018e7d0b8555c24bfb7c98962c50446fa", + "consent.ts": "922a2c9fb6a3d83a6b70f1bb02918646ae180f5ed1ed7325e71b2caf01358737", + "dock.css": "ffdb5be7e849c393f173fac9cd0fb0503c0ef4e53e4c1c86a8e198abfbbdb8d2", + "dock.ts": "abbb2929d52d592eb2730a8a90763e8caf333c458250fc89a08d637489ef4571", "dom.ts": "dc2adf64e70e600f28eaa2d84eed0b4ad7deadb6e200cd489ee7abb583269e62", - "icons.ts": "a8b146eb3772621e4b4349ad143da14170d28ed3dd68aad41748dbaeb8e99988", + "icons.ts": "2e3ec58ea5ccaae4243d72d55da10c39611bd02f486cdcd5b11b9459c6beb402", "keys.ts": "1adfc7daefa35b0e6eb8957250dca3926ded1c59fd51db7d60da6346caf0d561", "placement.ts": "0f7e03ef0b720af07995111f30dcb5ed124529d44cf5cb67ae4bfb1f96c7f880", "state.ts": "bef508e8343737f67adfbd7ae8cb8efb446968dfd4e7e0aff37da11f996955d7", - "strings.ts": "b1ad5ff88bd46e3631b12fc831fc919329ad051ba38c99927c1d5aed9eea5de8", + "strings.ts": "19a6a32f235b61dfed6179e2271a6d599f4357c9a6b9c09118bb65990d1e114f", "terminal.ts": "8bf886a7ad4dc69323e803acc13641a66e1d8614e9b85a6a60977fa30d8a56fc", - "tour.ts": "9b72d54ece42fd15b84054e21264453207c5e73261d387110a9abf91d29586aa" + "tour.ts": "2f83994051f4370c5d1630a827b4539eb12fd50e7fe9531f5641a4bf75615782" } } diff --git a/frontend/src/dock/adapter.ts b/frontend/src/dock/adapter.ts index 59476b9..6f13d08 100644 --- a/frontend/src/dock/adapter.ts +++ b/frontend/src/dock/adapter.ts @@ -7,18 +7,19 @@ export type DockProgram = 'claude' | 'codex' | 'cursor'; export type PtyKind = 'shell' | 'claude' | 'codex' | 'cursor' | 'agent'; export type ChatMode = 'ask' | 'auto-edits' | 'plan'; -export interface DockTerminal { id: string; title: string; alive: boolean; kind: PtyKind; tip?: string } +export interface DockTerminal<K extends string = never> { id: string; title: string; alive: boolean; kind: PtyKind | K; tip?: string; status?: string } export interface DockChannel { send(data: string): void; resize(cols: number, rows: number): void; onData(handler: (data: string | Uint8Array) => void): void; onExit(handler: () => void): void; onClose?(handler: () => void): void; + onStatus?(handler: (text: string) => void): void; close(): void; } export interface DockOpen { cols: number; rows: number; prompt?: string; resume?: string } -export interface DockProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null } -export type DockAgentStatus = Partial<Record<DockProgram, DockProgramStatus>>; +export interface DockProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null; label?: string; note?: string } +export type DockAgentStatus<K extends string = never> = Partial<Record<DockProgram | K, DockProgramStatus>>; export interface DockChatStatus { installed: boolean; version: string | null; @@ -53,8 +54,8 @@ export interface DockOwnChat { busy?(): boolean; askTarget?: HTMLElement; } -export interface DockOwnAsk { send?(text: string, tab: DockKind | null): DockSent; element?: HTMLElement } -export interface DockChatPane { pane(host: HTMLElement): DockOwnChat | void; ask?: 'none' | 'line' | DockOwnAsk } +export interface DockOwnAsk<K extends string = never> { send?(text: string, tab: DockKind | K | null): DockSent; element?: HTMLElement } +export interface DockChatPane<K extends string = never> { pane(host: HTMLElement): DockOwnChat | void; ask?: 'none' | 'line' | DockOwnAsk<K> } export type DockChatEvent = | { type: 'state'; running: boolean; state: string; session: string | null; mode?: ChatMode } | { type: 'user'; text: string; note?: string } @@ -84,36 +85,36 @@ export interface DockSizes { export type DockErrorKind = 'refused' | 'unreachable' | 'notInstalled' | 'oldEngine' | 'busy'; export interface DockWords { app: string; noun: string; lead: string; example: string; start?: string } export interface DockAppTab { id: string; label: string; icon: string; mount(host: HTMLElement): void | (() => void) } -export interface DockTabs { builtin: DockKind[]; own?: DockAppTab[] } +export interface DockTabs<K extends string = never> { builtin: Array<DockKind | K>; own?: DockAppTab[] } export interface DockStorage { key: string; legacy?: DockLegacy | string[] } export type DockPlacement = | { mode: 'own'; storage: DockStorage; sizes: DockSizes; canDockRight?(): boolean } | { mode: 'hosted'; request(open: boolean): void }; -export interface DockAdapter { +export interface DockAdapter<K extends string = never> { words: DockWords; strings?: Partial<Record<StringKey, string>>; placement: DockPlacement; passKey?(event: KeyboardEvent): boolean; isDockChord?(event: KeyboardEvent): boolean; chordLabel?(): string; - tabs(): DockTabs; + tabs(): DockTabs<K>; classes: { iconButton: string; button: string; primaryButton: string; input: string; select: string; note: string }; t(key: string, english: string): string; onTheme(handler: () => void): void; - keyHeaders(): Record<string, string>; + keyHeaders?(): Record<string, string>; errors: { message(err: unknown): string | null; kind?(err: unknown): DockErrorKind | null }; firstRun?(): boolean; terminal: { - list(): Promise<DockTerminal[]>; - open(kind: Exclude<PtyKind, 'agent'>, options: DockOpen): Promise<DockTerminal>; + list(): Promise<DockTerminal<K>[]>; + open(kind: Exclude<PtyKind, 'agent'> | K, options: DockOpen): Promise<DockTerminal<K>>; restart?(id: string): Promise<void>; close(id: string): Promise<void>; channel(id: string): DockChannel | Promise<DockChannel>; scrollback?: number; }; - agentStatus(): Promise<DockAgentStatus | null>; - chat?: DockChatEngine | DockChatPane; + agentStatus(): Promise<DockAgentStatus<K> | null>; + chat?: DockChatEngine | DockChatPane<K>; consent?: { subscribe(add: (request: ConsentRequest) => void, withdraw: (id: string) => void): void; answer(id: string, choice: ConsentChoice): Promise<void>; @@ -128,6 +129,9 @@ export interface DockAdapter { export const DOCK_PUBLIC = { classes: ['ft-dock', 'ft-consent', 'ft-tour', 'ft-term', 'ft-chat', 'ft-dock-pane', 'ft-notranslate', 'is-hosted', 'has-own-chat', 'has-no-ask', 'has-ask-line', 'ft-dock-ask', 'ft-dock-ask-own', 'ft-dock-head', 'ft-dock-tab', 'ft-dock-stage', 'ft-icon', 'is-on', 'is-own'], rootAttributes: ['data-ft-dock', 'data-ft-dock-side', 'data-ft-dock-h', 'data-ft-dock-w'], + partAttribute: 'data-dock-part', + parts: ['new', 'chat', 'launch.claude', 'more', 'restart', 'side', 'hide', 'menu', 'menu.settings', 'menu.guide', 'screen', 'note.copy', 'note.dismiss', 'ask', 'send', 'tab.chat', 'tab.close', 'consent', 'consent.deny', 'consent.once', 'consent.always'], + partsByKind: ['launch.', 'menu.launch.', 'tab.'], rootProperties: ['--ft-dock-size', '--ft-dock-wsize'], tokens: [ '--dock-bg', '--dock-bar-bg', '--dock-raised', '--dock-hover', '--dock-input-bg', '--dock-border', '--dock-edge', '--dock-divider', '--dock-tab-border', '--dock-outline', '--dock-scrim', diff --git a/frontend/src/dock/agents.ts b/frontend/src/dock/agents.ts new file mode 100644 index 0000000..083297e --- /dev/null +++ b/frontend/src/dock/agents.ts @@ -0,0 +1,22 @@ +import type { StringKey } from './strings'; + +export interface DockAgentKind { id: string; label: string; name?: StringKey; icon: string; ready: StringKey; missing: StringKey } + +export const DOCK_AGENTS: readonly DockAgentKind[] = [ + { id: 'claude', label: 'Claude Code', name: 'claudeCode', icon: 'agent', ready: 'programReady', missing: 'notInstalled' }, + { id: 'codex', label: 'Codex', name: 'codex', icon: 'codex', ready: 'programReady', missing: 'programMissing' }, + { id: 'cursor', label: 'Cursor', name: 'cursor', icon: 'cursor', ready: 'programReady', missing: 'programMissing' }, + { id: 'antigravity', label: 'Antigravity', name: 'antigravity', icon: 'antigravity', ready: 'programReady', missing: 'programMissing' }, +]; + +export const DOCK_PLAIN: readonly string[] = ['shell', 'chat', 'agent']; + +export function agentKind(id: string): DockAgentKind { + return DOCK_AGENTS.find((k) => k.id === id) ?? { id, label: id, icon: id, ready: 'programReady', missing: 'programMissing' }; +} + +export function agentKinds(builtin: readonly string[]): DockAgentKind[] { + const listed = DOCK_AGENTS.filter((k) => builtin.includes(k.id)); + const more = builtin.filter((id) => !DOCK_PLAIN.includes(id) && !DOCK_AGENTS.some((k) => k.id === id)).map(agentKind); + return [...listed, ...more]; +} diff --git a/frontend/src/dock/chat.ts b/frontend/src/dock/chat.ts index 64d02ae..2c02755 100644 --- a/frontend/src/dock/chat.ts +++ b/frontend/src/dock/chat.ts @@ -9,7 +9,7 @@ function toolName(name: string): string { return name.replace(/^mcp__/, '').replace(/__/g, ' '); } -export type ChatHost = Omit<DockAdapter, 'chat'> & { chat: DockChatEngine }; +export type ChatHost = Omit<DockAdapter<string>, 'chat'> & { chat: DockChatEngine }; export interface DockChatView { readonly root: HTMLElement; diff --git a/frontend/src/dock/consent.ts b/frontend/src/dock/consent.ts index 652b41d..ec20659 100644 --- a/frontend/src/dock/consent.ts +++ b/frontend/src/dock/consent.ts @@ -31,7 +31,7 @@ export class Consent { if (this.root) return this.root; const s = this.s; const c = this.a.classes; - const root = el<HTMLDialogElement>(`<dialog class="ft-consent" aria-labelledby="ft-consent-title" aria-describedby="ft-consent-what"> + const root = el<HTMLDialogElement>(`<dialog class="ft-consent" data-dock-part="consent" aria-labelledby="ft-consent-title" aria-describedby="ft-consent-what"> <div class="ft-consent-box"> <h2 class="ft-consent-title" id="ft-consent-title"></h2> <p class="ft-consent-count ${c.note}"></p> @@ -39,9 +39,9 @@ export class Consent { <p class="ft-consent-notes" hidden></p> <p class="ft-consent-notice ${c.note}" role="status" hidden>${s('consentChanged')}</p> <div class="ft-consent-buttons"> - <button type="button" class="${c.button} ft-consent-btn ft-consent-deny" data-choice="deny">${s('consentDeny')}</button> - <button type="button" class="${c.button} ft-consent-btn ft-consent-once" data-choice="once">${s('consentOnce')}</button> - <button type="button" class="${c.button} ${c.primaryButton} ft-consent-btn ft-consent-always" data-choice="always"></button> + <button type="button" class="${c.button} ft-consent-btn ft-consent-deny" data-dock-part="consent.deny" data-choice="deny">${s('consentDeny')}</button> + <button type="button" class="${c.button} ft-consent-btn ft-consent-once" data-dock-part="consent.once" data-choice="once">${s('consentOnce')}</button> + <button type="button" class="${c.button} ${c.primaryButton} ft-consent-btn ft-consent-always" data-dock-part="consent.always" data-choice="always"></button> </div> </div> </dialog>`); diff --git a/frontend/src/dock/dock.css b/frontend/src/dock/dock.css index 69eff56..1d1a8a5 100644 --- a/frontend/src/dock/dock.css +++ b/frontend/src/dock/dock.css @@ -22,11 +22,11 @@ .ft-dock-grip:hover { background: var(--dock-accent-line); } .ft-dock-head { flex: none; display: flex; align-items: center; gap: var(--dock-space-2); height: var(--dock-head-h); padding: 0 var(--dock-space-2); background: var(--dock-bar-bg); border-bottom: 1px solid var(--dock-divider, var(--dock-border)); min-width: 0; } .ft-dock-tabs { display: flex; align-items: center; gap: 2px; min-width: 0; overflow-x: auto; scrollbar-width: none; } -.ft-dock-spacer { flex: 1; } +.ft-dock-spacer { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: end; color: var(--dock-text-muted); font-size: var(--dock-fs-xs); user-select: text; -webkit-user-select: text; } .ft-dock-tab { display: inline-flex; align-items: center; flex: none; gap: 6px; height: var(--dock-tab-h, 26px); padding: 0 6px 0 9px; border: 1px solid transparent; border-radius: var(--dock-tab-radius, 6px); background: transparent; color: var(--dock-tab-text, var(--dock-text-dim)); font: inherit; font-size: var(--dock-fs-sm); cursor: pointer; white-space: nowrap; } .ft-dock-tab:hover { color: var(--dock-text); } .ft-dock-tab.is-on { border-color: var(--dock-tab-border); background: var(--dock-raised); color: var(--dock-text); } -.ft-dock-tab.is-claude > .ft-icon, .ft-dock-tab.is-chat > .ft-icon, .ft-dock-tab.is-codex > .ft-icon, .ft-dock-tab.is-cursor > .ft-icon { color: var(--dock-tab-accent, var(--dock-accent)); } +.ft-dock-tab.is-claude > .ft-icon, .ft-dock-tab.is-chat > .ft-icon, .ft-dock-tab.is-codex > .ft-icon, .ft-dock-tab.is-cursor > .ft-icon, .ft-dock-tab.is-program > .ft-icon { color: var(--dock-tab-accent, var(--dock-accent)); } .ft-dock-head .ft-dock-ibtn[hidden] { display: none; } .ft-dock-menu { position: absolute; top: calc(var(--dock-head-h) + var(--dock-space-1)); right: var(--dock-space-2); z-index: var(--z-raised); display: flex; flex-direction: column; gap: var(--dock-space-2); width: min(340px, calc(100% - 16px)); padding: var(--dock-space-2) var(--dock-space-3); border: 1px solid var(--dock-border); border-radius: var(--dock-radius-md); background: var(--dock-bar-bg); color: var(--dock-text); font-size: var(--dock-fs-sm); user-select: text; -webkit-user-select: text; } .ft-dock-menu[hidden], .ft-dock-menu-go[hidden], .ft-dock-menu-cmd[hidden] { display: none; } diff --git a/frontend/src/dock/dock.ts b/frontend/src/dock/dock.ts index 84312cd..bcbd54b 100644 --- a/frontend/src/dock/dock.ts +++ b/frontend/src/dock/dock.ts @@ -1,4 +1,5 @@ -import type { DockAdapter, DockAgentStatus, DockAppTab, DockChannel, DockKind, DockOwnAsk, DockPaneHidden, DockTerminal, PtyKind } from './adapter'; +import type { DockAdapter, DockAgentStatus, DockAppTab, DockChannel, DockKind, DockOwnAsk, DockPaneHidden, DockProgramStatus, DockTerminal } from './adapter'; +import { DOCK_AGENTS, agentKind, agentKinds, type DockAgentKind } from './agents'; import { ChatPane, OwnChat, type DockChatView } from './chat'; import { Consent } from './consent'; import { el, q, setClass, setDisabled, setHidden, setText } from './dom'; @@ -12,22 +13,24 @@ import { Tour, type TourStep } from './tour'; export type { DockAdapter, DockKind } from './adapter'; -const PROGRAMS = ['codex', 'cursor'] as const; -type Program = typeof PROGRAMS[number]; - interface Tab { id: string; term: DockTerm | null; host: HTMLElement; tab: HTMLElement; channel: DockChannel | null; - kind: PtyKind; + kind: string; seen: boolean; closed: boolean; + status: string; } -export class Dock { +interface Program { kind: DockAgentKind; button: HTMLButtonElement; row: HTMLElement } + +export class Dock<K extends string = never> { + private readonly a: DockAdapter<string>; private readonly s: Say; + private readonly kinds = new Map<string, Program>(); readonly root: HTMLElement; private readonly tabsEl: HTMLElement; private readonly stage: HTMLElement; @@ -41,13 +44,13 @@ export class Dock { private readonly tabs = new Map<string, Tab>(); private readonly owned = new Map<string, { spec: DockAppTab; tab: HTMLElement; host: HTMLElement; mounted: boolean; off: (() => void) | undefined }>(); private chat: DockChatView | null = null; - private readonly ownAsk: DockOwnAsk | null; + private readonly ownAsk: DockOwnAsk<string> | null; private chatTab: HTMLElement | null = null; private active: string | null = null; private started = false; private pending: Promise<void> | null = null; private emulator: Promise<typeof import('./terminal')> | null = null; - private asked: Promise<DockAgentStatus | null> | null = null; + private asked: Promise<DockAgentStatus<string> | null> | null = null; private mounted = false; private revealing = false; private readonly place: Placement; @@ -57,37 +60,35 @@ export class Dock { readonly consent: Consent | null; private readonly tour: Tour; - constructor(private readonly a: DockAdapter, parts: { consent?: Consent } = {}) { + constructor(adapter: DockAdapter<K>, parts: { consent?: Consent } = {}) { + const a = adapter as unknown as DockAdapter<string>; const s = strings(a); const c = a.classes; const ib = `${c.iconButton} ft-dock-ibtn`; + this.a = a; this.s = s; this.root = el(`<section class="ft-dock" aria-label="${s('terminal')}"> <div class="ft-dock-grip" role="separator" aria-orientation="horizontal" aria-label="${s('resize')}"></div> <div class="ft-dock-head"> <div class="ft-dock-tabs" role="tablist" aria-label="${s('terminals')}"></div> - <span class="ft-dock-spacer"></span> - <button type="button" class="${ib} ft-dock-codex" title="${s('codex')}" aria-label="${s('codex')}" hidden>${icon('codex', 15)}</button> - <button type="button" class="${ib} ft-dock-cursor" title="${s('cursor')}" aria-label="${s('cursor')}" hidden>${icon('cursor', 15)}</button> - <button type="button" class="${ib} ft-dock-new" title="${s('newTerminal')}" aria-label="${s('newTerminal')}">${icon('plus', 15)}</button> - <button type="button" class="${ib} ft-dock-chat" title="${s('chatAbout')}" aria-label="${s('chatWith')}">${icon('agentChat', 15)}</button> - <button type="button" class="${ib} ft-dock-claude" title="${s('claudeCode')}" aria-label="${s('claudeCode')}">${icon('agent', 15)}</button> - <button type="button" class="${ib} ft-dock-more" title="${s('moreAgents')}" aria-label="${s('moreAgents')}" aria-haspopup="true" aria-expanded="false">${icon('menu', 15)}</button> - <button type="button" class="${ib} ft-dock-restart" title="${s('restart')}" aria-label="${s('restart')}">${icon('refresh', 15)}</button> - <button type="button" class="${ib} ft-dock-side" title="${s('toRight')}" aria-label="${s('toRight')}"><span class="ft-dock-side-right">${icon('dockRight', 15)}</span><span class="ft-dock-side-bottom">${icon('dockBottom', 15)}</span></button> - <button type="button" class="${ib} ft-dock-hide" title="${s('hideTitle', { chord: chordLabel(a) })}" aria-label="${s('hide')}">${icon('close', 15)}</button> + <span class="ft-dock-spacer" data-dock-part="status" role="status"></span> + <button type="button" class="${ib} ft-dock-new" data-dock-part="new" title="${s('newTerminal')}" aria-label="${s('newTerminal')}">${icon('plus', 15)}</button> + <button type="button" class="${ib} ft-dock-chat" data-dock-part="chat" title="${s('chatAbout')}" aria-label="${s('chatWith')}">${icon('agentChat', 15)}</button> + <button type="button" class="${ib} ft-dock-claude" data-dock-part="launch.claude" title="${s('claudeCode')}" aria-label="${s('claudeCode')}">${icon('agent', 15)}</button> + <button type="button" class="${ib} ft-dock-more" data-dock-part="more" title="${s('moreAgents')}" aria-label="${s('moreAgents')}" aria-haspopup="true" aria-expanded="false">${icon('menu', 15)}</button> + <button type="button" class="${ib} ft-dock-restart" data-dock-part="restart" title="${s('restart')}" aria-label="${s('restart')}">${icon('refresh', 15)}</button> + <button type="button" class="${ib} ft-dock-side" data-dock-part="side" title="${s('toRight')}" aria-label="${s('toRight')}"><span class="ft-dock-side-right">${icon('dockRight', 15)}</span><span class="ft-dock-side-bottom">${icon('dockBottom', 15)}</span></button> + <button type="button" class="${ib} ft-dock-hide" data-dock-part="hide" title="${s('hideTitle', { chord: chordLabel(a) })}" aria-label="${s('hide')}">${icon('close', 15)}</button> </div> - <div class="ft-dock-menu" role="menu" hidden> - <div class="ft-dock-menu-row" data-kind="codex"><button type="button" class="${c.button} ft-dock-menu-go" role="menuitem">${icon('codex', 13)}<span>${s('codex')}</span></button><p class="ft-dock-menu-how ${c.note}"></p><code class="ft-dock-menu-cmd"></code></div> - <div class="ft-dock-menu-row" data-kind="cursor"><button type="button" class="${c.button} ft-dock-menu-go" role="menuitem">${icon('cursor', 13)}<span>${s('cursor')}</span></button><p class="ft-dock-menu-how ${c.note}"></p><code class="ft-dock-menu-cmd"></code></div> - <div class="ft-dock-menu-row ft-dock-menu-links"><button type="button" class="${c.button} ft-dock-menu-settings" role="menuitem">${s('outsideAgents')}</button><button type="button" class="${c.button} ft-dock-menu-tour" role="menuitem">${s('showAround')}</button></div> + <div class="ft-dock-menu" data-dock-part="menu" role="menu" hidden> + <div class="ft-dock-menu-row ft-dock-menu-links"><button type="button" class="${c.button} ft-dock-menu-settings" data-dock-part="menu.settings" role="menuitem">${s('outsideAgents')}</button><button type="button" class="${c.button} ft-dock-menu-tour" data-dock-part="menu.guide" role="menuitem">${s('showAround')}</button></div> </div> - <div class="ft-dock-stage"><p class="ft-dock-empty ${c.note}" hidden>${s('empty')}</p> - <div class="ft-dock-note" role="status" hidden><span class="ft-dock-note-text"></span><code class="ft-dock-note-cmd" hidden></code><button type="button" class="${c.button} ft-dock-note-copy" hidden>${s('copy')}</button><button type="button" class="${ib} ft-dock-note-x" title="${s('dismiss')}" aria-label="${s('dismiss')}">${icon('close', 12)}</button></div></div> + <div class="ft-dock-stage" data-dock-part="screen"><p class="ft-dock-empty ${c.note}" hidden>${s('empty')}</p> + <div class="ft-dock-note" role="status" hidden><span class="ft-dock-note-text"></span><code class="ft-dock-note-cmd" hidden></code><button type="button" class="${c.button} ft-dock-note-copy" data-dock-part="note.copy" hidden>${s('copy')}</button><button type="button" class="${ib} ft-dock-note-x" data-dock-part="note.dismiss" title="${s('dismiss')}" aria-label="${s('dismiss')}">${icon('close', 12)}</button></div></div> <form class="ft-dock-ask" autocomplete="off"> <span class="ft-dock-ask-mark">${icon('agent', 15)}</span> - <input class="${c.input} ft-dock-ask-input" type="text" spellcheck="false" placeholder="${s('askPlaceholder')}" aria-label="${s('askLabel')}"> - <button type="submit" class="${ib} ft-dock-ask-send" title="${s('send')}" aria-label="${s('send')}">${icon('send', 14)}</button> + <input class="${c.input} ft-dock-ask-input" data-dock-part="ask" type="text" spellcheck="false" placeholder="${s('askPlaceholder')}" aria-label="${s('askLabel')}"> + <button type="submit" class="${ib} ft-dock-ask-send" data-dock-part="send" title="${s('send')}" aria-label="${s('send')}">${icon('send', 14)}</button> </form> </section>`); this.tabsEl = q(this.root, '.ft-dock-tabs'); @@ -105,10 +106,6 @@ export class Dock { q(this.root, '.ft-dock-chat').addEventListener('click', () => void this.showChat()); q(this.root, '.ft-dock-hide').addEventListener('click', () => this.toggle(false)); q(this.root, '.ft-dock-side').addEventListener('click', () => { this.setSide(this.side() === 'right' ? 'bottom' : 'right'); this.focus(); }); - for (const kind of PROGRAMS) { - q(this.root, `.ft-dock-${kind}`).addEventListener('click', () => void this.program(kind)); - q(this.root, `.ft-dock-menu-row[data-kind="${kind}"] .ft-dock-menu-go`).addEventListener('click', () => { this.menu(false); void this.program(kind); }); - } q(this.root, '.ft-dock-more').addEventListener('click', () => { this.menu(q(this.root, '.ft-dock-menu').hidden === true); }); q(this.root, '.ft-dock-menu-settings').addEventListener('click', () => { this.menu(false); a.openSettings?.(); }); setHidden(q(this.root, '.ft-dock-menu-settings'), !a.openSettings); @@ -198,48 +195,80 @@ export class Dock { else await this.open(); } - activeKind(): DockKind | null { + activeKind(): DockKind | K | null { if (this.active === 'chat') return 'chat'; const kind = this.active ? this.tabs.get(this.active)?.kind : undefined; - return kind && kind !== 'agent' ? kind : null; + return kind && kind !== 'agent' ? kind as DockKind | K : null; } - isShowing(kind: DockKind): boolean { return this.isOpen() && this.activeKind() === kind; } + isShowing(kind: DockKind | K): boolean { return this.isOpen() && this.activeKind() === kind; } - async show(kind: DockKind): Promise<void> { + async show(kind: DockKind | K): Promise<void> { if (!this.isOpen()) this.toggle(true, 'none'); await this.ensure('none'); if (kind === 'chat') { await this.showChat(); return; } const own = [...this.tabs.values()].find((x) => x.kind === kind); if (own) this.select(own.id); else if (kind === 'claude') await this.claude(); - else if (kind === 'codex' || kind === 'cursor') await this.program(kind); + else if (kind !== 'shell') await this.program(kind); else await this.open(); } + private label(kind: DockAgentKind, status?: DockProgramStatus): string { + return kind.name ? this.s(kind.name) : this.a.t(kind.id, status?.label ?? kind.label); + } + + private listPrograms(): void { + const order = agentKinds(this.a.tabs().builtin).filter((kind) => kind.id !== 'claude'); + const c = this.a.classes; + for (const [at, kind] of order.entries()) { + if (this.kinds.has(kind.id)) continue; + const name = this.label(kind); + const button = el<HTMLButtonElement>(`<button type="button" class="${c.iconButton} ft-dock-ibtn ft-dock-${kind.id}" hidden>${icon(kind.icon, 15)}</button>`); + const row = el(`<div class="ft-dock-menu-row"><button type="button" class="${c.button} ft-dock-menu-go" role="menuitem">${icon(kind.icon, 13)}<span></span></button><p class="ft-dock-menu-how ${c.note}"></p><code class="ft-dock-menu-cmd"></code></div>`); + button.title = name; + button.setAttribute('aria-label', name); + row.dataset.kind = kind.id; + button.dataset.dockPart = `launch.${kind.id}`; + q(row, '.ft-dock-menu-go').dataset.dockPart = `menu.launch.${kind.id}`; + setText(q(row, '.ft-dock-menu-go > span:last-child'), name); + button.addEventListener('click', () => void this.program(kind.id)); + q(row, '.ft-dock-menu-go').addEventListener('click', () => { this.menu(false); void this.program(kind.id); }); + const next = order.slice(at + 1).map((later) => this.kinds.get(later.id)).find((later) => later !== undefined); + q(this.root, '.ft-dock-head').insertBefore(button, next?.button ?? q(this.root, '.ft-dock-new')); + q(this.root, '.ft-dock-menu').insertBefore(row, next?.row ?? q(this.root, '.ft-dock-menu-links')); + this.kinds.set(kind.id, { kind, button, row }); + } + } + private async programs(): Promise<void> { const status = await this.agents(); - for (const kind of PROGRAMS) { - const st = status?.[kind]; - const offered = this.offers(kind); + for (const { kind, button, row } of this.kinds.values()) { + const st = status?.[kind.id]; + const offered = this.offers(kind.id); const found = offered && !!st?.installed; - const row = q(this.root, `.ft-dock-menu-row[data-kind="${kind}"]`); setHidden(row, !offered || !st); - setHidden(q(this.root, `.ft-dock-${kind}`), !found); + setHidden(button, !found); setHidden(q(row, '.ft-dock-menu-go'), !found); - setText(q(row, '.ft-dock-menu-how'), this.s(found ? 'programReady' : 'programMissing', { program: this.s(kind) })); + const name = this.label(kind, st); + setText(q(row, '.ft-dock-menu-how'), st?.note || this.s(found ? kind.ready : kind.missing, { program: name })); setText(q(row, '.ft-dock-menu-cmd'), found ? '' : st?.install ?? ''); setHidden(q(row, '.ft-dock-menu-cmd'), found || !st?.install); + if (kind.name || button.title === name) continue; + button.title = name; + button.setAttribute('aria-label', name); + setText(q(row, '.ft-dock-menu-go > span:last-child'), name); } } - private offers(kind: DockKind): boolean { + private offers(kind: string): boolean { return this.a.tabs().builtin.includes(kind) && (kind !== 'chat' || !!this.a.chat); } activeTab(): string | null { return this.active; } refresh(): void { + this.listPrograms(); setHidden(q(this.root, '.ft-dock-new'), !this.offers('shell')); setHidden(q(this.root, '.ft-dock-chat'), !this.offers('chat')); setHidden(q(this.root, '.ft-dock-claude'), !this.offers('claude')); @@ -281,7 +310,7 @@ export class Dock { q(this.root, '.ft-dock-more').setAttribute('aria-expanded', String(open)); } - async program(kind: Program): Promise<boolean> { + async program(kind: string): Promise<boolean> { const size = this.size(); try { const info = await this.a.terminal.open(kind, { cols: size.cols, rows: size.rows }); @@ -297,7 +326,7 @@ export class Dock { } } - async toggleKind(kind: DockKind): Promise<void> { + async toggleKind(kind: DockKind | K): Promise<void> { if (this.isShowing(kind)) this.toggle(false); else await this.show(kind); } @@ -363,7 +392,7 @@ export class Dock { return this.emulator; } - private agents(): Promise<DockAgentStatus | null> { + private agents(): Promise<DockAgentStatus<string> | null> { if (!this.asked) { this.asked = this.a.agentStatus().catch(() => null); void this.asked.then(() => window.setTimeout(() => { this.asked = null; }, 1500)); @@ -371,7 +400,7 @@ export class Dock { return this.asked; } - private async list(): Promise<DockTerminal[]> { + private async list(): Promise<DockTerminal<string>[]> { try { return await this.a.terminal.list(); } catch { return []; } } @@ -444,7 +473,7 @@ export class Dock { this.stage.appendChild(this.chat.root); } if (!this.chatTab) { - const tab = el(`<button type="button" class="ft-dock-tab is-chat" role="tab" aria-selected="false">${icon('agentChat', 13)}<span class="ft-dock-tab-title">${this.s('chat')}</span><span class="ft-dock-tab-x" role="button" aria-label="${this.s('closeChat')}">${icon('close', 11)}</span></button>`); + const tab = el(`<button type="button" class="ft-dock-tab is-chat" data-dock-part="tab.chat" role="tab" aria-selected="false">${icon('agentChat', 13)}<span class="ft-dock-tab-title">${this.s('chat')}</span><span class="ft-dock-tab-x" data-dock-part="tab.close" role="button" aria-label="${this.s('closeChat')}">${icon('close', 11)}</span></button>`); tab.addEventListener('click', (e) => { if ((e.target as HTMLElement).closest('.ft-dock-tab-x')) this.closeChat(); else this.select('chat'); @@ -537,7 +566,7 @@ export class Dock { if (x.tab.title !== tip) x.tab.title = tip; } - private adopt(info: DockTerminal): void { + private adopt(info: DockTerminal<string>): void { if (this.tabs.has(info.id)) return; void this.attach(info, this.active === null || info.kind !== 'agent'); } @@ -570,13 +599,14 @@ export class Dock { return tab?.term ? { cols: tab.term.cols(), rows: tab.term.rows() } : { cols: 100, rows: 20 }; } - private async attach(info: DockTerminal, show: boolean): Promise<void> { + private async attach(info: DockTerminal<string>, show: boolean): Promise<void> { if (this.tabs.has(info.id)) { if (show) this.select(info.id); return; } - const kind: PtyKind = ['claude', 'agent', 'codex', 'cursor'].includes(info.kind) ? info.kind : 'shell'; + const program = DOCK_AGENTS.some((k) => k.id === info.kind) || this.kinds.has(info.kind); + const kind: string = program || info.kind === 'agent' ? info.kind : 'shell'; const agent = kind === 'agent'; - const mark = kind === 'claude' ? 'agent' : kind === 'codex' || kind === 'cursor' ? kind : 'terminal'; + const mark = program ? agentKind(kind).icon : 'terminal'; const host = el('<div class="ft-term" translate="no" dir="ltr" hidden></div>'); - const tab = el(`<button type="button" class="ft-dock-tab${kind === 'shell' || agent ? '' : ` is-${kind}`}${agent ? ' is-agent' : ''}" role="tab" aria-selected="false">${icon(mark, 13)}<span class="ft-dock-tab-title"></span><span class="ft-dock-tab-x" role="button" aria-label="${this.s('closeTab')}">${icon('close', 11)}</span></button>`); + const tab = el(`<button type="button" class="ft-dock-tab${kind === 'shell' || agent ? '' : ` is-${kind}`}${agent ? ' is-agent' : ''}${program ? ' is-program' : ''}" data-dock-part="tab.${kind}" role="tab" aria-selected="false">${icon(mark, 13)}<span class="ft-dock-tab-title"></span><span class="ft-dock-tab-x" data-dock-part="tab.close" role="button" aria-label="${this.s('closeTab')}">${icon('close', 11)}</span></button>`); setText(q(tab, '.ft-dock-tab-title'), info.title); if (agent) tab.title = this.s('agentTab'); tab.addEventListener('click', (e) => { @@ -586,7 +616,7 @@ export class Dock { this.stage.appendChild(host); this.tabsEl.appendChild(tab); if (info.tip) tab.dataset.tip = info.tip; - const entry: Tab = { id: info.id, term: null, host, tab, channel: null, kind, seen: false, closed: false }; + const entry: Tab = { id: info.id, term: null, host, tab, channel: null, kind, seen: false, closed: false, status: info.status ?? '' }; this.tabs.set(info.id, entry); setHidden(this.empty, true); this.ended(entry, !info.alive); @@ -610,9 +640,15 @@ export class Dock { channel.onData((data) => { entry.seen = true; entry.term?.write(data); }); channel.onExit(() => { entry.seen = true; this.ended(entry, true); }); channel.onClose?.(() => { if (entry.channel === channel) entry.channel = null; silent(); }); + channel.onStatus?.((text) => { entry.status = text; this.showStatus(); }); this.sendSize(entry); } + private showStatus(): void { + const x = this.active ? this.tabs.get(this.active) : undefined; + setText(q(this.root, '.ft-dock-spacer'), x?.status ?? ''); + } + private sendSize(x: Tab): void { if (x.term) x.channel?.resize(x.term.cols(), x.term.rows()); } @@ -644,6 +680,7 @@ export class Dock { o.tab.setAttribute('aria-selected', String(on)); } this.syncAsk(); + this.showStatus(); setDisabled(this.restartBtn, !this.tabs.has(id) || this.tabs.get(id)?.kind === 'agent'); this.fitActive(); if (focus) this.focus(); @@ -676,7 +713,7 @@ export class Dock { this.active = null; const next = [...this.tabs.keys()].pop() ?? (this.chatTab ? 'chat' : undefined); if (next) this.select(next); - else { setDisabled(this.restartBtn, true); this.syncAsk(); this.onTab(); } + else { setDisabled(this.restartBtn, true); this.syncAsk(); this.showStatus(); this.onTab(); } } setHidden(this.empty, this.tabs.size > 0 || !!this.chatTab); } diff --git a/frontend/src/dock/icons.ts b/frontend/src/dock/icons.ts index eccfac8..b57b519 100644 --- a/frontend/src/dock/icons.ts +++ b/frontend/src/dock/icons.ts @@ -8,6 +8,7 @@ const ICONS: Record<string, string> = { terminal: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4.5" width="18" height="15" rx="2"/><path d="M7 9.5l3 2.5-3 2.5M12.5 15h4.5"/></svg>`, codex: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M8.5 6.5L3 12l5.5 5.5M15.5 6.5L21 12l-5.5 5.5"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/></svg>`, cursor: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 4.5h5M8 4.5v15M5.5 19.5h5"/><path d="M13.5 10.5l7 2.8-3 1.2-1.2 3z"/></svg>`, + antigravity: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8.5" r="3.6"/><path d="M4.5 19.5h15"/><path d="M8 14.8v1.7M12 15.4v1.7M16 14.8v1.7"/></svg>`, dockRight: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4.5" width="18" height="15" rx="2"/><path d="M14.5 4.5v15"/><path d="M8 12h3.5M10 10l1.75 2L10 14"/></svg>`, dockBottom: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4.5" width="18" height="15" rx="2"/><path d="M3 14.5h18"/><path d="M12 7.5V11M10 9.5l2 1.75 2-1.75"/></svg>`, menu: `<svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><circle cx="12" cy="5.5" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="18.5" r="1.6"/></svg>`, diff --git a/frontend/src/dock/strings.ts b/frontend/src/dock/strings.ts index 5de91b9..1aae816 100644 --- a/frontend/src/dock/strings.ts +++ b/frontend/src/dock/strings.ts @@ -12,6 +12,7 @@ export const STRINGS = { hide: 'Hide Terminal', codex: 'Codex', cursor: 'Cursor', + antigravity: 'Antigravity', moreAgents: 'More agents', programMissing: '{program} is not on this computer yet: install it with the command below, then sign in once in a terminal.', programReady: '{program} is installed. Start it in a new tab.', diff --git a/frontend/src/dock/tour.ts b/frontend/src/dock/tour.ts index 94eb988..358cac3 100644 --- a/frontend/src/dock/tour.ts +++ b/frontend/src/dock/tour.ts @@ -40,7 +40,7 @@ export class Tour { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.end(true); } }; - constructor(private readonly a: DockAdapter) { + constructor(private readonly a: DockAdapter<string>) { this.s = strings(a); } diff --git a/frontend/src/version.ts b/frontend/src/version.ts index aa7ccda..3475238 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.34.0'; +export const VERSION = '0.35.0'; diff --git a/setup/agents.py b/setup/agents.py index a37288d..99044fc 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -2,6 +2,7 @@ import argparse import ast import hashlib +import importlib.util import json import os import re @@ -25,7 +26,7 @@ MANIFEST_REL = "agents/manifest.json" MCP_ROUTER = os.path.join(ROOT, "backend", "app", "routers", "mcp.py") MCP_BRIDGE = os.path.join(ROOT, "setup", "mcp_stdio.py") -DOCK = {"present": True, "positions": ["bottom", "right"], "tabs": ["chat", "terminal", "claude-code", "codex", "cursor", "activity"]} +DOCK = {"present": True, "positions": ["bottom", "right"], "tabs": ["chat", "terminal", "claude-code", "codex", "cursor", "antigravity", "activity"]} DOCK_DIR = os.path.join(ROOT, "frontend", "src", "dock") DOCK_DIR_REL = "frontend/src/dock" DOCK_MANIFEST = os.path.join(DOCK_DIR, "MANIFEST.json") @@ -178,6 +179,34 @@ def check_dock(problems): problems.append(f"{DOCK_DIR_REL}/{name}: does not match MANIFEST.json (the shared dock module changes only as a whole new version, copied from FormVis)") +LOOKUP_REL = "backend/app/services/agent_lookup.py" +LOOKUP = os.path.join(ROOT, "backend", "app", "services", "agent_lookup.py") +LOOKUP_HASHES = { + "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", + "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", +} + + +def lookup_problems(): + try: + raw = read_bytes(LOOKUP) + except OSError: + return [f"{LOOKUP_REL}: missing (the shared finder for the agent programs)"] + said = re.search(rb'^VERSION = "([^"\r\n]+)"\r?$', raw, re.M) + version = said.group(1).decode("ascii", "replace") if said else "unknown" + if LOOKUP_HASHES.get(version) != hashlib.sha256(raw).hexdigest(): + return [f"{LOOKUP_REL}: does not match the hash recorded for version {version} (the shared finder changes only as a whole new version)"] + return [] + + +def lookup(): + spec = importlib.util.spec_from_file_location("formtxt_agent_lookup", LOOKUP) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + def sync(): if not os.path.isdir(SOURCE): print("[agents] .claude/skills is missing", file=sys.stderr) @@ -209,6 +238,7 @@ def sync(): return 1 dock = [] check_dock(dock) + dock.extend(lookup_problems()) for line in dock: print(f"[agents] {line}", file=sys.stderr) return 1 if dock else 0 @@ -349,6 +379,7 @@ def check(): check_agent_files(problems) check_manifest(problems) check_dock(problems) + problems.extend(lookup_problems()) if problems: for line in problems: print(f"[agents] {line}", file=sys.stderr) @@ -380,20 +411,23 @@ def copy_skills(root, dry, said): def install_claude(home, dry, said): said.append("Claude Code:") - claude = shutil.which("claude") + finder = lookup() + found = finder.check(finder.find("claude", override_vars=("FORMTXT_CLAUDE_BIN",), home=home)) + claude = found.path if found.state == "runs" else None line = subprocess.list2cmdline([LAUNCH, *ARGS]) if claude: - have = subprocess.run([claude, "mcp", "get", LAUNCHER], capture_output=True, text=True) + env = finder.child_env(claude, home=home) + have = finder.run([claude, "mcp", "get", LAUNCHER], env, 60) if have.returncode == 0 and LAUNCH in have.stdout: said.append(f" MCP server {LAUNCHER} already set (user scope)") else: said.append(f" claude mcp add --scope user {LAUNCHER} -- {line}") if not dry: if have.returncode == 0: - subprocess.run([claude, "mcp", "remove", LAUNCHER, "--scope", "user"], capture_output=True) - subprocess.run([claude, "mcp", "add", "--scope", "user", LAUNCHER, "--", LAUNCH, *ARGS], check=True, capture_output=True) + finder.run([claude, "mcp", "remove", LAUNCHER, "--scope", "user"], env, 60) + finder.run([claude, "mcp", "add", "--scope", "user", LAUNCHER, "--", LAUNCH, *ARGS], env, 60).check_returncode() else: - said.append(f" the claude command is not installed here; once it is, run: claude mcp add --scope user {LAUNCHER} -- {line}") + said.append(f" {finder.sentence(found, finder.install('claude'))} Once it runs: claude mcp add --scope user {LAUNCHER} -- {line}") copy_skills(home / ".claude" / "skills", dry, said) @@ -437,11 +471,45 @@ def install_cursor(home, dry, said): copy_skills(home / ".agents" / "skills", dry, said) +def ours(entry): + return isinstance(entry, dict) and entry.get("args") == ARGS and Path(str(entry.get("command", ""))).name == Path(LAUNCH).name + + +def install_antigravity(home, dry, said): + said.append("Antigravity:") + cfg = home / ".gemini" / "config" / "mcp_config.json" + older = home / ".gemini" / "antigravity-cli" / "mcp_config.json" + if older.exists() and not cfg.exists(): + said.append(f" an older file was seen at {older} and left alone; the documented file is {cfg}") + try: + data = json.loads(cfg.read_text(encoding="utf-8") or "{}") if cfg.exists() else {} + except ValueError: + data = None + if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict): + said.append(f" {cfg} is not an MCP servers file FormTxt can read; left alone") + return + entry = {"command": LAUNCH, "args": ARGS} + have = data.get("mcpServers", {}).get(LAUNCHER) + if have == entry: + said.append(f" MCP server {LAUNCHER} already in {cfg}") + elif have is not None and not ours(have): + said.append(f" {cfg} has a server named {LAUNCHER} that FormTxt did not write; left alone") + else: + said.append(f" MCP server {LAUNCHER} -> {cfg}") + if not dry: + backup(cfg, dry) + data.setdefault("mcpServers", {})[LAUNCHER] = entry + cfg.parent.mkdir(parents=True, exist_ok=True) + part = cfg.with_name(cfg.name + f".part-{os.getpid()}") + part.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + os.replace(part, cfg) + + def install(clients, dry): home = Path(os.environ.get("HOME", str(Path.home()))) said = [] - for client in clients or ["claude", "codex", "cursor"]: - {"claude": install_claude, "codex": install_codex, "cursor": install_cursor}[client](home, dry, said) + for client in clients or ["claude", "codex", "cursor", "antigravity"]: + {"claude": install_claude, "codex": install_codex, "cursor": install_cursor, "antigravity": install_antigravity}[client](home, dry, said) print(("Would do (dry run):\n" if dry else "") + "\n".join(said)) if not dry: print("\nRestart the clients. The first command an agent runs asks you once, in the FormTxt window, to allow outside agents.") @@ -454,8 +522,8 @@ def main(): sync_parser = sub.add_parser("sync", help="mirror .claude/skills into .agents/skills and write agents/manifest.json") sync_parser.add_argument("--check", action="store_true", help="only check, as agents check does") sub.add_parser("check", help="check the mirror, the skills, the MCP configs and the manifest") - inst = sub.add_parser("install", help="register FormTxt's MCP server and skill with Claude Code, Codex and Cursor for this user") - inst.add_argument("clients", nargs="*", choices=["claude", "codex", "cursor"], help="which clients (default all three)") + inst = sub.add_parser("install", help="register FormTxt's MCP server with Claude Code, Codex, Cursor and Antigravity for this user, and its skill with the first three") + inst.add_argument("clients", nargs="*", choices=["claude", "codex", "cursor", "antigravity"], help="which clients (default all four)") inst.add_argument("--dry-run", action="store_true", help="say what would change and change nothing") args = parser.parse_args() if args.action == "install": diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 6b5657d..7d98665 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -865,7 +865,7 @@ dependencies = [ [[package]] name = "formtxt" -version = "0.34.0" +version = "0.35.0" dependencies = [ "fontdb", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 07c409b..952f024 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formtxt" -version = "0.34.0" +version = "0.35.0" description = "FormTxt desktop shell" authors = ["nodemode-ai"] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 81180be..1defebf 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": "FormTxt", - "version": "0.34.0", + "version": "0.35.0", "identifier": "ai.nodemode.formtxt", "build": { "devUrl": "http://localhost:5210",