mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Add the desktop app loop driver with commit, notify, report and tools modules, and update the quit prompt, task dialog and meter
AI Assisted
This commit is contained in:
1 parent
8db8df5791
commit
1f80fa6a7c
24 files changed
+9850
-64
No files matched your search
+109
-2
@@ -67,7 +67,7 @@ folder and the skills version before anything else shows; a later launch skips s
|
||||
|
||||
A **launch card** then asks which agent, model and effort (Claude and Codex only) to start on. The
|
||||
picker lists Claude Code, Devin and Codex, then any custom agents you added in the web console's
|
||||
**User Preferences → Agents** (saved in `~/.plan2code/agents.json`, shared with the `plan2code`
|
||||
**User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`, shared with the `plan2code`
|
||||
command), and starts on one that is actually installed, so a machine with only Devin or Codex is ready
|
||||
to go. Permission checks off is its own tick, on by default (see below; New Session keeps whatever
|
||||
you picked, and reuses the same agent); a CLI the app cannot find is named, with how to install it,
|
||||
@@ -89,7 +89,7 @@ needs attention and bounces once; on Linux a count badge appears where the deskt
|
||||
is no dot while the agent is busy or once a finished step has nothing left to press (a finished screen
|
||||
that still offers a button, such as back to the dashboard, keeps the green dot), and it clears when
|
||||
the agent ends or the page reloads. Turn it off with **Show on the taskbar when Plan2Code needs
|
||||
me** under **User Preferences → Desktop app** (shown only inside the app). The per-system details are in
|
||||
me** under **User Preferences → System → Desktop app** (shown only inside the app). The per-system details are in
|
||||
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
|
||||
|
||||
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
|
||||
@@ -121,6 +121,113 @@ involved. A slash command still offered to continue a step (such as `/plan2code-
|
||||
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
|
||||
agent CLI.
|
||||
|
||||
## Implementation Loop
|
||||
|
||||
The Implementation Loop builds every remaining phase of a documented spec for you, one after another,
|
||||
while you do something else. It is in the app only: the dashboard shows an **Implementation Loop**
|
||||
card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app
|
||||
confirms it once in its own window before anything runs.
|
||||
|
||||
**How it runs.** Each phase gets a fresh agent session, so a long spec never grows one tired
|
||||
conversation. The app, not the agent, decides when a phase counts: it reads the spec's marks, runs the
|
||||
quick check, marks the phase done and commits it. With commits on, it commits to the branch you are on and never
|
||||
pushes. With commits on, Start needs a clean working tree (the setup offers the Git board when it is
|
||||
not), so your own edits never end up inside a phase's commit.
|
||||
|
||||
**The setup.** The fields and their defaults:
|
||||
|
||||
- **Review each phase** (on): a fresh agent reviews the phase before it counts.
|
||||
- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the
|
||||
ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the
|
||||
Critical, Warning and Suggestion findings you tick (all three start ticked).
|
||||
- **When a phase asks something**: **Take the agent's best guess** (the default), which records the
|
||||
assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**.
|
||||
- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**.
|
||||
- **Quick check**: a command run after each phase, pre-filled from the project (for example
|
||||
`npm run build`). Clearing it still lets you start; the setup warns that nothing is checked.
|
||||
- **If a phase crashes or goes quiet**: **Retry it once** (on), and how many minutes with no file changes, in the project or the agent's
|
||||
session, count the agent as stuck (20). Waiting on your answer does not count.
|
||||
- **Send a notification** (no address, so off): a message from the loop when it waits on your answer or
|
||||
ends. Send it to a Discord, Slack, Microsoft Teams or Google Chat webhook, or to any `http` or `https`
|
||||
address with the message in its query string or a JSON body.
|
||||
- **Commit each phase** (on): one local commit per phase, with the subject and `AI Assisted`.
|
||||
|
||||
The last setup is remembered per project in `~/.plan2code/console/loop-setup.json`, so the next loop
|
||||
starts from it. The quick check is typed text the page never runs: the app reads it from that file
|
||||
itself and names it in its own window before the loop begins. The notification gets the same treatment,
|
||||
and Resume asks again if either one changed.
|
||||
|
||||
**The notification.** The loop says a question is waiting, that it is complete, or why it stopped. Nothing
|
||||
is sent when you stopped it yourself, and with **Take the agent's best guess** no question ever waits on
|
||||
you. What the app sends depends on the **Send to** choice:
|
||||
|
||||
| Send to | Request | Where the message goes |
|
||||
| --- | --- | --- |
|
||||
| A web address, query string | GET | A parameter you name (`message` by default), added to the address's own |
|
||||
| Discord webhook | POST JSON | `content`, with mentions turned off |
|
||||
| Slack webhook | POST JSON | `text` |
|
||||
| Microsoft Teams webhook | POST JSON | An Adaptive Card, for a Workflows "when a webhook request is received" trigger |
|
||||
| Google Chat webhook | POST JSON | `text` |
|
||||
| A web address, JSON body | POST JSON | A field you name (`message` by default) |
|
||||
|
||||
**Send a test** saves the setup and sends a test message right away, after the app names the address in its
|
||||
own window, so a wrong address shows up before a long run. A name can use letters, digits and `- _ . ~`. Pasting a Discord, Slack, Teams or Google Chat address picks
|
||||
its choice for you, since a plain GET to a Discord webhook answers 200 and posts nothing. The call has 10
|
||||
seconds and any 2xx answer counts. One that fails never changes what the loop does: the finish line or the
|
||||
stop screen's evidence says so, without repeating the address, which is stored in `loop-setup.json` and
|
||||
usually holds a token.
|
||||
|
||||
**It uses the app's agent.** The loop starts every phase on the agent and model you launched the app
|
||||
with, and it needs permission checks off. With them on, an agent would wait on a prompt that nobody
|
||||
sees, so **Start the loop** stays grayed out until you turn them off (see
|
||||
[Permission checks are off by default](#permission-checks-are-off-by-default-same-as-the-terminal)).
|
||||
|
||||
**What is locked while it drives.** Answers, sign-offs, launches, Workspace, Helpers, **Back** and
|
||||
**New Session** are read-only, and Ask is off, except for a question the loop is waiting on. Activities, Notebook, Help, Preferences, the documents
|
||||
and the code review stay usable, so you can watch, play, or read along.
|
||||
|
||||
**You can always see it's running.** From the moment you confirm Start until the loop ends, a banner runs
|
||||
across the top of the window, outside the console page, so it stays put as each phase's session comes and
|
||||
goes. It says what the loop is doing right now (starting, building, between phases, stopping), with the
|
||||
phase, its name and step, a pip per phase, the time so far and any retries. It turns amber when a question
|
||||
needs your answer. The window title says the same, for the taskbar. While the loop works, the page's Send
|
||||
button and "Nothing to send" line go away, and they come back when a question waits.
|
||||
|
||||
**Stopping it.** Two buttons on the banner: **Stop after this phase** lets the phase finish its
|
||||
review, mark and commit, then ends the loop; **Stop now** ends the agent at once, after you confirm, and never commits, retries or finishes the build (a commit already begun finishes first). Stop after can be canceled by pressing it again. After a window reload the banner and both buttons come back, and Change project and Change agent are blocked while the loop runs.
|
||||
Quitting the app ends the loop too, and the quit check says which phases are already committed.
|
||||
|
||||
**A question holds the loop.** When a phase needs an answer (with **Pause and wait for me**), the loop
|
||||
waits with no time limit and nothing is lost. The app calls you back with the taskbar dot, a flash
|
||||
of the window and the question sound, and carries on once you answer.
|
||||
|
||||
**When it stops by itself.** The loop ends on a stop screen, saying what failed and showing the
|
||||
evidence, when:
|
||||
|
||||
- the phase's named tests or the quick check fail;
|
||||
- Critical or Warning findings are left after the re-check, at a level the setup said to fix (a leftover Suggestion does not stop it);
|
||||
- a task is blocked or the spec conflicts with itself;
|
||||
- a commit is refused, for example by a pre-commit hook (the app puts the phase file back as it was, so the spec and git agree, and stops with the hook's first line; if the undo fails too, it says so and remembers it across a restart);
|
||||
- a staged file looks like a secret (`.env` and the like; `.example`, `.sample` and `.template` are fine) or is oversized (nothing stays staged, and the stop line names the file);
|
||||
- the project is on a detached HEAD (the loop will not start);
|
||||
- the agent's report is missing task data or says its tests failed (the phase is refused);
|
||||
- the watcher cannot read the session or hits an internal error (it ends on a stop screen, never a hang);
|
||||
- the Smart pick skipped a Critical finding.
|
||||
|
||||
A crashed or silent agent gets exactly one retry per phase when the retry tick is on, and none when it is off.
|
||||
It never retries a real failure. On a stop screen, **Resume the loop** carries on from the stopped
|
||||
phase and **Fix it by hand** opens an ordinary Implement session on it.
|
||||
|
||||
**The report.** One report follows the whole build, across stops and Resume. For every phase it says what
|
||||
was built and committed, the tests, the findings fixed, the findings it chose not to fix and why, the
|
||||
findings left open, each assumption with its note, and any other decisions the agent reported, plus every
|
||||
retry and stop, in order. The agent writes most of this, so it holds what the agent noticed; the task marks,
|
||||
the quick check and the commits are the app's own. The finish screen counts each kind per phase, and **Read
|
||||
the full report** opens it, saved as `specs/<feature>/LOOP-SUMMARY-<date>.md` (`-2` and so on for another
|
||||
the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build
|
||||
is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Resume needs a
|
||||
clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, which the loop card links to as "How the loop works".
|
||||
|
||||
## Keep it up to date
|
||||
|
||||
`plan2code update` brings the skills, the `plan2code` command and the app up together. If the app
|
||||
|
||||
Generated
+177
-2
@@ -381,7 +381,7 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"core-foundation",
|
||||
"core-graphics-types",
|
||||
"foreign-types",
|
||||
"foreign-types 0.5.0",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -759,6 +759,7 @@ dependencies = [
|
||||
name = "fake-agent"
|
||||
version = "3.0.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"terminal_size",
|
||||
]
|
||||
|
||||
@@ -827,6 +828,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
||||
dependencies = [
|
||||
"foreign-types-shared 0.1.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.5.0"
|
||||
@@ -834,7 +844,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
|
||||
dependencies = [
|
||||
"foreign-types-macros",
|
||||
"foreign-types-shared",
|
||||
"foreign-types-shared 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -848,6 +858,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types-shared"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types-shared"
|
||||
version = "0.3.1"
|
||||
@@ -870,6 +886,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1312,6 +1329,22 @@ dependencies = [
|
||||
"want",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-tls"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"native-tls",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
@@ -1863,6 +1896,23 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "native-tls"
|
||||
version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"openssl",
|
||||
"openssl-probe",
|
||||
"openssl-sys",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ndk"
|
||||
version = "0.9.0"
|
||||
@@ -2151,6 +2201,49 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.81"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"foreign-types 0.3.2",
|
||||
"libc",
|
||||
"openssl-macros",
|
||||
"openssl-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
@@ -2283,6 +2376,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"libc",
|
||||
"portable-pty",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
@@ -2561,21 +2655,26 @@ checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-tls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -2639,6 +2738,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -2654,6 +2762,15 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "0.8.22"
|
||||
@@ -2711,6 +2828,29 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"core-foundation",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "selectors"
|
||||
version = "0.38.0"
|
||||
@@ -3473,6 +3613,19 @@ dependencies = [
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tendril"
|
||||
version = "0.5.1"
|
||||
@@ -3592,6 +3745,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-native-tls"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
|
||||
dependencies = [
|
||||
"native-tls",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.20"
|
||||
@@ -3860,6 +4023,12 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version-compare"
|
||||
version = "0.2.1"
|
||||
@@ -4578,6 +4747,12 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
|
||||
@@ -6,7 +6,7 @@ The app is optional. The Node web console and the skills never depend on it, so
|
||||
|
||||
## Agents and the taskbar
|
||||
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents & models, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
|
||||
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
|
||||
|
||||
@@ -18,7 +18,7 @@ The app is optional. The Node web console and the skills never depend on it, so
|
||||
| macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused |
|
||||
| Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint |
|
||||
|
||||
There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
|
||||
There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → System → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
|
||||
|
||||
## Layout
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
|
||||
## Agents and the taskbar (each system)
|
||||
|
||||
- [ ] A custom agent added in the console's User Preferences → Agents (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments
|
||||
- [ ] A custom agent added in the console's User Preferences → Agents & models (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments
|
||||
- [ ] With no agent CLI on `PATH` and no custom agent, the first-run checklist and the launch card show the explainer with each install command and an **Install page** link, and Start is off
|
||||
- [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex)
|
||||
- [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app
|
||||
@@ -122,7 +122,7 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
|
||||
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
|
||||
- [ ] Reloading the window, or ending the agent, clears the dot
|
||||
- [ ] User Preferences → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app
|
||||
- [ ] User Preferences → System → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app
|
||||
|
||||
## Standalone path
|
||||
|
||||
|
||||
@@ -7,3 +7,4 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
terminal_size = "0.4"
|
||||
serde_json = "1"
|
||||
@@ -7,6 +7,10 @@
|
||||
//! EXIT <c> exit with code c
|
||||
//! SIZE print the terminal size once
|
||||
//! PID print the agent's process id as `PID <n>`
|
||||
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
|
||||
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
|
||||
//! `REPORT written` (`REPORT unavailable` when either is missing)
|
||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
//!
|
||||
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
||||
@@ -36,9 +40,47 @@ pub enum Command {
|
||||
Pid,
|
||||
/// `ENV NAME`: print the variable's value, for tests of what an agent is given.
|
||||
Env(String),
|
||||
/// `REPORT <json>`: the phase report the loop waits for, as the JSON text.
|
||||
Report(String),
|
||||
/// `HANG`: go silent, to model an agent that stops answering.
|
||||
Hang,
|
||||
Echo(String),
|
||||
}
|
||||
|
||||
/// Write `json` as the `loopOutcome` of the session named by the environment.
|
||||
/// Returns false when the session cannot be named.
|
||||
fn write_report(json: &str) -> bool {
|
||||
let (Ok(home), Ok(sid)) = (
|
||||
std::env::var("PLAN2CODE_CONSOLE_HOME"),
|
||||
std::env::var("PLAN2CODE_CONSOLE_SID"),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
write_report_to(std::path::Path::new(&home), &sid, json)
|
||||
}
|
||||
|
||||
/// `write_report` with the session named: `<home>/sessions/<sid>/state.json`.
|
||||
fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
||||
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
||||
return false;
|
||||
};
|
||||
let dir = home.join("sessions").join(sid);
|
||||
let file = dir.join("state.json");
|
||||
let mut state = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.filter(|value| value.is_object())
|
||||
// The console's own file always carries its schema number; a new one does too.
|
||||
.unwrap_or_else(|| serde_json::json!({ "schema": 1 }));
|
||||
state["loopOutcome"] = outcome;
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let temp = dir.join("state.json.tmp");
|
||||
let Ok(text) = serde_json::to_string(&state) else {
|
||||
return false;
|
||||
};
|
||||
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
||||
}
|
||||
|
||||
pub fn parse(line: &str) -> Command {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("STEP ") {
|
||||
@@ -60,6 +102,15 @@ pub fn parse(line: &str) -> Command {
|
||||
if let Some(name) = line.strip_prefix("ENV ") {
|
||||
return Command::Env(name.trim().to_string());
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("REPORT ") {
|
||||
let json = rest.trim();
|
||||
if serde_json::from_str::<serde_json::Value>(json).is_ok() {
|
||||
return Command::Report(json.to_string());
|
||||
}
|
||||
}
|
||||
if line == "HANG" {
|
||||
return Command::Hang;
|
||||
}
|
||||
Command::Echo(line.to_string())
|
||||
}
|
||||
|
||||
@@ -106,6 +157,19 @@ fn main() {
|
||||
"ENV {name}={}",
|
||||
std::env::var(&name).unwrap_or_default()
|
||||
)),
|
||||
Command::Report(json) => {
|
||||
if write_report(&json) {
|
||||
say("REPORT written")
|
||||
} else {
|
||||
say("REPORT unavailable")
|
||||
}
|
||||
}
|
||||
Command::Hang => {
|
||||
say("HANGING");
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||
}
|
||||
}
|
||||
@@ -128,6 +192,47 @@ mod tests {
|
||||
assert_eq!(parse("hello there"), Command::Echo("hello there".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_report_and_hang() {
|
||||
assert_eq!(
|
||||
parse("REPORT {\"phase\":2}"),
|
||||
Command::Report("{\"phase\":2}".into())
|
||||
);
|
||||
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_lands_in_the_session_file_beside_what_was_there() {
|
||||
let home = std::env::temp_dir().join(format!("fake-agent-report-{}", std::process::id()));
|
||||
let dir = home.join("sessions").join("s9");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// No file yet: a new one with the schema number.
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":2}"));
|
||||
let read = || -> serde_json::Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
||||
};
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 2);
|
||||
assert_eq!(read()["schema"], 1);
|
||||
// An existing object keeps its keys.
|
||||
std::fs::write(dir.join("state.json"), "{\"schema\":1,\"title\":\"t\"}").unwrap();
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":3}"));
|
||||
assert_eq!(read()["title"], "t");
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 3);
|
||||
// A garbage file is replaced, not trusted.
|
||||
std::fs::write(dir.join("state.json"), "not json").unwrap();
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":4}"));
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 4);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_with_bad_json_is_an_echo() {
|
||||
assert_eq!(
|
||||
parse("REPORT {not json"),
|
||||
Command::Echo("REPORT {not json".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_number_is_just_an_echo() {
|
||||
assert_eq!(parse("STEP x"), Command::Echo("STEP x".into()));
|
||||
|
||||
@@ -19,6 +19,9 @@ portable-pty = "0.9.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = "0.4"
|
||||
# The loop's call to a web address. The operating system's TLS, so a company's
|
||||
# own root certificates work and no second TLS stack is built.
|
||||
reqwest = { version = "0.13", default-features = false, features = ["blocking", "native-tls"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name and putting it in and out of full screen for an Activities game",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"]
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title", "core:window:allow-is-fullscreen", "core:window:allow-set-fullscreen"]
|
||||
}
|
||||
@@ -29,6 +29,12 @@ pub enum AgentState {
|
||||
/// manager: it runs with the manager's state locked.
|
||||
pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
|
||||
/// Runs when the Implementation Loop starts a phase's fresh agent: the app
|
||||
/// forgets the console session it was showing, so the new agent's `open`
|
||||
/// makes a session of its own. Like `BeforeFresh`, it must not call back into
|
||||
/// the manager.
|
||||
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||
/// so far: a new number means a fresh agent, so the terminal clears.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -101,6 +107,7 @@ struct Shared {
|
||||
folder: PathBuf,
|
||||
sink: Sink,
|
||||
before_fresh: Mutex<Option<BeforeFresh>>,
|
||||
forget_session: Mutex<Option<ForgetSession>>,
|
||||
/// Environment every agent this manager starts gets, on top of its own:
|
||||
/// the in-app signal that sends the agent's console pages to this window.
|
||||
extra_env: Mutex<Vec<(String, String)>>,
|
||||
@@ -128,6 +135,7 @@ impl AgentManager {
|
||||
folder,
|
||||
sink,
|
||||
before_fresh: Mutex::new(None),
|
||||
forget_session: Mutex::new(None),
|
||||
extra_env: Mutex::new(Vec::new()),
|
||||
generation: AtomicU64::new(0),
|
||||
inner: Mutex::new(Inner {
|
||||
@@ -153,6 +161,20 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `hook` whenever the loop starts a phase's fresh agent (`start_fresh`
|
||||
/// and `forget_session`).
|
||||
pub fn set_forget_session(&self, hook: ForgetSession) {
|
||||
if let Ok(mut slot) = self.shared.forget_session.lock() {
|
||||
*slot = Some(hook);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the app forget the console session it follows, so the next agent's
|
||||
/// `open` starts a new one.
|
||||
pub fn forget_session(&self) {
|
||||
self.shared.forget();
|
||||
}
|
||||
|
||||
/// Give every agent started from now on these variables (replacing any set before).
|
||||
pub fn set_env(&self, env: Vec<(String, String)>) {
|
||||
if let Ok(mut slot) = self.shared.extra_env.lock() {
|
||||
@@ -197,6 +219,54 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh agent on the stored launch choice with `prompt` as its
|
||||
/// only first prompt: the Implementation Loop's way to begin a phase. A
|
||||
/// running agent is killed first (the same path as Restart), but without
|
||||
/// Restart's brief note; the app still forgets the console session, so
|
||||
/// the new agent's `open` makes a new one. An agent that ended, or never
|
||||
/// ran, starts directly. Needs a launch choice from an earlier start.
|
||||
pub fn start_fresh(&self, prompt: String) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
let (choice, _) = inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?;
|
||||
inner.brief_note = None;
|
||||
inner.last_start = Some((choice, Some(prompt)));
|
||||
self.shared.forget();
|
||||
if inner.state == AgentState::Running {
|
||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
}
|
||||
match self.shared.spawn(&mut inner) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
reason: format!("could not start the agent: {e}"),
|
||||
};
|
||||
self.shared.emit(&inner);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored launch choice: agent, model, effort and permission mode.
|
||||
pub fn launch_choice(&self) -> Option<(Agent, Option<String>, Option<String>, PermissionMode)> {
|
||||
lock(&self.shared.inner)
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| {
|
||||
(
|
||||
choice.kind.clone(),
|
||||
choice.model.clone(),
|
||||
choice.effort.clone(),
|
||||
choice.mode,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> AgentSnapshot {
|
||||
self.shared.snapshot(&lock(&self.shared.inner))
|
||||
}
|
||||
@@ -296,6 +366,17 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self) {
|
||||
let hook = self
|
||||
.forget_session
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| slot.clone());
|
||||
if let Some(run) = hook {
|
||||
run();
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&self, inner: &Inner) {
|
||||
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||
}
|
||||
|
||||
@@ -243,7 +243,7 @@ impl ConsoleSupervisor {
|
||||
if !session.embed {
|
||||
// Do not leave an old console running that the frame cannot show.
|
||||
let _ = node_command(console_dir)
|
||||
.args(["stop", "--session", &session.sid])
|
||||
.args(stop_args(&session.sid))
|
||||
.current_dir(project_dir)
|
||||
.output();
|
||||
return Err(OLD_CONSOLE.to_string());
|
||||
@@ -327,13 +327,15 @@ impl ConsoleSupervisor {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `console.mjs stop --session <sid>`: the console's own orderly shutdown.
|
||||
/// `console.mjs stop --session <sid> --force`: the console's own orderly
|
||||
/// shutdown. `--force` because the app's shutdown is not the agent's ending:
|
||||
/// the session may be unfinished, and `stop` refuses a session with no finish.
|
||||
pub fn stop(&mut self) -> Result<(), String> {
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
let output = node_command(&self.console_dir)
|
||||
.args(["stop", "--session", &self.session.sid])
|
||||
.args(stop_args(&self.session.sid))
|
||||
.current_dir(&self.project_dir)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
@@ -382,10 +384,25 @@ impl Drop for ConsoleSupervisor {
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments of the app's own `stop`: always `--force`, since the app's
|
||||
/// shutdown is not the agent's ending and `stop` refuses a session with no finish.
|
||||
fn stop_args(sid: &str) -> [&str; 4] {
|
||||
["stop", "--session", sid, "--force"]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_apps_stop_calls_pass_force() {
|
||||
let args = stop_args("20261101-120000-abcdef");
|
||||
assert_eq!(
|
||||
args,
|
||||
["stop", "--session", "20261101-120000-abcdef", "--force"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_the_session_url() {
|
||||
let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap();
|
||||
|
||||
@@ -7,6 +7,11 @@ pub mod attention;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod handoff;
|
||||
pub mod loop_commit;
|
||||
pub mod loop_driver;
|
||||
pub mod loop_notify;
|
||||
pub mod loop_report;
|
||||
pub mod loop_tools;
|
||||
pub mod node_check;
|
||||
pub mod project;
|
||||
pub mod pty_host;
|
||||
|
||||
@@ -0,0 +1,861 @@
|
||||
//! The commit step of the Implementation Loop: its order, and nothing else.
|
||||
//!
|
||||
//! A passed phase goes through five calls, in this order: `prepare` (everything
|
||||
//! that can fail, before any file is touched), `stage_and_check` (stage, then
|
||||
//! refuse a secret or an oversized file), `mark` (save the files, mark the
|
||||
//! phase done, write the approval line), `commit` (stage the marked files and
|
||||
//! commit) and, when the commit fails, `undo` (put the saved text back). The
|
||||
//! driver decides what to say and where to stop; this module only does the work
|
||||
//! and names the failure.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::loop_driver::{with_approval_line, write_atomic};
|
||||
use crate::loop_report::LoopReport;
|
||||
use crate::loop_tools;
|
||||
|
||||
/// What `prepare` settled before any file was touched.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Prepared {
|
||||
pub message: String,
|
||||
pub phase_file: PathBuf,
|
||||
}
|
||||
|
||||
/// The phase file named by a row of `specs.mjs status`, as a path under
|
||||
/// `<project>/<spec>/`. Refuses a name that is missing, empty, climbs out of
|
||||
/// the folder (`..`, a separator, a drive letter) or does not exist.
|
||||
pub fn phase_file(project: &Path, spec: &str, entry: &Value) -> Result<PathBuf, String> {
|
||||
let file = entry["file"].as_str().unwrap_or("").trim();
|
||||
if file.is_empty() {
|
||||
return Err("the spec names no phase file for this phase".to_string());
|
||||
}
|
||||
let unsafe_name = file.contains("..")
|
||||
|| file.contains('/')
|
||||
|| file.contains('\\')
|
||||
|| file.contains('\0')
|
||||
|| file.chars().nth(1) == Some(':');
|
||||
if unsafe_name {
|
||||
return Err(format!(
|
||||
"the phase file name {file} is not a plain file name"
|
||||
));
|
||||
}
|
||||
let path = project.join(spec).join(file);
|
||||
if !path.is_file() {
|
||||
return Err(format!("the phase file {file} does not exist in {spec}"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Everything that can fail before a file changes: the commit message and the
|
||||
/// phase file. Nothing is written.
|
||||
pub fn prepare(
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
entry: &Value,
|
||||
subject: &str,
|
||||
) -> Result<Prepared, String> {
|
||||
let phase_file = phase_file(project, spec, entry)?;
|
||||
let message = loop_tools::commit_message(project, subject)
|
||||
.map_err(|e| format!("the commit message was refused: {e}"))?;
|
||||
Ok(Prepared {
|
||||
message,
|
||||
phase_file,
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of the two files `specs.mjs mark` changes, before and after the
|
||||
/// loop wrote them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Marked {
|
||||
/// The phase file before the mark, and as the loop left it.
|
||||
pub saved: String,
|
||||
pub written: String,
|
||||
/// The same for `overview.md`, whose checkbox the mark flips.
|
||||
pub overview: PathBuf,
|
||||
pub overview_saved: String,
|
||||
pub overview_written: String,
|
||||
}
|
||||
|
||||
fn read(file: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(file).map_err(|e| format!("{} could not be read ({e})", file.display()))
|
||||
}
|
||||
|
||||
/// Why `mark` failed, and whether the files could be put back. When they could
|
||||
/// not, the phase may be left marked done and the driver must say so.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MarkFailure {
|
||||
pub message: String,
|
||||
pub put_back_failed: bool,
|
||||
}
|
||||
|
||||
/// Mark the phase done and write the approval line, keeping the text of both
|
||||
/// files so `undo` can take it back. On any failure both files are put back
|
||||
/// before the error is returned.
|
||||
pub fn mark(
|
||||
prepared: &Prepared,
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
phase: u32,
|
||||
approval: &str,
|
||||
) -> Result<Marked, MarkFailure> {
|
||||
let plain = |message: String| MarkFailure {
|
||||
message,
|
||||
put_back_failed: false,
|
||||
};
|
||||
let overview = project.join(spec).join("overview.md");
|
||||
let saved = read(&prepared.phase_file).map_err(plain)?;
|
||||
let overview_saved = read(&overview).map_err(plain)?;
|
||||
let fail = |message: String| {
|
||||
let phase_back = write_atomic(&prepared.phase_file, &saved);
|
||||
let overview_back = write_atomic(&overview, &overview_saved);
|
||||
MarkFailure {
|
||||
put_back_failed: phase_back.is_err() || overview_back.is_err(),
|
||||
message,
|
||||
}
|
||||
};
|
||||
let run = loop_tools::specs_mark_done(project, spec, phase);
|
||||
if !run.ok {
|
||||
return Err(fail(run.output.trim().to_string()));
|
||||
}
|
||||
let written = read(&prepared.phase_file)
|
||||
.map(|text| with_approval_line(&text, approval))
|
||||
.and_then(|text| {
|
||||
write_atomic(&prepared.phase_file, &text)
|
||||
.map(|()| text)
|
||||
.map_err(|e| format!("the approval line could not be written ({e})"))
|
||||
})
|
||||
.map_err(&fail)?;
|
||||
let overview_written = read(&overview).map_err(&fail)?;
|
||||
Ok(Marked {
|
||||
saved,
|
||||
written,
|
||||
overview,
|
||||
overview_saved,
|
||||
overview_written,
|
||||
})
|
||||
}
|
||||
|
||||
/// Take the mark back: both files get their saved text again, but only while
|
||||
/// both still hold what the loop wrote, so an edit the person made in between
|
||||
/// is never overwritten. Nothing is written unless both can be restored, so the
|
||||
/// mark is either fully off or fully on; the error names each file that could
|
||||
/// not be.
|
||||
pub fn undo(prepared: &Prepared, marked: &Marked) -> Result<(), String> {
|
||||
let files = [
|
||||
(&prepared.phase_file, &marked.saved, &marked.written),
|
||||
(
|
||||
&marked.overview,
|
||||
&marked.overview_saved,
|
||||
&marked.overview_written,
|
||||
),
|
||||
];
|
||||
let name = |file: &Path| {
|
||||
file.file_name()
|
||||
.map_or_else(String::new, |n| n.to_string_lossy().into_owned())
|
||||
};
|
||||
let changed: Vec<String> = files
|
||||
.iter()
|
||||
.filter(|(file, _, written)| std::fs::read_to_string(file).ok().as_ref() != Some(*written))
|
||||
.map(|(file, _, _)| name(file))
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
return Err(format!(
|
||||
"{} changed since the loop wrote it, so it was not restored",
|
||||
changed.join(" and ")
|
||||
));
|
||||
}
|
||||
for (file, saved, _) in files {
|
||||
write_atomic(file, saved)
|
||||
.map_err(|e| format!("{} could not be restored ({e})", name(file)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Which call failed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
Add,
|
||||
Commit,
|
||||
}
|
||||
|
||||
/// A failed `git add` or `git commit`, with what it printed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CommitFailure {
|
||||
pub stage: Stage,
|
||||
pub first_line: String,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// The first non-empty line of `output`, trimmed, at most 160 characters.
|
||||
pub fn first_line(output: &str) -> String {
|
||||
let line = output
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|l| !l.is_empty())
|
||||
.unwrap_or("");
|
||||
if line.chars().count() > 160 {
|
||||
let cut: String = line.chars().take(157).collect();
|
||||
format!("{cut}...")
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest file the loop will commit.
|
||||
pub const MAX_STAGED_BYTES: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// File-name suffixes of a key or certificate.
|
||||
const SECRET_SUFFIXES: [&str; 5] = [".pem", ".key", ".p12", ".pfx", ".keystore"];
|
||||
/// Names an `.env` file may carry and still be committed: a template.
|
||||
const ENV_TEMPLATES: [&str; 3] = [".example", ".sample", ".template"];
|
||||
/// Private-key files with no suffix.
|
||||
const KEY_NAMES: [&str; 2] = ["id_rsa", "id_ed25519"];
|
||||
|
||||
/// Why a staged file must not be committed, or `None`. Only the file name is
|
||||
/// read (the part after the last separator, any case), so a folder named `.env`
|
||||
/// does not match and `environment.md` or `monkey.txt` does not either.
|
||||
pub fn denied(path: &str) -> Option<&'static str> {
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
let name = name.to_lowercase();
|
||||
if name == ".env"
|
||||
|| (name.starts_with(".env.") && !ENV_TEMPLATES.iter().any(|suffix| name.ends_with(suffix)))
|
||||
{
|
||||
return Some("an environment file");
|
||||
}
|
||||
if SECRET_SUFFIXES.iter().any(|suffix| name.ends_with(suffix)) {
|
||||
return Some("a key or certificate");
|
||||
}
|
||||
if KEY_NAMES.contains(&name.as_str()) {
|
||||
return Some("a private key");
|
||||
}
|
||||
if name == "credentials.json" || name.starts_with("secrets.") {
|
||||
return Some("a credentials file");
|
||||
}
|
||||
if name.ends_with(".loop-tmp") {
|
||||
return Some("a temporary file of the loop");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A staged file and its size on disk.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StagedFile {
|
||||
pub path: String,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// Whether the file is over `MAX_STAGED_BYTES`.
|
||||
pub fn too_big(file: &StagedFile) -> bool {
|
||||
file.bytes > MAX_STAGED_BYTES
|
||||
}
|
||||
|
||||
/// Staged files the loop refuses to commit, by their names.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StagedProblem {
|
||||
pub files: Vec<String>,
|
||||
pub why: &'static str,
|
||||
/// Set when the files could not be taken out of the index again: git's
|
||||
/// first line. They are still staged.
|
||||
pub left_staged: Option<String>,
|
||||
}
|
||||
|
||||
/// Why `stage_and_check` stopped: `git add` itself failed, or the staged list
|
||||
/// holds something that must not be committed (and was unstaged again).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StageError {
|
||||
Add(CommitFailure),
|
||||
Problem(StagedProblem),
|
||||
}
|
||||
|
||||
/// Stage everything and look at the list before anything is marked. Any
|
||||
/// secret-looking or oversized file takes everything out of the index again and
|
||||
/// returns every offending path.
|
||||
pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
|
||||
let added = loop_tools::git_add_all(project);
|
||||
if !added.ok {
|
||||
return Err(StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&added.output),
|
||||
output: added.output,
|
||||
}));
|
||||
}
|
||||
let staged = loop_tools::git_staged(project).map_err(|output| {
|
||||
StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&output),
|
||||
output,
|
||||
})
|
||||
})?;
|
||||
// Staged names are relative to the repository's top folder.
|
||||
let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf());
|
||||
let mut secrets = false;
|
||||
let mut big = false;
|
||||
let mut files = Vec::new();
|
||||
for path in staged {
|
||||
// A deleted file is gone from the tree: it counts as 0 bytes.
|
||||
let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len());
|
||||
let file = StagedFile { path, bytes };
|
||||
let is_secret = denied(&file.path).is_some();
|
||||
let is_big = too_big(&file);
|
||||
if is_secret || is_big {
|
||||
secrets |= is_secret;
|
||||
big |= is_big;
|
||||
files.push(file.path);
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let unstaged = loop_tools::git_unstage_all(project);
|
||||
let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output));
|
||||
let why = match (secrets, big) {
|
||||
(true, true) => "look like secrets or are over 5 MB",
|
||||
(true, false) => "look like secrets",
|
||||
_ => "are over 5 MB",
|
||||
};
|
||||
Err(StageError::Problem(StagedProblem {
|
||||
files,
|
||||
why,
|
||||
left_staged,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Commit what `stage_and_check` staged, plus the two files the mark changed
|
||||
/// since: the phase file and `overview.md`. The short hash of the new commit.
|
||||
/// `limit` is the commit's own time limit, for a slow hook.
|
||||
pub fn commit(
|
||||
project: &Path,
|
||||
prepared: &Prepared,
|
||||
marked: &Marked,
|
||||
limit: Duration,
|
||||
) -> Result<Option<String>, CommitFailure> {
|
||||
let added = loop_tools::git_add_paths(project, &[&prepared.phase_file, &marked.overview]);
|
||||
if !added.ok {
|
||||
return Err(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&added.output),
|
||||
output: added.output,
|
||||
});
|
||||
}
|
||||
let done = loop_tools::git_commit_with(project, &prepared.message, limit);
|
||||
if !done.ok {
|
||||
// A cut-off commit says so on its last line, after whatever a hook
|
||||
// printed first; lead with that.
|
||||
let cut_off = done
|
||||
.output
|
||||
.lines()
|
||||
.last()
|
||||
.filter(|line| line.starts_with("(stopped after"))
|
||||
.map(|line| {
|
||||
format!(
|
||||
"the commit was {} (a hook ran too long)",
|
||||
line.trim_matches(|c| c == '(' || c == ')')
|
||||
)
|
||||
});
|
||||
return Err(CommitFailure {
|
||||
stage: Stage::Commit,
|
||||
first_line: cut_off.unwrap_or_else(|| first_line(&done.output)),
|
||||
output: done.output,
|
||||
});
|
||||
}
|
||||
Ok(loop_tools::git_head_short(project))
|
||||
}
|
||||
|
||||
/// Take what a failed commit left staged out of the index, so a commit the
|
||||
/// person makes by hand does not carry a mark the loop took back.
|
||||
pub fn unstage(project: &Path) {
|
||||
let _ = loop_tools::git_unstage_all(project);
|
||||
}
|
||||
|
||||
/// The phases the spec shows done (`done`) that the commit log does not hold:
|
||||
/// one the loop built whose recorded commit is gone from the history, and the
|
||||
/// phase a failed undo left marked. A phase the loop never recorded is trusted
|
||||
/// (the person built it).
|
||||
pub fn marks_without_commits(
|
||||
project: &Path,
|
||||
_spec: &str,
|
||||
done: &[u32],
|
||||
report: &LoopReport,
|
||||
) -> Vec<u32> {
|
||||
let mut missing: Vec<u32> = report
|
||||
.passed()
|
||||
.iter()
|
||||
.filter(|entry| done.contains(&entry.phase))
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.commit
|
||||
.as_deref()
|
||||
.is_some_and(|hash| !loop_tools::git_commit_exists(project, hash))
|
||||
})
|
||||
.map(|entry| entry.phase)
|
||||
.collect();
|
||||
if let Some(left) = &report.marked_not_committed {
|
||||
if done.contains(&left.phase) && !missing.contains(&left.phase) {
|
||||
missing.push(left.phase);
|
||||
}
|
||||
}
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// With commit on, the phases `status` shows done that have no commit behind
|
||||
/// them (see `marks_without_commits`). With commit off a mark is trusted.
|
||||
/// Reads only: nothing is written until the person has confirmed the Start.
|
||||
pub fn unbacked_marks(
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
status: &Value,
|
||||
report: &LoopReport,
|
||||
commit: bool,
|
||||
) -> Vec<u32> {
|
||||
if !commit {
|
||||
return Vec::new();
|
||||
}
|
||||
let done: Vec<u32> = status["phases"]
|
||||
.as_array()
|
||||
.map(|all| {
|
||||
all.iter()
|
||||
.filter(|p| p["marker"].as_str() == Some("x"))
|
||||
.filter_map(|p| u32::try_from(p["number"].as_u64()?).ok())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
marks_without_commits(project, spec, &done, report)
|
||||
}
|
||||
|
||||
/// Open each of `phases` again through `specs.mjs`: `open` first, which also
|
||||
/// sets a Complete phase file back to In Progress, then `in-progress`.
|
||||
pub fn reopen(project: &Path, spec: &str, phases: &[u32]) -> Result<(), String> {
|
||||
for &n in phases {
|
||||
for to in ["open", "in-progress"] {
|
||||
let run = loop_tools::specs_mark(project, spec, n, to);
|
||||
if !run.ok {
|
||||
return Err(format!(
|
||||
"Phase {n} is marked done with no commit, and could not be opened again: {}",
|
||||
first_line(&run.output)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn temp_spec(name: &str) -> (PathBuf, PathBuf) {
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"plan2code-loop-commit-{name}-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let spec = base.join("specs/lunch");
|
||||
std::fs::create_dir_all(&spec).unwrap();
|
||||
(base, spec)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_line_skips_blanks_and_is_cut_at_160_characters() {
|
||||
assert_eq!(first_line("\n \n lint says no \nsecond"), "lint says no");
|
||||
assert_eq!(first_line(""), "");
|
||||
let long = "x".repeat(300);
|
||||
let line = first_line(&long);
|
||||
assert_eq!(line.chars().count(), 160);
|
||||
assert!(line.ends_with("..."));
|
||||
assert_eq!(first_line(&"y".repeat(160)).chars().count(), 160);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_file_must_be_a_plain_name_that_exists() {
|
||||
let (base, spec) = temp_spec("names");
|
||||
std::fs::write(spec.join("phase-2.md"), "x").unwrap();
|
||||
std::fs::write(base.join("secret.md"), "x").unwrap();
|
||||
let ok = phase_file(&base, "specs/lunch", &json!({ "file": "phase-2.md" }));
|
||||
assert_eq!(ok.unwrap(), spec.join("phase-2.md"));
|
||||
for (entry, word) in [
|
||||
(json!({}), "no phase file"),
|
||||
(json!({ "file": "" }), "no phase file"),
|
||||
(json!({ "file": " " }), "no phase file"),
|
||||
(json!({ "file": "../../secret.md" }), "plain file name"),
|
||||
(json!({ "file": "sub/phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "sub\\phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "C:phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "phase-9.md" }), "does not exist"),
|
||||
] {
|
||||
let err = phase_file(&base, "specs/lunch", &entry).unwrap_err();
|
||||
assert!(err.contains(word), "{entry}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
const OVERVIEW: &str =
|
||||
"# Lunch - Overview\n\n## Phase Checklist\n\n- [/] [Phase 2: P2](./phase-2.md)\n";
|
||||
const PHASE: &str = "# Phase 2: P2\n\n**Status:** In Progress\n\n## Tasks\n\n- [x] **Task 2.1:** First\n\n## Phase Completion Summary\n\nBuilt it.\n";
|
||||
|
||||
fn marked_spec(name: &str) -> (PathBuf, Prepared) {
|
||||
let (base, spec) = temp_spec(name);
|
||||
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
|
||||
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
|
||||
let prepared = Prepared {
|
||||
message: "Add it\n\nAI Assisted".to_string(),
|
||||
phase_file: spec.join("phase-2.md"),
|
||||
};
|
||||
(base, prepared)
|
||||
}
|
||||
|
||||
fn node_ready() -> bool {
|
||||
loop_tools::skill_script("specs.mjs").is_some()
|
||||
&& std::process::Command::new("node")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_writes_the_approval_line_and_undo_puts_both_files_back() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("undo");
|
||||
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved by the loop.").unwrap();
|
||||
let overview = std::fs::read_to_string(&marked.overview).unwrap();
|
||||
assert!(overview.contains("[x] [Phase 2"), "{overview}");
|
||||
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
|
||||
assert!(phase.contains("Approved by the loop."), "{phase}");
|
||||
assert_eq!(phase, marked.written);
|
||||
undo(&prepared, &marked).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&marked.overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_will_not_overwrite_an_edit_made_since_and_names_the_file() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("edited");
|
||||
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let mut edited = marked.written.clone();
|
||||
edited.push_str("\nMy own note.\n");
|
||||
std::fs::write(&prepared.phase_file, &edited).unwrap();
|
||||
let err = undo(&prepared, &marked).unwrap_err();
|
||||
assert!(err.contains("phase-2.md"), "{err}");
|
||||
assert!(!err.contains("overview.md"), "{err}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
edited,
|
||||
"the edit stays"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&marked.overview).unwrap(),
|
||||
marked.overview_written,
|
||||
"nothing is restored unless both files can be"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_refuses_an_unsafe_phase_file_before_anything_is_touched() {
|
||||
let (base, prepared) = marked_spec("prepare");
|
||||
for file in ["../../secret.md", "", "phase-9.md"] {
|
||||
let err =
|
||||
prepare(&base, "specs/lunch", &json!({ "file": file }), "Add it").unwrap_err();
|
||||
assert!(!err.is_empty());
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
let overview = base.join("specs/lunch/overview.md");
|
||||
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_are_found_with_commit_on_and_reopened_only_when_asked() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("reopen");
|
||||
mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let status = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(status["phases"][0]["marker"], "x");
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
|
||||
phase: 2,
|
||||
file: "phase-2.md".into(),
|
||||
});
|
||||
// Commit off: a mark is trusted.
|
||||
assert!(unbacked_marks(&base, "specs/lunch", &status, &report, false).is_empty());
|
||||
// Commit on: the saved fact names the phase, and finding it writes nothing.
|
||||
let found = unbacked_marks(&base, "specs/lunch", &status, &report, true);
|
||||
assert_eq!(found, vec![2]);
|
||||
let still = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(still["phases"][0]["marker"], "x");
|
||||
// Reopening sets the overview and the phase file's Status back.
|
||||
reopen(&base, "specs/lunch", &found).unwrap();
|
||||
let after = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(after["phases"][0]["marker"], "/");
|
||||
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
|
||||
assert!(phase.contains("**Status:** In Progress"), "{phase}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_mark_leaves_both_files_as_they_were() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("failed-mark");
|
||||
// Phase 9 is not in the overview, so the script refuses.
|
||||
let err = mark(&prepared, &base, "specs/lunch", 9, "Approved.").unwrap_err();
|
||||
assert!(!err.message.is_empty());
|
||||
assert!(!err.put_back_failed);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
let overview = base.join("specs/lunch/overview.md");
|
||||
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_that_names_a_marked_phase_is_rebuilt_only_when_the_spec_shows_it_done() {
|
||||
let (base, _) = temp_spec("marks");
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
|
||||
phase: 3,
|
||||
file: "phase-3.md".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
marks_without_commits(&base, "specs/lunch", &[1, 3], &report),
|
||||
vec![3]
|
||||
);
|
||||
assert!(marks_without_commits(&base, "specs/lunch", &[1], &report).is_empty());
|
||||
}
|
||||
|
||||
fn git_in(repo: &Path, args: &[&str]) -> String {
|
||||
let out = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(repo)
|
||||
.output()
|
||||
.expect("run git");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn git_ready() -> bool {
|
||||
let found = std::process::Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success());
|
||||
if !found {
|
||||
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_looking_names_are_denied_and_templates_are_not() {
|
||||
for name in [
|
||||
".env",
|
||||
".env.local",
|
||||
".env.production",
|
||||
".ENV",
|
||||
"a/b/.env",
|
||||
"server.pem",
|
||||
"tls.KEY",
|
||||
"cert.p12",
|
||||
"cert.pfx",
|
||||
"release.keystore",
|
||||
"id_rsa",
|
||||
"home/.ssh/id_ed25519",
|
||||
"credentials.json",
|
||||
"config\\credentials.json",
|
||||
"secrets.yml",
|
||||
"Secrets.json",
|
||||
"x/y.loop-tmp",
|
||||
] {
|
||||
assert!(denied(name).is_some(), "{name} should be denied");
|
||||
}
|
||||
for name in [
|
||||
".env.example",
|
||||
".env.production.example",
|
||||
".env.local.sample",
|
||||
".env.sample",
|
||||
".env.template",
|
||||
"app/.env.EXAMPLE",
|
||||
"environment.md",
|
||||
"monkey.txt",
|
||||
"keyboard.rs",
|
||||
"id_rsa.pub",
|
||||
"my-credentials.json.md",
|
||||
"secretsauce.md",
|
||||
"src/.env/readme.md",
|
||||
"tmp.loop-tmp.md",
|
||||
] {
|
||||
assert_eq!(denied(name), None, "{name} should be allowed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_too_big_only_over_five_megabytes() {
|
||||
let file = |bytes| StagedFile {
|
||||
path: "a.bin".into(),
|
||||
bytes,
|
||||
};
|
||||
assert!(!too_big(&file(0)));
|
||||
assert!(!too_big(&file(MAX_STAGED_BYTES)));
|
||||
assert!(too_big(&file(MAX_STAGED_BYTES + 1)));
|
||||
}
|
||||
|
||||
fn init_repo(name: &str) -> PathBuf {
|
||||
let (base, _) = temp_spec(name);
|
||||
git_in(&base, &["init", "-q"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Loop Test"),
|
||||
("user.email", "loop@example.com"),
|
||||
("commit.gpgsign", "false"),
|
||||
("core.autocrlf", "false"),
|
||||
("core.hooksPath", ".git/hooks"),
|
||||
] {
|
||||
git_in(&base, &["config", key, value]);
|
||||
}
|
||||
base
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_stops_on_every_secret_and_oversized_file_and_unstages_all() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-problem");
|
||||
std::fs::write(repo.join("ok.txt"), "fine").unwrap();
|
||||
std::fs::write(repo.join(".env"), "KEY=1").unwrap();
|
||||
std::fs::write(repo.join(".env.example"), "KEY=").unwrap();
|
||||
std::fs::create_dir_all(repo.join("sub")).unwrap();
|
||||
std::fs::write(repo.join("sub/server.pem"), "x").unwrap();
|
||||
let big = std::fs::File::create(repo.join("big.bin")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
// No commit yet: unstaging must work without a HEAD.
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
let mut files = problem.files.clone();
|
||||
files.sort();
|
||||
assert_eq!(files, vec![".env", "big.bin", "sub/server.pem"]);
|
||||
assert_eq!(problem.why, "look like secrets or are over 5 MB");
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
|
||||
// Once the offenders are gone, the same call stages the rest.
|
||||
std::fs::remove_file(repo.join(".env")).unwrap();
|
||||
std::fs::remove_file(repo.join("big.bin")).unwrap();
|
||||
std::fs::remove_file(repo.join("sub/server.pem")).unwrap();
|
||||
stage_and_check(&repo).expect("a clean list passes");
|
||||
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
|
||||
assert!(staged.contains("ok.txt") && staged.contains(".env.example"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_ordinary_file_passes_and_a_big_one_alone_says_so() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-deleted");
|
||||
std::fs::write(repo.join("a.txt"), "a").unwrap();
|
||||
git_in(&repo, &["add", "-A"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "First"]);
|
||||
std::fs::remove_file(repo.join("a.txt")).unwrap();
|
||||
stage_and_check(&repo).expect("a deletion of an ordinary file passes");
|
||||
git_in(&repo, &["reset", "-q"]);
|
||||
let big = std::fs::File::create(repo.join("huge.dat")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
assert_eq!(problem.files, vec!["huge.dat"]);
|
||||
assert_eq!(problem.why, "are over 5 MB");
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
|
||||
if !git_ready() || !node_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("commit-ignored");
|
||||
std::fs::write(repo.join(".gitignore"), "specs/\n").unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "a").unwrap();
|
||||
let spec = repo.join("specs/lunch");
|
||||
std::fs::create_dir_all(&spec).unwrap();
|
||||
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
|
||||
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
|
||||
let prepared = Prepared {
|
||||
message: "Add it\n\nAI Assisted".to_string(),
|
||||
phase_file: spec.join("phase-2.md"),
|
||||
};
|
||||
stage_and_check(&repo).unwrap();
|
||||
let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap();
|
||||
assert!(head.is_some());
|
||||
let shown = git_in(&repo, &["show", "--name-only", "--format=%s", "HEAD"]);
|
||||
assert!(shown.contains("a.txt"), "{shown}");
|
||||
assert!(!shown.contains("specs/"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_commit_hash_is_checked_against_the_history() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let (base, _) = temp_spec("hashes");
|
||||
git_in(&base, &["init", "-q"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Loop Test"),
|
||||
("user.email", "loop@example.com"),
|
||||
("commit.gpgsign", "false"),
|
||||
] {
|
||||
git_in(&base, &["config", key, value]);
|
||||
}
|
||||
std::fs::write(base.join("a.txt"), "a").unwrap();
|
||||
git_in(&base, &["add", "-A"]);
|
||||
git_in(&base, &["commit", "-q", "-m", "First"]);
|
||||
let real = git_in(&base, &["rev-parse", "--short", "HEAD"]);
|
||||
assert!(loop_tools::git_commit_exists(&base, &real));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "deadbee"));
|
||||
assert!(!loop_tools::git_commit_exists(&base, ""));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "--all"));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "HEAD"));
|
||||
|
||||
let entry = |phase: u32, commit: Option<&str>| crate::loop_report::ReportEntry {
|
||||
phase,
|
||||
commit: commit.map(str::to_string),
|
||||
..crate::loop_report::ReportEntry::default()
|
||||
};
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.entries.push(entry(2, Some(real.as_str())));
|
||||
report.entries.push(entry(3, Some("deadbee")));
|
||||
// Built with commit off: no hash, so nothing to check.
|
||||
report.entries.push(entry(4, None));
|
||||
// Never recorded by the loop (built by hand): trusted.
|
||||
let done = [1, 2, 3, 4];
|
||||
assert_eq!(
|
||||
marks_without_commits(&base, "specs/lunch", &done, &report),
|
||||
vec![3]
|
||||
);
|
||||
// A phase the spec no longer shows done is not listed.
|
||||
assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,416 @@
|
||||
//! The Implementation Loop's notification to a web address the person chose,
|
||||
//! when it needs them or ends: a plain GET with the message in the query
|
||||
//! string, or a POST in the shape a chat service's webhook wants. The kind, the
|
||||
//! address and the name come from `loop-setup.json` and the app names them in
|
||||
//! its own Start confirm; the message is written by the loop. A failed call
|
||||
//! never changes what the loop does, and its reason never repeats the address,
|
||||
//! which may hold a token.
|
||||
|
||||
use reqwest::{blocking::Client, header::CONTENT_TYPE, redirect::Policy, Url};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How the message reaches the address. To add a service: a variant here, its
|
||||
/// body in `request_for`, its words in `describe`, and its row in the setup
|
||||
/// screen's `NOTIFY_KINDS` and `loop-setup.mjs`'s list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum NotifyKind {
|
||||
/// A GET with the message in a query string parameter the person names.
|
||||
#[default]
|
||||
Query,
|
||||
/// A POST of a JSON object with the message in a field the person names.
|
||||
Json,
|
||||
Discord,
|
||||
Slack,
|
||||
Teams,
|
||||
GoogleChat,
|
||||
}
|
||||
|
||||
impl NotifyKind {
|
||||
/// Whether the person names the parameter or field that holds the message.
|
||||
pub fn uses_param(self) -> bool {
|
||||
matches!(self, NotifyKind::Query | NotifyKind::Json)
|
||||
}
|
||||
}
|
||||
|
||||
pub const DEFAULT_PARAM: &str = "message";
|
||||
const MAX_URL: usize = 2000;
|
||||
const MAX_PARAM: usize = 64;
|
||||
const CALL_LIMIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Whether `url` is an http or https address the app may call: printable ASCII
|
||||
/// (anything else percent-encoded), a host, and no user name or password.
|
||||
pub fn valid_url(url: &str) -> bool {
|
||||
if url.len() > MAX_URL || !url.chars().all(|c| ('!'..='~').contains(&c)) {
|
||||
return false;
|
||||
}
|
||||
let lower = url.to_ascii_lowercase();
|
||||
let Some(rest) = lower
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| lower.strip_prefix("https://"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||
!authority.is_empty()
|
||||
&& !authority.contains('@')
|
||||
&& Url::parse(url).is_ok_and(|u| u.host_str().is_some())
|
||||
}
|
||||
|
||||
/// Whether `name` can stand as a query parameter's name without being encoded.
|
||||
pub fn valid_param(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= MAX_PARAM
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~'))
|
||||
}
|
||||
|
||||
fn encode(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for byte in text.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(char::from(byte));
|
||||
} else {
|
||||
out.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `url` with `param=message` in its query. The address's other parameters and
|
||||
/// fragment stay; a parameter of the same name is replaced.
|
||||
pub fn target_url(url: &str, param: &str, message: &str) -> String {
|
||||
let (rest, fragment) = match url.split_once('#') {
|
||||
Some((rest, fragment)) => (rest, Some(fragment)),
|
||||
None => (url, None),
|
||||
};
|
||||
let (base, query) = rest.split_once('?').unwrap_or((rest, ""));
|
||||
let mut pairs: Vec<String> = query
|
||||
.split('&')
|
||||
.filter(|pair| !pair.is_empty() && pair.split('=').next() != Some(param))
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
pairs.push(format!("{param}={}", encode(message)));
|
||||
let mut out = format!("{base}?{}", pairs.join("&"));
|
||||
if let Some(fragment) = fragment {
|
||||
out.push('#');
|
||||
out.push_str(fragment);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the setup's notification fields can be used, for an address that is set.
|
||||
pub fn valid_setup(kind: NotifyKind, url: &str, param: &str) -> bool {
|
||||
valid_url(url) && (!kind.uses_param() || valid_param(param))
|
||||
}
|
||||
|
||||
/// Slack treats these three as its own markup in message text.
|
||||
fn slack_escaped(text: &str) -> String {
|
||||
text.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
/// The address to call and, for a POST, the JSON body.
|
||||
pub fn request_for(
|
||||
kind: NotifyKind,
|
||||
url: &str,
|
||||
param: &str,
|
||||
message: &str,
|
||||
) -> (String, Option<Value>) {
|
||||
let body = match kind {
|
||||
NotifyKind::Query => return (target_url(url, param, message), None),
|
||||
NotifyKind::Json => json!({ param: message }),
|
||||
// No mentions, whatever a spec is called: this must never ping a channel.
|
||||
NotifyKind::Discord => json!({ "content": message, "allowed_mentions": { "parse": [] } }),
|
||||
NotifyKind::Slack => json!({ "text": slack_escaped(message) }),
|
||||
NotifyKind::GoogleChat => json!({ "text": message }),
|
||||
// A Teams workflow's "when a webhook request is received" trigger.
|
||||
NotifyKind::Teams => json!({
|
||||
"type": "message",
|
||||
"attachments": [{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"contentUrl": null,
|
||||
"content": {
|
||||
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
"type": "AdaptiveCard",
|
||||
"version": "1.4",
|
||||
"body": [{ "type": "TextBlock", "text": message, "wrap": true }],
|
||||
},
|
||||
}],
|
||||
}),
|
||||
};
|
||||
(url.to_string(), Some(body))
|
||||
}
|
||||
|
||||
/// The Start confirm's words for what the app will do.
|
||||
pub fn describe(kind: NotifyKind, url: &str, param: &str) -> String {
|
||||
match kind {
|
||||
NotifyKind::Query => format!("the app calls: {url} with a message in {param}"),
|
||||
NotifyKind::Json => format!("the app posts to: {url} with a message in {param}"),
|
||||
NotifyKind::Discord => format!("the app posts to Discord at: {url}"),
|
||||
NotifyKind::Slack => format!("the app posts to Slack at: {url}"),
|
||||
NotifyKind::Teams => format!("the app posts to Microsoft Teams at: {url}"),
|
||||
NotifyKind::GoogleChat => format!("the app posts to Google Chat at: {url}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the message, within ten seconds. Any 2xx answer counts as sent. The
|
||||
/// error is safe to show: it never holds the address.
|
||||
pub fn send(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> {
|
||||
let client = Client::builder()
|
||||
.timeout(CALL_LIMIT)
|
||||
.redirect(Policy::limited(5))
|
||||
.build()
|
||||
.map_err(|_| "the app could not prepare the call".to_string())?;
|
||||
let (address, body) = request_for(kind, url, param, message);
|
||||
let request = match body {
|
||||
None => client.get(address),
|
||||
Some(body) => client
|
||||
.post(address)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(body.to_string()),
|
||||
};
|
||||
let response = request.send().map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
"it did not answer within 10 seconds".to_string()
|
||||
} else if e.is_connect() {
|
||||
"the app could not connect to it".to_string()
|
||||
} else {
|
||||
"the call failed".to_string()
|
||||
}
|
||||
})?;
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("it answered {}", status.as_u16()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
/// Answer one request with `status` on a local port; gives back the whole request.
|
||||
fn one_call(status: &'static str) -> (String, thread::JoinHandle<String>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let handle = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut request = String::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
let n = stream.read(&mut buf).unwrap();
|
||||
request.push_str(&String::from_utf8_lossy(&buf[..n]));
|
||||
let Some((head, body)) = request.split_once("\r\n\r\n") else {
|
||||
continue;
|
||||
};
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|l| {
|
||||
l.to_ascii_lowercase()
|
||||
.strip_prefix("content-length: ")
|
||||
.map(str::to_string)
|
||||
})
|
||||
.and_then(|l| l.parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
if n == 0 || body.len() >= length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let answer =
|
||||
format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(answer.as_bytes()).unwrap();
|
||||
request
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}/hook?team=a"), handle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_http_and_https_addresses_with_a_host_are_valid() {
|
||||
for good in [
|
||||
"http://example.com",
|
||||
"https://example.com/hook?x=1#top",
|
||||
"HTTPS://EXAMPLE.COM/a%20b",
|
||||
"http://127.0.0.1:8080/",
|
||||
] {
|
||||
assert!(valid_url(good), "{good}");
|
||||
}
|
||||
for bad in [
|
||||
"",
|
||||
"example.com",
|
||||
"ftp://example.com",
|
||||
"file:///c:/x",
|
||||
"javascript:alert(1)",
|
||||
"https:/example.com",
|
||||
"https://",
|
||||
"https://?x=1",
|
||||
"https://exa mple.com",
|
||||
"https://example.com/é",
|
||||
"https://me:secret@example.com/",
|
||||
"https://example.com/\nx",
|
||||
] {
|
||||
assert!(!valid_url(bad), "{bad}");
|
||||
}
|
||||
assert!(!valid_url(&format!(
|
||||
"https://e.com/{}",
|
||||
"x".repeat(MAX_URL)
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_name_needs_no_encoding() {
|
||||
for good in ["message", "msg_1", "a-b.c~d", "M"] {
|
||||
assert!(valid_param(good), "{good}");
|
||||
}
|
||||
for bad in ["", "a b", "a=b", "a&b", "a?b", "a#b", "a%20b", "é", "[x]"] {
|
||||
assert!(!valid_param(bad), "{bad}");
|
||||
}
|
||||
assert!(!valid_param(&"x".repeat(MAX_PARAM + 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_message_lands_encoded_in_the_query_beside_what_is_there() {
|
||||
assert_eq!(
|
||||
target_url("https://e.com/hook", "message", "a b&c=d/é"),
|
||||
"https://e.com/hook?message=a%20b%26c%3Dd%2F%C3%A9"
|
||||
);
|
||||
assert_eq!(
|
||||
target_url("https://e.com/hook?t=1&x=2#top", "msg", "hi"),
|
||||
"https://e.com/hook?t=1&x=2&msg=hi#top"
|
||||
);
|
||||
assert_eq!(
|
||||
target_url("https://e.com/?msg=old&t=1", "msg", "new"),
|
||||
"https://e.com/?t=1&msg=new",
|
||||
"a parameter of the same name is replaced"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_call_is_a_get_with_the_message_in_the_query() {
|
||||
let (url, server) = one_call("200 OK");
|
||||
assert_eq!(send(NotifyKind::Query, &url, "message", "all done"), Ok(()));
|
||||
assert_eq!(
|
||||
server.join().unwrap().lines().next().unwrap(),
|
||||
"GET /hook?team=a&message=all%20done HTTP/1.1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_webhook_gets_a_post_of_json_at_the_address_as_given() {
|
||||
let (url, server) = one_call("204 No Content");
|
||||
assert_eq!(
|
||||
send(NotifyKind::Discord, &url, "ignored", "all done"),
|
||||
Ok(())
|
||||
);
|
||||
let request = server.join().unwrap();
|
||||
assert_eq!(
|
||||
request.lines().next().unwrap(),
|
||||
"POST /hook?team=a HTTP/1.1"
|
||||
);
|
||||
assert!(request
|
||||
.to_ascii_lowercase()
|
||||
.contains("content-type: application/json"));
|
||||
let (_, body) = request.split_once("\r\n\r\n").unwrap();
|
||||
let body: Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(body["content"], "all done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_service_gets_the_shape_it_wants() {
|
||||
let body = |kind, message| {
|
||||
request_for(kind, "https://e.com/x", "note", message)
|
||||
.1
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(body(NotifyKind::Json, "hi"), json!({ "note": "hi" }));
|
||||
assert_eq!(
|
||||
body(NotifyKind::Discord, "@everyone hi"),
|
||||
json!({ "content": "@everyone hi", "allowed_mentions": { "parse": [] } }),
|
||||
"a mention in a spec's name pings nobody"
|
||||
);
|
||||
assert_eq!(
|
||||
body(NotifyKind::Slack, "a <b> & c"),
|
||||
json!({ "text": "a <b> & c" })
|
||||
);
|
||||
assert_eq!(body(NotifyKind::GoogleChat, "hi"), json!({ "text": "hi" }));
|
||||
let teams = body(NotifyKind::Teams, "hi");
|
||||
assert_eq!(teams["type"], "message");
|
||||
let attachment = &teams["attachments"][0];
|
||||
assert_eq!(
|
||||
attachment["contentType"],
|
||||
"application/vnd.microsoft.card.adaptive"
|
||||
);
|
||||
assert_eq!(attachment["content"]["type"], "AdaptiveCard");
|
||||
assert_eq!(attachment["content"]["body"][0]["text"], "hi");
|
||||
assert_eq!(
|
||||
request_for(NotifyKind::Slack, "https://e.com/x", "n", "m").0,
|
||||
"https://e.com/x"
|
||||
);
|
||||
assert_eq!(
|
||||
request_for(NotifyKind::Query, "https://e.com/x", "n", "m"),
|
||||
("https://e.com/x?n=m".to_string(), None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kind_reads_by_its_saved_name_and_only_some_need_a_name() {
|
||||
for (name, kind) in [
|
||||
("query", NotifyKind::Query),
|
||||
("json", NotifyKind::Json),
|
||||
("discord", NotifyKind::Discord),
|
||||
("slack", NotifyKind::Slack),
|
||||
("teams", NotifyKind::Teams),
|
||||
("google-chat", NotifyKind::GoogleChat),
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_value::<NotifyKind>(json!(name)).unwrap(),
|
||||
kind
|
||||
);
|
||||
}
|
||||
assert!(valid_setup(NotifyKind::Slack, "https://e.com/", "a b"));
|
||||
assert!(!valid_setup(NotifyKind::Query, "https://e.com/", "a b"));
|
||||
assert!(!valid_setup(NotifyKind::Json, "https://e.com/", ""));
|
||||
assert!(!valid_setup(NotifyKind::Slack, "e.com", "message"));
|
||||
}
|
||||
|
||||
// Needs the internet, so only by hand: `cargo test live_https -- --ignored`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_https_reaches_a_real_certificate() {
|
||||
assert_eq!(
|
||||
send(NotifyKind::Query, "https://example.com/", "message", "test"),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_says_why_without_the_address() {
|
||||
let (url, server) = one_call("503 Service Unavailable");
|
||||
assert_eq!(
|
||||
send(NotifyKind::Query, &url, "message", "x"),
|
||||
Err("it answered 503".to_string())
|
||||
);
|
||||
server.join().unwrap();
|
||||
|
||||
// A port nothing listens on.
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let err = send(
|
||||
NotifyKind::Slack,
|
||||
&format!("http://127.0.0.1:{port}/secret-token"),
|
||||
"message",
|
||||
"x",
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(!err.contains("secret-token"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
//! The Implementation Loop's report: everything the loop did on the person's
|
||||
//! behalf, across stops and resumes, until every phase is built.
|
||||
//!
|
||||
//! While a build is under way the report lives in `loop-reports.json` in the
|
||||
//! console's folder, saved after every phase, retry and stop. It cannot live in
|
||||
//! the project yet: a file there would dirty the tree, and Resume needs a clean
|
||||
//! one to commit each phase. When the last phase is built it is written to
|
||||
//! `specs/<feature>/LOOP-SUMMARY-<date>.md` and its entry here goes away.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::loop_driver::{fold_key, write_atomic, Finding, Outcome};
|
||||
|
||||
pub const REPORTS_FILE: &str = "loop-reports.json";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EntryResult {
|
||||
#[default]
|
||||
Passed,
|
||||
Stopped,
|
||||
Retried,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Assumption {
|
||||
pub task: String,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// One thing that happened to a phase, in the order it happened.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ReportEntry {
|
||||
pub at: String,
|
||||
pub phase: u32,
|
||||
pub name: String,
|
||||
pub result: EntryResult,
|
||||
/// Why it stopped or was retried; empty for a phase that passed.
|
||||
pub line: String,
|
||||
pub commit: Option<String>,
|
||||
pub subject: String,
|
||||
pub summary: String,
|
||||
pub tests: String,
|
||||
/// Whether the phase got as far as reporting; false for a crash or a stop mid-build.
|
||||
pub reported: bool,
|
||||
pub review_ran: bool,
|
||||
pub fixed: Vec<Finding>,
|
||||
pub skipped: Vec<Finding>,
|
||||
pub left_open: Vec<Finding>,
|
||||
pub assumed: Vec<Assumption>,
|
||||
pub blocked: Vec<String>,
|
||||
pub conflicts: Vec<String>,
|
||||
pub decisions: Vec<String>,
|
||||
/// Things the app noticed that did not stop the phase (leftover Suggestions).
|
||||
pub warnings: Vec<String>,
|
||||
pub retries: u32,
|
||||
}
|
||||
|
||||
impl ReportEntry {
|
||||
/// An entry's review, tasks and decisions, from the phase's report.
|
||||
pub fn with_outcome(mut self, outcome: &Outcome) -> ReportEntry {
|
||||
self.reported = true;
|
||||
self.subject.clone_from(&outcome.subject);
|
||||
self.summary.clone_from(&outcome.summary);
|
||||
self.tests = match &outcome.tests {
|
||||
Some(t) if !t.summary.is_empty() => t.summary.clone(),
|
||||
Some(t) if t.passed => "passed".to_string(),
|
||||
Some(t) if t.ran => "failed".to_string(),
|
||||
_ => "not reported".to_string(),
|
||||
};
|
||||
if let Some(review) = &outcome.review {
|
||||
self.review_ran = review.ran;
|
||||
self.fixed.clone_from(&review.fixed);
|
||||
self.left_open.clone_from(&review.unfixed);
|
||||
if let Some(triage) = &review.triage {
|
||||
self.skipped.clone_from(&triage.skipped);
|
||||
}
|
||||
}
|
||||
self.blocked.clone_from(&outcome.tasks.blocked);
|
||||
self.conflicts.clone_from(&outcome.conflicts);
|
||||
self.decisions.clone_from(&outcome.decisions);
|
||||
for task in &outcome.tasks.assumed {
|
||||
if !self.assumed.iter().any(|a| &a.task == task) {
|
||||
self.assumed.push(Assumption {
|
||||
task: task.clone(),
|
||||
note: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A phase the loop marked done whose commit failed and whose mark could not be
|
||||
/// taken back: it survives an app restart, so Resume can rebuild the phase.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct MarkedNotCommitted {
|
||||
pub phase: u32,
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LoopReport {
|
||||
pub spec: String,
|
||||
pub started: String,
|
||||
pub entries: Vec<ReportEntry>,
|
||||
pub marked_not_committed: Option<MarkedNotCommitted>,
|
||||
}
|
||||
|
||||
impl LoopReport {
|
||||
pub fn new(spec: &str, started: &str) -> LoopReport {
|
||||
LoopReport {
|
||||
spec: spec.to_string(),
|
||||
started: started.to_string(),
|
||||
entries: Vec::new(),
|
||||
marked_not_committed: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_marked(&mut self, phase: u32, file: &str) {
|
||||
self.marked_not_committed = Some(MarkedNotCommitted {
|
||||
phase,
|
||||
file: file.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn clear_marked(&mut self) {
|
||||
self.marked_not_committed = None;
|
||||
}
|
||||
|
||||
/// Each phase's latest pass, by phase number.
|
||||
pub fn passed(&self) -> Vec<&ReportEntry> {
|
||||
let mut seen: Vec<&ReportEntry> = Vec::new();
|
||||
for entry in self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| e.result == EntryResult::Passed)
|
||||
{
|
||||
seen.retain(|e| e.phase != entry.phase);
|
||||
seen.push(entry);
|
||||
}
|
||||
seen.sort_by_key(|e| e.phase);
|
||||
seen
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- the store
|
||||
|
||||
fn key(project: &Path, spec: &str) -> String {
|
||||
format!("{}|{spec}", fold_key(project))
|
||||
}
|
||||
|
||||
fn read_store(home: &Path) -> Value {
|
||||
std::fs::read_to_string(home.join(REPORTS_FILE))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
||||
.filter(|store| store["schema"].as_u64() == Some(1) && store["reports"].is_object())
|
||||
.unwrap_or_else(|| json!({ "schema": 1, "reports": {} }))
|
||||
}
|
||||
|
||||
/// The report under way for this spec, if a build of it has not finished.
|
||||
pub fn load(home: &Path, project: &Path, spec: &str) -> Option<LoopReport> {
|
||||
let store = read_store(home);
|
||||
serde_json::from_value(store["reports"].get(key(project, spec))?.clone()).ok()
|
||||
}
|
||||
|
||||
pub fn save(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> {
|
||||
let mut store = read_store(home);
|
||||
store["reports"][key(project, &report.spec)] = json!(report);
|
||||
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
|
||||
}
|
||||
|
||||
pub fn remove(home: &Path, project: &Path, spec: &str) -> Result<(), String> {
|
||||
let mut store = read_store(home);
|
||||
let gone = store["reports"]
|
||||
.as_object_mut()
|
||||
.and_then(|all| all.remove(&key(project, spec)));
|
||||
if gone.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------ the phase file
|
||||
|
||||
/// The `[?]` tasks in a phase file and their `Assumed:` notes: on the task's own
|
||||
/// line or on an indented line under it.
|
||||
pub fn assumptions_in(phase_text: &str) -> Vec<Assumption> {
|
||||
let mut found: Vec<Assumption> = Vec::new();
|
||||
let mut open = false;
|
||||
for line in phase_text.lines() {
|
||||
let trimmed = line.trim_start();
|
||||
let indented = trimmed.len() < line.len();
|
||||
if let Some(rest) = trimmed.strip_prefix("- [?]") {
|
||||
found.push(Assumption {
|
||||
task: task_id(rest),
|
||||
note: note_in(rest).unwrap_or_default(),
|
||||
});
|
||||
open = true;
|
||||
} else if !indented {
|
||||
open = false;
|
||||
} else if open {
|
||||
if let (Some(last), Some(note)) = (found.last_mut(), note_in(trimmed)) {
|
||||
if last.note.is_empty() {
|
||||
last.note = note;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn note_in(text: &str) -> Option<String> {
|
||||
let (_, note) = text.split_once("Assumed:")?;
|
||||
let note = note.trim().trim_end_matches("**").trim();
|
||||
(!note.is_empty()).then(|| note.to_string())
|
||||
}
|
||||
|
||||
/// `2.4` from ` **Task 2.4:** Do it`; the line itself when it names no task.
|
||||
fn task_id(rest: &str) -> String {
|
||||
let id = rest.split_once("Task ").and_then(|(_, after)| {
|
||||
let id: String = after
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit() || *c == '.')
|
||||
.collect();
|
||||
(!id.is_empty()).then(|| id.trim_end_matches('.').to_string())
|
||||
});
|
||||
id.unwrap_or_else(|| rest.trim().to_string())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- the markdown
|
||||
|
||||
fn cell(text: &str) -> String {
|
||||
text.replace('|', "\\|").replace(['\r', '\n'], " ")
|
||||
}
|
||||
|
||||
fn finding_line(f: &Finding) -> String {
|
||||
let file = if f.file.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" (`{}`)", cell(&f.file))
|
||||
};
|
||||
format!("- {}: {}{file}", f.level.word(), cell(&f.title))
|
||||
}
|
||||
|
||||
fn section(md: &mut String, title: &str, lines: &[String], none: &str) {
|
||||
md.push_str(&format!("\n**{title}**\n\n"));
|
||||
if lines.is_empty() {
|
||||
md.push_str(none);
|
||||
md.push('\n');
|
||||
} else {
|
||||
md.push_str(&lines.join("\n"));
|
||||
md.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_markdown(md: &mut String, e: &ReportEntry) {
|
||||
let word = match e.result {
|
||||
EntryResult::Passed => "built",
|
||||
EntryResult::Stopped => "stopped",
|
||||
EntryResult::Retried => "retried",
|
||||
};
|
||||
md.push_str(&format!(
|
||||
"\n### Phase {}: {} ({word}, {})\n\n",
|
||||
e.phase,
|
||||
cell(&e.name),
|
||||
e.at
|
||||
));
|
||||
if !e.line.is_empty() {
|
||||
md.push_str(&format!("{}\n\n", cell(&e.line)));
|
||||
}
|
||||
if let Some(commit) = &e.commit {
|
||||
md.push_str(&format!("- Commit: `{commit}` {}\n", cell(&e.subject)));
|
||||
} else if e.result == EntryResult::Passed {
|
||||
md.push_str("- Commit: not committed\n");
|
||||
}
|
||||
if e.retries > 0 {
|
||||
md.push_str(&format!("- Retries: {}\n", e.retries));
|
||||
}
|
||||
if !e.warnings.is_empty() {
|
||||
let notes: Vec<String> = e.warnings.iter().map(|w| cell(w)).collect();
|
||||
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
|
||||
}
|
||||
if !e.reported {
|
||||
md.push_str(
|
||||
"- The agent ended before reporting, so its review and decisions are unknown.\n",
|
||||
);
|
||||
} else {
|
||||
md.push_str(&format!("- Summary: {}\n", cell(&e.summary)));
|
||||
md.push_str(&format!("- Tests: {}\n", cell(&e.tests)));
|
||||
}
|
||||
if !e.blocked.is_empty() {
|
||||
md.push_str(&format!("- Blocked tasks: {}\n", e.blocked.join(", ")));
|
||||
}
|
||||
for conflict in &e.conflicts {
|
||||
md.push_str(&format!("- Spec conflict: {}\n", cell(conflict)));
|
||||
}
|
||||
let assumed: Vec<String> = e
|
||||
.assumed
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let note = if a.note.is_empty() {
|
||||
"(no note in the phase file)"
|
||||
} else {
|
||||
&a.note
|
||||
};
|
||||
format!("- Task {}: {}", cell(&a.task), cell(note))
|
||||
})
|
||||
.collect();
|
||||
if e.reported || !assumed.is_empty() {
|
||||
section(md, "Assumptions it made", &assumed, "None.");
|
||||
}
|
||||
if !e.reported {
|
||||
return;
|
||||
}
|
||||
let decisions: Vec<String> = e
|
||||
.decisions
|
||||
.iter()
|
||||
.map(|d| format!("- {}", cell(d)))
|
||||
.collect();
|
||||
section(
|
||||
md,
|
||||
"Other decisions it reported",
|
||||
&decisions,
|
||||
"None reported.",
|
||||
);
|
||||
if !e.review_ran {
|
||||
md.push_str("\n**Review:** did not run.\n");
|
||||
return;
|
||||
}
|
||||
let fixed: Vec<String> = e.fixed.iter().map(finding_line).collect();
|
||||
section(md, "Findings it fixed", &fixed, "None.");
|
||||
let skipped: Vec<String> = e
|
||||
.skipped
|
||||
.iter()
|
||||
.map(|f| {
|
||||
format!(
|
||||
"{}: {}",
|
||||
finding_line(f),
|
||||
cell(f.reason.as_deref().unwrap_or("(no reason given)"))
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
section(md, "Findings it chose not to fix", &skipped, "None.");
|
||||
let left: Vec<String> = e.left_open.iter().map(finding_line).collect();
|
||||
section(md, "Findings left open", &left, "None.");
|
||||
}
|
||||
|
||||
/// The report's body: the table of phases and every entry, oldest first.
|
||||
pub fn body_markdown(report: &LoopReport) -> String {
|
||||
let mut md = String::from(
|
||||
"Everything below comes from each phase's report, as its agent wrote it, except the \
|
||||
task marks, the quick check and the commits, which the app checked or made itself. \
|
||||
An agent can only report the decisions it noticed making.\n",
|
||||
);
|
||||
let passed = report.passed();
|
||||
if !passed.is_empty() {
|
||||
md.push_str(
|
||||
"\n## Phases\n\n| Phase | Commit | Subject | Fixed | Not fixed | Left open | Assumed | Other decisions | Retries |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
);
|
||||
for e in &passed {
|
||||
md.push_str(&format!(
|
||||
"| Phase {}: {} | {} | {} | {} | {} | {} | {} | {} | {} |\n",
|
||||
e.phase,
|
||||
cell(&e.name),
|
||||
e.commit.as_deref().unwrap_or("not committed"),
|
||||
cell(&e.subject),
|
||||
e.fixed.len(),
|
||||
e.skipped.len(),
|
||||
e.left_open.len(),
|
||||
e.assumed.len(),
|
||||
e.decisions.len(),
|
||||
e.retries,
|
||||
));
|
||||
}
|
||||
}
|
||||
md.push_str("\n## What happened, in order\n");
|
||||
if report.entries.is_empty() {
|
||||
md.push_str("\nNo phase has finished or stopped yet.\n");
|
||||
}
|
||||
for entry in &report.entries {
|
||||
entry_markdown(&mut md, entry);
|
||||
}
|
||||
md
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::loop_driver::FixLevel;
|
||||
|
||||
fn finding(title: &str, reason: Option<&str>) -> Finding {
|
||||
Finding {
|
||||
level: FixLevel::Warning,
|
||||
title: title.into(),
|
||||
file: "src/y.js".into(),
|
||||
reason: reason.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(phase: u32, result: EntryResult) -> ReportEntry {
|
||||
ReportEntry {
|
||||
at: "2026-11-01 10:00".into(),
|
||||
phase,
|
||||
name: format!("P{phase}"),
|
||||
result,
|
||||
..ReportEntry::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_store_keeps_a_report_per_project_and_spec_until_it_is_removed() {
|
||||
let home = std::env::temp_dir().join(format!("plan2code-report-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let (a, b) = (Path::new("C:/one"), Path::new("C:/two"));
|
||||
assert_eq!(load(&home, a, "specs/x"), None);
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(1, EntryResult::Passed));
|
||||
save(&home, a, &report).unwrap();
|
||||
save(&home, b, &LoopReport::new("specs/x", "later")).unwrap();
|
||||
assert_eq!(load(&home, a, "specs/x").unwrap(), report);
|
||||
assert_eq!(load(&home, a, "specs/other"), None);
|
||||
remove(&home, a, "specs/x").unwrap();
|
||||
assert_eq!(load(&home, a, "specs/x"), None);
|
||||
assert_eq!(load(&home, b, "specs/x").unwrap().started, "later");
|
||||
remove(&home, a, "specs/x").unwrap();
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_store_reads_as_empty_and_is_replaced() {
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("plan2code-report-bad-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::write(home.join(REPORTS_FILE), "not json").unwrap();
|
||||
assert_eq!(load(&home, Path::new("C:/one"), "specs/x"), None);
|
||||
let report = LoopReport::new("specs/x", "now");
|
||||
save(&home, Path::new("C:/one"), &report).unwrap();
|
||||
assert_eq!(load(&home, Path::new("C:/one"), "specs/x").unwrap(), report);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assumptions_come_from_the_task_line_or_the_line_under_it() {
|
||||
let text = "# Phase 2\n\n- [x] **Task 2.1:** Done\n - Assumed: not this one\n- [?] **Task 2.2:** Pick a store\n - Test: through the route\n - Assumed: SQLite, since the spec names no store\n- [?] **Task 2.3:** Pick a port. Assumed: 8080\n- [?] **Task 2.4:** No note\n\n## Notes\n\nAssumed: not under a task\n";
|
||||
assert_eq!(
|
||||
assumptions_in(text),
|
||||
vec![
|
||||
Assumption {
|
||||
task: "2.2".into(),
|
||||
note: "SQLite, since the spec names no store".into()
|
||||
},
|
||||
Assumption {
|
||||
task: "2.3".into(),
|
||||
note: "8080".into()
|
||||
},
|
||||
Assumption {
|
||||
task: "2.4".into(),
|
||||
note: String::new()
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_lists_every_kind_of_decision_with_its_reason() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
let mut built = entry(2, EntryResult::Passed);
|
||||
built.reported = true;
|
||||
built.review_ran = true;
|
||||
built.commit = Some("a1b2c3d".into());
|
||||
built.subject = "Add | the driver".into();
|
||||
built.summary = "Built it".into();
|
||||
built.tests = "14 pass".into();
|
||||
built.fixed.push(finding("Null check", None));
|
||||
built
|
||||
.skipped
|
||||
.push(finding("Rename", Some("Outside this phase")));
|
||||
built.left_open.push(finding("Name the timer", None));
|
||||
built.assumed.push(Assumption {
|
||||
task: "2.2".into(),
|
||||
note: "SQLite".into(),
|
||||
});
|
||||
built.assumed.push(Assumption {
|
||||
task: "2.3".into(),
|
||||
note: String::new(),
|
||||
});
|
||||
built
|
||||
.decisions
|
||||
.push("Kept the old route for callers".into());
|
||||
built.retries = 1;
|
||||
report.entries.push(built);
|
||||
let md = body_markdown(&report);
|
||||
assert!(
|
||||
md.contains("| Phase 2: P2 | a1b2c3d | Add \\| the driver | 1 | 1 | 1 | 2 | 1 | 1 |")
|
||||
);
|
||||
assert!(md.contains("- warning: Null check (`src/y.js`)"));
|
||||
assert!(md.contains("- warning: Rename (`src/y.js`): Outside this phase"));
|
||||
assert!(md.contains("- warning: Name the timer (`src/y.js`)"));
|
||||
assert!(md.contains("- Task 2.2: SQLite"));
|
||||
assert!(md.contains("- Task 2.3: (no note in the phase file)"));
|
||||
assert!(md.contains("- Kept the old route for callers"));
|
||||
assert!(md.contains("- Tests: 14 pass"));
|
||||
assert!(md.contains("- Retries: 1"));
|
||||
assert!(!md.contains('\u{2014}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_that_never_reported_says_so_and_keeps_what_the_file_shows() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
let mut stopped = entry(3, EntryResult::Stopped);
|
||||
stopped.line = "Phase 3 stopped: the agent crashed".into();
|
||||
stopped.assumed.push(Assumption {
|
||||
task: "3.1".into(),
|
||||
note: "Port 8080".into(),
|
||||
});
|
||||
report.entries.push(stopped);
|
||||
let md = body_markdown(&report);
|
||||
assert!(md.contains("Phase 3 stopped: the agent crashed"));
|
||||
assert!(md.contains("its review and decisions are unknown"));
|
||||
assert!(md.contains("- Task 3.1: Port 8080"));
|
||||
assert!(!md.contains("Findings it fixed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_pass_is_the_phases_row_and_earlier_attempts_stay_in_the_story() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(1, EntryResult::Stopped));
|
||||
let mut first = entry(1, EntryResult::Passed);
|
||||
first.subject = "first".into();
|
||||
report.entries.push(first);
|
||||
report.entries.push(entry(2, EntryResult::Passed));
|
||||
let mut again = entry(1, EntryResult::Passed);
|
||||
again.subject = "again".into();
|
||||
report.entries.push(again);
|
||||
let passed = report.passed();
|
||||
assert_eq!(passed.len(), 2);
|
||||
assert_eq!(passed[0].phase, 1);
|
||||
assert_eq!(passed[0].subject, "again");
|
||||
assert_eq!(passed[1].phase, 2);
|
||||
assert_eq!(body_markdown(&report).matches("### Phase 1").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings_show_under_the_phase_and_an_old_store_loads_without_them() {
|
||||
let mut e = entry(2, EntryResult::Passed);
|
||||
e.warnings = vec!["2 Suggestions left unfixed".into(), "a | b".into()];
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(e);
|
||||
let md = body_markdown(&report);
|
||||
assert!(
|
||||
md.contains("- Warnings: 2 Suggestions left unfixed; a \\| b"),
|
||||
"{md}"
|
||||
);
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(3, EntryResult::Passed));
|
||||
assert!(!body_markdown(&report).contains("Warnings"));
|
||||
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
|
||||
assert!(old.warnings.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
//! The commands the Implementation Loop runs on its own: the spec scripts, git,
|
||||
//! the console's `post` and the person's quick check. Each call has a time
|
||||
//! limit and keeps its output. No shell runs here except the quick check, whose
|
||||
//! text comes only from `loop-setup.json` (never from a page message).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::console_supervisor::find_console_dir;
|
||||
|
||||
/// What a finished (or stopped) call left behind.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolRun {
|
||||
pub ok: bool,
|
||||
pub code: Option<i32>,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// Output kept per call: the tail, which is where a failure says why.
|
||||
const OUTPUT_LIMIT: usize = 200 * 1024;
|
||||
|
||||
/// The limit for node and git calls.
|
||||
pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
|
||||
/// The limit for the person's quick check.
|
||||
pub const CHECK_LIMIT: Duration = Duration::from_secs(15 * 60);
|
||||
|
||||
const POLL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Appends `bytes`, dropping from the front when over `limit`.
|
||||
fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
|
||||
buf.extend_from_slice(bytes);
|
||||
if buf.len() > limit {
|
||||
let excess = buf.len() - limit;
|
||||
buf.drain(..excess);
|
||||
}
|
||||
}
|
||||
|
||||
fn pump<R: Read + Send + 'static>(
|
||||
mut source: R,
|
||||
sink: Arc<Mutex<Vec<u8>>>,
|
||||
) -> thread::JoinHandle<()> {
|
||||
thread::spawn(move || {
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
match source.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
if let Ok(mut buf) = sink.lock() {
|
||||
append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `cmd` to its end or `limit`, with `stdin` written when given. Stdout and
|
||||
/// stderr share one kept `output`. The child is killed when the limit passes.
|
||||
fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
|
||||
run_limited_with(cmd, stdin, limit, true)
|
||||
}
|
||||
|
||||
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
|
||||
/// from stdout must not be mixed with a warning git printed beside it.
|
||||
fn run_limited_with(
|
||||
mut cmd: Command,
|
||||
stdin: Option<&str>,
|
||||
limit: Duration,
|
||||
keep_stderr: bool,
|
||||
) -> ToolRun {
|
||||
cmd.env("PATH", crate::node_check::resolved_path());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
cmd.stdin(if stdin.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(if keep_stderr {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
});
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
return ToolRun {
|
||||
ok: false,
|
||||
code: None,
|
||||
output: format!("could not start: {e}"),
|
||||
}
|
||||
}
|
||||
};
|
||||
let sink = Arc::new(Mutex::new(Vec::new()));
|
||||
let readers = [
|
||||
child.stdout.take().map(|s| pump(s, Arc::clone(&sink))),
|
||||
child.stderr.take().map(|s| pump(s, Arc::clone(&sink))),
|
||||
];
|
||||
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
|
||||
// A child that exits before reading closes the pipe: not an error here.
|
||||
let _ = pipe.write_all(text.as_bytes());
|
||||
}
|
||||
let pid = child.id();
|
||||
let started = Instant::now();
|
||||
let mut timed_out = false;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status),
|
||||
Ok(None) => {
|
||||
if started.elapsed() >= limit {
|
||||
timed_out = true;
|
||||
kill_tree(pid);
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
// A descendant that outlives the child can keep the pipes open: wait a
|
||||
// short grace for the readers, then leave them behind.
|
||||
let grace = Instant::now() + Duration::from_secs(3);
|
||||
for reader in readers.into_iter().flatten() {
|
||||
while !reader.is_finished() && Instant::now() < grace {
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
if reader.is_finished() {
|
||||
let _ = reader.join();
|
||||
}
|
||||
}
|
||||
let mut output = sink
|
||||
.lock()
|
||||
.map(|buf| String::from_utf8_lossy(&buf).into_owned())
|
||||
.unwrap_or_default();
|
||||
if timed_out {
|
||||
if !output.is_empty() && !output.ends_with('\n') {
|
||||
output.push('\n');
|
||||
}
|
||||
output.push_str(&format!("(stopped after {})", describe_limit(limit)));
|
||||
}
|
||||
ToolRun {
|
||||
ok: status.is_some_and(|s| s.success()),
|
||||
code: status.and_then(|s| s.code()),
|
||||
output,
|
||||
}
|
||||
}
|
||||
|
||||
/// "1 minute", "15 minutes", "2 seconds".
|
||||
fn describe_limit(limit: Duration) -> String {
|
||||
let secs = limit.as_secs();
|
||||
let (n, unit) = if secs >= 60 {
|
||||
(secs / 60, "minute")
|
||||
} else {
|
||||
(secs.max(1), "second")
|
||||
};
|
||||
format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
/// End a call's whole process tree, not just the program it started.
|
||||
fn kill_tree(pid: u32) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/T", "/F"])
|
||||
.creation_flags(0x08000000)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = Command::new("pkill")
|
||||
.args(["-KILL", "-P", &pid.to_string()])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
}
|
||||
|
||||
fn node_script(script: &Path, project: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(script).args(args).current_dir(project);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn git(project: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.args(args).current_dir(project);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A skill script (`specs.mjs`, `commit-msg.mjs`): beside the console's skill
|
||||
/// first (`<console dir>/../../scripts/`), then the Implement skills' own.
|
||||
pub fn skill_script(name: &str) -> Option<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
// Tests run the repository's own scripts, so they need no installed skill
|
||||
// (CI has none) and cannot drift from the source.
|
||||
#[cfg(test)]
|
||||
candidates.push(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../src/skill-scripts")
|
||||
.join(name),
|
||||
);
|
||||
if let Ok(console) = find_console_dir() {
|
||||
if let Some(skill) = console.parent().and_then(Path::parent) {
|
||||
candidates.push(skill.join("scripts").join(name));
|
||||
}
|
||||
}
|
||||
if let Some(home) = std::env::home_dir() {
|
||||
let skills = home.join(".agents").join("skills");
|
||||
for skill in ["plan2code-3-implement", "plan2code-3-implement-review"] {
|
||||
candidates.push(skills.join(skill).join("scripts").join(name));
|
||||
}
|
||||
}
|
||||
candidates.into_iter().find(|path| path.is_file())
|
||||
}
|
||||
|
||||
fn script_or_err(name: &str) -> Result<PathBuf, String> {
|
||||
skill_script(name).ok_or_else(|| format!("the Plan2Code skill script {name} is not installed"))
|
||||
}
|
||||
|
||||
/// `specs.mjs status <spec>`, parsed.
|
||||
pub fn specs_status(project: &Path, spec: &str) -> Result<serde_json::Value, String> {
|
||||
let script = script_or_err("specs.mjs")?;
|
||||
let run = run_limited(
|
||||
node_script(&script, project, &["status", spec]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
parse_json_object(&run)
|
||||
}
|
||||
|
||||
/// `specs.mjs mark <spec> --phase N --to done`.
|
||||
pub fn specs_mark_done(project: &Path, spec: &str, phase: u32) -> ToolRun {
|
||||
specs_mark(project, spec, phase, "done")
|
||||
}
|
||||
|
||||
/// `specs.mjs mark <spec> --phase N --to <to>` (`in-progress` reopens a phase).
|
||||
pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun {
|
||||
let script = match script_or_err("specs.mjs") {
|
||||
Ok(script) => script,
|
||||
Err(output) => {
|
||||
return ToolRun {
|
||||
ok: false,
|
||||
code: None,
|
||||
output,
|
||||
}
|
||||
}
|
||||
};
|
||||
let phase = phase.to_string();
|
||||
run_limited(
|
||||
node_script(
|
||||
&script,
|
||||
project,
|
||||
&["mark", spec, "--phase", &phase, "--to", to],
|
||||
),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
}
|
||||
|
||||
/// `commit-msg.mjs --subject <subject> --add-all`: the checked message. The
|
||||
/// script's own subject checks are the only ones.
|
||||
pub fn commit_message(project: &Path, subject: &str) -> Result<String, String> {
|
||||
let script = script_or_err("commit-msg.mjs")?;
|
||||
let run = run_limited(
|
||||
node_script(&script, project, &["--subject", subject, "--add-all"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
parse_commit_msg(&run.output)
|
||||
}
|
||||
|
||||
/// What `commit-msg.mjs` printed, read without a shell: its `message` when
|
||||
/// `ok`, otherwise its error, otherwise whatever it printed.
|
||||
fn parse_commit_msg(stdout: &str) -> Result<String, String> {
|
||||
let run = ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: stdout.to_string(),
|
||||
};
|
||||
let value = parse_json_object(&run).map_err(|_| stdout.trim().to_string())?;
|
||||
if value["ok"].as_bool() == Some(true) {
|
||||
if let Some(message) = value["message"].as_str() {
|
||||
return Ok(message.to_string());
|
||||
}
|
||||
}
|
||||
// `error` is a machine code; `message` is the human text.
|
||||
Err(value["message"]
|
||||
.as_str()
|
||||
.or_else(|| value["error"].as_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| stdout.trim().to_string()))
|
||||
}
|
||||
|
||||
pub fn git_add_all(project: &Path) -> ToolRun {
|
||||
run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `git commit -F -` with the message on stdin: no shell, nothing quoted.
|
||||
pub fn git_commit(project: &Path, message: &str) -> ToolRun {
|
||||
git_commit_with(project, message, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `git_commit` with its own time limit: a slow hook is not killed at the
|
||||
/// limit of the quick calls.
|
||||
pub fn git_commit_with(project: &Path, message: &str, limit: Duration) -> ToolRun {
|
||||
run_limited(git(project, &["commit", "-F", "-"]), Some(message), limit)
|
||||
}
|
||||
|
||||
/// `git add -- <paths>`: stage exactly these files. A path git ignores (a
|
||||
/// `specs/` folder in `.gitignore`) is left out, as `git add -A` leaves it out,
|
||||
/// not refused.
|
||||
pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
|
||||
let wanted: Vec<&Path> = paths
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|path| {
|
||||
let mut cmd = git(project, &["check-ignore", "-q", "--"]);
|
||||
cmd.arg(path);
|
||||
!run_limited(cmd, None, QUICK_LIMIT).ok
|
||||
})
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: String::new(),
|
||||
};
|
||||
}
|
||||
let mut cmd = git(project, &["add", "--"]);
|
||||
cmd.args(wanted);
|
||||
run_limited(cmd, None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// The names of the staged files, as `git diff --cached --name-only -z` prints
|
||||
/// them: NUL-separated, so no path is quoted.
|
||||
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["diff", "--cached", "--name-only", "-z"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
);
|
||||
if !run.ok {
|
||||
return Err(run.output.trim().to_string());
|
||||
}
|
||||
Ok(split_nul(&run.output))
|
||||
}
|
||||
|
||||
fn split_nul(text: &str) -> Vec<String> {
|
||||
text.split('\0')
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The repository's top folder: staged names are relative to it, not to
|
||||
/// `project`, which may be a subfolder.
|
||||
pub fn git_toplevel(project: &Path) -> Option<PathBuf> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["rev-parse", "--show-toplevel"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
);
|
||||
let top = run.output.trim();
|
||||
(run.ok && !top.is_empty()).then(|| PathBuf::from(top))
|
||||
}
|
||||
|
||||
/// Whether `HEAD` names a commit (false in a repository with no commit yet).
|
||||
fn git_has_head(project: &Path) -> bool {
|
||||
run_limited(
|
||||
git(project, &["rev-parse", "--verify", "-q", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
.ok
|
||||
}
|
||||
|
||||
/// Take everything out of the index again; the files keep their contents.
|
||||
pub fn git_unstage_all(project: &Path) -> ToolRun {
|
||||
if git_has_head(project) {
|
||||
run_limited(git(project, &["reset", "-q"]), None, QUICK_LIMIT)
|
||||
} else {
|
||||
// Before a first commit there is no HEAD to reset to.
|
||||
run_limited(
|
||||
git(project, &["rm", "-r", "--cached", "-q", ":/"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The branch `HEAD` is on: `Ok(None)` for a detached HEAD, an error when
|
||||
/// `project` is not a git repository.
|
||||
pub fn git_branch(project: &Path) -> Result<Option<String>, String> {
|
||||
let run = run_limited(
|
||||
git(project, &["symbolic-ref", "--short", "-q", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
let name = run.output.trim();
|
||||
if run.ok && !name.is_empty() {
|
||||
return Ok(Some(name.to_string()));
|
||||
}
|
||||
// `symbolic-ref -q` exits 1 and prints nothing for a detached HEAD; any
|
||||
// other failure (not a repository, git missing) prints something.
|
||||
if run.code == Some(1) && name.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(name.to_string())
|
||||
}
|
||||
|
||||
/// Whether `hash` names a commit in this repository.
|
||||
pub fn git_commit_exists(project: &Path, hash: &str) -> bool {
|
||||
if hash.is_empty() || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return false;
|
||||
}
|
||||
let target = format!("{hash}^{{commit}}");
|
||||
run_limited(
|
||||
git(project, &["cat-file", "-e", &target]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
.ok
|
||||
}
|
||||
|
||||
pub fn git_head_short(project: &Path) -> Option<String> {
|
||||
let run = run_limited(
|
||||
git(project, &["rev-parse", "--short", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
let hash = run.output.trim();
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
}
|
||||
|
||||
/// The full hash of `HEAD`, when there is a commit.
|
||||
pub fn git_head_full(project: &Path) -> Option<String> {
|
||||
let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT);
|
||||
let hash = run.output.trim();
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
}
|
||||
|
||||
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
|
||||
pub fn git_status_porcelain(project: &Path) -> Result<Vec<String>, String> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["status", "--porcelain=v1", "-z"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
);
|
||||
if !run.ok {
|
||||
return Err(run.output.trim().to_string());
|
||||
}
|
||||
Ok(parse_porcelain(&run.output))
|
||||
}
|
||||
|
||||
/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no
|
||||
/// quoting. A rename or copy record is followed by one more field, the old
|
||||
/// path, which is skipped (the new path is the one listed).
|
||||
pub fn parse_porcelain(text: &str) -> Vec<String> {
|
||||
let mut paths = Vec::new();
|
||||
let mut fields = text.split('\0');
|
||||
while let Some(record) = fields.next() {
|
||||
let mut chars = record.chars();
|
||||
let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else {
|
||||
continue;
|
||||
};
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') {
|
||||
fields.next();
|
||||
}
|
||||
paths.push(path.to_string());
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// `node console.mjs post --session <sid> --file -` with `patch` on stdin.
|
||||
pub fn console_post(console_dir: &Path, sid: &str, patch: &serde_json::Value) -> ToolRun {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(console_dir.join("console.mjs"))
|
||||
.args(["post", "--session", sid, "--file", "-"]);
|
||||
run_limited(cmd, Some(&patch.to_string()), QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `node console.mjs open --resume <sid> --no-open --workflow <workflow>`: the
|
||||
/// console holding a session again after it went away, without a browser.
|
||||
pub fn console_resume(console_dir: &Path, sid: &str, workflow: &str) -> ToolRun {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(console_dir.join("console.mjs")).args([
|
||||
"open",
|
||||
"--resume",
|
||||
sid,
|
||||
"--no-open",
|
||||
"--workflow",
|
||||
workflow,
|
||||
]);
|
||||
run_limited(cmd, None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// The person's quick check through the platform shell, in `project`.
|
||||
pub fn quick_check(project: &Path, command: &str, limit: Duration) -> ToolRun {
|
||||
let mut cmd;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd = Command::new("cmd");
|
||||
// Raw, so a quoted argument reaches cmd.exe as typed (the usual
|
||||
// argument quoting would turn each quote into a backslash-quote).
|
||||
cmd.arg("/C").raw_arg(command);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
cmd = Command::new("sh");
|
||||
cmd.args(["-c", command]);
|
||||
}
|
||||
cmd.current_dir(project);
|
||||
run_limited(cmd, None, limit)
|
||||
}
|
||||
|
||||
fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
|
||||
let text = run.output.trim();
|
||||
// Stderr shares the output: take the first line that starts the object.
|
||||
let start = text.find('{').unwrap_or(0);
|
||||
// Only the first value counts: stderr lines may trail the object.
|
||||
let first = serde_json::Deserializer::from_str(&text[start..])
|
||||
.into_iter::<serde_json::Value>()
|
||||
.next();
|
||||
match first {
|
||||
Some(Ok(value)) if value.is_object() => Ok(value),
|
||||
_ => Err(if text.is_empty() {
|
||||
"the tool printed nothing".to_string()
|
||||
} else {
|
||||
text.to_string()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
|
||||
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
|
||||
assert_eq!(parse_commit_msg(ok).unwrap(), "Add it\n\nAI Assisted");
|
||||
// Stderr noise before the object does not matter.
|
||||
let noisy = format!("warning: something\n{ok}\n");
|
||||
assert_eq!(parse_commit_msg(&noisy).unwrap(), "Add it\n\nAI Assisted");
|
||||
assert_eq!(
|
||||
parse_commit_msg(r#"{"ok":false,"error":"subject too long"}"#).unwrap_err(),
|
||||
"subject too long"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_commit_msg(r#"{"ok":false,"message":"no subject"}"#).unwrap_err(),
|
||||
"no subject"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_commit_msg("not json at all\n").unwrap_err(),
|
||||
"not json at all"
|
||||
);
|
||||
assert!(parse_commit_msg("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_as_the_script_really_prints_it_reads_as_its_message() {
|
||||
let real = "{\n \"ok\": false,\n \"error\": \"unsafe-subject\",\n \"message\": \"The subject has a double quote.\",\n \"next\": \"Rephrase.\"\n}\nerror: The subject has a double quote.\nnext: Rephrase.\n";
|
||||
assert_eq!(
|
||||
parse_commit_msg(real).unwrap_err(),
|
||||
"The subject has a double quote."
|
||||
);
|
||||
// ok without a message is still an error, never an empty commit.
|
||||
assert!(parse_commit_msg(r#"{"ok":true}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kept_output_is_the_tail() {
|
||||
let mut buf = Vec::new();
|
||||
append_tail(&mut buf, b"0123456789", 6);
|
||||
append_tail(&mut buf, b"AB", 6);
|
||||
assert_eq!(buf, b"6789AB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn porcelain_lists_paths_and_the_new_name_of_a_rename() {
|
||||
let text = " M src/a.rs\0?? new file.txt\0R new.rs\0old.rs\0A \"quoted\".txt\0";
|
||||
assert_eq!(
|
||||
parse_porcelain(text),
|
||||
vec!["src/a.rs", "new file.txt", "new.rs", "\"quoted\".txt"]
|
||||
);
|
||||
assert!(parse_porcelain("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renames_old_path_is_never_read_as_a_record() {
|
||||
// The old path could look like a record; it is skipped by position.
|
||||
let text = "R new.rs\0 M fake.rs\0 M real.rs\0";
|
||||
assert_eq!(parse_porcelain(text), vec!["new.rs", "real.rs"]);
|
||||
// A work-tree rename (intent-to-add) carries the old path too.
|
||||
assert_eq!(parse_porcelain(" R new.rs\0 M fake.rs\0"), vec!["new.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_names_are_split_on_nul() {
|
||||
assert_eq!(
|
||||
split_nul("a b.txt\0dir/c.rs\0"),
|
||||
vec!["a b.txt", "dir/c.rs"]
|
||||
);
|
||||
assert!(split_nul("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_outlives_its_limit_is_stopped_and_says_so() {
|
||||
#[cfg(windows)]
|
||||
let cmd = {
|
||||
let mut c = Command::new("ping");
|
||||
c.args(["-n", "30", "127.0.0.1"]);
|
||||
c
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cmd = {
|
||||
let mut c = Command::new("sleep");
|
||||
c.arg("30");
|
||||
c
|
||||
};
|
||||
let run = run_limited(cmd, None, Duration::from_millis(300));
|
||||
assert!(!run.ok);
|
||||
assert!(run.output.ends_with("(stopped after 1 second)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_reaches_the_child_and_its_output_is_kept() {
|
||||
#[cfg(windows)]
|
||||
let cmd = {
|
||||
let mut c = Command::new("findstr");
|
||||
c.arg("x*");
|
||||
c
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cmd = Command::new("cat");
|
||||
let run = run_limited(cmd, Some("hello loop\n"), Duration::from_secs(10));
|
||||
assert!(run.ok, "{}", run.output);
|
||||
assert!(run.output.contains("hello loop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_json_object_in_mixed_output_is_parsed() {
|
||||
let run = ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: "warning: noise\n{\"ok\":true,\"n\":1}\n".to_string(),
|
||||
};
|
||||
assert_eq!(parse_json_object(&run).unwrap()["n"], 1);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,10 @@ use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||
use plan2code_app_lib::console_supervisor::{
|
||||
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
|
||||
};
|
||||
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::quit_prompt::{quit_prompt, QuitCase};
|
||||
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
use plan2code_app_lib::settings;
|
||||
#[cfg(windows)]
|
||||
@@ -49,6 +50,13 @@ struct AppState {
|
||||
// The app itself, once it is set up: the agent's sink clears the taskbar
|
||||
// through it when the agent ends.
|
||||
app: Arc<OnceLock<tauri::AppHandle>>,
|
||||
// The Implementation Loop running now, if any: in memory only, so an app
|
||||
// restart ends it (NFR-5).
|
||||
loop_run: LoopSlot,
|
||||
// The last loop's project, spec, launch choice and confirmed quick check,
|
||||
// kept after the running record is gone so Resume, Fix it by hand and
|
||||
// Finalize still work. Memory only.
|
||||
last_loop: Mutex<Option<LastLoop>>,
|
||||
}
|
||||
|
||||
// The console page's last state as the taskbar shows it (attention.rs), and
|
||||
@@ -225,6 +233,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app));
|
||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||
agent.set_before_fresh(before_fresh_hook(state));
|
||||
agent.set_forget_session(forget_session_hook(state));
|
||||
*guard = Some(Arc::clone(&agent));
|
||||
Ok(agent)
|
||||
}
|
||||
@@ -253,6 +262,19 @@ fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
||||
})
|
||||
}
|
||||
|
||||
// What the loop does before a phase's fresh agent starts: forget the console
|
||||
// session the window follows, so the new agent's `open` starts its own.
|
||||
fn forget_session_hook(state: &AppState) -> plan2code_app_lib::agent_manager::ForgetSession {
|
||||
let announce = Arc::clone(&state.announce);
|
||||
Arc::new(move || {
|
||||
if let Ok(guard) = announce.lock() {
|
||||
if let Some(server) = guard.as_ref() {
|
||||
server.forget_current();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||
state.agent.lock().ok().and_then(|guard| guard.clone())
|
||||
}
|
||||
@@ -332,6 +354,20 @@ fn sync_agent_env(app: &tauri::AppHandle) {
|
||||
// the same frontend id; dropping one (as happened here when it replaced the
|
||||
// reattach registration) sends the frontend an "end" message that
|
||||
// unregisters that id for good, breaking all future sends through it.
|
||||
// The window's own commands that would end or replace the loop's agent refuse
|
||||
// while a loop runs, between phases too (the slot holds a record then). The
|
||||
// loop's own agent starts go through `loop_driver::start_with`, not these
|
||||
// commands, and `agent_input` stays open so a trust or login prompt can be
|
||||
// answered.
|
||||
fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
return Err(format!(
|
||||
"A loop is running. Stop it before you change the {what}."
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke
|
||||
fn agent_start(
|
||||
@@ -344,6 +380,7 @@ fn agent_start(
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
) -> Result<(), String> {
|
||||
refuse_while_looping(&state, "agent")?;
|
||||
let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
|
||||
let mode =
|
||||
PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
|
||||
@@ -376,6 +413,7 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(),
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
|
||||
refuse_while_looping(&state, "agent")?;
|
||||
current_agent(&state)
|
||||
.ok_or("no agent has been started")?
|
||||
.restart()
|
||||
@@ -434,7 +472,11 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.last);
|
||||
let prompt = quit_prompt(last);
|
||||
// A running loop has its own words, naming what is committed.
|
||||
let prompt = match loop_driver::quit_facts(&app.state::<AppState>().loop_run) {
|
||||
Some((phase, phases, committed)) => loop_quit_prompt(phase, phases, &committed),
|
||||
None => quit_prompt(last),
|
||||
};
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Some(parent) = app
|
||||
@@ -462,12 +504,12 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
||||
// reads Esc as "not the first button".
|
||||
let app = app.clone();
|
||||
app.dialog()
|
||||
.message(prompt.message)
|
||||
.title(prompt.heading)
|
||||
.message(prompt.message.clone())
|
||||
.title(prompt.heading.clone())
|
||||
.kind(kind)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
prompt.quit.to_string(),
|
||||
prompt.stay.to_string(),
|
||||
prompt.quit.clone(),
|
||||
prompt.stay.clone(),
|
||||
))
|
||||
.show({
|
||||
let app = app.clone();
|
||||
@@ -480,13 +522,19 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
||||
});
|
||||
}
|
||||
|
||||
// A running loop counts even between two phases, when no agent runs for a moment.
|
||||
fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
||||
current_agent(&app.state::<AppState>()).is_some_and(|agent| agent.is_active())
|
||||
let state = app.state::<AppState>();
|
||||
loop_driver::is_running(&state.loop_run)
|
||||
|| current_agent(&state).is_some_and(|agent| agent.is_active())
|
||||
}
|
||||
|
||||
// Stops the agent, then the console, then exits.
|
||||
// Stops the loop, the agent, then the console, then exits. The loop goes first:
|
||||
// its record is dropped without a word to the page, so its watch thread never
|
||||
// takes the ended agent for a crash.
|
||||
fn quit_app(app: &tauri::AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
loop_driver::abandon(&state.loop_run);
|
||||
if let Some(agent) = current_agent(&state) {
|
||||
agent.stop();
|
||||
}
|
||||
@@ -503,10 +551,17 @@ fn quit_app(app: &tauri::AppHandle) {
|
||||
// person's move or needs attention while the window is not focused. An
|
||||
// unknown word does nothing.
|
||||
#[tauri::command]
|
||||
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
|
||||
let Some(next) = Signal::from_id(&signal) else {
|
||||
return;
|
||||
};
|
||||
fn set_attention(app: tauri::AppHandle, signal: String) {
|
||||
if let Some(next) = Signal::from_id(&signal) {
|
||||
apply_signal(&app, next);
|
||||
}
|
||||
}
|
||||
|
||||
// The dot and the flash for a state. The page's `attention` message comes here,
|
||||
// and so does the loop when a question starts holding it: the dot and flash
|
||||
// then do not depend on the page, which is locked while the loop drives.
|
||||
fn apply_signal(app: &tauri::AppHandle, next: Signal) {
|
||||
let state = app.state::<AppState>();
|
||||
let Some(window) = app.get_webview_window("main") else {
|
||||
return;
|
||||
};
|
||||
@@ -733,6 +788,7 @@ fn pick_project_folder(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<String>, String> {
|
||||
refuse_while_looping(&state, "project")?;
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
@@ -781,6 +837,7 @@ fn change_project(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<String>, String> {
|
||||
refuse_while_looping(&state, "project")?;
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
@@ -844,6 +901,290 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// What the setup screen shows about the agent a loop would use: the running
|
||||
// agent's launch choice, else what the launcher chose.
|
||||
#[tauri::command]
|
||||
fn loop_facts(state: State<'_, AppState>) -> LoopFacts {
|
||||
let running = state
|
||||
.loop_run
|
||||
.lock()
|
||||
.map(|guard| guard.is_some())
|
||||
.unwrap_or(false);
|
||||
if let Some((agent, model, effort, mode)) =
|
||||
current_agent(&state).and_then(|a| a.launch_choice())
|
||||
{
|
||||
return LoopFacts {
|
||||
agent: Some(agent.id().to_string()),
|
||||
agent_label: Some(agent.label().to_string()),
|
||||
model,
|
||||
effort,
|
||||
permission_mode: Some(mode.id().to_string()),
|
||||
prompt_support: loop_driver::prompt_support(&agent),
|
||||
running,
|
||||
};
|
||||
}
|
||||
let agent = state.launch.agent.as_deref().and_then(agents::find_agent);
|
||||
LoopFacts {
|
||||
agent: agent.as_ref().map(|a| a.id().to_string()),
|
||||
agent_label: agent.as_ref().map(|a| a.label().to_string()),
|
||||
model: state.launch.model.clone(),
|
||||
effort: None,
|
||||
permission_mode: None,
|
||||
prompt_support: agent.as_ref().is_none_or(loop_driver::prompt_support),
|
||||
running,
|
||||
}
|
||||
}
|
||||
|
||||
// What the loop tells the window and the taskbar: the strip's state on every
|
||||
// change, and the app's own attention when a question holds it.
|
||||
fn loop_hooks(app: &tauri::AppHandle) -> Hooks {
|
||||
let for_strip = app.clone();
|
||||
let for_attention = app.clone();
|
||||
Hooks {
|
||||
emit: Box::new(move |event| {
|
||||
let _ = for_strip.emit("loop-state", &event);
|
||||
}),
|
||||
attention: Box::new(move || apply_signal(&for_attention, Signal::Attention)),
|
||||
}
|
||||
}
|
||||
|
||||
// Starts a loop on `spec`: checks, the app's own confirm, then the first phase.
|
||||
// Async so the confirm's blocking dialog never waits on the main thread. The
|
||||
// setup comes from `loop-setup.json`, never from the page's message. With
|
||||
// `skip_confirm_if_same`, the confirm is skipped when the quick check and the
|
||||
// web address are the ones the person last confirmed (Resume): a changed one is
|
||||
// asked again.
|
||||
async fn start_loop(
|
||||
app: &tauri::AppHandle,
|
||||
state: &AppState,
|
||||
spec: String,
|
||||
skip_confirm_if_same: bool,
|
||||
) -> Result<bool, String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
return Err("A loop is already running".to_string());
|
||||
}
|
||||
let project = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone())
|
||||
.ok_or("no project folder chosen")?;
|
||||
let agent = current_agent(state)
|
||||
.filter(|a| a.folder() == &project)
|
||||
.ok_or("Start an agent first, with permission checks off.")?;
|
||||
// A stopped agent has forgotten its launch choice; the last loop kept it.
|
||||
let launch = agent
|
||||
.launch_choice()
|
||||
.or_else(|| {
|
||||
state
|
||||
.last_loop
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|last| last.as_ref().map(|l| l.launch.clone()))
|
||||
})
|
||||
.ok_or("Start an agent first, with permission checks off.")?;
|
||||
// Resume (the only caller that skips the confirm) on a spec this app
|
||||
// stopped: the stopped phase's uncommitted work is expected in the tree.
|
||||
let resuming = skip_confirm_if_same
|
||||
&& state.last_loop.lock().ok().is_some_and(|last| {
|
||||
last.as_ref()
|
||||
.is_some_and(|l| l.project == project && l.spec == spec)
|
||||
});
|
||||
let record = loop_driver::prepare(
|
||||
&project,
|
||||
&spec,
|
||||
launch.3,
|
||||
loop_driver::prompt_support(&launch.0),
|
||||
resuming,
|
||||
)?;
|
||||
let check = record.setup.quick_check.clone();
|
||||
let notify = loop_driver::confirmed_notify(&record.setup);
|
||||
// A Resume that rebuilds a phase or takes uncommitted files into its commit
|
||||
// is asked again: the confirm is where the person is told.
|
||||
let unchanged = skip_confirm_if_same
|
||||
&& record.rebuilt.is_empty()
|
||||
&& record.resumed_files.is_none()
|
||||
&& !loop_driver::commits_to_trunk(&record)
|
||||
&& state
|
||||
.last_loop
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.is_some_and(|last| {
|
||||
last.project == project
|
||||
&& last.spec == spec
|
||||
&& last.confirmed_check == check
|
||||
&& last.confirmed_notify == notify
|
||||
});
|
||||
if !unchanged {
|
||||
let go = app
|
||||
.dialog()
|
||||
.message(loop_driver::confirm_text(&record))
|
||||
.title("Implementation Loop")
|
||||
.kind(MessageDialogKind::Info)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
"Start".to_string(),
|
||||
"Cancel".to_string(),
|
||||
))
|
||||
.blocking_show();
|
||||
if !go {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
loop_driver::reopen_rebuilt(&record)?;
|
||||
loop_driver::begin(
|
||||
&state.loop_run,
|
||||
agent,
|
||||
record,
|
||||
launch.clone(),
|
||||
loop_hooks(app),
|
||||
)?;
|
||||
if let Ok(mut last) = state.last_loop.lock() {
|
||||
*last = Some(LastLoop {
|
||||
project,
|
||||
spec,
|
||||
launch,
|
||||
confirmed_check: check,
|
||||
confirmed_notify: notify,
|
||||
});
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn loop_start(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
spec: String,
|
||||
) -> Result<bool, String> {
|
||||
start_loop(&app, &state, spec, false).await
|
||||
}
|
||||
|
||||
// Send a test: the setup screen saved first, and the address comes from
|
||||
// `loop-setup.json`, never from the page's message. The app names it in its own
|
||||
// confirm. Answers whether a test was sent: false when the person said no.
|
||||
#[tauri::command]
|
||||
async fn loop_notify_test(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
let project = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone())
|
||||
.ok_or("no project folder chosen")?;
|
||||
let setup = loop_driver::read_setup(&project)?;
|
||||
let text = loop_driver::notify_test_confirm(&setup)?;
|
||||
let go = app
|
||||
.dialog()
|
||||
.message(text)
|
||||
.title("Implementation Loop")
|
||||
.kind(MessageDialogKind::Info)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
"Send".to_string(),
|
||||
"Cancel".to_string(),
|
||||
))
|
||||
.blocking_show();
|
||||
if !go {
|
||||
return Ok(false);
|
||||
}
|
||||
// The HTTP client blocks, and panics on an async runtime's own thread.
|
||||
tauri::async_runtime::spawn_blocking(move || loop_driver::send_notify_test(&setup))
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// Stop after this phase: it finishes its review, mark and commit, then the
|
||||
// loop stops instead of starting the next.
|
||||
#[tauri::command]
|
||||
fn loop_stop_after_phase(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
on: bool,
|
||||
) -> Result<(), String> {
|
||||
let event = loop_driver::request_stop_after(&state.loop_run, on)?;
|
||||
let _ = app.emit("loop-state", &event);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Stop now: the flag is set first, then the agent (if one is running) ends at
|
||||
// once. The page asked the person first ("End the agent now? This phase's
|
||||
// changes stay uncommitted."); the strip says Stopping, and the driver tells
|
||||
// the stop screen on its next look.
|
||||
#[tauri::command]
|
||||
fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let agent = current_agent(&state);
|
||||
// The event goes out before the agent is ended (which can take a while), so
|
||||
// the strip's "ended" can never be followed by an older "Stopping".
|
||||
loop_driver::request_stop_now(&state.loop_run, agent.as_deref(), |event| {
|
||||
let _ = app.emit("loop-state", event);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// What the loop is doing, for a window that just loaded or just started
|
||||
// listening: the strip event, or nothing when no loop runs.
|
||||
#[tauri::command]
|
||||
fn loop_state(state: State<'_, AppState>) -> Option<loop_driver::LoopStateEvent> {
|
||||
loop_driver::current_event(&state.loop_run)
|
||||
}
|
||||
|
||||
// The last loop, for the stop and finish screens' buttons.
|
||||
fn last_loop(state: &AppState) -> Result<LastLoop, String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
return Err("A loop is running".to_string());
|
||||
}
|
||||
let last = state
|
||||
.last_loop
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.clone()
|
||||
.ok_or("No loop has run in this session")?;
|
||||
let here = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone());
|
||||
if here.as_ref() != Some(&last.project) {
|
||||
return Err("The project changed since that loop".to_string());
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
// Resume: start again on the same spec. The app reads the setup and the
|
||||
// spec's marks afresh; the Start dialog is skipped only while the quick check
|
||||
// is the one the person last confirmed.
|
||||
#[tauri::command]
|
||||
async fn loop_resume(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let last = last_loop(&state)?;
|
||||
start_loop(&app, &state, last.spec, true).await.map(|_| ())
|
||||
}
|
||||
|
||||
// Fix it by hand: an ordinary Implement session on the stopped phase, with no
|
||||
// `--loop`, so the person talks to the agent as usual.
|
||||
#[tauri::command]
|
||||
fn loop_fix(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let last = last_loop(&state)?;
|
||||
let agent = current_agent(&state).ok_or("No agent is available")?;
|
||||
loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let last = last_loop(&state)?;
|
||||
let agent = current_agent(&state).ok_or("No agent is available")?;
|
||||
loop_driver::start_with(
|
||||
&agent,
|
||||
&last.launch,
|
||||
loop_driver::finalize_prompt(&last.spec),
|
||||
)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
|
||||
let status = node_check::check_node();
|
||||
@@ -890,6 +1231,15 @@ fn main() {
|
||||
console_start,
|
||||
console_status,
|
||||
console_stop,
|
||||
loop_start,
|
||||
loop_notify_test,
|
||||
loop_facts,
|
||||
loop_stop_after_phase,
|
||||
loop_stop_now,
|
||||
loop_state,
|
||||
loop_resume,
|
||||
loop_fix,
|
||||
loop_finalize,
|
||||
set_attention,
|
||||
clear_attention_cmd,
|
||||
set_taskbar_signal
|
||||
@@ -918,6 +1268,8 @@ fn main() {
|
||||
let taken =
|
||||
take_announced(&state, ¬ice, window_origin(&handle), session_on_disk);
|
||||
if taken {
|
||||
// A running loop follows its phase's session from here.
|
||||
loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid);
|
||||
let _ = handle.emit("console-page", ¬ice);
|
||||
} else {
|
||||
eprintln!(
|
||||
@@ -1204,6 +1556,46 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
fn state_with_loop(running: bool) -> AppState {
|
||||
let state = state_for("project-a");
|
||||
if running {
|
||||
*state.loop_run.lock().unwrap() = Some(loop_driver::RunningRecord::new(
|
||||
PathBuf::from("project-a"),
|
||||
"specs/x".into(),
|
||||
loop_driver::LoopSetup::default(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_refuses_to_change_project_or_agent_while_a_loop_runs() {
|
||||
let state = state_with_loop(true);
|
||||
let project = refuse_while_looping(&state, "project").expect_err("a loop is running");
|
||||
assert!(project.contains("A loop is running"), "{project:?}");
|
||||
assert!(project.contains("project"), "{project:?}");
|
||||
let agent = refuse_while_looping(&state, "agent").expect_err("a loop is running");
|
||||
assert!(agent.contains("change the agent."), "{agent:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_changes_project_and_agent_freely_with_no_loop() {
|
||||
let state = state_with_loop(false);
|
||||
assert!(refuse_while_looping(&state, "project").is_ok());
|
||||
assert!(refuse_while_looping(&state, "agent").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_state_data_is_none_with_no_loop_and_the_strip_event_with_one() {
|
||||
let idle = state_with_loop(false);
|
||||
assert!(loop_driver::current_event(&idle.loop_run).is_none());
|
||||
let busy = state_with_loop(true);
|
||||
let event = loop_driver::current_event(&busy.loop_run).expect("a loop runs");
|
||||
assert!(event.running);
|
||||
assert_eq!(event.spec_name, "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
|
||||
let Some(sup) = real_console() else { return };
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
//! agent is not mid-step at all but waiting on the person's answer in the web
|
||||
//! console, so the check reads the page's last taskbar signal (attention.rs)
|
||||
//! and says which case it is. Anything it cannot be sure of is the working
|
||||
//! case, the safer warning. Knows nothing about Tauri; main.rs shows it.
|
||||
//! case, the safer warning. While the Implementation Loop builds a phase the
|
||||
//! words are the loop's own (`loop_quit_prompt`). Knows nothing about Tauri;
|
||||
//! main.rs shows it.
|
||||
|
||||
use crate::attention::Signal;
|
||||
|
||||
@@ -16,38 +18,73 @@ pub enum QuitCase {
|
||||
}
|
||||
|
||||
/// Everything the box says.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct QuitPrompt {
|
||||
pub case: QuitCase,
|
||||
pub title: &'static str,
|
||||
pub heading: &'static str,
|
||||
pub message: &'static str,
|
||||
pub quit: &'static str,
|
||||
pub stay: &'static str,
|
||||
pub title: String,
|
||||
pub heading: String,
|
||||
pub message: String,
|
||||
pub quit: String,
|
||||
pub stay: String,
|
||||
}
|
||||
|
||||
fn words(case: QuitCase, heading: &str, message: &str, quit: &str) -> QuitPrompt {
|
||||
QuitPrompt {
|
||||
case,
|
||||
title: "Plan2Code".to_string(),
|
||||
heading: heading.to_string(),
|
||||
message: message.to_string(),
|
||||
quit: quit.to_string(),
|
||||
stay: "Stay".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt for the page's last signal (`None` before the page has sent one).
|
||||
pub fn quit_prompt(last: Option<Signal>) -> QuitPrompt {
|
||||
match last {
|
||||
Some(Signal::Ready | Signal::Plain) => QuitPrompt {
|
||||
case: QuitCase::Waiting,
|
||||
title: "Plan2Code",
|
||||
heading: "Done for now?",
|
||||
message: "Your agent is just waiting on your next answer. Quit and this session ends.",
|
||||
quit: "Quit",
|
||||
stay: "Stay",
|
||||
},
|
||||
Some(Signal::Busy | Signal::Attention) | None => QuitPrompt {
|
||||
case: QuitCase::Working,
|
||||
title: "Plan2Code",
|
||||
heading: "Leave while your agent is busy?",
|
||||
message: "If you quit now, the agent stops mid-step. Everything it has saved so far stays put.",
|
||||
quit: "Quit and stop it",
|
||||
stay: "Stay",
|
||||
},
|
||||
Some(Signal::Ready | Signal::Plain) => words(
|
||||
QuitCase::Waiting,
|
||||
"Done for now?",
|
||||
"Your agent is just waiting on your next answer. Quit and this session ends.",
|
||||
"Quit",
|
||||
),
|
||||
Some(Signal::Busy | Signal::Attention) | None => words(
|
||||
QuitCase::Working,
|
||||
"Leave while your agent is busy?",
|
||||
"If you quit now, the agent stops mid-step. Everything it has saved so far stays put.",
|
||||
"Quit and stop it",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// "Phase 1", "Phases 1 and 2", "Phases 1, 2 and 3".
|
||||
fn phase_list(committed: &[u32]) -> String {
|
||||
let numbers: Vec<String> = committed.iter().map(u32::to_string).collect();
|
||||
match numbers.as_slice() {
|
||||
[] => String::new(),
|
||||
[one] => format!("Phase {one}"),
|
||||
[init @ .., last] => format!("Phases {} and {last}", init.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The words for quitting while the Implementation Loop builds a phase.
|
||||
/// `committed` lists the phase numbers already committed.
|
||||
pub fn loop_quit_prompt(phase: u32, phases: u32, committed: &[u32]) -> QuitPrompt {
|
||||
let done = match committed.len() {
|
||||
0 => "No phase is committed yet".to_string(),
|
||||
1 => format!("{} is committed", phase_list(committed)),
|
||||
_ => format!("{} are committed", phase_list(committed)),
|
||||
};
|
||||
words(
|
||||
QuitCase::Working,
|
||||
"Stop the loop and quit?",
|
||||
&format!(
|
||||
"Phase {phase} of {phases} is mid-build. {done}; this phase's changes stay uncommitted."
|
||||
),
|
||||
"Quit and stop the loop",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -92,11 +129,38 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn no_text_carries_an_em_dash() {
|
||||
for last in [None, Some(Signal::Busy), Some(Signal::Ready)] {
|
||||
let p = quit_prompt(last);
|
||||
for text in [p.title, p.heading, p.message, p.quit, p.stay] {
|
||||
let mut all = vec![loop_quit_prompt(2, 4, &[1]), loop_quit_prompt(1, 4, &[])];
|
||||
all.extend([None, Some(Signal::Busy), Some(Signal::Ready)].map(quit_prompt));
|
||||
for p in all {
|
||||
for text in [&p.title, &p.heading, &p.message, &p.quit, &p.stay] {
|
||||
assert!(!text.contains('\u{2014}'), "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loop_wording_names_what_is_committed() {
|
||||
let none = loop_quit_prompt(1, 4, &[]);
|
||||
assert_eq!(none.heading, "Stop the loop and quit?");
|
||||
assert_eq!(none.title, "Plan2Code");
|
||||
assert_eq!(none.quit, "Quit and stop the loop");
|
||||
assert_eq!(none.stay, "Stay");
|
||||
assert_eq!(none.case, QuitCase::Working);
|
||||
assert_eq!(
|
||||
none.message,
|
||||
"Phase 1 of 4 is mid-build. No phase is committed yet; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(2, 4, &[1]).message,
|
||||
"Phase 2 of 4 is mid-build. Phase 1 is committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(3, 4, &[1, 2]).message,
|
||||
"Phase 3 of 4 is mid-build. Phases 1 and 2 are committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(4, 4, &[1, 2, 3]).message,
|
||||
"Phase 4 of 4 is mid-build. Phases 1, 2 and 3 are committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,11 +53,11 @@ unsafe extern "system" fn on_event(
|
||||
/// Quit was pressed; anything else (Stay, Esc, the close button, a failure to
|
||||
/// show the box) keeps the app open.
|
||||
pub fn ask(parent: HWND, prompt: &QuitPrompt) -> bool {
|
||||
let title = wide(prompt.title);
|
||||
let heading = wide(prompt.heading);
|
||||
let message = wide(prompt.message);
|
||||
let quit = wide(prompt.quit);
|
||||
let stay = wide(prompt.stay);
|
||||
let title = wide(&prompt.title);
|
||||
let heading = wide(&prompt.heading);
|
||||
let message = wide(&prompt.message);
|
||||
let quit = wide(&prompt.quit);
|
||||
let stay = wide(&prompt.stay);
|
||||
let buttons = [
|
||||
TASKDIALOG_BUTTON {
|
||||
nButtonID: ID_QUIT,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.0.0",
|
||||
"identifier": "com.plan2code.app",
|
||||
"identifier": "com.plan2code.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
"beforeDevCommand": "node scripts/vendor.mjs",
|
||||
|
||||
+273
-5
@@ -2,7 +2,7 @@
|
||||
// agent's terminal panel docked at the bottom with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor } from './meter.js';
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
@@ -20,6 +20,27 @@ const agentBypassEl = document.getElementById('agent-bypass');
|
||||
const agentNoneEl = document.getElementById('agent-none');
|
||||
const agentStatusEl = document.getElementById('agent-status');
|
||||
const restartBtn = document.getElementById('agent-restart');
|
||||
const loopBannerEl = document.getElementById('loop-banner');
|
||||
const loopTitleEl = document.getElementById('loop-title');
|
||||
const loopDetailEl = document.getElementById('loop-detail');
|
||||
const loopPipsEl = document.getElementById('loop-pips');
|
||||
const loopHintEl = document.getElementById('loop-hint');
|
||||
const loopSpecEl = document.getElementById('loop-spec');
|
||||
const loopElapsedEl = document.getElementById('loop-elapsed');
|
||||
const loopRetriesEl = document.getElementById('loop-retries');
|
||||
const loopStopAfterBtn = document.getElementById('loop-stop-after');
|
||||
const loopStopNowBtn = document.getElementById('loop-stop-now');
|
||||
const loopErrorEl = document.getElementById('loop-error');
|
||||
const loopRetryBtn = document.getElementById('loop-retry');
|
||||
// Whether Stop after this phase is on, as the last state said; a press asks for the opposite.
|
||||
let loopStopAfterOn = false;
|
||||
// True while an Implementation Loop runs: New Session stays hidden meanwhile.
|
||||
let loopRunning = false;
|
||||
let loopStep = '';
|
||||
// Whether this loop's one-time typing note was shown; a new loop resets it.
|
||||
let loopTypingNoted = false;
|
||||
const LOOP_TYPING_NOTE = 'A loop is running. Typing here can derail the phase it is working on.';
|
||||
const LOOP_TYPING_NOTE_MS = 8000;
|
||||
const changeAgentBtn = document.getElementById('change-agent');
|
||||
const changeProjectBtn = document.getElementById('change-project');
|
||||
const barRowEl = document.getElementById('bar-row');
|
||||
@@ -82,7 +103,10 @@ const agentActive = () => agent.state === 'running';
|
||||
|
||||
const terminal = await mountTerminal(document.getElementById('term'), {
|
||||
onInput: (data) => {
|
||||
if (agentActive()) invoke('agent_input', { data });
|
||||
if (agentActive()) {
|
||||
noteTypingDuringLoop();
|
||||
invoke('agent_input', { data });
|
||||
}
|
||||
},
|
||||
onResize: (cols, rows) => {
|
||||
if (agentActive()) invoke('agent_resize', { cols, rows });
|
||||
@@ -129,7 +153,7 @@ function applyAgentState(next, { skipReset } = {}) {
|
||||
// ended (New Session keeps the previous agent, model, effort and mode);
|
||||
// Change agent, in that menu, only once ended, when there is a real choice
|
||||
// to make again.
|
||||
restartBtn.hidden = !(active || ended);
|
||||
restartBtn.hidden = loopRunning || !(active || ended);
|
||||
changeAgentBtn.hidden = !ended;
|
||||
// Checked mode needs no marker; bypass always gets the "checks off" badge
|
||||
// on the agent, for exactly as long as that agent runs.
|
||||
@@ -171,6 +195,17 @@ function setAgentStatus(text, { error = false } = {}) {
|
||||
agentStatusEl.classList.toggle('is-error', error && Boolean(text));
|
||||
}
|
||||
|
||||
// The first key typed in the terminal while a loop runs: a note beside the agent,
|
||||
// once per loop, gone after a few seconds. The key itself is always delivered.
|
||||
function noteTypingDuringLoop() {
|
||||
if (!loopRunning || loopTypingNoted) return;
|
||||
loopTypingNoted = true;
|
||||
setAgentStatus(LOOP_TYPING_NOTE);
|
||||
setTimeout(() => {
|
||||
if (agentStatusEl.textContent === LOOP_TYPING_NOTE) setAgentStatus('');
|
||||
}, LOOP_TYPING_NOTE_MS);
|
||||
}
|
||||
|
||||
// The agent menu's first lines: what the agent is doing and, while it runs,
|
||||
// which permission mode it started with.
|
||||
function renderAgentMenuHead(label, { active, ended, bypassActive }) {
|
||||
@@ -638,6 +673,8 @@ function loadFrame(url) {
|
||||
frameReady = false;
|
||||
// The page going away takes its taskbar dot with it; the new one tells its own.
|
||||
clearAttention();
|
||||
// And a game it had in full screen.
|
||||
setGameFull(false);
|
||||
clearTimeout(helloTimer);
|
||||
helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS);
|
||||
frame.src = url;
|
||||
@@ -668,6 +705,9 @@ window.addEventListener('message', (event) => {
|
||||
if (on === null) return;
|
||||
if (appState) appState.taskbarSignal = on;
|
||||
invoke('set_taskbar_signal', { on }).catch(() => {});
|
||||
} else if (kind === 'activities-full') {
|
||||
const on = taskbarSwitch(event.data);
|
||||
if (on !== null) setGameFull(on);
|
||||
} else if (kind === 'agent-continue') {
|
||||
typeContinue();
|
||||
} else if (kind === 'new-session') {
|
||||
@@ -675,9 +715,66 @@ window.addEventListener('message', (event) => {
|
||||
if (!restartBtn.hidden) restartBtn.click();
|
||||
} else if (kind === 'looks') {
|
||||
applyAccent(event.data.accent, { save: true });
|
||||
} else if (kind === 'loop-facts') {
|
||||
// The setup screen asks what agent a loop would use. The answer is facts
|
||||
// only; the page never sends the app any setup value.
|
||||
const source = event.source;
|
||||
invoke('loop_facts')
|
||||
.then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*'))
|
||||
.catch(() => {});
|
||||
} else if (kind === 'loop-resume' || kind === 'loop-fix' || kind === 'loop-finalize') {
|
||||
// Fixed requests, no free text: the page answers with ok or the error.
|
||||
const source = event.source;
|
||||
const command = { 'loop-resume': 'loop_resume', 'loop-fix': 'loop_fix', 'loop-finalize': 'loop_finalize' }[kind];
|
||||
invoke(command)
|
||||
.then(() => source.postMessage({ plan2code: `${kind}-result`, ok: true, error: null }, '*'))
|
||||
.catch((error) => source.postMessage({ plan2code: `${kind}-result`, ok: false, error: String(error) }, '*'));
|
||||
} else if (kind === 'loop-notify-test') {
|
||||
// Send a test: no values at all. The app reads the saved setup itself and
|
||||
// asks the person to confirm in its own dialog.
|
||||
const source = event.source;
|
||||
invoke('loop_notify_test')
|
||||
.then((sent) => source.postMessage({ plan2code: 'loop-notify-test-result', ok: true, sent, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'loop-notify-test-result', ok: false, sent: false, error: String(error) }, '*')
|
||||
);
|
||||
} else if (kind === 'loop-start') {
|
||||
// Start: a spec folder name only. The app validates it, reads the saved
|
||||
// setup itself and asks the person to confirm in its own dialog.
|
||||
const source = event.source;
|
||||
const spec = typeof event.data.spec === 'string' ? event.data.spec : '';
|
||||
invoke('loop_start', { spec })
|
||||
.then((started) => source.postMessage({ plan2code: 'loop-start-result', ok: true, started, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'loop-start-result', ok: false, error: String(error) }, '*')
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// An Activities game in full screen: the console's frame is laid over the
|
||||
// bar and the terminal (over, not instead of, so the terminal keeps its size
|
||||
// and the agent sees no resize), and the window goes full screen. Off, both
|
||||
// go back; the window leaves full screen only if this put it there.
|
||||
let fullByGame = false;
|
||||
|
||||
function setGameFull(on) {
|
||||
document.body.classList.toggle('console-full', on);
|
||||
const win = window.__TAURI__.window.getCurrentWindow();
|
||||
if (on) {
|
||||
win
|
||||
.isFullscreen()
|
||||
.then((already) => {
|
||||
if (already) return;
|
||||
fullByGame = true;
|
||||
return win.setFullscreen(true);
|
||||
})
|
||||
.catch(() => {});
|
||||
} else if (fullByGame) {
|
||||
fullByGame = false;
|
||||
win.setFullscreen(false).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Its "Not running... type continue" line, pressed: the keystrokes
|
||||
// continueKeys names, each on its own a moment after the last, so an agent
|
||||
// that treats one burst of input as a paste still reads the Enter as a submit.
|
||||
@@ -727,6 +824,8 @@ async function onNoHello() {
|
||||
if (frameReady || !consoleKnown || restarting) return;
|
||||
// A page that does not answer cannot say it is done needing the person.
|
||||
clearAttention();
|
||||
// The next phase's console is on its way; the poll says so instead.
|
||||
if (loopRunning && loopStep === 'Starting') return;
|
||||
let status = null;
|
||||
try {
|
||||
status = await invoke('console_status');
|
||||
@@ -794,12 +893,19 @@ async function pollConsole() {
|
||||
markConsoleAlive();
|
||||
return;
|
||||
}
|
||||
const action = deadConsoleAction({ loopRunning, loopStep, frameReady, reconnects, limit: RECONNECT_LIMIT });
|
||||
if (action === 'wait-for-phase') {
|
||||
// Covers the old phase's page and its "Lost contact" until the new one
|
||||
// says hello. Never over a question the box is already asking.
|
||||
if (stateCancelEl.hidden) showState(loopDetailEl.textContent);
|
||||
return;
|
||||
}
|
||||
markConsoleDead();
|
||||
if (frameReady && reconnects < RECONNECT_LIMIT) {
|
||||
if (action === 'reconnect') {
|
||||
reconnects += 1;
|
||||
showState('The console stopped. Reconnecting');
|
||||
await reconnectConsole();
|
||||
} else if (!frameReady) {
|
||||
} else if (action === 'no-hello') {
|
||||
onNoHello();
|
||||
}
|
||||
} catch {
|
||||
@@ -856,6 +962,8 @@ async function restartConsole() {
|
||||
// not repeated here.
|
||||
function showAnnounced(notice) {
|
||||
restarting = false;
|
||||
// A new page is a new start: the budget is per run of trouble, not per launch.
|
||||
reconnects = 0;
|
||||
if (!consoleKnown) {
|
||||
consoleKnown = true;
|
||||
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
|
||||
@@ -869,6 +977,164 @@ function showAnnounced(notice) {
|
||||
|
||||
window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload));
|
||||
|
||||
// "45s", "12m", "1h 12m": whole units, the largest two at most.
|
||||
function formatElapsed(ms) {
|
||||
const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
|
||||
if (total < 60) return `${total}s`;
|
||||
const minutes = Math.floor(total / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
// The Implementation Loop's banner across the window, drawn from the app's
|
||||
// loop-state. It lives here and not in the console page because a loop runs
|
||||
// across many sessions: the page changes under it, and this does not.
|
||||
let loopTimer = null;
|
||||
let loopStartedAt = 0;
|
||||
|
||||
function tickLoopElapsed() {
|
||||
loopElapsedEl.textContent = formatElapsed(Date.now() - loopStartedAt);
|
||||
}
|
||||
|
||||
function setLoopTitle(title) {
|
||||
window.__TAURI__.window.getCurrentWindow().setTitle(title).catch(() => {});
|
||||
}
|
||||
|
||||
// The app ending the loop's last agent ended that agent's console too, so the
|
||||
// page holding the stop or finish card has to be brought back, at once and
|
||||
// whatever the budget says: it is the one thing the person came back to read.
|
||||
async function showLoopEnd() {
|
||||
reconnects = 0;
|
||||
try {
|
||||
const status = await invoke('console_status');
|
||||
if (status.state === 'dead') await reconnectConsole();
|
||||
} catch {
|
||||
// The poll looks again on its next tick.
|
||||
}
|
||||
}
|
||||
|
||||
// Change project and Change agent are off while a loop runs, with the reason on
|
||||
// them; the app refuses them too.
|
||||
function applyLoopLocks(state) {
|
||||
const { locked, reason } = loopLocks(state);
|
||||
for (const button of [changeProjectBtn, changeAgentBtn]) {
|
||||
button.disabled = locked;
|
||||
button.title = locked ? reason : '';
|
||||
}
|
||||
}
|
||||
|
||||
// Asks the app what the loop is doing: a reloaded window has missed every
|
||||
// loop-state event so far, and one sent between the first ask and the listener
|
||||
// is caught by asking again once it listens.
|
||||
async function syncLoopState() {
|
||||
// The reply and the loop-state event travel apart: an event that landed while
|
||||
// the question was out is newer than the answer, which then is dropped.
|
||||
const seen = loopEventSeq;
|
||||
try {
|
||||
const state = await invoke('loop_state');
|
||||
if (seen !== loopEventSeq) return;
|
||||
// No loop and none drawn: nothing to redraw. One drawn that is gone: it ended.
|
||||
if (state) applyLoopState(state);
|
||||
else if (loopRunning) applyLoopState({ running: false });
|
||||
} catch {
|
||||
// The next loop-state event tells it.
|
||||
}
|
||||
}
|
||||
|
||||
function applyLoopState(state) {
|
||||
if (!state || !state.running) {
|
||||
const wasRunning = loopRunning;
|
||||
loopRunning = false;
|
||||
loopStep = '';
|
||||
if (wasRunning) showLoopEnd();
|
||||
clearInterval(loopTimer);
|
||||
loopTimer = null;
|
||||
loopBannerEl.hidden = true;
|
||||
applyLoopLocks({ running: false });
|
||||
setLoopTitle(windowTitleFor(projectPathEl.textContent));
|
||||
// New Session's visibility is applyAgentState's rule alone.
|
||||
applyAgentState(agent, { skipReset: true });
|
||||
return;
|
||||
}
|
||||
if (!loopRunning) loopTypingNoted = false;
|
||||
loopRunning = true;
|
||||
loopStep = state.step || '';
|
||||
restartBtn.hidden = true;
|
||||
applyLoopLocks(state);
|
||||
const banner = loopBanner(state);
|
||||
loopBannerEl.hidden = false;
|
||||
loopBannerEl.dataset.tone = banner.tone;
|
||||
// Only a change of words: this is a live region, and screen readers read it out.
|
||||
if (loopTitleEl.textContent !== banner.title) loopTitleEl.textContent = banner.title;
|
||||
if (loopDetailEl.textContent !== banner.detail) loopDetailEl.textContent = banner.detail;
|
||||
loopHintEl.textContent = banner.hint;
|
||||
loopSpecEl.textContent = state.specName || '';
|
||||
loopPipsEl.replaceChildren(
|
||||
...banner.pips.map((kind, i) => {
|
||||
const pip = document.createElement('span');
|
||||
pip.className = `loop-pip ${kind}`;
|
||||
pip.title = `Phase ${i + 1}`;
|
||||
return pip;
|
||||
})
|
||||
);
|
||||
setLoopTitle(loopWindowTitle(projectPathEl.textContent, state));
|
||||
const stopLabels = loopStopLabels(state);
|
||||
loopStopAfterOn = !!state.stopAfterPhase;
|
||||
loopStopAfterBtn.disabled = stopLabels.afterDisabled;
|
||||
loopStopAfterBtn.textContent = stopLabels.afterText;
|
||||
loopStopNowBtn.disabled = stopLabels.nowDisabled;
|
||||
// A good state means the last press went through.
|
||||
hideLoopError();
|
||||
const retries = Number(state.retriesUsed) || 0;
|
||||
loopRetriesEl.hidden = retries <= 0;
|
||||
loopRetriesEl.textContent = retries === 1 ? '1 retry' : `${retries} retries`;
|
||||
loopStartedAt = Number(state.startedAtMs) || Date.now();
|
||||
tickLoopElapsed();
|
||||
if (!loopTimer) loopTimer = setInterval(tickLoopElapsed, 1000);
|
||||
}
|
||||
|
||||
let loopEventSeq = 0;
|
||||
window.__TAURI__.event
|
||||
.listen('loop-state', (event) => {
|
||||
loopEventSeq += 1;
|
||||
applyLoopState(event.payload);
|
||||
})
|
||||
.then(syncLoopState, () => {});
|
||||
|
||||
// A press that fails shows why next to the buttons, with a Retry for the same press.
|
||||
let loopRetryAction = null;
|
||||
function hideLoopError() {
|
||||
loopErrorEl.hidden = true;
|
||||
loopErrorEl.textContent = '';
|
||||
loopRetryBtn.hidden = true;
|
||||
loopRetryAction = null;
|
||||
}
|
||||
function pressLoop(command, args) {
|
||||
const press = () =>
|
||||
invoke(command, args).then(hideLoopError, (e) => {
|
||||
loopErrorEl.textContent = `Could not do that: ${String(e && e.message ? e.message : e)}`;
|
||||
loopErrorEl.hidden = false;
|
||||
loopRetryBtn.hidden = false;
|
||||
loopRetryAction = press;
|
||||
});
|
||||
return press();
|
||||
}
|
||||
loopRetryBtn.onclick = () => {
|
||||
if (loopRetryAction) loopRetryAction();
|
||||
};
|
||||
loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn });
|
||||
loopStopNowBtn.onclick = () =>
|
||||
showState(
|
||||
"End the agent now? This phase's changes stay uncommitted.",
|
||||
'Stop now',
|
||||
() => {
|
||||
frameReady ? hideState() : showState('No dashboard has loaded yet.');
|
||||
pressLoop('loop_stop_now');
|
||||
},
|
||||
() => (frameReady ? hideState() : showState('No dashboard has loaded yet.')),
|
||||
{ tired: true }
|
||||
);
|
||||
|
||||
// The right end of the bar: whether the console stopped answering and where
|
||||
// the skills stand against this app, drawn as one next step (meter.js
|
||||
// barNextSteps decides which, and its button), with the rest as "+N more".
|
||||
@@ -1081,6 +1347,8 @@ async function main() {
|
||||
} catch {
|
||||
// Nothing to reattach to is not fatal: carry on as a plain first paint.
|
||||
}
|
||||
// A reloaded window learns of a running loop before it draws the agent.
|
||||
await syncLoopState();
|
||||
if (reattach && reattach.state !== 'idle') {
|
||||
if (state.projectDir) setProjectDir(state.projectDir);
|
||||
await recoverAfterReload(reattach);
|
||||
|
||||
@@ -50,6 +50,46 @@
|
||||
#agent-none { color: var(--ink-3); }
|
||||
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
|
||||
#agent-status.is-error { color: #f48771; }
|
||||
/* The Implementation Loop, for as long as one runs: the loudest thing in the
|
||||
window on purpose. The accent says it is working; amber says it needs you. */
|
||||
#loop-banner {
|
||||
--banner-color: var(--accent); --banner-bg: var(--accent-soft); --banner-line: var(--accent-line);
|
||||
flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px;
|
||||
padding: 10px 14px 10px 16px; font-size: 13px; color: var(--ink);
|
||||
background: var(--banner-bg); border-bottom: 1px solid var(--banner-line); box-shadow: inset 4px 0 0 var(--banner-color);
|
||||
}
|
||||
#loop-banner[hidden] { display: none; }
|
||||
#loop-banner[data-tone="waiting"] { --banner-color: #e5a93c; --banner-bg: #3a2b10; --banner-line: #7a5a1e; }
|
||||
#loop-now { flex: 1 1 320px; min-width: 0; display: grid; gap: 3px; }
|
||||
#loop-headline { display: flex; align-items: center; gap: 9px; }
|
||||
#loop-dot { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--banner-color); animation: loop-pulse 1.8s ease-in-out infinite; }
|
||||
#loop-banner[data-tone="waiting"] #loop-dot { animation-duration: 0.9s; }
|
||||
@keyframes loop-pulse { 0%, 100% { box-shadow: 0 0 0 0 transparent; opacity: 1; } 50% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--banner-color) 30%, transparent); opacity: 0.75; } }
|
||||
#loop-title { margin: 0; font-size: 15px; font-weight: 700; line-height: 1.25; }
|
||||
#loop-detail { margin: 0; color: var(--ink-2); overflow-wrap: anywhere; }
|
||||
#loop-progress { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; margin-top: 3px; color: var(--ink-3); font-size: 12px; }
|
||||
#loop-pips { display: flex; flex-wrap: wrap; gap: 3px; }
|
||||
.loop-pip { width: 16px; height: 5px; border-radius: 3px; background: var(--rule-2); }
|
||||
.loop-pip.done { background: var(--banner-color); }
|
||||
.loop-pip.current { background: var(--banner-color); animation: loop-pip 1.8s ease-in-out infinite; }
|
||||
@keyframes loop-pip { 50% { opacity: 0.4; } }
|
||||
#loop-spec { color: var(--ink-2); font-weight: 600; }
|
||||
#loop-elapsed { font-variant-numeric: tabular-nums; }
|
||||
#loop-retries { color: #f48771; }
|
||||
#loop-actions { flex: none; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
#loop-actions button {
|
||||
appearance: none; font: inherit; font-size: 12.5px; font-weight: 600; line-height: 1.2;
|
||||
padding: 6px 12px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--banner-line); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
#loop-actions button:hover:not(:disabled) { border-color: var(--banner-color); background: var(--panel-2); }
|
||||
#loop-actions button:disabled { cursor: default; opacity: 0.65; }
|
||||
#loop-actions button:focus-visible { outline: 2px solid var(--banner-color); outline-offset: 2px; }
|
||||
#loop-actions #loop-error { align-self: center; max-width: 320px; color: #f48771; font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
#loop-actions [hidden] { display: none; }
|
||||
#loop-actions #loop-stop-now { color: #f48771; }
|
||||
#loop-actions #loop-stop-now:hover:not(:disabled) { border-color: #f48771; }
|
||||
@media (prefers-reduced-motion: reduce) { #loop-dot, .loop-pip.current { animation: none; } }
|
||||
#bar-grow { flex: 1; min-width: 0; }
|
||||
/* The one next step for the console or the skills, at the right end. */
|
||||
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
@@ -84,6 +124,9 @@
|
||||
#workspace.dock-right { flex-direction: row; }
|
||||
|
||||
#dashboard { flex: 1; min-height: 0; min-width: 0; position: relative; }
|
||||
/* An Activities game in full screen: the console's frame over the whole
|
||||
window, the bar and the terminal left as they are underneath. */
|
||||
body.console-full #console-frame { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 1000; }
|
||||
#console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #1e1e1e; }
|
||||
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; }
|
||||
#dashboard-state[hidden] { display: none; }
|
||||
@@ -253,6 +296,28 @@
|
||||
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
|
||||
</div>
|
||||
</header>
|
||||
<!-- The Implementation Loop, while one runs (app.js loop-state, meter.js loopBanner). -->
|
||||
<section id="loop-banner" aria-label="Implementation Loop" hidden>
|
||||
<div id="loop-now">
|
||||
<div role="status" aria-live="polite">
|
||||
<div id="loop-headline"><span id="loop-dot" aria-hidden="true"></span><p id="loop-title"></p></div>
|
||||
<p id="loop-detail"></p>
|
||||
</div>
|
||||
<div id="loop-progress">
|
||||
<span id="loop-pips" aria-hidden="true"></span>
|
||||
<span id="loop-spec"></span>
|
||||
<span id="loop-elapsed"></span>
|
||||
<span id="loop-retries" hidden></span>
|
||||
<span id="loop-hint"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loop-actions">
|
||||
<button id="loop-stop-after" type="button">Stop after this phase</button>
|
||||
<button id="loop-stop-now" type="button">Stop now</button>
|
||||
<span id="loop-error" role="alert" hidden></span>
|
||||
<button id="loop-retry" type="button" hidden>Retry</button>
|
||||
</div>
|
||||
</section>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
|
||||
|
||||
@@ -128,6 +128,83 @@ export function windowTitleFor(dir) {
|
||||
return name ? `Plan2Code - ${name}` : "Plan2Code";
|
||||
}
|
||||
|
||||
/**
|
||||
* The window title while a loop runs, so its state shows in the taskbar too.
|
||||
*/
|
||||
export function loopWindowTitle(dir, state) {
|
||||
const name = lastSegment(dir);
|
||||
const what = state.step === "Waiting on you" ? `Loop needs you: Phase ${state.phase}` : `Loop: Phase ${state.phase} of ${state.phases}`;
|
||||
return name ? `${what} - ${name}` : what;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the loop banner says, from the app's `loop-state`: the one clear word on
|
||||
* what the loop is doing right now. `tone` is "running" or "waiting", `hint` the
|
||||
* line beside the phase pips and `pips` one "done", "current" or "todo" per phase
|
||||
* of the spec up to the last this run builds.
|
||||
*/
|
||||
export function loopBanner(state) {
|
||||
const { phase, phases, phaseName, step } = state;
|
||||
const named = phaseName ? `Phase ${phase} of ${phases}: ${phaseName}` : `Phase ${phase} of ${phases}`;
|
||||
const pips = Array.from({ length: Math.max(phases, 0) }, (_, i) => (i + 1 < phase ? "done" : i + 1 === phase ? "current" : "todo"));
|
||||
const base = { tone: "running", pips, hint: "Working on its own. You can walk away." };
|
||||
if (state.stopping) {
|
||||
return { ...base, title: "Stopping", detail: "The agent is ending. Nothing more will be committed.", hint: "The stop screen follows in a moment." };
|
||||
}
|
||||
if (step === "Waiting on you") {
|
||||
return { ...base, tone: "waiting", title: "The loop needs your answer", detail: `${named} is waiting on the question below.`, hint: "Nothing is lost while it waits." };
|
||||
}
|
||||
if (state.stopAfterPhase) {
|
||||
return { ...base, title: "Stopping after this phase", detail: `${named} finishes its checks and commit, then the loop stops.`, hint: "Stop now ends the agent at once." };
|
||||
}
|
||||
if (step === "Starting") {
|
||||
if (state.phaseRetried) return { ...base, title: `Retrying Phase ${phase}`, detail: `The agent crashed or went quiet, so a fresh one is picking up ${named}.` };
|
||||
if (state.previousPhase) {
|
||||
const how = state.previousCommitted ? "done and committed" : "done";
|
||||
return { ...base, title: `Phase ${state.previousPhase} ${how}`, detail: `Opening a fresh agent for ${named}.` };
|
||||
}
|
||||
return { ...base, title: "Starting the loop", detail: `Opening a fresh agent for ${named}.` };
|
||||
}
|
||||
return { ...base, title: "Implementation loop running", detail: step ? `${named} \u00b7 ${step}` : named };
|
||||
}
|
||||
|
||||
/**
|
||||
* The two stop buttons from the app's `loop-state`: "Stop after this phase" is
|
||||
* a toggle (its label says what a press does), off on the last phase, and both
|
||||
* buttons are off once Stop now was pressed.
|
||||
*/
|
||||
export function loopStopLabels(state) {
|
||||
const stopping = Boolean(state.stopping);
|
||||
const on = Boolean(state.stopAfterPhase);
|
||||
return {
|
||||
afterText: on ? "Cancel stop after this phase" : "Stop after this phase",
|
||||
afterDisabled: stopping || (!on && state.canStopAfter === false),
|
||||
nowDisabled: stopping,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The bar's Change project and Change agent controls while a loop runs: off,
|
||||
* with one short reason on them. The app refuses both commands too.
|
||||
*/
|
||||
export function loopLocks(state) {
|
||||
const locked = Boolean(state && state.running);
|
||||
return { locked, reason: locked ? "A loop is running. Stop it before you change the project or agent." : "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the window does about a console that stopped answering. On Windows the
|
||||
* agent's console dies with the agent (the app ends the agent's whole Job
|
||||
* Object), so between a loop's phases a dead console is expected: the next
|
||||
* phase opens its own, and the loop itself stops if it never does. The budget
|
||||
* guards against a console that keeps dying, not against a long session.
|
||||
*/
|
||||
export function deadConsoleAction({ loopRunning, loopStep, frameReady, reconnects, limit }) {
|
||||
if (loopRunning && loopStep === "Starting") return "wait-for-phase";
|
||||
if (!frameReady) return "no-hello";
|
||||
return reconnects < limit ? "reconnect" : "offer-button";
|
||||
}
|
||||
|
||||
/**
|
||||
* A project folder's own name, for the bar's project menu: the same last
|
||||
* segment the window title uses, or the whole path when there is none (a
|
||||
@@ -150,7 +227,9 @@ function lastSegment(dir) {
|
||||
* The console page's taskbar messages, checked here before anything reaches
|
||||
* the app (attention.rs decides what they mean). `attention` carries one of
|
||||
* the four states the page's favicon has; `taskbar` carries the Desktop app
|
||||
* switch as a boolean. Anything else is null, and nothing is forwarded.
|
||||
* switch as a boolean, and `activities-full` an Activities game going in or
|
||||
* out of full screen the same way (taskbarSwitch checks both). Anything else
|
||||
* is null, and nothing is forwarded.
|
||||
*/
|
||||
export const ATTENTION_STATES = Object.freeze(['busy', 'ready', 'attention', 'plain']);
|
||||
|
||||
|
||||
+157
-1
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -298,3 +298,159 @@ test("app.js forwards attention and taskbar through those checks, and clears the
|
||||
assert.match(APP_JS, /async function onNoHello\(\) \{\s+if \(frameReady \|\| !consoleKnown \|\| restarting\) return;[\s\S]{0,120}clearAttention\(\);/);
|
||||
assert.match(APP_JS, /plan2code: 'taskbar-state', on/, "the page hears the saved switch on its hello");
|
||||
});
|
||||
|
||||
test("the loop banner says what the loop is doing at every moment", () => {
|
||||
const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, phaseRetried: false, previousPhase: null, previousCommitted: false };
|
||||
const said = (extra) => loopBanner({ ...base, ...extra });
|
||||
|
||||
const running = said({});
|
||||
assert.equal(running.tone, "running");
|
||||
assert.equal(running.title, "Implementation loop running");
|
||||
assert.equal(running.detail, "Phase 2 of 4: API \u00b7 Build");
|
||||
assert.deepEqual(running.pips, ["done", "current", "todo", "todo"]);
|
||||
|
||||
assert.equal(said({ phase: 1, step: "Starting" }).title, "Starting the loop");
|
||||
assert.equal(said({ phase: 1, step: "Starting" }).detail, "Opening a fresh agent for Phase 1 of 4: API.");
|
||||
assert.equal(said({ step: "Starting", previousPhase: 1, previousCommitted: true }).title, "Phase 1 done and committed");
|
||||
assert.equal(said({ step: "Starting", previousPhase: 1 }).title, "Phase 1 done", "commits off: claims none");
|
||||
assert.equal(said({ step: "Starting", previousPhase: 1, phaseRetried: true }).title, "Retrying Phase 2", "a retry is not a new phase");
|
||||
|
||||
const waiting = said({ step: "Waiting on you" });
|
||||
assert.equal(waiting.tone, "waiting");
|
||||
assert.equal(waiting.title, "The loop needs your answer");
|
||||
assert.equal(said({ step: "Waiting on you", stopAfterPhase: true }).tone, "waiting", "a waiting question outranks a stop on its way");
|
||||
|
||||
const stopping = said({ stopAfterPhase: true });
|
||||
assert.equal(stopping.title, "Stopping after this phase");
|
||||
assert.equal(stopping.tone, "running");
|
||||
|
||||
assert.equal(said({ phaseName: "" }).detail, "Phase 2 of 4 \u00b7 Build");
|
||||
assert.deepEqual(said({ phase: 0, phases: 0 }).pips, []);
|
||||
});
|
||||
|
||||
test("Stop now turns the banner to Stopping, ahead of a question or a stop on its way", () => {
|
||||
const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: true };
|
||||
for (const extra of [{}, { step: "Waiting on you" }, { stopAfterPhase: true }, { step: "Starting" }]) {
|
||||
const banner = loopBanner({ ...base, ...extra });
|
||||
assert.equal(banner.title, "Stopping");
|
||||
assert.equal(banner.detail, "The agent is ending. Nothing more will be committed.");
|
||||
assert.equal(banner.tone, "running");
|
||||
assert.ok(banner.hint, "it has a hint");
|
||||
}
|
||||
assert.equal(loopBanner({ ...base, stopping: false }).title, "Implementation loop running");
|
||||
});
|
||||
|
||||
test("the stop buttons: Stop after is a toggle, off on the last phase, and both are off while stopping", () => {
|
||||
const base = { stopAfterPhase: false, stopping: false, canStopAfter: true };
|
||||
assert.deepEqual(loopStopLabels(base), { afterText: "Stop after this phase", afterDisabled: false, nowDisabled: false });
|
||||
assert.deepEqual(loopStopLabels({ ...base, stopAfterPhase: true }), { afterText: "Cancel stop after this phase", afterDisabled: false, nowDisabled: false }, "it can be turned off again");
|
||||
assert.equal(loopStopLabels({ ...base, canStopAfter: false }).afterDisabled, true, "the last phase has nothing to stop after");
|
||||
assert.equal(loopStopLabels({ ...base, canStopAfter: false }).nowDisabled, false, "Stop now stays on the last phase");
|
||||
assert.equal(loopStopLabels({ stopAfterPhase: false }).afterDisabled, false, "a state without the field leaves it on");
|
||||
assert.deepEqual(loopStopLabels({ ...base, stopping: true }), { afterText: "Stop after this phase", afterDisabled: true, nowDisabled: true });
|
||||
assert.equal(loopStopLabels({ ...base, stopAfterPhase: true, stopping: true }).afterDisabled, true);
|
||||
});
|
||||
|
||||
test("app.js sends the toggle's wish and shows a failed press with a Retry", () => {
|
||||
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||
assert.match(app, /invoke\(command, args\)\.then\(hideLoopError/, "a good press clears the error");
|
||||
assert.match(app, /pressLoop\('loop_stop_after_phase', \{ on: !loopStopAfterOn \}\)/);
|
||||
assert.match(app, /pressLoop\('loop_stop_now'\)/);
|
||||
assert.match(app, /loopRetryBtn\.hidden = false/, "a failed press offers Retry");
|
||||
const html = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "index.html"), "utf8");
|
||||
assert.match(html, /id="loop-error"[^>]*hidden/);
|
||||
assert.match(html, /id="loop-retry"[^>]*hidden/);
|
||||
});
|
||||
|
||||
test("a console dead between a loop's phases waits for the next phase; any other gets the budget", () => {
|
||||
const base = { loopRunning: false, loopStep: "", frameReady: true, reconnects: 0, limit: 3 };
|
||||
assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Starting" }), "wait-for-phase");
|
||||
assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Starting", reconnects: 3 }), "wait-for-phase", "never counts against the budget");
|
||||
assert.equal(deadConsoleAction({ ...base, loopRunning: true, loopStep: "Build" }), "reconnect", "mid-phase the agent still needs its page");
|
||||
assert.equal(deadConsoleAction(base), "reconnect");
|
||||
assert.equal(deadConsoleAction({ ...base, reconnects: 3 }), "offer-button");
|
||||
assert.equal(deadConsoleAction({ ...base, frameReady: false }), "no-hello");
|
||||
});
|
||||
|
||||
test("app.js refills the reconnect budget on a new page and brings the page back when a loop ends", () => {
|
||||
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||
const announced = app.slice(app.indexOf("function showAnnounced"), app.indexOf("window.__TAURI__.event.listen('console-page'"));
|
||||
assert.match(announced, /reconnects = 0/, "a budget never refilled ran out by a loop's Phase 3 and the stop card was never seen");
|
||||
const applied = app.slice(app.indexOf("function applyLoopState"), app.indexOf("loopRunning = true;"));
|
||||
assert.match(applied, /if \(wasRunning\) showLoopEnd\(\)/);
|
||||
assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/);
|
||||
});
|
||||
|
||||
test("the window title says a loop is running, and when it needs the person", () => {
|
||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch");
|
||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch");
|
||||
assert.equal(loopWindowTitle("", { phase: 1, phases: 2, step: "Build" }), "Loop: Phase 1 of 2");
|
||||
});
|
||||
|
||||
test("the loop banner and its stop buttons sit outside the bar, so nothing else competes with them", () => {
|
||||
const banner = INDEX_HTML.indexOf('id="loop-banner"');
|
||||
const barEnd = INDEX_HTML.indexOf("</header>");
|
||||
const workspace = INDEX_HTML.indexOf('<div id="workspace">');
|
||||
assert.ok(barEnd < banner && banner < workspace, "between the bar and the workspace");
|
||||
assert.ok(INDEX_HTML.indexOf('id="loop-stop-now"') > banner, "the stop buttons moved with it");
|
||||
assert.ok(!INDEX_HTML.includes('id="loop-strip"'));
|
||||
assert.match(INDEX_HTML, /id="loop-banner"[^>]*\bhidden\b/, "hidden until a loop runs");
|
||||
assert.match(INDEX_HTML, /role="status" aria-live="polite"/);
|
||||
assert.match(INDEX_HTML, /prefers-reduced-motion: reduce\) \{ #loop-dot/);
|
||||
assert.match(APP_JS, /listen\('loop-state'/);
|
||||
});
|
||||
|
||||
test("loopLocks turns Change project and Change agent off, with one reason, only while a loop runs", () => {
|
||||
const on = loopLocks({ running: true, phase: 2, phases: 4 });
|
||||
assert.equal(on.locked, true);
|
||||
assert.equal(on.reason, "A loop is running. Stop it before you change the project or agent.");
|
||||
for (const state of [{ running: false }, {}, null, undefined]) {
|
||||
assert.deepEqual(loopLocks(state), { locked: false, reason: "" });
|
||||
}
|
||||
});
|
||||
|
||||
test("the banner and stop buttons agree for a state carrying stopping, stopAfterPhase or the last phase", () => {
|
||||
const base = { running: true, phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: false, canStopAfter: true };
|
||||
const stopping = { ...base, stopping: true };
|
||||
assert.equal(loopBanner(stopping).title, "Stopping");
|
||||
assert.deepEqual(loopStopLabels(stopping), { afterText: "Stop after this phase", afterDisabled: true, nowDisabled: true });
|
||||
const after = { ...base, stopAfterPhase: true };
|
||||
assert.equal(loopBanner(after).title, "Stopping after this phase");
|
||||
assert.deepEqual(loopStopLabels(after), { afterText: "Cancel stop after this phase", afterDisabled: false, nowDisabled: false });
|
||||
const last = { ...base, canStopAfter: false };
|
||||
assert.equal(loopBanner(last).title, "Implementation loop running");
|
||||
assert.equal(loopStopLabels(last).afterDisabled, true);
|
||||
});
|
||||
|
||||
test("app.js asks loop_state after attach and again once it listens, without calling a reload a loop's end", () => {
|
||||
assert.match(APP_JS, /async function syncLoopState\(\)[\s\S]*?invoke\('loop_state'\)/);
|
||||
assert.match(APP_JS, /\.listen\('loop-state'[\s\S]*?\.then\(syncLoopState/, "asked again once the listener is up");
|
||||
const attach = APP_JS.indexOf("invoke('agent_reattach'");
|
||||
const sync = APP_JS.indexOf("await syncLoopState()", attach);
|
||||
assert.ok(attach > 0 && sync > attach, "asked right after the reattach");
|
||||
assert.match(APP_JS, /const seen = loopEventSeq;[\s\S]*?if \(seen !== loopEventSeq\) return;/, "an event that landed while loop_state was out wins over its answer");
|
||||
assert.match(APP_JS, /else if \(loopRunning\) applyLoopState\(\{ running: false \}\)/, "no loop and none drawn redraws nothing");
|
||||
assert.match(APP_JS, /const wasRunning = loopRunning;[\s\S]*?if \(wasRunning\) showLoopEnd\(\)/, "only a drawn loop ends with the finish redraw");
|
||||
});
|
||||
|
||||
test("app.js locks the change buttons through loopLocks and shows the typing note once per loop", () => {
|
||||
assert.match(APP_JS, /const \{ locked, reason \} = loopLocks\(state\);[\s\S]*?button\.disabled = locked/);
|
||||
assert.match(APP_JS, /applyLoopLocks\(\{ running: false \}\)/, "the ended branch gives them back");
|
||||
assert.match(APP_JS, /if \(!loopRunning\) loopTypingNoted = false/, "a new loop shows the note again");
|
||||
assert.ok(APP_JS.includes("noteTypingDuringLoop();\n invoke('agent_input'"), "the note comes before, and never replaces, the delivery of the key");
|
||||
assert.ok(APP_JS.includes("A loop is running. Typing here can derail the phase it is working on."));
|
||||
});
|
||||
|
||||
test("main.rs guards the window's agent and project commands, and registers loop_state", () => {
|
||||
const rust = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "src-tauri", "src", "main.rs"), "utf8");
|
||||
const body = (name) => {
|
||||
const at = rust.indexOf(`fn ${name}(`);
|
||||
assert.ok(at > 0, `${name} exists`);
|
||||
return rust.slice(at, rust.indexOf("\n}\n", at));
|
||||
};
|
||||
for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"]]) {
|
||||
assert.ok(body(name).includes(`refuse_while_looping(&state, "${what}")?;`), `${name} refuses while a loop runs`);
|
||||
}
|
||||
assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt");
|
||||
assert.match(rust, /generate_handler!\[[\s\S]*?loop_stop_now,\s*loop_state,/);
|
||||
});
|
||||
Reference in new issue
Block a user